id
stringlengths 3
8
| content
stringlengths 100
981k
|
---|---|
462271
|
import os
import sys
import threading
import subprocess
def _try_to_kill(process):
try:
process.kill()
except Exception:
pass
def touch(path):
if not os.path.exists(path):
with open(path, 'w') as _:
pass
class Process(object):
def __init__(self, args):
self._process = subprocess.Popen(args)
self._event = threading.Event()
self._result = None
thread = threading.Thread(target=self._run)
thread.setDaemon(True)
thread.start()
def _run(self):
self._process.communicate()
self._result = self._process.returncode
self._event.set()
def wait(self, timeout):
self._event.wait(timeout=timeout)
_try_to_kill(self._process)
return self._result
if __name__ == '__main__':
yndexer = sys.argv[1]
timeout = int(sys.argv[2])
output_file = sys.argv[3]
input_file = sys.argv[4]
partition_count = sys.argv[5]
partition_index = sys.argv[6]
process = Process([yndexer, '-f', input_file, '-y', output_file, '-c', partition_count, '-i', partition_index])
result = process.wait(timeout=timeout)
if result != 0:
print >> sys.stderr, 'Yndexing process finished with code', result
touch(output_file)
|
462275
|
from twitch.helix import Video
from tcd.settings import Settings
class Format:
def __init__(self, video: Video, format_name: str):
self.video: Video = video
self.format_name: str = format_name
self.format_dictionary: dict = Settings().config['formats'][format_name]
|
462319
|
import input_parser
import pandas as pd
import app_classifier
import config
import timing
class ClassificationResult:
def __init__(self, accuracy, file_name):
self.accuracy = accuracy
self.file_name = file_name
def __str__(self):
return "Total accuracy: " + str(self.accuracy) + " for " + self.file_name
def explorative_classification():
file_contents, label_list = input_parser.parse_input_files(config.get_record_dir(), combine_sc_vectors=False)
results = []
for idx, fc in enumerate(file_contents):
labels = label_list[idx]
print("\nEvaluate ", fc.file_name)
X = [fc]
Y = pd.Series(labels)
total_accuracy = app_classifier.do_kfold_cross_validation(X, Y, verbose=False)
results.append(ClassificationResult(total_accuracy, fc.file_name))
results.sort(key = lambda classificationResult: classificationResult.accuracy, reverse=True)
print("\nSummary for files in " + config.get_record_dir() + ":\n")
for r in results:
print(r)
def main():
timing.start_measurement()
print("Do explorative classification with separate input files")
explorative_classification()
timing.stop_measurement()
main()
|
462325
|
def message_says_hello(msg):
"""Make sure that the response was friendly"""
assert msg.payload.get("message") == "hello world"
|
462346
|
from typing import Mapping, Sequence, Union
import torch
from pyro.distributions import TorchDistribution
from torch.distributions import register_kl
from torch.distributions.constraints import Constraint
from .multivariate import MultivariateDistribution
def _iterate_parts(value, ndims: Sequence[int]):
for ndim in ndims:
yield value[..., :ndim]
value = value[..., ndim:]
class _FactorisedSupport(Constraint):
def __init__(self, supports: Sequence[Constraint], ndims: Sequence[int]):
self.supports = supports
self.ndims = ndims
def check(self, value):
return all(support.check(part)
for support, part in zip(self.supports, _iterate_parts(value, self.ndims)))
class Factorised(MultivariateDistribution):
arg_constraints = {}
def __init__(self, factors: Union[Sequence[TorchDistribution], Mapping[str, TorchDistribution]],
validate_args=None, var_names=None):
if isinstance(factors, Mapping):
if var_names is not None:
raise ValueError("var_names should not be given alongside a factor dictionary")
var_names = list(factors.keys())
factors = list(factors.values())
self.factors = factors
batch_shape = factors[0].batch_shape
event_shape = torch.Size([sum(factor.event_shape[0] for factor in self.factors)])
self._ndims = [factor.event_shape[0] if len(factor.event_shape) > 0 else 1
for factor in self.factors]
super().__init__(batch_shape, event_shape, validate_args, var_names=var_names)
def expand(self, batch_shape, _instance=None):
new = self._get_checked_instance(Factorised, _instance)
batch_shape = torch.Size(batch_shape)
new.factors = [factor.expand(batch_shape) for factor in self.factors]
new._ndims = self._ndims
super(Factorised, new).__init__(batch_shape, self.event_shape, validate_args=False,
var_names=self.variable_names)
new._validate_args = self._validate_args
return new
@property
def has_rsample(self):
return any(factor.has_rsample for factor in self.factors)
@property
def support(self):
return _FactorisedSupport([factor.support for factor in self.factors], self._ndims)
def rsample(self, sample_shape=torch.Size()):
return torch.cat([factor.rsample(sample_shape) for factor in self.factors], dim=-1)
@property
def num_variables(self):
return len(self.factors)
@property
def variable_shapes(self):
return [factor.event_shape[0] for factor in self.factors]
def _marginalise_single(self, factor_index: int) -> TorchDistribution:
return self.factors[factor_index]
def _marginalise_multi(self, factor_indices: Sequence[int]) -> 'Factorised':
return Factorised([self.factors[i] for i in factor_indices],
validate_args=self._validate_args)
def _condition(self, marg_indices, cond_indices, cond_values, squeeze):
cond_dist = self.marginalise(marg_indices[0] if squeeze else marg_indices)
cond_batch_shape = torch.Size([cond_values[0].shape[0]]) + cond_dist.batch_shape
return cond_dist.expand(cond_batch_shape)
def log_prob(self, value):
return sum(factor.log_prob(part)
for factor, part in zip(self.factors, self.partition_dimensions(value)))
def entropy(self):
return sum(factor.entropy() for factor in self.factors)
def partition_dimensions(self, data):
return _iterate_parts(data, self._ndims)
@property
def mean(self):
return torch.cat([factor.mean for factor in self.factors], dim=-1)
@property
def variance(self):
return sum(factor.variance for factor in self.factors)
def __repr__(self):
factors = self.factors
if self.variable_names is not None:
factors = dict(zip(self.variable_names, factors))
return self.__class__.__name__ + f"({factors})"
@register_kl(Factorised, Factorised)
def _kl_factorised_factorised(p: Factorised, q: Factorised):
return sum(kl_divergence(p_factor, q_factor)
for p_factor, q_factor in zip(p.factors, q.factors))
if __name__ == '__main__':
from pyro.distributions import Dirichlet, MultivariateNormal
from torch.distributions import kl_divergence
from distributions.mixture import Mixture
B, D1, D2 = 5, 3, 4
N = 1000
dist1 = MultivariateNormal(torch.zeros(D1), torch.eye(D1)).expand((B,))
dist2 = Dirichlet(torch.ones(D2)).expand((B,))
print(dist1.batch_shape, dist1.event_shape)
print(dist2.batch_shape, dist2.event_shape)
fact = Factorised([dist1, dist2])
print(fact.batch_shape, fact.event_shape)
samples = fact.rsample((N,))
print(samples[0])
print(samples.shape)
logp = fact.log_prob(samples)
print(logp.shape)
entropy = fact.entropy()
print(entropy.shape)
print(entropy, -logp.mean())
print()
print(kl_divergence(fact, fact))
mixture = Mixture(torch.ones(B), fact)
samples = mixture.rsample((N,))
logp = mixture.log_prob(samples)
print(samples.shape)
print(logp.shape)
|
462368
|
from fabric.api import hide, run, env
import time
import json
def run_cmd(cmd):
with hide('output', 'running', 'warnings'):
return run(cmd, timeout=1200)
def check(**kwargs):
''' Login over SSH and execute shell command '''
jdata = kwargs['jdata']
logger = kwargs['logger']
env.gateway = jdata['data']['gateway']
env.host_string = jdata['data']['host_string']
env.user = jdata['data']['username']
env.key = jdata['data']['sshkey']
env.shell = "/bin/sh -c"
env.disable_known_hosts = True
env.warn_only = True
env.abort_on_prompts = True
results = run_cmd("uname -a")
if results.succeeded:
if "FreeBSD" in results:
cmd = "swapinfo"
results = run_cmd(cmd)
if results.succeeded:
lines = results.splitlines()
swapinfo = lines[1].split()
total_swap = int(swapinfo[1])
used_swap = int(swapinfo[2])
else:
return None
else:
cmd = "cat /proc/meminfo"
results = run_cmd(cmd)
if results.succeeded:
swapstats = {}
for line in results.splitlines():
line_data = line.split()
key = line_data[0].rstrip(":")
swapstats[key] = int(line_data[1])
total_swap = swapstats['SwapTotal']
used_swap = swapstats['SwapTotal'] - swapstats['SwapFree']
else:
return None
else:
return None
logger.debug("swap-used: Total Swap {0} Swap Used {1} ".format(total_swap, used_swap))
if total_swap == 0:
# avoid dividing by zero
return True
used_perc = float(used_swap) / float(total_swap)
threshold = float(jdata['data']['threshold']) / 100
logger.debug("swap-used: Used Percent {0} Threshold {1}".format(used_perc, threshold))
if used_perc < threshold:
return True
else:
return False
|
462374
|
import pysinsy
from nnmnkwii.io import hts
# TODO: consider replacing pysinsy to pure python implementation
_global_sinsy = None
def _lazy_init(dic_dir=None):
if dic_dir is None:
dic_dir = pysinsy.get_default_dic_dir()
global _global_sinsy
if _global_sinsy is None:
_global_sinsy = pysinsy.sinsy.Sinsy()
assert _global_sinsy.setLanguages("j", dic_dir)
def xml2lab(xml):
"""Convert musicxml to HTS full context labels
Args:
xml (str): Path to musicxml file.
Returns:
HTS full context labels
"""
_lazy_init()
_global_sinsy.loadScoreFromMusicXML(xml)
label = _global_sinsy.createLabelData(False, 1, 1)
label = hts.load(lines=label.getData())
_global_sinsy.clearScore()
return label
|
462390
|
def main():
for x in range(4):
if x == 5:
break
else:
print("Well of course that didn't happen")
for x in range(7):
if x == 5:
break
else:
print("H-hey wait!")
i = 0
while i < 3:
print("Works with while too")
for x in range(3):
print("BTW don't worry about nested breaks")
break
if i == 10:
break
i += 1
else:
print("Yeah not likely")
print(i)
if __name__ == '__main__':
main()
|
462396
|
import unittest
from chainer import function_node
from chainer import testing
def dummy():
pass
class TestNoNumpyFunction(unittest.TestCase):
def test_no_numpy_function(self):
with self.assertRaises(ValueError):
testing.unary_math_function_unittest(dummy) # no numpy.dummy
class DummyLinear(function_node.FunctionNode):
@property
def label(self):
return 'dummy_linear'
def forward(self, x):
return x[0],
def backward(self, indexes, gy):
return gy[0],
def dummy_linear(x):
return DummyLinear().apply((x,))[0]
@testing.unary_math_function_unittest(dummy_linear,
func_expected=lambda x, dtype: x)
class TestIsLinear(unittest.TestCase):
pass
testing.run_module(__name__, __file__)
|
462401
|
import os
from prometheus_client import CONTENT_TYPE_LATEST, CollectorRegistry, \
core, multiprocess, start_http_server
from prometheus_client.exposition import generate_latest
from sanic.response import raw
from . import endpoint, metrics
from .exceptions import SanicPrometheusError
class MonitorSetup:
def __init__(self, app, metrics_path, multiprocess_on=False):
self._app = app
self._multiprocess_on = multiprocess_on
self._metrics_path = metrics_path
def expose_endpoint(self):
"""
Expose /metrics endpoint on the same Sanic server.
This may be useful if Sanic is launched from a container
and you do not want to expose more than one port for some
reason.
"""
@self._app.route(self._metrics_path, methods=['GET'])
async def expose_metrics(request):
return raw(self._get_metrics_data(),
content_type=CONTENT_TYPE_LATEST)
def start_server(self, addr='', port=8000):
"""
Expose /metrics endpoint on a new server that will
be launched on `<addr>:<port>`.
This may be useful if you want to restrict access to
metrics data with firewall rules.
NOTE: can not be used in multiprocessing mode
"""
if self._multiprocess_on:
raise SanicPrometheusError(
"start_server can not be used when multiprocessing " +
"is turned on")
start_http_server(addr=addr, port=port)
def _get_metrics_data(self):
if not self._multiprocess_on:
registry = core.REGISTRY
else:
registry = CollectorRegistry()
multiprocess.MultiProcessCollector(registry)
data = generate_latest(registry)
return data
def monitor(app, endpoint_type='url:1',
get_endpoint_fn=None,
latency_buckets=None,
mmc_period_sec=30,
multiprocess_mode='all',
metrics_path='/metrics',
is_middleware=True,
metrics_list=None):
"""
Regiesters a bunch of metrics for Sanic server
(request latency, count, etc) and exposes /metrics endpoint
to allow Prometheus to scrape them out.
:param metrics_list:
:param is_middleware:
:param metrics_path:
:param multiprocess_mode:
:param app: an instance of sanic.app
:param endpoint_type: All request related metrics have a label called
'endpoint'. It can be fetched from Sanic `request`
object using different strategies specified by
`endpoint_type`:
url - full relative path of a request URL
(i.e. for http://something/a/b/c?f=x you end up
having `/a/b/c` as the endpoint)
url:n - like URL but with at most `n` path elements
in the endpoint (i.e. with `url:1`
http://something/a/b/c becomes `/a`).
custom - custom endpoint fetching funciton that
should be specified by `get_endpoint_fn`
:param get_endpoint_fn: a custom endpoint fetching function that is ignored
until `endpoint_type='custom'`.
get_endpoint_fn = lambda r: ...
where `r` is Sanic request object
:param latency_buckets: an optional list of bucket sizes for latency
histogram (see prometheus `Histogram` metric)
:param mmc_period_sec: set a period (in seconds) of how frequently memory
usage related metrics are collected.
Setting it to None will disable memory metrics
collection.
:multiprocess_mode':
:metrics_path: path where metrics will be exposed
NOTE: memory usage is not collected when when multiprocessing is enabled
"""
multiprocess_on = 'prometheus_multiproc_dir' in os.environ
get_endpoint = endpoint.fn_by_type(endpoint_type, get_endpoint_fn)
memcollect_enabled = mmc_period_sec is not None
@app.listener('before_server_start')
def before_start(app, loop):
app.metrics = {}
metrics.init(
app,
latency_buckets, multiprocess_mode,
memcollect_enabled=memcollect_enabled,
metrics_list=metrics_list,
)
if is_middleware is True:
@app.middleware('request')
async def before_request(request):
if request.path != metrics_path and request.method != "OPTIONS":
metrics.before_request_handler(request)
@app.middleware('response')
async def before_response(request, response):
if request.path != metrics_path and request.method != "OPTIONS":
metrics.after_request_handler(request, response, get_endpoint)
if multiprocess_on:
@app.listener('after_server_stop')
def after_stop(app, loop):
multiprocess.mark_process_dead(os.getpid())
elif memcollect_enabled:
@app.listener('before_server_start')
async def start_memcollect_task(app, loop):
app.memcollect_task = loop.create_task(
metrics.periodic_memcollect_task(
app,
mmc_period_sec,
loop
)
)
@app.listener('after_server_stop')
async def stop_memcollect_task(app, loop):
app.memcollect_task.cancel()
return MonitorSetup(app, metrics_path, multiprocess_on)
__all__ = ['monitor']
|
462409
|
from typing import List, Tuple
from drkns.configunit.ConfigUnit import ConfigUnit
from drkns.generation.GenerationTemplate import GenerationTemplate
from drkns.generation.generation.get_group_block import get_group_block
from drkns.generation.pattern_util \
import format_list_in_template
from drkns.generation._tags import groups_tag, all_group_names_tag
def get_formatted_from_groups_configuration(
generation_template: GenerationTemplate,
groups: List[Tuple[str, List[ConfigUnit], List[str]]]
) -> str:
group_blocks = []
all_group_names = []
for group_name, group_config_units, dependency_groups_name in groups:
group_block = get_group_block(
generation_template, group_name, group_config_units,
dependency_groups_name)
group_blocks.append(group_block)
all_group_names.append(group_name)
formatted = generation_template.template
formatted = format_list_in_template(
groups_tag, group_blocks, formatted, line_level=True)
formatted = format_list_in_template(
all_group_names_tag, all_group_names, formatted, line_level=False)
return formatted
|
462414
|
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
import pdb
import requests
import time
from random import randint
import csv
class amazon_review_scraper:
# Ignore SSL certificate errors
ssl._create_default_https_context = ssl._create_unverified_context
csv_data = []
csv_head = ["Rating", "Title", "Date", "Verified Purchase", "Body", "Helpful Votes"]
def __init__(self, url, start_page, end_page, time_upper_limit):
self.url = url
self.set_url()
self.start_page = int(start_page)
self.end_page = int(end_page)
self.time_upper_limit = time_upper_limit
def set_sleep_timer(self):
sleep_time = randint(0, int(self.time_upper_limit))
print("\nSleeping for " + str(sleep_time) + " seconds.")
time.sleep(sleep_time)
def set_url(self):
# removing pageNumber parameter if it exists in the url
url = self.url.split("&pageNumber")
if len(url) > 1:
self.url = url[0]
else :
self.url = url
def set_start_page(self, start_page):
url = self.url + "&pageNumber=" + str(start_page)
return url
def build_rating(self, review):
return str(review).split("<span class=\"a-icon-alt\">")[1].split("</span>")[0].split(" ")[0]
def build_title(self, review):
return str(review).split("data-hook=\"review-title\"")[1].split("\">")[1].split("</a>")[0]
def build_date(self, review):
return str(review).split("data-hook=\"review-date\">")[1].split("</span>")[0].split("on ")[1]
def build_verified_purchase(self, review):
# Yes = purchased, No = not purchased
try:
str(review).split("data-hook=\"avp-badge\">")[1].split("</span>")[0]
return "Yes"
except:
return "No"
def build_body(self, review):
body = str(review).split("data-hook=\"review-body\">")[1].split("</span>")[0] + "\n"
# to remove <br>, <br/> and </br>
body = body.replace("<br>", ".").replace("<br/>", ".").replace("</br>", ".").strip()
return body
def build_votes(self, review):
try :
votes = str(review).split("data-hook=\"helpful-vote-statement\"")[1].split(">")[1].split("<")[0].strip().split()
if votes[0] == "One" :
return "1"
else :
return votes[0]
except :
return "0"
def scrape(self):
start_page = self.start_page
end_page = self.end_page
if end_page < start_page:
print("Start page cannot be greater than end page. Please try again.")
exit()
self.csv_data.append(self.csv_head)
while start_page <= end_page :
try:
url = self.set_start_page(start_page)
except:
print("URL entered is wrong. Please try again with the right URL.")
exit()
# Sleep because Amazon might block your IP if there are too many requests every second
self.set_sleep_timer()
print("Scraping page " + str(start_page) + ".")
# Amazon blocks requests that don't come from browser. Hence need to mention user-agent
user_agent = 'Mozilla/5.0'
headers = {'User-Agent' : user_agent}
values = {}
data = urllib.parse.urlencode(values).encode('utf-8')
req = urllib.request.Request(url, data, headers)
response = urllib.request.urlopen(req)
html = response.read()
soup = BeautifulSoup(html, 'html.parser')
reviews = soup.find_all("div", attrs={"class": "a-section review"})
for review in reviews :
csv_body = []
# Star Rating
rating = self.build_rating(review)
csv_body.append(rating)
# Title
title = self.build_title(review)
csv_body.append(title)
# Date
date = self.build_date(review)
csv_body.append(date)
# Verified Purchase
verified_purchase = self.build_verified_purchase(review)
csv_body.append(verified_purchase)
# Body
body = self.build_body(review)
csv_body.append(body)
# Helpful Votes
votes = self.build_votes(review)
csv_body.append(votes)
self.csv_data.append(csv_body)
start_page += 1
def write_csv(self, file_name):
print("\nWriting to file.\n")
with open((file_name + '.csv'), 'w') as csv_file :
writer = csv.writer(csv_file, delimiter=',')
writer.writerows(self.csv_data)
|
462422
|
from pylab import *
from scipy import *
from scipy import optimize
import argparse
import sys
import os
# Generate data points with noise
# Read in csv file and set length and width
"""
This program reads in a set of points from a csv file and interprets these points.
These points correspond to a torpedo, emperor, or wire.
Goal: Calculate aspect ratio and height.
Output: Aspect ratio and height (written to a csv file).
"""
# c**2 = a**2 + b **2 - 2ab cos (theta)
# theta = arc cos((c**2 - a**2 - b**2)/ -2ab)
# Returns the angle of a triangle with hypoteneus c and legs a and b
def lawOfCos(c,a,b):
try:
return acos((c**2 - a**2 - b**2)/(-2.*a*b))
finally:
# No angle
return 0
# c = sqrt(a**2 + b**2)
# input: x and y of both points
# output: distance between points
def distance(a_x,a_y,b_x,b_y):
return math.sqrt((b_y - a_y)**2. + (b_x - a_x)**2.)
parser = argparse.ArgumentParser()
parser.add_argument('-r','--redTorpedo',action = "store_true")
parser.add_argument('-b','--blueTorpedo',action= "store_true")
parser.add_argument('-w','--wire',action = "store_true")
parser.add_argument('-e','--emperor',action = "store_true")
args = parser.parse_args()
if (args.redTorpedo):
csv_file = open('red_torpedo_raw_data.csv','r')
out_file = open('red_torpedo.csv','w')
elif (args.blueTorpedo):
csv_file = open('blue_torpedo_raw_data.csv','r')
out_file = open('blue_torpedo.csv','w')
elif (args.wire):
csv_file = open('wire_raw_data.csv','r')
out_file = open('wire.csv','w')
elif (args.emperor):
csv_file = open('emperor_raw_data.csv','r')
out_file = open('emperor.csv','w')
raw_data = csv_file.readlines()
csv_file.close()
#process raw data
for line in raw_data:
split_line = line.split(',')
tl_x = split_line[0]
tl_y = split_line[1]
tr_x = split_line[2]
tr_y = split_line[3]
bl_x = split_line[4]
bl_y = split_line[5]
br_x = split_line[6]
br_y = split_line[7]
north_dist = split_line[8]
east_dist = split_line[9]
total_dist = split_line[10]
#width and heights
tw = distance(tl_x,tl_y,tr_x,tr_y)
top_width = tw
bw = distance(bl_x,br_y,bl_x,bl_y)
bottom_width = bw
lh = distance(tl_x,tl_y,bl_x,bl_y)
left_height = lh
rh = distance(tr_x,tr_y,br_x,br_x)
right_height = rh
#average height edge
#used for distance to center of the object
average_edge = (lh + rh) / 2
#aspect ratio
larger_width = max(tw,bw)
larger_height = max(lh,rh)
aspect = larger_width/larger_height
#angle to object
angle = math.atan2(north,east)
csv_line = [average_edge,aspect,angle]
out_file.write(csv_line)
out_file.close()
"""
#unused for now
#finds angles of each edge of perceived quadrilateral
for i in range(len(raw_data)):
#diagonals
tl_diag, br_diag = distance(tr_x[i],tr_y[i],bl_x[i],bl_y[i])
tr_diag, bl_diag = distance(tl_x[i],tl_y[i],br_x[i],br_y[i])
#angles
tla = lawOfCos(tl_diag,tw,lh)
tl_angle[i] = tla
tra = lawOfcos(tr_diag,tw,rh)
tr_angle[i] = tra
bla = lawOfCos(bl_diag,bw,lh)
bl_angle[i] = bla
bra = lawOfCos(br_diag,bw,rh)
br_angle[i] = bra
"""
|
462509
|
import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.daylighting import DaylightingDelightControls
log = logging.getLogger(__name__)
class TestDaylightingDelightControls(unittest.TestCase):
def setUp(self):
self.fd, self.path = tempfile.mkstemp()
def tearDown(self):
os.remove(self.path)
def test_create_daylightingdelightcontrols(self):
pyidf.validation_level = ValidationLevel.error
obj = DaylightingDelightControls()
# alpha
var_name = "Name"
obj.name = var_name
# object-list
var_zone_name = "object-list|Zone Name"
obj.zone_name = var_zone_name
# integer
var_lighting_control_type = 2
obj.lighting_control_type = var_lighting_control_type
# real
var_minimum_input_power_fraction_for_continuous_dimming_control = 0.3
obj.minimum_input_power_fraction_for_continuous_dimming_control = var_minimum_input_power_fraction_for_continuous_dimming_control
# real
var_minimum_light_output_fraction_for_continuous_dimming_control = 0.3
obj.minimum_light_output_fraction_for_continuous_dimming_control = var_minimum_light_output_fraction_for_continuous_dimming_control
# integer
var_number_of_stepped_control_steps = 6
obj.number_of_stepped_control_steps = var_number_of_stepped_control_steps
# real
var_probability_lighting_will_be_reset_when_needed_in_manual_stepped_control = 0.5
obj.probability_lighting_will_be_reset_when_needed_in_manual_stepped_control = var_probability_lighting_will_be_reset_when_needed_in_manual_stepped_control
# real
var_gridding_resolution = 0.0001
obj.gridding_resolution = var_gridding_resolution
idf = IDF()
idf.add(obj)
idf.save(self.path, check=False)
with open(self.path, mode='r') as f:
for line in f:
log.debug(line.strip())
idf2 = IDF(self.path)
self.assertEqual(idf2.daylightingdelightcontrolss[0].name, var_name)
self.assertEqual(idf2.daylightingdelightcontrolss[0].zone_name, var_zone_name)
self.assertEqual(idf2.daylightingdelightcontrolss[0].lighting_control_type, var_lighting_control_type)
self.assertAlmostEqual(idf2.daylightingdelightcontrolss[0].minimum_input_power_fraction_for_continuous_dimming_control, var_minimum_input_power_fraction_for_continuous_dimming_control)
self.assertAlmostEqual(idf2.daylightingdelightcontrolss[0].minimum_light_output_fraction_for_continuous_dimming_control, var_minimum_light_output_fraction_for_continuous_dimming_control)
self.assertEqual(idf2.daylightingdelightcontrolss[0].number_of_stepped_control_steps, var_number_of_stepped_control_steps)
self.assertAlmostEqual(idf2.daylightingdelightcontrolss[0].probability_lighting_will_be_reset_when_needed_in_manual_stepped_control, var_probability_lighting_will_be_reset_when_needed_in_manual_stepped_control)
self.assertAlmostEqual(idf2.daylightingdelightcontrolss[0].gridding_resolution, var_gridding_resolution)
|
462510
|
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# Using Boyer-Moore Majority Vote Algorithm
# Since we only use equality comparison, and cnt_a and cnt_b are initialized to 0
# thus initializing a and b to 0 doesn't change result even if the nums contains negative numbers
# or 0.
a = b = 0
cnt_a = cnt_b = 0
for e in nums:
if a == e:
cnt_a += 1
elif b == e:
cnt_b += 1
elif cnt_a == 0:
a = e
cnt_a = 1
elif cnt_b == 0:
b = e
cnt_b = 1
else:
cnt_a -= 1
cnt_b -= 1
cnt_a = cnt_b = 0
for e in nums:
if e == a:
cnt_a += 1
elif e == b:
cnt_b += 1
result = []
total = len(nums)
if cnt_a > total // 3:
result.append(a)
if cnt_b > total // 3:
result.append(b)
return result
|
462524
|
from __future__ import print_function, division
import unittest
class Vector:
def __init__(s, *args, **_kwargs):
kwargs = {
'base_class': (int, float),
}
kwargs.update(_kwargs)
s.base = kwargs['base_class']
if len(args) == 1 and hasattr(args[0], '__iter__'):
s.v = tuple(args[0])
elif len(args) != 0:
s.v = tuple(args)
else:
s.v = ["dummy"]
if not all(isinstance(x, s.base) for x in s.v):
raise ValueError('Invalid Argument Specified: {!r}'.format(args))
def norm(s):
import math
# Calculate euclidean norm
return math.sqrt(sum(map(lambda x: x**2, s.v)))
def _prepare_other_as_vector(s, other):
if not isinstance(other, s.__class__):
other = s.__class__(other)
if len(s) != len(other):
raise ValueError('Vector\'s dimension doesn\'t match: {!r}'.format(other))
return other
def add(s, other):
other = s._prepare_other_as_vector(other)
return s.__class__(map(lambda x: x[0] + x[1], zip(s.v, other.v)), base_class=s.base)
def sub(s, other):
other = s._prepare_other_as_vector(other)
return s.__class__(map(lambda x: x[0] - x[1], zip(s.v, other.v)), base_class=s.base)
def scalar_mult(s, other):
if not isinstance(other, s.base):
raise ValueError('{!r} must be an instance of {!r}'.format(other, s.base))
return s.__class__(map(lambda x: other * x, s.v), base_class=s.base)
def inner_product(s, other):
try:
other = s._prepare_other_as_vector(other)
except ValueError:
raise ValueError('Inner product can calculate between vector and vector: {!r}'.format(other))
return sum(map(lambda x: x[0] * x[1], zip(s.v, other.v)))
def __len__(s):
return len(s.v)
def __getitem__(s, n):
assert n < len(s), 'The specified index out of bounds: {}'.format(n)
return s.v[n]
def __iter__(s):
return iter(s.v)
def __eq__(s, other):
if isinstance(other, Vector):
return s.v == other.v
elif hasattr(other, '__iter__'):
return s.v == tuple(other)
return False
def __repr__(s):
return '{}({!r})'.format(s.__class__.__name__, s.v)
def __str__(s):
return '({})'.format(', '.join(map(str, s.v)))
|
462535
|
import numpy as np
import warnings
import os
import h5py
from tqdm import tqdm
import pickle
from torch.utils.data import Dataset
warnings.filterwarnings('ignore')
def pc_normalize(pc):
centroid = np.mean(pc, axis=0)
pc = pc - centroid
m = np.max(np.sqrt(np.sum(pc**2, axis=1)))
pc = pc / m
return pc
def farthest_point_sample(point, npoint):
"""
Input:
xyz: pointcloud data, [N, D]
npoint: number of samples
Return:
centroids: sampled pointcloud index, [npoint, D]
"""
N, D = point.shape
xyz = point[:,:3]
centroids = np.zeros((npoint,))
distance = np.ones((N,)) * 1e10
farthest = np.random.randint(0, N)
for i in range(npoint):
centroids[i] = farthest
centroid = xyz[farthest, :]
dist = np.sum((xyz - centroid) ** 2, -1)
mask = dist < distance
distance[mask] = dist[mask]
farthest = np.argmax(distance, -1)
point = point[centroids.astype(np.int32)]
return point
def convert_to_binary_mask(masks):
binary_masks = []
for i in range(masks.shape[0]):
binary_mask = np.ones(masks[i].shape)
bg_idx = np.where(masks[i,:]==-1)
binary_mask[bg_idx] = 0
binary_masks.append(binary_mask)
binary_masks = np.array(binary_masks)
return binary_masks
class ScanObjectNNDataLoader(Dataset):
def __init__(self, root, npoint=1024, split='train', uniform=False, normal_channel=True, cache_size=15000):
self.root = root
self.npoints = npoint
self.uniform = uniform
#self.catfile = os.path.join(self.root, 'modelnet40_shape_names.txt')
#self.cat = [line.rstrip() for line in open(self.catfile)]
#self.classes = dict(zip(self.cat, range(len(self.cat))))
self.normal_channel = normal_channel
#shape_ids = {}
#shape_ids['train'] = [line.rstrip() for line in open(os.path.join(self.root, 'modelnet40_train.txt'))]
#shape_ids['test'] = [line.rstrip() for line in open(os.path.join(self.root, 'modelnet40_test.txt'))]
assert (split == 'train' or split == 'test')
#shape_names = ['_'.join(x.split('_')[0:-1]) for x in shape_ids[split]]
# list of (shape_name, shape_txt_file_path) tuple
data = h5py.File(self.root + '/' + split + '_objectdataset_augmentedrot_scale75.h5', 'r')
self.points = data['data'][:]
self.labels = data['label'][:]
self.masks = convert_to_binary_mask(data['mask'][:])
print('The size of %s data is %d'%(split,self.points.shape[0]))
self.cache_size = cache_size # how many data points to cache in memory
self.cache = {} # from index to (point_set, cls) tuple
def __len__(self):
return self.points.shape[0]
def _get_item(self, index):
if index in self.cache:
point_set, cls, mask = self.cache[index]
else:
point_set = self.points[index]
cls = self.labels[index]
mask = self.masks[index]
#fn = self.datapath[index]
#cls = self.classes[self.datapath[index][0]]
#cls = np.array([cls]).astype(np.int32)
#point_set = self.all_data[fn[1]]
if self.uniform:
point_set = farthest_point_sample(point_set, self.npoints)
else:
point_set = point_set[0:self.npoints,:]
mask = mask[0:self.npoints]
point_set[:, 0:3] = pc_normalize(point_set[:, 0:3])
if not self.normal_channel:
point_set = point_set[:, 0:3]
if len(self.cache) < self.cache_size:
self.cache[index] = (point_set, cls, mask)
return point_set, cls, mask
def __getitem__(self, index):
return self._get_item(index)
if __name__ == '__main__':
import torch
data = ModelNetDataLoader('/data/modelnet40_normal_resampled/',split='train', uniform=False, normal_channel=True,)
DataLoader = torch.utils.data.DataLoader(data, batch_size=12, shuffle=True)
for point,label in DataLoader:
print(point.shape)
print(label.shape)
|
462538
|
def getResNet50Init():
string = '\
layer {\n\
bottom: "image"\n\
top: "conv1"\n\
name: "conv1"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 64\n\
kernel_size: 7\n\
pad: 3\n\
stride: 2\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "conv1"\n\
top: "conv1"\n\
name: "bn_conv1"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "conv1"\n\
top: "conv1"\n\
name: "scale_conv1"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "conv1"\n\
top: "conv1"\n\
name: "conv1_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "conv1"\n\
top: "pool1"\n\
name: "pool1"\n\
type: "Pooling"\n\
pooling_param {\n\
kernel_size: 3\n\
stride: 2\n\
pool: MAX\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "pool1"\n\
top: "res2a_branch1"\n\
name: "res2a_branch1"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 256\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2a_branch1"\n\
top: "res2a_branch1"\n\
name: "bn2a_branch1"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2a_branch1"\n\
top: "res2a_branch1"\n\
name: "scale2a_branch1"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "pool1"\n\
top: "res2a_branch2a"\n\
name: "res2a_branch2a"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 64\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2a_branch2a"\n\
top: "res2a_branch2a"\n\
name: "bn2a_branch2a"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2a_branch2a"\n\
top: "res2a_branch2a"\n\
name: "scale2a_branch2a"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2a_branch2a"\n\
top: "res2a_branch2a"\n\
name: "res2a_branch2a_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "res2a_branch2a"\n\
top: "res2a_branch2b"\n\
name: "res2a_branch2b"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 64\n\
kernel_size: 3\n\
pad: 1\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2a_branch2b"\n\
top: "res2a_branch2b"\n\
name: "bn2a_branch2b"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2a_branch2b"\n\
top: "res2a_branch2b"\n\
name: "scale2a_branch2b"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2a_branch2b"\n\
top: "res2a_branch2b"\n\
name: "res2a_branch2b_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "res2a_branch2b"\n\
top: "res2a_branch2c"\n\
name: "res2a_branch2c"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 256\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2a_branch2c"\n\
top: "res2a_branch2c"\n\
name: "bn2a_branch2c"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2a_branch2c"\n\
top: "res2a_branch2c"\n\
name: "scale2a_branch2c"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2a_branch1"\n\
bottom: "res2a_branch2c"\n\
top: "res2a"\n\
name: "res2a"\n\
type: "Eltwise"\n\
}\n\
\n\
layer {\n\
bottom: "res2a"\n\
top: "res2a"\n\
name: "res2a_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "res2a"\n\
top: "res2b_branch2a"\n\
name: "res2b_branch2a"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 64\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2b_branch2a"\n\
top: "res2b_branch2a"\n\
name: "bn2b_branch2a"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2b_branch2a"\n\
top: "res2b_branch2a"\n\
name: "scale2b_branch2a"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2b_branch2a"\n\
top: "res2b_branch2a"\n\
name: "res2b_branch2a_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "res2b_branch2a"\n\
top: "res2b_branch2b"\n\
name: "res2b_branch2b"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 64\n\
kernel_size: 3\n\
pad: 1\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2b_branch2b"\n\
top: "res2b_branch2b"\n\
name: "bn2b_branch2b"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2b_branch2b"\n\
top: "res2b_branch2b"\n\
name: "scale2b_branch2b"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2b_branch2b"\n\
top: "res2b_branch2b"\n\
name: "res2b_branch2b_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "res2b_branch2b"\n\
top: "res2b_branch2c"\n\
name: "res2b_branch2c"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 256\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2b_branch2c"\n\
top: "res2b_branch2c"\n\
name: "bn2b_branch2c"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2b_branch2c"\n\
top: "res2b_branch2c"\n\
name: "scale2b_branch2c"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2a"\n\
bottom: "res2b_branch2c"\n\
top: "res2b"\n\
name: "res2b"\n\
type: "Eltwise"\n\
}\n\
\n\
layer {\n\
bottom: "res2b"\n\
top: "res2b"\n\
name: "res2b_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "res2b"\n\
top: "res2c_branch2a"\n\
name: "res2c_branch2a"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 64\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2c_branch2a"\n\
top: "res2c_branch2a"\n\
name: "bn2c_branch2a"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2c_branch2a"\n\
top: "res2c_branch2a"\n\
name: "scale2c_branch2a"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2c_branch2a"\n\
top: "res2c_branch2a"\n\
name: "res2c_branch2a_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "res2c_branch2a"\n\
top: "res2c_branch2b"\n\
name: "res2c_branch2b"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 64\n\
kernel_size: 3\n\
pad: 1\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2c_branch2b"\n\
top: "res2c_branch2b"\n\
name: "bn2c_branch2b"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2c_branch2b"\n\
top: "res2c_branch2b"\n\
name: "scale2c_branch2b"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2c_branch2b"\n\
top: "res2c_branch2b"\n\
name: "res2c_branch2b_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "res2c_branch2b"\n\
top: "res2c_branch2c"\n\
name: "res2c_branch2c"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 256\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2c_branch2c"\n\
top: "res2c_branch2c"\n\
name: "bn2c_branch2c"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2c_branch2c"\n\
top: "res2c_branch2c"\n\
name: "scale2c_branch2c"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2b"\n\
bottom: "res2c_branch2c"\n\
top: "res2c"\n\
name: "res2c"\n\
type: "Eltwise"\n\
}\n\
\n\
layer {\n\
bottom: "res2c"\n\
top: "res2c"\n\
name: "res2c_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "res2c"\n\
top: "res3a_branch1"\n\
name: "res3a_branch1"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 512\n\
kernel_size: 1\n\
pad: 0\n\
stride: 2\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3a_branch1"\n\
top: "res3a_branch1"\n\
name: "bn3a_branch1"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3a_branch1"\n\
top: "res3a_branch1"\n\
name: "scale3a_branch1"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res2c"\n\
top: "res3a_branch2a"\n\
name: "res3a_branch2a"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 1\n\
pad: 0\n\
stride: 2\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3a_branch2a"\n\
top: "res3a_branch2a"\n\
name: "bn3a_branch2a"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3a_branch2a"\n\
top: "res3a_branch2a"\n\
name: "scale3a_branch2a"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3a_branch2a"\n\
top: "res3a_branch2a"\n\
name: "res3a_branch2a_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "res3a_branch2a"\n\
top: "res3a_branch2b"\n\
name: "res3a_branch2b"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 3\n\
pad: 1\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3a_branch2b"\n\
top: "res3a_branch2b"\n\
name: "bn3a_branch2b"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3a_branch2b"\n\
top: "res3a_branch2b"\n\
name: "scale3a_branch2b"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3a_branch2b"\n\
top: "res3a_branch2b"\n\
name: "res3a_branch2b_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "res3a_branch2b"\n\
top: "res3a_branch2c"\n\
name: "res3a_branch2c"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 512\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3a_branch2c"\n\
top: "res3a_branch2c"\n\
name: "bn3a_branch2c"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3a_branch2c"\n\
top: "res3a_branch2c"\n\
name: "scale3a_branch2c"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3a_branch1"\n\
bottom: "res3a_branch2c"\n\
top: "res3a"\n\
name: "res3a"\n\
type: "Eltwise"\n\
}\n\
\n\
layer {\n\
bottom: "res3a"\n\
top: "res3a"\n\
name: "res3a_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "res3a"\n\
top: "res3b_branch2a"\n\
name: "res3b_branch2a"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3b_branch2a"\n\
top: "res3b_branch2a"\n\
name: "bn3b_branch2a"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3b_branch2a"\n\
top: "res3b_branch2a"\n\
name: "scale3b_branch2a"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3b_branch2a"\n\
top: "res3b_branch2a"\n\
name: "res3b_branch2a_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "res3b_branch2a"\n\
top: "res3b_branch2b"\n\
name: "res3b_branch2b"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 3\n\
pad: 1\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3b_branch2b"\n\
top: "res3b_branch2b"\n\
name: "bn3b_branch2b"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3b_branch2b"\n\
top: "res3b_branch2b"\n\
name: "scale3b_branch2b"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3b_branch2b"\n\
top: "res3b_branch2b"\n\
name: "res3b_branch2b_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "res3b_branch2b"\n\
top: "res3b_branch2c"\n\
name: "res3b_branch2c"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 512\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3b_branch2c"\n\
top: "res3b_branch2c"\n\
name: "bn3b_branch2c"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3b_branch2c"\n\
top: "res3b_branch2c"\n\
name: "scale3b_branch2c"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3a"\n\
bottom: "res3b_branch2c"\n\
top: "res3b"\n\
name: "res3b"\n\
type: "Eltwise"\n\
}\n\
\n\
layer {\n\
bottom: "res3b"\n\
top: "res3b"\n\
name: "res3b_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "res3b"\n\
top: "res3c_branch2a"\n\
name: "res3c_branch2a"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3c_branch2a"\n\
top: "res3c_branch2a"\n\
name: "bn3c_branch2a"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3c_branch2a"\n\
top: "res3c_branch2a"\n\
name: "scale3c_branch2a"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3c_branch2a"\n\
top: "res3c_branch2a"\n\
name: "res3c_branch2a_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "res3c_branch2a"\n\
top: "res3c_branch2b"\n\
name: "res3c_branch2b"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 3\n\
pad: 1\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3c_branch2b"\n\
top: "res3c_branch2b"\n\
name: "bn3c_branch2b"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3c_branch2b"\n\
top: "res3c_branch2b"\n\
name: "scale3c_branch2b"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3c_branch2b"\n\
top: "res3c_branch2b"\n\
name: "res3c_branch2b_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "res3c_branch2b"\n\
top: "res3c_branch2c"\n\
name: "res3c_branch2c"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 512\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3c_branch2c"\n\
top: "res3c_branch2c"\n\
name: "bn3c_branch2c"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3c_branch2c"\n\
top: "res3c_branch2c"\n\
name: "scale3c_branch2c"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3b"\n\
bottom: "res3c_branch2c"\n\
top: "res3c"\n\
name: "res3c"\n\
type: "Eltwise"\n\
}\n\
\n\
layer {\n\
bottom: "res3c"\n\
top: "res3c"\n\
name: "res3c_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "res3c"\n\
top: "res3d_branch2a"\n\
name: "res3d_branch2a"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3d_branch2a"\n\
top: "res3d_branch2a"\n\
name: "bn3d_branch2a"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3d_branch2a"\n\
top: "res3d_branch2a"\n\
name: "scale3d_branch2a"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3d_branch2a"\n\
top: "res3d_branch2a"\n\
name: "res3d_branch2a_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "res3d_branch2a"\n\
top: "res3d_branch2b"\n\
name: "res3d_branch2b"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 3\n\
pad: 1\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3d_branch2b"\n\
top: "res3d_branch2b"\n\
name: "bn3d_branch2b"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3d_branch2b"\n\
top: "res3d_branch2b"\n\
name: "scale3d_branch2b"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3d_branch2b"\n\
top: "res3d_branch2b"\n\
name: "res3d_branch2b_relu"\n\
type: "ReLU"\n\
}\n\
\n\
layer {\n\
bottom: "res3d_branch2b"\n\
top: "res3d_branch2c"\n\
name: "res3d_branch2c"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 512\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3d_branch2c"\n\
top: "res3d_branch2c"\n\
name: "bn3d_branch2c"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3d_branch2c"\n\
top: "res3d_branch2c"\n\
name: "scale3d_branch2c"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
\n\
layer {\n\
bottom: "res3c"\n\
bottom: "res3d_branch2c"\n\
top: "res3d"\n\
name: "res3d"\n\
type: "Eltwise"\n\
}\n\
\n\
layer {\n\
bottom: "res3d"\n\
top: "res3d"\n\
name: "res3d_relu"\n\
type: "ReLU"\n\
}\n'
return string
def getResNet152Init():
string = '\
layer {\n\
bottom: "image"\n\
top: "conv1"\n\
name: "conv1"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 64\n\
kernel_size: 7\n\
pad: 3\n\
stride: 2\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "conv1"\n\
top: "conv1"\n\
name: "bn_conv1"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "conv1"\n\
top: "conv1"\n\
name: "scale_conv1"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "conv1"\n\
bottom: "conv1"\n\
name: "conv1_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "conv1"\n\
top: "pool1"\n\
name: "pool1"\n\
type: "Pooling"\n\
pooling_param {\n\
kernel_size: 3\n\
stride: 2\n\
pool: MAX\n\
}\n\
}\n\
layer {\n\
bottom: "pool1"\n\
top: "res2a_branch1"\n\
name: "res2a_branch1"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 256\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res2a_branch1"\n\
top: "res2a_branch1"\n\
name: "bn2a_branch1"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res2a_branch1"\n\
top: "res2a_branch1"\n\
name: "scale2a_branch1"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
bottom: "pool1"\n\
top: "res2a_branch2a"\n\
name: "res2a_branch2a"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 64\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res2a_branch2a"\n\
top: "res2a_branch2a"\n\
name: "bn2a_branch2a"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res2a_branch2a"\n\
top: "res2a_branch2a"\n\
name: "scale2a_branch2a"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res2a_branch2a"\n\
bottom: "res2a_branch2a"\n\
name: "res2a_branch2a_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res2a_branch2a"\n\
top: "res2a_branch2b"\n\
name: "res2a_branch2b"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 64\n\
kernel_size: 3\n\
pad: 1\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res2a_branch2b"\n\
top: "res2a_branch2b"\n\
name: "bn2a_branch2b"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res2a_branch2b"\n\
top: "res2a_branch2b"\n\
name: "scale2a_branch2b"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res2a_branch2b"\n\
bottom: "res2a_branch2b"\n\
name: "res2a_branch2b_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res2a_branch2b"\n\
top: "res2a_branch2c"\n\
name: "res2a_branch2c"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 256\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res2a_branch2c"\n\
top: "res2a_branch2c"\n\
name: "bn2a_branch2c"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res2a_branch2c"\n\
top: "res2a_branch2c"\n\
name: "scale2a_branch2c"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
bottom: "res2a_branch1"\n\
bottom: "res2a_branch2c"\n\
top: "res2a"\n\
name: "res2a"\n\
type: "Eltwise"\n\
}\n\
layer {\n\
bottom: "res2a"\n\
top: "res2a"\n\
name: "res2a_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res2a"\n\
top: "res2b_branch2a"\n\
name: "res2b_branch2a"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 64\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res2b_branch2a"\n\
top: "res2b_branch2a"\n\
name: "bn2b_branch2a"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res2b_branch2a"\n\
top: "res2b_branch2a"\n\
name: "scale2b_branch2a"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res2b_branch2a"\n\
bottom: "res2b_branch2a"\n\
name: "res2b_branch2a_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res2b_branch2a"\n\
top: "res2b_branch2b"\n\
name: "res2b_branch2b"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 64\n\
kernel_size: 3\n\
pad: 1\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res2b_branch2b"\n\
top: "res2b_branch2b"\n\
name: "bn2b_branch2b"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res2b_branch2b"\n\
top: "res2b_branch2b"\n\
name: "scale2b_branch2b"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res2b_branch2b"\n\
bottom: "res2b_branch2b"\n\
name: "res2b_branch2b_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res2b_branch2b"\n\
top: "res2b_branch2c"\n\
name: "res2b_branch2c"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 256\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res2b_branch2c"\n\
top: "res2b_branch2c"\n\
name: "bn2b_branch2c"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res2b_branch2c"\n\
top: "res2b_branch2c"\n\
name: "scale2b_branch2c"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
bottom: "res2a"\n\
bottom: "res2b_branch2c"\n\
top: "res2b"\n\
name: "res2b"\n\
type: "Eltwise"\n\
}\n\
layer {\n\
bottom: "res2b"\n\
top: "res2b"\n\
name: "res2b_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res2b"\n\
top: "res2c_branch2a"\n\
name: "res2c_branch2a"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 64\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res2c_branch2a"\n\
top: "res2c_branch2a"\n\
name: "bn2c_branch2a"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res2c_branch2a"\n\
top: "res2c_branch2a"\n\
name: "scale2c_branch2a"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res2c_branch2a"\n\
bottom: "res2c_branch2a"\n\
name: "res2c_branch2a_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res2c_branch2a"\n\
top: "res2c_branch2b"\n\
name: "res2c_branch2b"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 64\n\
kernel_size: 3\n\
pad: 1\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res2c_branch2b"\n\
top: "res2c_branch2b"\n\
name: "bn2c_branch2b"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res2c_branch2b"\n\
top: "res2c_branch2b"\n\
name: "scale2c_branch2b"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res2c_branch2b"\n\
bottom: "res2c_branch2b"\n\
name: "res2c_branch2b_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res2c_branch2b"\n\
top: "res2c_branch2c"\n\
name: "res2c_branch2c"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 256\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res2c_branch2c"\n\
top: "res2c_branch2c"\n\
name: "bn2c_branch2c"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res2c_branch2c"\n\
top: "res2c_branch2c"\n\
name: "scale2c_branch2c"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
bottom: "res2b"\n\
bottom: "res2c_branch2c"\n\
top: "res2c"\n\
name: "res2c"\n\
type: "Eltwise"\n\
}\n\
layer {\n\
bottom: "res2c"\n\
top: "res2c"\n\
name: "res2c_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res2c"\n\
top: "res3a_branch1"\n\
name: "res3a_branch1"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 512\n\
kernel_size: 1\n\
pad: 0\n\
stride: 2\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3a_branch1"\n\
top: "res3a_branch1"\n\
name: "bn3a_branch1"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3a_branch1"\n\
top: "res3a_branch1"\n\
name: "scale3a_branch1"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
bottom: "res2c"\n\
top: "res3a_branch2a"\n\
name: "res3a_branch2a"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 1\n\
pad: 0\n\
stride: 2\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3a_branch2a"\n\
top: "res3a_branch2a"\n\
name: "bn3a_branch2a"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3a_branch2a"\n\
top: "res3a_branch2a"\n\
name: "scale3a_branch2a"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res3a_branch2a"\n\
bottom: "res3a_branch2a"\n\
name: "res3a_branch2a_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3a_branch2a"\n\
top: "res3a_branch2b"\n\
name: "res3a_branch2b"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 3\n\
pad: 1\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3a_branch2b"\n\
top: "res3a_branch2b"\n\
name: "bn3a_branch2b"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3a_branch2b"\n\
top: "res3a_branch2b"\n\
name: "scale3a_branch2b"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res3a_branch2b"\n\
bottom: "res3a_branch2b"\n\
name: "res3a_branch2b_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3a_branch2b"\n\
top: "res3a_branch2c"\n\
name: "res3a_branch2c"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 512\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3a_branch2c"\n\
top: "res3a_branch2c"\n\
name: "bn3a_branch2c"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3a_branch2c"\n\
top: "res3a_branch2c"\n\
name: "scale3a_branch2c"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3a_branch1"\n\
bottom: "res3a_branch2c"\n\
top: "res3a"\n\
name: "res3a"\n\
type: "Eltwise"\n\
}\n\
layer {\n\
bottom: "res3a"\n\
top: "res3a"\n\
name: "res3a_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3a"\n\
top: "res3b1_branch2a"\n\
name: "res3b1_branch2a"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b1_branch2a"\n\
top: "res3b1_branch2a"\n\
name: "bn3b1_branch2a"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b1_branch2a"\n\
top: "res3b1_branch2a"\n\
name: "scale3b1_branch2a"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res3b1_branch2a"\n\
bottom: "res3b1_branch2a"\n\
name: "res3b1_branch2a_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3b1_branch2a"\n\
top: "res3b1_branch2b"\n\
name: "res3b1_branch2b"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 3\n\
pad: 1\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b1_branch2b"\n\
top: "res3b1_branch2b"\n\
name: "bn3b1_branch2b"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b1_branch2b"\n\
top: "res3b1_branch2b"\n\
name: "scale3b1_branch2b"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res3b1_branch2b"\n\
bottom: "res3b1_branch2b"\n\
name: "res3b1_branch2b_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3b1_branch2b"\n\
top: "res3b1_branch2c"\n\
name: "res3b1_branch2c"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 512\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b1_branch2c"\n\
top: "res3b1_branch2c"\n\
name: "bn3b1_branch2c"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b1_branch2c"\n\
top: "res3b1_branch2c"\n\
name: "scale3b1_branch2c"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3a"\n\
bottom: "res3b1_branch2c"\n\
top: "res3b1"\n\
name: "res3b1"\n\
type: "Eltwise"\n\
}\n\
layer {\n\
bottom: "res3b1"\n\
top: "res3b1"\n\
name: "res3b1_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3b1"\n\
top: "res3b2_branch2a"\n\
name: "res3b2_branch2a"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b2_branch2a"\n\
top: "res3b2_branch2a"\n\
name: "bn3b2_branch2a"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b2_branch2a"\n\
top: "res3b2_branch2a"\n\
name: "scale3b2_branch2a"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res3b2_branch2a"\n\
bottom: "res3b2_branch2a"\n\
name: "res3b2_branch2a_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3b2_branch2a"\n\
top: "res3b2_branch2b"\n\
name: "res3b2_branch2b"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 3\n\
pad: 1\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b2_branch2b"\n\
top: "res3b2_branch2b"\n\
name: "bn3b2_branch2b"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b2_branch2b"\n\
top: "res3b2_branch2b"\n\
name: "scale3b2_branch2b"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res3b2_branch2b"\n\
bottom: "res3b2_branch2b"\n\
name: "res3b2_branch2b_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3b2_branch2b"\n\
top: "res3b2_branch2c"\n\
name: "res3b2_branch2c"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 512\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b2_branch2c"\n\
top: "res3b2_branch2c"\n\
name: "bn3b2_branch2c"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b2_branch2c"\n\
top: "res3b2_branch2c"\n\
name: "scale3b2_branch2c"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b1"\n\
bottom: "res3b2_branch2c"\n\
top: "res3b2"\n\
name: "res3b2"\n\
type: "Eltwise"\n\
}\n\
layer {\n\
bottom: "res3b2"\n\
top: "res3b2"\n\
name: "res3b2_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3b2"\n\
top: "res3b3_branch2a"\n\
name: "res3b3_branch2a"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b3_branch2a"\n\
top: "res3b3_branch2a"\n\
name: "bn3b3_branch2a"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b3_branch2a"\n\
top: "res3b3_branch2a"\n\
name: "scale3b3_branch2a"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res3b3_branch2a"\n\
bottom: "res3b3_branch2a"\n\
name: "res3b3_branch2a_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3b3_branch2a"\n\
top: "res3b3_branch2b"\n\
name: "res3b3_branch2b"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 3\n\
pad: 1\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b3_branch2b"\n\
top: "res3b3_branch2b"\n\
name: "bn3b3_branch2b"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b3_branch2b"\n\
top: "res3b3_branch2b"\n\
name: "scale3b3_branch2b"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res3b3_branch2b"\n\
bottom: "res3b3_branch2b"\n\
name: "res3b3_branch2b_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3b3_branch2b"\n\
top: "res3b3_branch2c"\n\
name: "res3b3_branch2c"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 512\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b3_branch2c"\n\
top: "res3b3_branch2c"\n\
name: "bn3b3_branch2c"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b3_branch2c"\n\
top: "res3b3_branch2c"\n\
name: "scale3b3_branch2c"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b2"\n\
bottom: "res3b3_branch2c"\n\
top: "res3b3"\n\
name: "res3b3"\n\
type: "Eltwise"\n\
}\n\
layer {\n\
bottom: "res3b3"\n\
top: "res3b3"\n\
name: "res3b3_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3b3"\n\
top: "res3b4_branch2a"\n\
name: "res3b4_branch2a"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b4_branch2a"\n\
top: "res3b4_branch2a"\n\
name: "bn3b4_branch2a"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b4_branch2a"\n\
top: "res3b4_branch2a"\n\
name: "scale3b4_branch2a"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res3b4_branch2a"\n\
bottom: "res3b4_branch2a"\n\
name: "res3b4_branch2a_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3b4_branch2a"\n\
top: "res3b4_branch2b"\n\
name: "res3b4_branch2b"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 3\n\
pad: 1\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b4_branch2b"\n\
top: "res3b4_branch2b"\n\
name: "bn3b4_branch2b"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b4_branch2b"\n\
top: "res3b4_branch2b"\n\
name: "scale3b4_branch2b"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res3b4_branch2b"\n\
bottom: "res3b4_branch2b"\n\
name: "res3b4_branch2b_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3b4_branch2b"\n\
top: "res3b4_branch2c"\n\
name: "res3b4_branch2c"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 512\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b4_branch2c"\n\
top: "res3b4_branch2c"\n\
name: "bn3b4_branch2c"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b4_branch2c"\n\
top: "res3b4_branch2c"\n\
name: "scale3b4_branch2c"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b3"\n\
bottom: "res3b4_branch2c"\n\
top: "res3b4"\n\
name: "res3b4"\n\
type: "Eltwise"\n\
}\n\
layer {\n\
bottom: "res3b4"\n\
top: "res3b4"\n\
name: "res3b4_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3b4"\n\
top: "res3b5_branch2a"\n\
name: "res3b5_branch2a"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b5_branch2a"\n\
top: "res3b5_branch2a"\n\
name: "bn3b5_branch2a"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b5_branch2a"\n\
top: "res3b5_branch2a"\n\
name: "scale3b5_branch2a"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res3b5_branch2a"\n\
bottom: "res3b5_branch2a"\n\
name: "res3b5_branch2a_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3b5_branch2a"\n\
top: "res3b5_branch2b"\n\
name: "res3b5_branch2b"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 3\n\
pad: 1\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b5_branch2b"\n\
top: "res3b5_branch2b"\n\
name: "bn3b5_branch2b"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b5_branch2b"\n\
top: "res3b5_branch2b"\n\
name: "scale3b5_branch2b"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res3b5_branch2b"\n\
bottom: "res3b5_branch2b"\n\
name: "res3b5_branch2b_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3b5_branch2b"\n\
top: "res3b5_branch2c"\n\
name: "res3b5_branch2c"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 512\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b5_branch2c"\n\
top: "res3b5_branch2c"\n\
name: "bn3b5_branch2c"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b5_branch2c"\n\
top: "res3b5_branch2c"\n\
name: "scale3b5_branch2c"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b4"\n\
bottom: "res3b5_branch2c"\n\
top: "res3b5"\n\
name: "res3b5"\n\
type: "Eltwise"\n\
}\n\
layer {\n\
bottom: "res3b5"\n\
top: "res3b5"\n\
name: "res3b5_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3b5"\n\
top: "res3b6_branch2a"\n\
name: "res3b6_branch2a"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b6_branch2a"\n\
top: "res3b6_branch2a"\n\
name: "bn3b6_branch2a"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b6_branch2a"\n\
top: "res3b6_branch2a"\n\
name: "scale3b6_branch2a"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res3b6_branch2a"\n\
bottom: "res3b6_branch2a"\n\
name: "res3b6_branch2a_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3b6_branch2a"\n\
top: "res3b6_branch2b"\n\
name: "res3b6_branch2b"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 3\n\
pad: 1\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b6_branch2b"\n\
top: "res3b6_branch2b"\n\
name: "bn3b6_branch2b"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b6_branch2b"\n\
top: "res3b6_branch2b"\n\
name: "scale3b6_branch2b"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res3b6_branch2b"\n\
bottom: "res3b6_branch2b"\n\
name: "res3b6_branch2b_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3b6_branch2b"\n\
top: "res3b6_branch2c"\n\
name: "res3b6_branch2c"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 512\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b6_branch2c"\n\
top: "res3b6_branch2c"\n\
name: "bn3b6_branch2c"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b6_branch2c"\n\
top: "res3b6_branch2c"\n\
name: "scale3b6_branch2c"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b5"\n\
bottom: "res3b6_branch2c"\n\
top: "res3b6"\n\
name: "res3b6"\n\
type: "Eltwise"\n\
}\n\
layer {\n\
bottom: "res3b6"\n\
top: "res3b6"\n\
name: "res3b6_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3b6"\n\
top: "res3b7_branch2a"\n\
name: "res3b7_branch2a"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b7_branch2a"\n\
top: "res3b7_branch2a"\n\
name: "bn3b7_branch2a"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b7_branch2a"\n\
top: "res3b7_branch2a"\n\
name: "scale3b7_branch2a"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res3b7_branch2a"\n\
bottom: "res3b7_branch2a"\n\
name: "res3b7_branch2a_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3b7_branch2a"\n\
top: "res3b7_branch2b"\n\
name: "res3b7_branch2b"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 128\n\
kernel_size: 3\n\
pad: 1\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b7_branch2b"\n\
top: "res3b7_branch2b"\n\
name: "bn3b7_branch2b"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b7_branch2b"\n\
top: "res3b7_branch2b"\n\
name: "scale3b7_branch2b"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
top: "res3b7_branch2b"\n\
bottom: "res3b7_branch2b"\n\
name: "res3b7_branch2b_relu"\n\
type: "ReLU"\n\
}\n\
layer {\n\
bottom: "res3b7_branch2b"\n\
top: "res3b7_branch2c"\n\
name: "res3b7_branch2c"\n\
type: "Convolution"\n\
convolution_param {\n\
num_output: 512\n\
kernel_size: 1\n\
pad: 0\n\
stride: 1\n\
bias_term: false\n\
}\n\
}\n\
layer {\n\
bottom: "res3b7_branch2c"\n\
top: "res3b7_branch2c"\n\
name: "bn3b7_branch2c"\n\
type: "BatchNorm"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b7_branch2c"\n\
top: "res3b7_branch2c"\n\
name: "scale3b7_branch2c"\n\
type: "Scale"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
bottom: "res3b6"\n\
bottom: "res3b7_branch2c"\n\
top: "res3b7"\n\
name: "res3b7"\n\
type: "Eltwise"\n\
}\n\
layer {\n\
bottom: "res3b7"\n\
top: "res3b7"\n\
name: "res3b7_relu"\n\
type: "ReLU"\n\
}\n'
return string
def getResNet101v2Init():
string = '\
layer {\n\
name: "conv1"\n\
type: "Convolution"\n\
bottom: "image"\n\
top: "conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 64\n\
pad: 3\n\
kernel_size: 7\n\
stride: 2\n\
}\n\
}\n\
layer {\n\
name: "conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "conv1"\n\
top: "conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "conv1_scale"\n\
type: "Scale"\n\
bottom: "conv1"\n\
top: "conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "conv1_relu"\n\
type: "ReLU"\n\
bottom: "conv1"\n\
top: "conv1"\n\
}\n\
layer {\n\
name: "pool1"\n\
type: "Pooling"\n\
bottom: "conv1"\n\
top: "pool1"\n\
pooling_param {\n\
pool: MAX\n\
kernel_size: 3\n\
stride: 2\n\
}\n\
}\n\
layer {\n\
name: "res1_conv1"\n\
type: "Convolution"\n\
bottom: "pool1"\n\
top: "res1_conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 64\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res1_conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "res1_conv1"\n\
top: "res1_conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res1_conv1_scale"\n\
type: "Scale"\n\
bottom: "res1_conv1"\n\
top: "res1_conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res1_conv1_relu"\n\
type: "ReLU"\n\
bottom: "res1_conv1"\n\
top: "res1_conv1"\n\
}\n\
layer {\n\
name: "res1_conv2"\n\
type: "Convolution"\n\
bottom: "res1_conv1"\n\
top: "res1_conv2"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 64\n\
pad: 1\n\
kernel_size: 3\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res1_conv2_bn"\n\
type: "BatchNorm"\n\
bottom: "res1_conv2"\n\
top: "res1_conv2"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res1_conv2_scale"\n\
type: "Scale"\n\
bottom: "res1_conv2"\n\
top: "res1_conv2"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res1_conv2_relu"\n\
type: "ReLU"\n\
bottom: "res1_conv2"\n\
top: "res1_conv2"\n\
}\n\
layer {\n\
name: "res1_conv3"\n\
type: "Convolution"\n\
bottom: "res1_conv2"\n\
top: "res1_conv3"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 256\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res1_match_conv"\n\
type: "Convolution"\n\
bottom: "pool1"\n\
top: "res1_match_conv"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 256\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res1_eletwise"\n\
type: "Eltwise"\n\
bottom: "res1_match_conv"\n\
bottom: "res1_conv3"\n\
top: "res1_eletwise"\n\
eltwise_param {\n\
operation: SUM\n\
}\n\
}\n\
layer {\n\
name: "res2_bn"\n\
type: "BatchNorm"\n\
bottom: "res1_eletwise"\n\
top: "res2_bn"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res2_scale"\n\
type: "Scale"\n\
bottom: "res2_bn"\n\
top: "res2_bn"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res2_relu"\n\
type: "ReLU"\n\
bottom: "res2_bn"\n\
top: "res2_bn"\n\
}\n\
layer {\n\
name: "res2_conv1"\n\
type: "Convolution"\n\
bottom: "res2_bn"\n\
top: "res2_conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 64\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res2_conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "res2_conv1"\n\
top: "res2_conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res2_conv1_scale"\n\
type: "Scale"\n\
bottom: "res2_conv1"\n\
top: "res2_conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res2_conv1_relu"\n\
type: "ReLU"\n\
bottom: "res2_conv1"\n\
top: "res2_conv1"\n\
}\n\
layer {\n\
name: "res2_conv2"\n\
type: "Convolution"\n\
bottom: "res2_conv1"\n\
top: "res2_conv2"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 64\n\
pad: 1\n\
kernel_size: 3\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res2_conv2_bn"\n\
type: "BatchNorm"\n\
bottom: "res2_conv2"\n\
top: "res2_conv2"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res2_conv2_scale"\n\
type: "Scale"\n\
bottom: "res2_conv2"\n\
top: "res2_conv2"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res2_conv2_relu"\n\
type: "ReLU"\n\
bottom: "res2_conv2"\n\
top: "res2_conv2"\n\
}\n\
layer {\n\
name: "res2_conv3"\n\
type: "Convolution"\n\
bottom: "res2_conv2"\n\
top: "res2_conv3"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 256\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res2_eletwise"\n\
type: "Eltwise"\n\
bottom: "res1_eletwise"\n\
bottom: "res2_conv3"\n\
top: "res2_eletwise"\n\
eltwise_param {\n\
operation: SUM\n\
}\n\
}\n\
layer {\n\
name: "res3_bn"\n\
type: "BatchNorm"\n\
bottom: "res2_eletwise"\n\
top: "res3_bn"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res3_scale"\n\
type: "Scale"\n\
bottom: "res3_bn"\n\
top: "res3_bn"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res3_relu"\n\
type: "ReLU"\n\
bottom: "res3_bn"\n\
top: "res3_bn"\n\
}\n\
layer {\n\
name: "res3_conv1"\n\
type: "Convolution"\n\
bottom: "res3_bn"\n\
top: "res3_conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 64\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res3_conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "res3_conv1"\n\
top: "res3_conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res3_conv1_scale"\n\
type: "Scale"\n\
bottom: "res3_conv1"\n\
top: "res3_conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res3_conv1_relu"\n\
type: "ReLU"\n\
bottom: "res3_conv1"\n\
top: "res3_conv1"\n\
}\n\
layer {\n\
name: "res3_conv2"\n\
type: "Convolution"\n\
bottom: "res3_conv1"\n\
top: "res3_conv2"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 64\n\
pad: 1\n\
kernel_size: 3\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res3_conv2_bn"\n\
type: "BatchNorm"\n\
bottom: "res3_conv2"\n\
top: "res3_conv2"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res3_conv2_scale"\n\
type: "Scale"\n\
bottom: "res3_conv2"\n\
top: "res3_conv2"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res3_conv2_relu"\n\
type: "ReLU"\n\
bottom: "res3_conv2"\n\
top: "res3_conv2"\n\
}\n\
layer {\n\
name: "res3_conv3"\n\
type: "Convolution"\n\
bottom: "res3_conv2"\n\
top: "res3_conv3"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 256\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res3_eletwise"\n\
type: "Eltwise"\n\
bottom: "res2_eletwise"\n\
bottom: "res3_conv3"\n\
top: "res3_eletwise"\n\
eltwise_param {\n\
operation: SUM\n\
}\n\
}\n\
layer {\n\
name: "res4_bn"\n\
type: "BatchNorm"\n\
bottom: "res3_eletwise"\n\
top: "res4_bn"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res4_scale"\n\
type: "Scale"\n\
bottom: "res4_bn"\n\
top: "res4_bn"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res4_relu"\n\
type: "ReLU"\n\
bottom: "res4_bn"\n\
top: "res4_bn"\n\
}\n\
layer {\n\
name: "res4_conv1"\n\
type: "Convolution"\n\
bottom: "res4_bn"\n\
top: "res4_conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res4_conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "res4_conv1"\n\
top: "res4_conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res4_conv1_scale"\n\
type: "Scale"\n\
bottom: "res4_conv1"\n\
top: "res4_conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res4_conv1_relu"\n\
type: "ReLU"\n\
bottom: "res4_conv1"\n\
top: "res4_conv1"\n\
}\n\
layer {\n\
name: "res4_conv2"\n\
type: "Convolution"\n\
bottom: "res4_conv1"\n\
top: "res4_conv2"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 1\n\
kernel_size: 3\n\
stride: 2\n\
}\n\
}\n\
layer {\n\
name: "res4_conv2_bn"\n\
type: "BatchNorm"\n\
bottom: "res4_conv2"\n\
top: "res4_conv2"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res4_conv2_scale"\n\
type: "Scale"\n\
bottom: "res4_conv2"\n\
top: "res4_conv2"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res4_conv2_relu"\n\
type: "ReLU"\n\
bottom: "res4_conv2"\n\
top: "res4_conv2"\n\
}\n\
layer {\n\
name: "res4_conv3"\n\
type: "Convolution"\n\
bottom: "res4_conv2"\n\
top: "res4_conv3"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 512\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res4_match_conv"\n\
type: "Convolution"\n\
bottom: "res4_bn"\n\
top: "res4_match_conv"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 512\n\
pad: 0\n\
kernel_size: 1\n\
stride: 2\n\
}\n\
}\n\
layer {\n\
name: "res4_eletwise"\n\
type: "Eltwise"\n\
bottom: "res4_match_conv"\n\
bottom: "res4_conv3"\n\
top: "res4_eletwise"\n\
eltwise_param {\n\
operation: SUM\n\
}\n\
}\n\
layer {\n\
name: "res5_bn"\n\
type: "BatchNorm"\n\
bottom: "res4_eletwise"\n\
top: "res5_bn"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res5_scale"\n\
type: "Scale"\n\
bottom: "res5_bn"\n\
top: "res5_bn"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res5_relu"\n\
type: "ReLU"\n\
bottom: "res5_bn"\n\
top: "res5_bn"\n\
}\n\
layer {\n\
name: "res5_conv1"\n\
type: "Convolution"\n\
bottom: "res5_bn"\n\
top: "res5_conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res5_conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "res5_conv1"\n\
top: "res5_conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res5_conv1_scale"\n\
type: "Scale"\n\
bottom: "res5_conv1"\n\
top: "res5_conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res5_conv1_relu"\n\
type: "ReLU"\n\
bottom: "res5_conv1"\n\
top: "res5_conv1"\n\
}\n\
layer {\n\
name: "res5_conv2"\n\
type: "Convolution"\n\
bottom: "res5_conv1"\n\
top: "res5_conv2"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 1\n\
kernel_size: 3\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res5_conv2_bn"\n\
type: "BatchNorm"\n\
bottom: "res5_conv2"\n\
top: "res5_conv2"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res5_conv2_scale"\n\
type: "Scale"\n\
bottom: "res5_conv2"\n\
top: "res5_conv2"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res5_conv2_relu"\n\
type: "ReLU"\n\
bottom: "res5_conv2"\n\
top: "res5_conv2"\n\
}\n\
layer {\n\
name: "res5_conv3"\n\
type: "Convolution"\n\
bottom: "res5_conv2"\n\
top: "res5_conv3"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 512\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res5_eletwise"\n\
type: "Eltwise"\n\
bottom: "res4_eletwise"\n\
bottom: "res5_conv3"\n\
top: "res5_eletwise"\n\
eltwise_param {\n\
operation: SUM\n\
}\n\
}\n\
layer {\n\
name: "res6_bn"\n\
type: "BatchNorm"\n\
bottom: "res5_eletwise"\n\
top: "res6_bn"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res6_scale"\n\
type: "Scale"\n\
bottom: "res6_bn"\n\
top: "res6_bn"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res6_relu"\n\
type: "ReLU"\n\
bottom: "res6_bn"\n\
top: "res6_bn"\n\
}\n\
layer {\n\
name: "res6_conv1"\n\
type: "Convolution"\n\
bottom: "res6_bn"\n\
top: "res6_conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res6_conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "res6_conv1"\n\
top: "res6_conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res6_conv1_scale"\n\
type: "Scale"\n\
bottom: "res6_conv1"\n\
top: "res6_conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res6_conv1_relu"\n\
type: "ReLU"\n\
bottom: "res6_conv1"\n\
top: "res6_conv1"\n\
}\n\
layer {\n\
name: "res6_conv2"\n\
type: "Convolution"\n\
bottom: "res6_conv1"\n\
top: "res6_conv2"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 1\n\
kernel_size: 3\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res6_conv2_bn"\n\
type: "BatchNorm"\n\
bottom: "res6_conv2"\n\
top: "res6_conv2"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res6_conv2_scale"\n\
type: "Scale"\n\
bottom: "res6_conv2"\n\
top: "res6_conv2"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res6_conv2_relu"\n\
type: "ReLU"\n\
bottom: "res6_conv2"\n\
top: "res6_conv2"\n\
}\n\
layer {\n\
name: "res6_conv3"\n\
type: "Convolution"\n\
bottom: "res6_conv2"\n\
top: "res6_conv3"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 512\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res6_eletwise"\n\
type: "Eltwise"\n\
bottom: "res5_eletwise"\n\
bottom: "res6_conv3"\n\
top: "res6_eletwise"\n\
eltwise_param {\n\
operation: SUM\n\
}\n\
}\n\
layer {\n\
name: "res7_bn"\n\
type: "BatchNorm"\n\
bottom: "res6_eletwise"\n\
top: "res7_bn"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res7_scale"\n\
type: "Scale"\n\
bottom: "res7_bn"\n\
top: "res7_bn"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res7_relu"\n\
type: "ReLU"\n\
bottom: "res7_bn"\n\
top: "res7_bn"\n\
}\n\
layer {\n\
name: "res7_conv1"\n\
type: "Convolution"\n\
bottom: "res7_bn"\n\
top: "res7_conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res7_conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "res7_conv1"\n\
top: "res7_conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res7_conv1_scale"\n\
type: "Scale"\n\
bottom: "res7_conv1"\n\
top: "res7_conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res7_conv1_relu"\n\
type: "ReLU"\n\
bottom: "res7_conv1"\n\
top: "res7_conv1"\n\
}\n\
layer {\n\
name: "res7_conv2"\n\
type: "Convolution"\n\
bottom: "res7_conv1"\n\
top: "res7_conv2"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 1\n\
kernel_size: 3\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res7_conv2_bn"\n\
type: "BatchNorm"\n\
bottom: "res7_conv2"\n\
top: "res7_conv2"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res7_conv2_scale"\n\
type: "Scale"\n\
bottom: "res7_conv2"\n\
top: "res7_conv2"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res7_conv2_relu"\n\
type: "ReLU"\n\
bottom: "res7_conv2"\n\
top: "res7_conv2"\n\
}\n\
layer {\n\
name: "res7_conv3"\n\
type: "Convolution"\n\
bottom: "res7_conv2"\n\
top: "res7_conv3"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 512\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res7_eletwise"\n\
type: "Eltwise"\n\
bottom: "res6_eletwise"\n\
bottom: "res7_conv3"\n\
top: "res7_eletwise"\n\
eltwise_param {\n\
operation: SUM\n\
}\n\
}\n\
layer {\n\
name: "res8_bn"\n\
type: "BatchNorm"\n\
bottom: "res7_eletwise"\n\
top: "res8_bn"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res8_scale"\n\
type: "Scale"\n\
bottom: "res8_bn"\n\
top: "res8_bn"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res8_relu"\n\
type: "ReLU"\n\
bottom: "res8_bn"\n\
top: "res8_bn"\n\
}\n\
layer {\n\
name: "res8_conv1"\n\
type: "Convolution"\n\
bottom: "res8_bn"\n\
top: "res8_conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 256\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res8_conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "res8_conv1"\n\
top: "res8_conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res8_conv1_scale"\n\
type: "Scale"\n\
bottom: "res8_conv1"\n\
top: "res8_conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res8_conv1_relu"\n\
type: "ReLU"\n\
bottom: "res8_conv1"\n\
top: "res8_conv1"\n\
}\n'
return string
def getResNet152v2Init():
string = '\
layer {\n\
name: "conv1"\n\
type: "Convolution"\n\
bottom: "image"\n\
top: "conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 64\n\
pad: 3\n\
kernel_size: 7\n\
stride: 2\n\
}\n\
}\n\
layer {\n\
name: "conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "conv1"\n\
top: "conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "conv1_scale"\n\
type: "Scale"\n\
bottom: "conv1"\n\
top: "conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "conv1_relu"\n\
type: "ReLU"\n\
bottom: "conv1"\n\
top: "conv1"\n\
}\n\
layer {\n\
name: "pool1"\n\
type: "Pooling"\n\
bottom: "conv1"\n\
top: "pool1"\n\
pooling_param {\n\
pool: MAX\n\
kernel_size: 3\n\
stride: 2\n\
}\n\
}\n\
layer {\n\
name: "res1_conv1"\n\
type: "Convolution"\n\
bottom: "pool1"\n\
top: "res1_conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 64\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res1_conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "res1_conv1"\n\
top: "res1_conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res1_conv1_scale"\n\
type: "Scale"\n\
bottom: "res1_conv1"\n\
top: "res1_conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res1_conv1_relu"\n\
type: "ReLU"\n\
bottom: "res1_conv1"\n\
top: "res1_conv1"\n\
}\n\
layer {\n\
name: "res1_conv2"\n\
type: "Convolution"\n\
bottom: "res1_conv1"\n\
top: "res1_conv2"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 64\n\
pad: 1\n\
kernel_size: 3\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res1_conv2_bn"\n\
type: "BatchNorm"\n\
bottom: "res1_conv2"\n\
top: "res1_conv2"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res1_conv2_scale"\n\
type: "Scale"\n\
bottom: "res1_conv2"\n\
top: "res1_conv2"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res1_conv2_relu"\n\
type: "ReLU"\n\
bottom: "res1_conv2"\n\
top: "res1_conv2"\n\
}\n\
layer {\n\
name: "res1_conv3"\n\
type: "Convolution"\n\
bottom: "res1_conv2"\n\
top: "res1_conv3"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 256\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res1_match_conv"\n\
type: "Convolution"\n\
bottom: "pool1"\n\
top: "res1_match_conv"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 256\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
bias_filler {\n\
type: "constant"\n\
value: 0.2\n\
}\n\
}\n\
}\n\
layer {\n\
name: "res1_eletwise"\n\
type: "Eltwise"\n\
bottom: "res1_match_conv"\n\
bottom: "res1_conv3"\n\
top: "res1_eletwise"\n\
eltwise_param {\n\
operation: SUM\n\
}\n\
}\n\
layer {\n\
name: "res2_bn"\n\
type: "BatchNorm"\n\
bottom: "res1_eletwise"\n\
top: "res2_bn"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res2_scale"\n\
type: "Scale"\n\
bottom: "res2_bn"\n\
top: "res2_bn"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res2_relu"\n\
type: "ReLU"\n\
bottom: "res2_bn"\n\
top: "res2_bn"\n\
}\n\
layer {\n\
name: "res2_conv1"\n\
type: "Convolution"\n\
bottom: "res2_bn"\n\
top: "res2_conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 64\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res2_conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "res2_conv1"\n\
top: "res2_conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res2_conv1_scale"\n\
type: "Scale"\n\
bottom: "res2_conv1"\n\
top: "res2_conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res2_conv1_relu"\n\
type: "ReLU"\n\
bottom: "res2_conv1"\n\
top: "res2_conv1"\n\
}\n\
layer {\n\
name: "res2_conv2"\n\
type: "Convolution"\n\
bottom: "res2_conv1"\n\
top: "res2_conv2"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 64\n\
pad: 1\n\
kernel_size: 3\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res2_conv2_bn"\n\
type: "BatchNorm"\n\
bottom: "res2_conv2"\n\
top: "res2_conv2"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res2_conv2_scale"\n\
type: "Scale"\n\
bottom: "res2_conv2"\n\
top: "res2_conv2"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res2_conv2_relu"\n\
type: "ReLU"\n\
bottom: "res2_conv2"\n\
top: "res2_conv2"\n\
}\n\
layer {\n\
name: "res2_conv3"\n\
type: "Convolution"\n\
bottom: "res2_conv2"\n\
top: "res2_conv3"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 256\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res2_eletwise"\n\
type: "Eltwise"\n\
bottom: "res1_eletwise"\n\
bottom: "res2_conv3"\n\
top: "res2_eletwise"\n\
eltwise_param {\n\
operation: SUM\n\
}\n\
}\n\
layer {\n\
name: "res3_bn"\n\
type: "BatchNorm"\n\
bottom: "res2_eletwise"\n\
top: "res3_bn"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res3_scale"\n\
type: "Scale"\n\
bottom: "res3_bn"\n\
top: "res3_bn"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res3_relu"\n\
type: "ReLU"\n\
bottom: "res3_bn"\n\
top: "res3_bn"\n\
}\n\
layer {\n\
name: "res3_conv1"\n\
type: "Convolution"\n\
bottom: "res3_bn"\n\
top: "res3_conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 64\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res3_conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "res3_conv1"\n\
top: "res3_conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res3_conv1_scale"\n\
type: "Scale"\n\
bottom: "res3_conv1"\n\
top: "res3_conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res3_conv1_relu"\n\
type: "ReLU"\n\
bottom: "res3_conv1"\n\
top: "res3_conv1"\n\
}\n\
layer {\n\
name: "res3_conv2"\n\
type: "Convolution"\n\
bottom: "res3_conv1"\n\
top: "res3_conv2"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 64\n\
pad: 1\n\
kernel_size: 3\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res3_conv2_bn"\n\
type: "BatchNorm"\n\
bottom: "res3_conv2"\n\
top: "res3_conv2"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res3_conv2_scale"\n\
type: "Scale"\n\
bottom: "res3_conv2"\n\
top: "res3_conv2"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res3_conv2_relu"\n\
type: "ReLU"\n\
bottom: "res3_conv2"\n\
top: "res3_conv2"\n\
}\n\
layer {\n\
name: "res3_conv3"\n\
type: "Convolution"\n\
bottom: "res3_conv2"\n\
top: "res3_conv3"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 256\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res3_eletwise"\n\
type: "Eltwise"\n\
bottom: "res2_eletwise"\n\
bottom: "res3_conv3"\n\
top: "res3_eletwise"\n\
eltwise_param {\n\
operation: SUM\n\
}\n\
}\n\
layer {\n\
name: "res4_bn"\n\
type: "BatchNorm"\n\
bottom: "res3_eletwise"\n\
top: "res4_bn"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res4_scale"\n\
type: "Scale"\n\
bottom: "res4_bn"\n\
top: "res4_bn"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res4_relu"\n\
type: "ReLU"\n\
bottom: "res4_bn"\n\
top: "res4_bn"\n\
}\n\
layer {\n\
name: "res4_conv1"\n\
type: "Convolution"\n\
bottom: "res4_bn"\n\
top: "res4_conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res4_conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "res4_conv1"\n\
top: "res4_conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res4_conv1_scale"\n\
type: "Scale"\n\
bottom: "res4_conv1"\n\
top: "res4_conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res4_conv1_relu"\n\
type: "ReLU"\n\
bottom: "res4_conv1"\n\
top: "res4_conv1"\n\
}\n\
layer {\n\
name: "res4_conv2"\n\
type: "Convolution"\n\
bottom: "res4_conv1"\n\
top: "res4_conv2"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 1\n\
kernel_size: 3\n\
stride: 2\n\
}\n\
}\n\
layer {\n\
name: "res4_conv2_bn"\n\
type: "BatchNorm"\n\
bottom: "res4_conv2"\n\
top: "res4_conv2"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res4_conv2_scale"\n\
type: "Scale"\n\
bottom: "res4_conv2"\n\
top: "res4_conv2"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res4_conv2_relu"\n\
type: "ReLU"\n\
bottom: "res4_conv2"\n\
top: "res4_conv2"\n\
}\n\
layer {\n\
name: "res4_conv3"\n\
type: "Convolution"\n\
bottom: "res4_conv2"\n\
top: "res4_conv3"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 512\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res4_match_conv"\n\
type: "Convolution"\n\
bottom: "res4_bn"\n\
top: "res4_match_conv"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 512\n\
pad: 0\n\
kernel_size: 1\n\
stride: 2\n\
bias_filler {\n\
type: "constant"\n\
value: 0.2\n\
}\n\
}\n\
}\n\
layer {\n\
name: "res4_eletwise"\n\
type: "Eltwise"\n\
bottom: "res4_match_conv"\n\
bottom: "res4_conv3"\n\
top: "res4_eletwise"\n\
eltwise_param {\n\
operation: SUM\n\
}\n\
}\n\
layer {\n\
name: "res5_bn"\n\
type: "BatchNorm"\n\
bottom: "res4_eletwise"\n\
top: "res5_bn"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res5_scale"\n\
type: "Scale"\n\
bottom: "res5_bn"\n\
top: "res5_bn"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res5_relu"\n\
type: "ReLU"\n\
bottom: "res5_bn"\n\
top: "res5_bn"\n\
}\n\
layer {\n\
name: "res5_conv1"\n\
type: "Convolution"\n\
bottom: "res5_bn"\n\
top: "res5_conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res5_conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "res5_conv1"\n\
top: "res5_conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res5_conv1_scale"\n\
type: "Scale"\n\
bottom: "res5_conv1"\n\
top: "res5_conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res5_conv1_relu"\n\
type: "ReLU"\n\
bottom: "res5_conv1"\n\
top: "res5_conv1"\n\
}\n\
layer {\n\
name: "res5_conv2"\n\
type: "Convolution"\n\
bottom: "res5_conv1"\n\
top: "res5_conv2"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 1\n\
kernel_size: 3\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res5_conv2_bn"\n\
type: "BatchNorm"\n\
bottom: "res5_conv2"\n\
top: "res5_conv2"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res5_conv2_scale"\n\
type: "Scale"\n\
bottom: "res5_conv2"\n\
top: "res5_conv2"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res5_conv2_relu"\n\
type: "ReLU"\n\
bottom: "res5_conv2"\n\
top: "res5_conv2"\n\
}\n\
layer {\n\
name: "res5_conv3"\n\
type: "Convolution"\n\
bottom: "res5_conv2"\n\
top: "res5_conv3"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 512\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res5_eletwise"\n\
type: "Eltwise"\n\
bottom: "res4_eletwise"\n\
bottom: "res5_conv3"\n\
top: "res5_eletwise"\n\
eltwise_param {\n\
operation: SUM\n\
}\n\
}\n\
layer {\n\
name: "res6_bn"\n\
type: "BatchNorm"\n\
bottom: "res5_eletwise"\n\
top: "res6_bn"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res6_scale"\n\
type: "Scale"\n\
bottom: "res6_bn"\n\
top: "res6_bn"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res6_relu"\n\
type: "ReLU"\n\
bottom: "res6_bn"\n\
top: "res6_bn"\n\
}\n\
layer {\n\
name: "res6_conv1"\n\
type: "Convolution"\n\
bottom: "res6_bn"\n\
top: "res6_conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res6_conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "res6_conv1"\n\
top: "res6_conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res6_conv1_scale"\n\
type: "Scale"\n\
bottom: "res6_conv1"\n\
top: "res6_conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res6_conv1_relu"\n\
type: "ReLU"\n\
bottom: "res6_conv1"\n\
top: "res6_conv1"\n\
}\n\
layer {\n\
name: "res6_conv2"\n\
type: "Convolution"\n\
bottom: "res6_conv1"\n\
top: "res6_conv2"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 1\n\
kernel_size: 3\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res6_conv2_bn"\n\
type: "BatchNorm"\n\
bottom: "res6_conv2"\n\
top: "res6_conv2"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res6_conv2_scale"\n\
type: "Scale"\n\
bottom: "res6_conv2"\n\
top: "res6_conv2"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res6_conv2_relu"\n\
type: "ReLU"\n\
bottom: "res6_conv2"\n\
top: "res6_conv2"\n\
}\n\
layer {\n\
name: "res6_conv3"\n\
type: "Convolution"\n\
bottom: "res6_conv2"\n\
top: "res6_conv3"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 512\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res6_eletwise"\n\
type: "Eltwise"\n\
bottom: "res5_eletwise"\n\
bottom: "res6_conv3"\n\
top: "res6_eletwise"\n\
eltwise_param {\n\
operation: SUM\n\
}\n\
}\n\
layer {\n\
name: "res7_bn"\n\
type: "BatchNorm"\n\
bottom: "res6_eletwise"\n\
top: "res7_bn"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res7_scale"\n\
type: "Scale"\n\
bottom: "res7_bn"\n\
top: "res7_bn"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res7_relu"\n\
type: "ReLU"\n\
bottom: "res7_bn"\n\
top: "res7_bn"\n\
}\n\
layer {\n\
name: "res7_conv1"\n\
type: "Convolution"\n\
bottom: "res7_bn"\n\
top: "res7_conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res7_conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "res7_conv1"\n\
top: "res7_conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res7_conv1_scale"\n\
type: "Scale"\n\
bottom: "res7_conv1"\n\
top: "res7_conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res7_conv1_relu"\n\
type: "ReLU"\n\
bottom: "res7_conv1"\n\
top: "res7_conv1"\n\
}\n\
layer {\n\
name: "res7_conv2"\n\
type: "Convolution"\n\
bottom: "res7_conv1"\n\
top: "res7_conv2"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 1\n\
kernel_size: 3\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res7_conv2_bn"\n\
type: "BatchNorm"\n\
bottom: "res7_conv2"\n\
top: "res7_conv2"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res7_conv2_scale"\n\
type: "Scale"\n\
bottom: "res7_conv2"\n\
top: "res7_conv2"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res7_conv2_relu"\n\
type: "ReLU"\n\
bottom: "res7_conv2"\n\
top: "res7_conv2"\n\
}\n\
layer {\n\
name: "res7_conv3"\n\
type: "Convolution"\n\
bottom: "res7_conv2"\n\
top: "res7_conv3"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 512\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res7_eletwise"\n\
type: "Eltwise"\n\
bottom: "res6_eletwise"\n\
bottom: "res7_conv3"\n\
top: "res7_eletwise"\n\
eltwise_param {\n\
operation: SUM\n\
}\n\
}\n\
layer {\n\
name: "res8_bn"\n\
type: "BatchNorm"\n\
bottom: "res7_eletwise"\n\
top: "res8_bn"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res8_scale"\n\
type: "Scale"\n\
bottom: "res8_bn"\n\
top: "res8_bn"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res8_relu"\n\
type: "ReLU"\n\
bottom: "res8_bn"\n\
top: "res8_bn"\n\
}\n\
layer {\n\
name: "res8_conv1"\n\
type: "Convolution"\n\
bottom: "res8_bn"\n\
top: "res8_conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res8_conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "res8_conv1"\n\
top: "res8_conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res8_conv1_scale"\n\
type: "Scale"\n\
bottom: "res8_conv1"\n\
top: "res8_conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res8_conv1_relu"\n\
type: "ReLU"\n\
bottom: "res8_conv1"\n\
top: "res8_conv1"\n\
}\n\
layer {\n\
name: "res8_conv2"\n\
type: "Convolution"\n\
bottom: "res8_conv1"\n\
top: "res8_conv2"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 1\n\
kernel_size: 3\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res8_conv2_bn"\n\
type: "BatchNorm"\n\
bottom: "res8_conv2"\n\
top: "res8_conv2"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res8_conv2_scale"\n\
type: "Scale"\n\
bottom: "res8_conv2"\n\
top: "res8_conv2"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res8_conv2_relu"\n\
type: "ReLU"\n\
bottom: "res8_conv2"\n\
top: "res8_conv2"\n\
}\n\
layer {\n\
name: "res8_conv3"\n\
type: "Convolution"\n\
bottom: "res8_conv2"\n\
top: "res8_conv3"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 512\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res8_eletwise"\n\
type: "Eltwise"\n\
bottom: "res7_eletwise"\n\
bottom: "res8_conv3"\n\
top: "res8_eletwise"\n\
eltwise_param {\n\
operation: SUM\n\
}\n\
}\n\
layer {\n\
name: "res9_bn"\n\
type: "BatchNorm"\n\
bottom: "res8_eletwise"\n\
top: "res9_bn"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res9_scale"\n\
type: "Scale"\n\
bottom: "res9_bn"\n\
top: "res9_bn"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res9_relu"\n\
type: "ReLU"\n\
bottom: "res9_bn"\n\
top: "res9_bn"\n\
}\n\
layer {\n\
name: "res9_conv1"\n\
type: "Convolution"\n\
bottom: "res9_bn"\n\
top: "res9_conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res9_conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "res9_conv1"\n\
top: "res9_conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res9_conv1_scale"\n\
type: "Scale"\n\
bottom: "res9_conv1"\n\
top: "res9_conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res9_conv1_relu"\n\
type: "ReLU"\n\
bottom: "res9_conv1"\n\
top: "res9_conv1"\n\
}\n\
layer {\n\
name: "res9_conv2"\n\
type: "Convolution"\n\
bottom: "res9_conv1"\n\
top: "res9_conv2"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 1\n\
kernel_size: 3\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res9_conv2_bn"\n\
type: "BatchNorm"\n\
bottom: "res9_conv2"\n\
top: "res9_conv2"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res9_conv2_scale"\n\
type: "Scale"\n\
bottom: "res9_conv2"\n\
top: "res9_conv2"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res9_conv2_relu"\n\
type: "ReLU"\n\
bottom: "res9_conv2"\n\
top: "res9_conv2"\n\
}\n\
layer {\n\
name: "res9_conv3"\n\
type: "Convolution"\n\
bottom: "res9_conv2"\n\
top: "res9_conv3"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 512\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res9_eletwise"\n\
type: "Eltwise"\n\
bottom: "res8_eletwise"\n\
bottom: "res9_conv3"\n\
top: "res9_eletwise"\n\
eltwise_param {\n\
operation: SUM\n\
}\n\
}\n\
layer {\n\
name: "res10_bn"\n\
type: "BatchNorm"\n\
bottom: "res9_eletwise"\n\
top: "res10_bn"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res10_scale"\n\
type: "Scale"\n\
bottom: "res10_bn"\n\
top: "res10_bn"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res10_relu"\n\
type: "ReLU"\n\
bottom: "res10_bn"\n\
top: "res10_bn"\n\
}\n\
layer {\n\
name: "res10_conv1"\n\
type: "Convolution"\n\
bottom: "res10_bn"\n\
top: "res10_conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res10_conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "res10_conv1"\n\
top: "res10_conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res10_conv1_scale"\n\
type: "Scale"\n\
bottom: "res10_conv1"\n\
top: "res10_conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res10_conv1_relu"\n\
type: "ReLU"\n\
bottom: "res10_conv1"\n\
top: "res10_conv1"\n\
}\n\
layer {\n\
name: "res10_conv2"\n\
type: "Convolution"\n\
bottom: "res10_conv1"\n\
top: "res10_conv2"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 1\n\
kernel_size: 3\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res10_conv2_bn"\n\
type: "BatchNorm"\n\
bottom: "res10_conv2"\n\
top: "res10_conv2"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res10_conv2_scale"\n\
type: "Scale"\n\
bottom: "res10_conv2"\n\
top: "res10_conv2"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res10_conv2_relu"\n\
type: "ReLU"\n\
bottom: "res10_conv2"\n\
top: "res10_conv2"\n\
}\n\
layer {\n\
name: "res10_conv3"\n\
type: "Convolution"\n\
bottom: "res10_conv2"\n\
top: "res10_conv3"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 512\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res10_eletwise"\n\
type: "Eltwise"\n\
bottom: "res9_eletwise"\n\
bottom: "res10_conv3"\n\
top: "res10_eletwise"\n\
eltwise_param {\n\
operation: SUM\n\
}\n\
}\n\
layer {\n\
name: "res11_bn"\n\
type: "BatchNorm"\n\
bottom: "res10_eletwise"\n\
top: "res11_bn"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res11_scale"\n\
type: "Scale"\n\
bottom: "res11_bn"\n\
top: "res11_bn"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res11_relu"\n\
type: "ReLU"\n\
bottom: "res11_bn"\n\
top: "res11_bn"\n\
}\n\
layer {\n\
name: "res11_conv1"\n\
type: "Convolution"\n\
bottom: "res11_bn"\n\
top: "res11_conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res11_conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "res11_conv1"\n\
top: "res11_conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res11_conv1_scale"\n\
type: "Scale"\n\
bottom: "res11_conv1"\n\
top: "res11_conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res11_conv1_relu"\n\
type: "ReLU"\n\
bottom: "res11_conv1"\n\
top: "res11_conv1"\n\
}\n\
layer {\n\
name: "res11_conv2"\n\
type: "Convolution"\n\
bottom: "res11_conv1"\n\
top: "res11_conv2"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 128\n\
pad: 1\n\
kernel_size: 3\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res11_conv2_bn"\n\
type: "BatchNorm"\n\
bottom: "res11_conv2"\n\
top: "res11_conv2"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res11_conv2_scale"\n\
type: "Scale"\n\
bottom: "res11_conv2"\n\
top: "res11_conv2"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res11_conv2_relu"\n\
type: "ReLU"\n\
bottom: "res11_conv2"\n\
top: "res11_conv2"\n\
}\n\
layer {\n\
name: "res11_conv3"\n\
type: "Convolution"\n\
bottom: "res11_conv2"\n\
top: "res11_conv3"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 512\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res11_eletwise"\n\
type: "Eltwise"\n\
bottom: "res10_eletwise"\n\
bottom: "res11_conv3"\n\
top: "res11_eletwise"\n\
eltwise_param {\n\
operation: SUM\n\
}\n\
}\n\
layer {\n\
name: "res12_bn"\n\
type: "BatchNorm"\n\
bottom: "res11_eletwise"\n\
top: "res12_bn"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res12_scale"\n\
type: "Scale"\n\
bottom: "res12_bn"\n\
top: "res12_bn"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res12_relu"\n\
type: "ReLU"\n\
bottom: "res12_bn"\n\
top: "res12_bn"\n\
}\n\
layer {\n\
name: "res12_conv1"\n\
type: "Convolution"\n\
bottom: "res12_bn"\n\
top: "res12_conv1"\n\
convolution_param {\n\
bias_term: false\n\
num_output: 256\n\
pad: 0\n\
kernel_size: 1\n\
stride: 1\n\
}\n\
}\n\
layer {\n\
name: "res12_conv1_bn"\n\
type: "BatchNorm"\n\
bottom: "res12_conv1"\n\
top: "res12_conv1"\n\
batch_norm_param {\n\
use_global_stats: true\n\
}\n\
}\n\
layer {\n\
name: "res12_conv1_scale"\n\
type: "Scale"\n\
bottom: "res12_conv1"\n\
top: "res12_conv1"\n\
scale_param {\n\
bias_term: true\n\
}\n\
}\n\
layer {\n\
name: "res12_conv1_relu"\n\
type: "ReLU"\n\
bottom: "res12_conv1"\n\
top: "res12_conv1"\n\
}\n'
return string
|
462540
|
import time
import torch
import torch.utils.data
from kge.job import Job
from kge.job.train import TrainingJob, _generate_worker_init_fn
class TrainingJob1vsAll(TrainingJob):
"""Samples SPO pairs and queries sp_ and _po, treating all other entities as negative."""
def __init__(
self, config, dataset, parent_job=None, model=None, forward_only=False
):
super().__init__(
config, dataset, parent_job, model=model, forward_only=forward_only
)
config.log("Initializing spo training job...")
self.type_str = "1vsAll"
if self.__class__ == TrainingJob1vsAll:
for f in Job.job_created_hooks:
f(self)
def _prepare(self):
"""Construct dataloader"""
super()._prepare()
self.num_examples = self.dataset.split(self.train_split).size(0)
self.loader = torch.utils.data.DataLoader(
range(self.num_examples),
collate_fn=lambda batch: {
"triples": self.dataset.split(self.train_split)[batch, :].long()
},
shuffle=True,
batch_size=self.batch_size,
num_workers=self.config.get("train.num_workers"),
worker_init_fn=_generate_worker_init_fn(self.config),
pin_memory=self.config.get("train.pin_memory"),
)
def _prepare_batch(
self, batch_index, batch, result: TrainingJob._ProcessBatchResult
):
result.size = len(batch["triples"])
def _process_subbatch(
self,
batch_index,
batch,
subbatch_slice,
result: TrainingJob._ProcessBatchResult,
):
batch_size = result.size
# prepare
result.prepare_time -= time.time()
triples = batch["triples"][subbatch_slice].to(self.device)
result.prepare_time += time.time()
# forward/backward pass (sp)
result.forward_time -= time.time()
scores_sp = self.model.score_sp(triples[:, 0], triples[:, 1])
loss_value_sp = self.loss(scores_sp, triples[:, 2]) / batch_size
result.avg_loss += loss_value_sp.item()
result.forward_time += time.time()
result.backward_time = -time.time()
if not self.is_forward_only:
loss_value_sp.backward()
result.backward_time += time.time()
# forward/backward pass (po)
result.forward_time -= time.time()
scores_po = self.model.score_po(triples[:, 1], triples[:, 2])
loss_value_po = self.loss(scores_po, triples[:, 0]) / batch_size
result.avg_loss += loss_value_po.item()
result.forward_time += time.time()
result.backward_time -= time.time()
if not self.is_forward_only:
loss_value_po.backward()
result.backward_time += time.time()
|
462542
|
favorite_places = {
'znn': ['chengdu', 'shanghai', 'hangzhou'],
'yl': ['chengdu', 'huang montains'],
'other': ['xian', 'xinjiang', 'nanji']
}
for name, places in favorite_places.items():
print("\n" + name.title() + " likes the following places:")
for place in places:
print("- " + place.title())
|
462594
|
import os
import types
import pandas as pd
import pytest
from skmine.datasets import fimi
from skmine.datasets import get_data_home
def mock_urlopen(url):
for i in range(2):
transaction = " ".join("{}".format(i * j) for j in range(2)) + " \n"
yield bytes(transaction, encoding="utf-8")
def mock_read_pickle(*args, **kwargs):
return pd.Series([[1, 2, 3], [4, 5]])
def test_fetch_any(monkeypatch):
name = "imaginary_dataset"
# force file to be in DATA_HOME, so we don't need to fetch it
monkeypatch.setattr(os, "listdir", lambda *args: ["{}.dat".format(name)])
monkeypatch.setattr(pd, "read_pickle", mock_read_pickle)
data = fimi.fetch_any("{}.dat".format(name))
assert data.shape == (2,)
pd.testing.assert_series_equal(pd.Series([3, 2], name=name), data.map(len))
# now DATA_HOME to be empty, file has to be fetched
monkeypatch.setattr(os, "listdir", lambda *args: list())
monkeypatch.setattr(fimi, "urlopen", mock_urlopen)
name = "other_imaginary_dataset"
data = fimi.fetch_any("{}.dat".format(name))
assert data.shape == (2,)
pd.testing.assert_series_equal(pd.Series([2, 2], name=name), data.map(len))
|
462613
|
from typing import Optional
from typing import Text, Dict, Any
from tfx import types
from tfx.dsl.components.base import base_component
from tfx.dsl.components.base import executor_spec
from tfx.types.component_spec import ChannelParameter
from tfx.types.component_spec import ComponentSpec
from tfx.types.component_spec import ExecutionParameter
from tfx.types.standard_artifacts import Examples, Model, Schema, \
ModelEvaluation, ModelBlessing
from zenml.components.evaluator import constants
from zenml.components.evaluator import executor
class ZenMLEvaluatorSpec(ComponentSpec):
PARAMETERS = {constants.SOURCE: ExecutionParameter(type=Text),
constants.ARGS: ExecutionParameter(Text)}
INPUTS = {
constants.EXAMPLES: ChannelParameter(type=Examples),
constants.MODEL: ChannelParameter(type=Model, optional=True),
constants.BASELINE_MODEL: ChannelParameter(type=Model, optional=True),
constants.SCHEMA: ChannelParameter(type=Schema, optional=True)
}
OUTPUTS = {
constants.EVALUATION: ChannelParameter(type=ModelEvaluation),
constants.BLESSING: ChannelParameter(type=ModelBlessing,
optional=True),
}
class Evaluator(base_component.BaseComponent):
"""
A new adapted version version of the TFX Evaluator component.
In contrast to the original evaluator component, it utilizes a ZenML
EvaluatorStep and allows the model agnostic evaluation.
"""
SPEC_CLASS = ZenMLEvaluatorSpec
EXECUTOR_SPEC = executor_spec.ExecutorClassSpec(executor.Executor)
def __init__(
self,
source: Text,
source_args: Dict[Text, Any],
examples: types.Channel = None,
model: types.Channel = None,
baseline_model: Optional[types.Channel] = None,
blessing: Optional[types.Channel] = None,
output: Optional[types.Channel] = None,
schema: Optional[types.Channel] = None):
# Create the output artifact if not provided
evaluation = output or types.Channel(type=ModelEvaluation)
blessing = blessing or types.Channel(type=ModelBlessing)
# Create the spec
spec = ZenMLEvaluatorSpec(source=source,
args=source_args,
examples=examples,
model=model,
baseline_model=baseline_model,
blessing=blessing,
schema=schema,
evaluation=evaluation)
super(Evaluator, self).__init__(spec=spec)
|
462620
|
import numpy as np
import tensorflow as tf
from collections import Counter
from textdect.convertmodel import ConvertedModel
from misc.freezemodel import FreezedModel
from mesgclsf.datapreptools import resize_to_desired
from mesgclsf.s2train import FEATURE_HEIGHT, FEATURE_WIDTH
def classify(classifier, session, img_arr, stride=16):
"""
Take an image file (an output from the first step), read and analyze the image, and
returns the class ID of the input image based on the message content on it.
Args:
classifier: A FreezedModel constructed based on a trained model for step 2.
session: The TensorFlow session.
img_arr: A numpy ndarray that holds the image features.
stride: Optional. The stride of the sliding.
Returns:
class_id: Message class ID of the input image.
confidence: A percentage indicating how many slided images were predicted as
this class identified by the class_id.
"""
height, width = FEATURE_HEIGHT, FEATURE_WIDTH
resized_img = resize_to_desired(img_arr)
img_height, img_width = resized_img.shape
assert img_height == height
features = []
for x in range(0, img_width - FEATURE_WIDTH + 1, stride):
this_win = resized_img[:, x:x + FEATURE_WIDTH]
features.append(this_win.reshape(-1))
_, indices = classifier.predict(session, np.asarray(features))
img_cnt = len(features)
cls_list = []
for i in range(img_cnt):
cls_list.append(indices[i][0])
class_id, pos_cnt = Counter(cls_list).most_common()[0]
confidence = (pos_cnt / img_cnt) * 100.0
return class_id, confidence
def detect_and_classify(detector, classifier, session, image_array, debug=False):
boxes = detector.predict(session, image_array)
for box in boxes:
xmin, ymin, xmax, ymax = box.get_coordinates()
gry_arr = cv2.cvtColor(image_array, cv2.COLOR_BGR2GRAY)
area_img = gry_arr[ymin:ymax, xmin:xmax]
cls_id, conf = classify(classifier, session, area_img)
if debug:
cv2.rectangle(image_array, (xmin, ymin), (xmax, ymax), (255, 0, 0), 1)
print("class ID: {}, confidence: {}".format(cls_id, conf))
if __name__ == "__main__":
import cv2
import json
import os
import matplotlib.pyplot as plt
from time import time
from settings import PROJECT_ROOT
t0 = time()
model_dir = os.path.join(PROJECT_ROOT, 'Data', 'Result')
s1_model = 's1_keras_model.pb'
lss_model = 's2_lss_model.pb'
tas_model = 's2_tas_model.pb'
sign_type = 'TAS' # LSS or TAS
img_file = os.path.join(PROJECT_ROOT, 'Data', 'Step1', 'Test', 'sign1.jpg')
img_arr = cv2.imread(img_file)
s1_config_file = os.path.join(PROJECT_ROOT, 'textdect', 'config.json')
with open(s1_config_file) as config_buffer:
s1_config = json.loads(config_buffer.read())
with tf.Graph().as_default() as graph:
detector = ConvertedModel(s1_config, graph, 's1_keras', model_dir, s1_model)
lss_classifier = FreezedModel(graph, 's2_lss', model_dir, lss_model)
tas_classifier = FreezedModel(graph, 's2_tas', model_dir, tas_model)
with tf.Session(graph=graph) as sess:
if sign_type == 'LSS':
detect_and_classify(detector, lss_classifier, sess, img_arr, debug=True)
else:
detect_and_classify(detector, tas_classifier, sess, img_arr, debug=True)
t1 = time()
print("Running time: {:4.2f} seconds".format(t1-t0))
plt.imshow(img_arr)
plt.show()
|
462635
|
import sys
import numpy as np
from PyQt5 import QtWidgets
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QDialog, QPushButton, QWidget, QHBoxLayout, QApplication, QLabel, QVBoxLayout, QGridLayout
from PyQt5.uic import loadUi
import cv2
imageT = None
import windowSize
class mywin(QtWidgets.QDialog):
def __init__(self):
super(mywin, self).__init__()
# loadUi('img.ui',self)
self.desktop = QApplication.desktop()
self.screenRect = self.desktop.screenGeometry()
self.height = self.screenRect.height()
self.width = self.screenRect.width()
self.setWindowTitle("PyScrcpy")
print("pc屏幕分辨率为", (self.height, self.width))
minAxis = min(self.width, self.height) * 0.9 // 2 * 2
minAxis = int(minAxis)
self.resize(minAxis * 9 // 16, minAxis)
layout = QHBoxLayout()
frameLayout = QHBoxLayout()
buttonLayout = QVBoxLayout()
self.all_btn = all_btn = QPushButton()
all_btn.setText("一键启动")
self.start_btn = start_btn = QPushButton()
start_btn.setText("启动server")
self.androit_btn = androit_btn = QPushButton()
androit_btn.setText("启动android")
self.qrShow_btn=qrShow_btn=QPushButton()
qrShow_btn.setText("显示二维码")
# self.load_btn.clicked.connect(self.loadimage)
# self.
buttonLayout.addWidget(all_btn)
buttonLayout.addWidget(start_btn)
buttonLayout.addWidget(androit_btn)
buttonLayout.addWidget(qrShow_btn)
buttonLayout.addStretch()
self.img_label = QLabel()
# self.img_label.setMinimumWidth(720)
frameLayout.addWidget(self.img_label)
layout.addLayout(buttonLayout)
layout.addLayout(frameLayout)
self.setLayout(layout)
# self.setLayout(wLayout)
def loadimage(self):
global imageT
# image = cv2.cvtColor(imageT, cv2.COLOR_BGR2RGB)
self.qimg = QImage(imageT.data, imageT.shape[1], imageT.shape[0], QImage.Format_RGB888)
# QPixmap.loadFromData()
# self.qimg = self.qimg.rgbSwapped()
self.img_label.setPixmap(QPixmap.fromImage(self.qimg))
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = mywin()
window.show()
window.setWindowTitle("window")
# window.setGeometry(100,100,400,300)
sys.exit(app.exec_())
|
462667
|
from citrus import *
import img
import sf2d
ST_LOAD = 0
ST_DISP = 1
ST_END = 2
class App:
state = ST_LOAD
bg = None
load_pat = ['-', '\\', '|', '/']
load_pat_idx = 0
def __init__(self):
sf2d.init()
console.init(gfx.SCREEN_BOTTOM)
self.bg_loader = img.load_png(open('romfs:/bgtest.png', 'rb'), background=True)
def run(self):
while apt.main_loop():
hid.scan_input()
if self.state == ST_LOAD:
self.load_state()
elif self.state == ST_DISP:
self.display_state()
elif self.state == ST_END:
sf2d.fini()
break
def load_state(self):
tex = self.bg_loader.get_image()
if tex is not None:
del self.bg_loader
self.bg = sf2d.Texture(tex[0], tex[1], sf2d.TEXFMT_RGBA8, sf2d.PLACE_RAM, tex[3])
self.state = ST_DISP
print('\x1b[1;1H' + (' ' * 50))
return
print('\x1b[1;1HLoading %s' % self.load_pat[self.load_pat_idx])
self.load_pat_idx += 1
if self.load_pat_idx >= len(self.load_pat):
self.load_pat_idx = 0
sf2d.swap_buffers()
def display_state(self):
if hid.keys_down() & hid.KEY_START:
self.state = ST_END
sf2d.start_frame(gfx.SCREEN_TOP, gfx.SIDE_LEFT)
self.bg.draw(0, 0)
sf2d.end_frame()
sf2d.swap_buffers()
App().run()
|
462692
|
import os
from pathlib import Path
from unittest.mock import patch
import pytest
from streamlink_cli.utils.path import replace_chars, replace_path
from tests import posix_only, windows_only
@pytest.mark.parametrize("char", [i for i in range(32)])
def test_replace_chars_unprintable(char: int):
assert replace_chars(f"foo{chr(char)}{chr(char)}bar") == "foo_bar", "Replaces unprintable characters"
@posix_only
@pytest.mark.parametrize("char", "/".split())
def test_replace_chars_posix(char: str):
assert replace_chars(f"foo{char}{char}bar") == "foo_bar", "Replaces multiple unsupported characters in a row"
@windows_only
@pytest.mark.parametrize("char", "\x7f\"*/:<>?\\|".split())
def test_replace_chars_windows(char: str):
assert replace_chars(f"foo{char}{char}bar") == "foo_bar", "Replaces multiple unsupported characters in a row"
@posix_only
def test_replace_chars_posix_all():
assert replace_chars("".join(chr(i) for i in range(32)) + "/") == "_"
@windows_only
def test_replace_chars_windows_all():
assert replace_chars("".join(chr(i) for i in range(32)) + "\x7f\"*/:<>?\\|") == "_"
@posix_only
def test_replace_chars_posix_override():
all_chars = "".join(chr(i) for i in range(32)) + "\x7f\"*:/<>?\\|"
assert replace_chars(all_chars) == "_\x7f\"*:_<>?\\|"
assert replace_chars(all_chars, "posix") == "_\x7f\"*:_<>?\\|"
assert replace_chars(all_chars, "unix") == "_\x7f\"*:_<>?\\|"
assert replace_chars(all_chars, "windows") == "_"
assert replace_chars(all_chars, "win32") == "_"
@windows_only
def test_replace_chars_windows_override():
all_chars = "".join(chr(i) for i in range(32)) + "\x7f\"*:/<>?\\|"
assert replace_chars(all_chars) == "_"
assert replace_chars(all_chars, "posix") == "_\x7f\"*:_<>?\\|"
assert replace_chars(all_chars, "unix") == "_\x7f\"*:_<>?\\|"
assert replace_chars(all_chars, "windows") == "_"
assert replace_chars(all_chars, "win32") == "_"
def test_replace_chars_replacement():
assert replace_chars("\x00", None, "+") == "+"
def test_replace_path():
def mapper(s):
return dict(foo=".", bar="..").get(s, s)
path = Path("foo", ".", "bar", "..", "baz")
expected = Path("_", ".", "_", "..", "baz")
assert replace_path(path, mapper) == expected, "Only replaces mapped parts which are in the special parts tuple"
@posix_only
def test_replace_path_expanduser_posix():
with patch.object(os, "environ", {"HOME": "/home/foo"}):
assert replace_path("~/bar", lambda s: s) == Path("/home/foo/bar")
assert replace_path("foo/bar", lambda s: dict(foo="~").get(s, s)) == Path("~/bar")
@windows_only
def test_replace_path_expanduser_windows():
with patch.object(os, "environ", {"USERPROFILE": "C:\\Users\\foo"}):
assert replace_path("~\\bar", lambda s: s) == Path("C:\\Users\\foo\\bar")
assert replace_path("foo\\bar", lambda s: dict(foo="~").get(s, s)) == Path("~\\bar")
|
462693
|
import theano, cPickle
import theano.tensor as T
import numpy as np
from fftconv import cufft, cuifft
def initialize_matrix(n_in, n_out, name, rng, init='rand'):
if (init=='rand') or (init=='randSmall'):
bin = np.sqrt(6. / (n_in + n_out))
values = np.asarray(rng.uniform(low=-bin,
high=bin,
size=(n_in, n_out)),
dtype=theano.config.floatX)
if (init=='randSmall'):
values=np.float32(0.01)*values
elif (init=='identity'):
if (n_in >= n_out):
values = np.concatenate([np.eye(n_out).astype(theano.config.floatX),np.zeros((n_in-n_out,n_out)).astype(theano.config.floatX)],axis=0)
else:
values = np.concatenate([np.eye(n_in).astype(theano.config.floatX),np.zeros((n_in,n_out-n_in)).astype(theano.config.floatX)],axis=1)
else:
raise ValueError("Unknown initialization method ["+init+"]")
return theano.shared(value=values, name=name)
def initialize_matrix_np(n_in, n_out, rng):
bin = np.sqrt(6. / (n_in + n_out))
values = np.asarray(rng.uniform(low=-bin,
high=bin,
size=(n_in, n_out)),
dtype=theano.config.floatX)
return values
def do_fft(input, n_hidden):
fft_input = T.reshape(input, (input.shape[0], 2, n_hidden))
fft_input = fft_input.dimshuffle(0,2,1)
fft_output = cufft(fft_input) / T.sqrt(n_hidden)
fft_output = fft_output.dimshuffle(0,2,1)
output = T.reshape(fft_output, (input.shape[0], 2*n_hidden))
return output
def do_ifft(input, n_hidden):
ifft_input = T.reshape(input, (input.shape[0], 2, n_hidden))
ifft_input = ifft_input.dimshuffle(0,2,1)
ifft_output = cuifft(ifft_input) / T.sqrt(n_hidden)
ifft_output = ifft_output.dimshuffle(0,2,1)
output = T.reshape(ifft_output, (input.shape[0], 2*n_hidden))
return output
def times_diag(input, n_hidden, diag, swap_re_im):
# input is a Ix2n_hidden matrix, where I is number
# of training examples
# diag is a n_hidden-dimensional real vector, which creates
# the 2n_hidden x 2n_hidden complex diagonal matrix using
# e.^{j.*diag}=cos(diag)+j.*sin(diag)
d = T.concatenate([diag, -diag]) #d is 2n_hidden
Re = T.cos(d).dimshuffle('x',0)
Im = T.sin(d).dimshuffle('x',0)
input_times_Re = input * Re
input_times_Im = input * Im
output = input_times_Re + input_times_Im[:, swap_re_im]
return output
def vec_permutation(input, index_permute):
return input[:, index_permute]
def times_reflection(input, n_hidden, reflection):
input_re = input[:, :n_hidden]
input_im = input[:, n_hidden:]
reflect_re = reflection[:n_hidden]
reflect_im = reflection[n_hidden:]
vstarv = (reflection**2).sum()
input_re_reflect_re = T.dot(input_re, reflect_re)
input_re_reflect_im = T.dot(input_re, reflect_im)
input_im_reflect_re = T.dot(input_im, reflect_re)
input_im_reflect_im = T.dot(input_im, reflect_im)
a = T.outer(input_re_reflect_re - input_im_reflect_im, reflect_re)
b = T.outer(input_re_reflect_im + input_im_reflect_re, reflect_im)
c = T.outer(input_re_reflect_re - input_im_reflect_im, reflect_im)
d = T.outer(input_re_reflect_im + input_im_reflect_re, reflect_re)
output = input
output = T.inc_subtensor(output[:, :n_hidden], - 2. / vstarv * (a + b))
output = T.inc_subtensor(output[:, n_hidden:], - 2. / vstarv * (d - c))
return output
def times_reflection_sub(input, n_hidden, n_sub, reflection):
#print "n_hidden=%d, n_sub=%d" % (n_hidden,n_sub)
input_re = input[:, :n_hidden]
input_im = input[:, n_hidden:]
n_start=n_hidden-n_sub
#print "n_start=%d" % n_start
reflect_re = reflection[n_start:n_hidden]
reflect_im = reflection[(n_hidden+n_start):]
vstarv = (reflect_re**2).sum() + (reflect_im**2).sum()
input_re_reflect_re = T.dot(input_re[:,n_start:], reflect_re)
input_re_reflect_im = T.dot(input_re[:,n_start:], reflect_im)
input_im_reflect_re = T.dot(input_im[:,n_start:], reflect_re)
input_im_reflect_im = T.dot(input_im[:,n_start:], reflect_im)
a = T.outer(input_re_reflect_re - input_im_reflect_im, reflect_re)
b = T.outer(input_re_reflect_im + input_im_reflect_re, reflect_im)
c = T.outer(input_re_reflect_re - input_im_reflect_im, reflect_im)
d = T.outer(input_re_reflect_im + input_im_reflect_re, reflect_re)
output = input
output = T.inc_subtensor(output[:, n_start:n_hidden], - 2. / vstarv * (a + b))
output = T.inc_subtensor(output[:, (n_hidden+n_start):], - 2. / vstarv * (d - c))
return output
def times_givens(input,n_hidden,gparams,idx):
# input is a Ix2n complex matrix in augmented ReIm form.
# gparams is a 3-dim vector parameterizing a Givens rotation.
# idx are two indices of the Givens rotation.
#
# output will be Ix2n complex matrix in augmented ReIm form
# Givens rotation using gparams=(phi,psi,chi) is
# [ cos(phi)*exp( j*psi), sin(phi)*exp( j*chi) ]
# [-sin(phi)*exp(-j*psi), cos(phi)*exp(-j*chi) ]
cos_phi=T.cos(gparams[0])
sin_phi=T.sin(gparams[0])
cos_psi=T.cos(gparams[1])
sin_psi=T.sin(gparams[1])
cos_chi=T.cos(gparams[2])
sin_chi=T.sin(gparams[2])
G11_re=cos_phi*cos_psi
G11_im=cos_phi*sin_psi
G12_re=sin_phi*cos_chi
G12_im=sin_phi*sin_chi
G21_re=-sin_phi*cos_chi
G21_im= sin_phi*sin_chi
G22_re= cos_phi*cos_psi
G22_im=-cos_phi*sin_psi
idx=T.cast(idx,'int64')
output=input
# Re{y_{i1}}=Re{ G11*x_{i1}+G12*x_{i2} }
#output[:,idx[0]]
output = T.set_subtensor(output[:,idx[0]], \
(G11_re*input[:,idx[0]]-G11_im*input[:,idx[0]+n_hidden]) \
+(G12_re*input[:,idx[1]]-G12_im*input[:,idx[1]+n_hidden]))
# Im{y_{i1}}=Im{ G11*x_{i1}+G12*x_{i2} }
#output[:,idx[0]+n_hidden]
output = T.set_subtensor(output[:,idx[0]+n_hidden], \
(G11_im*input[:,idx[0]]+G11_re*input[:,idx[0]+n_hidden]) \
+(G12_im*input[:,idx[1]]+G12_re*input[:,idx[1]+n_hidden]))
# Re{y_{i2}}=Re{ G21*x_{i1}+G22*x_{i2} }
#output[:,idx[1]]
output = T.set_subtensor(output[:,idx[1]], \
(G21_re*input[:,idx[0]]-G21_im*input[:,idx[0]+n_hidden]) \
+(G22_re*input[:,idx[1]]-G22_im*input[:,idx[1]+n_hidden]))
# Im{y_{i2}}=Im{ G21*x_{i1}+G22*x_{i2} }
#output[:,idx[1]+n_hidden]
output = T.set_subtensor(output[:,idx[1]+n_hidden], \
(G21_im*input[:,idx[0]]+G21_re*input[:,idx[0]+n_hidden]) \
+(G22_im*input[:,idx[1]]+G22_re*input[:,idx[1]+n_hidden]))
return output
def compute_cost_t(lin_output, loss_function, y_t, ymask_t=None, z_t=None, lam=0.0):
if (loss_function == 'CE') or (loss_function == 'CE_of_sum'):
RNN_output = T.nnet.softmax(lin_output)
CE = T.nnet.categorical_crossentropy(RNN_output, y_t)
if ymask_t is not None:
RNN_output=RNN_output*ymask_t
CE = CE*(ymask_t.dimshuffle(0,))
cost_t = CE.mean()
acc_t =(T.eq(T.argmax(RNN_output, axis=-1), y_t)).mean(dtype=theano.config.floatX)
elif loss_function == 'MSE':
mse = (lin_output - y_t)**2
if ymask_t is not None:
mse = mse*((ymask_t[:,0]).dimshuffle(0,'x'))
#mse = mse*ymask_t[:,0:1]
cost_t = mse.mean()
#acc_t = theano.shared(np.float32(0.0))
acc_t = cost_t
elif loss_function == 'MSEplusL1':
mseOnly = (lin_output - y_t)**2
L1 = T.sqrt(1e-5 + T.sum(lin_output**2,axis=1,keepdims=True))
mse = mseOnly + lam*L1
if ymask_t is not None:
mse = mse*((ymask_t[:,0]).dimshuffle(0,'x'))
cost_t = mse.mean()
acc_t = mseOnly.mean()
#elif loss_function == 'NMSE':
# err=(lin_output - y_t)**2
# err_sum=T.sum(err,axis=0)
# err_sum=T.sum(err_sum,axis=-1)
# ypow=y_t**2
# ypow_sum=T.sum(ypow,axis=0)
# ypow_sum=T.sum(ypow_sum,axis=-1)
# cost_t = (err_sum / (1e-5+ypow_sum)).mean()
# acc_t = theano.shared(np.float32(0.0))
elif (loss_function == 'g_loss') or (loss_function == 'none_in_scan'):
cost_t=theano.shared(np.float32(0.0))
acc_t =theano.shared(np.float32(0.0))
elif loss_function == 'd_loss':
RNN_output = T.nnet.sigmoid(lin_output)
# clip the output of the sigmoid to avoid 0s, and thus NaNs in cross entropy:
RNN_output_clip = T.clip(RNN_output,1e-7,1.0-1e-7)
costs_t = T.nnet.binary_crossentropy(RNN_output_clip, y_t)
if ymask_t is not None:
costs_t = costs_t*(ymask_t.dimshuffle(0,))
cost_t = costs_t.mean()
idx_half=costs_t.shape[0]/2
costs_t_fake=costs_t[:idx_half]
costs_t_real=costs_t[idx_half:]
acc_t = [costs_t_fake.mean()/2,costs_t_real.mean()/2]
return cost_t, acc_t
def initialize_data_nodes(loss_function, input_type, out_every_t):
# if input_type is real or complex, will be size n_fram x n_input x n_utt
x = T.tensor3() if input_type == 'real' or input_type == 'complex' else T.matrix(dtype='int32')
if 'CE' in loss_function:
y = T.matrix(dtype='int32') if out_every_t else T.vector(dtype='int32')
else:
# y will be n_fram x n_output x n_utt
y = T.tensor3() if out_every_t else T.matrix()
return x, y
def IRNN(n_input, n_hidden, n_output, input_type='real', out_every_t=False, loss_function='CE'):
np.random.seed(1234)
rng = np.random.RandomState(1234)
x, y = initialize_data_nodes(loss_function, input_type, out_every_t)
inputs = [x, y]
h_0 = theano.shared(np.zeros((1, n_hidden), dtype=theano.config.floatX))
V = initialize_matrix(n_input, n_hidden, 'V', rng)
W = theano.shared(np.identity(n_hidden, dtype=theano.config.floatX))
out_mat = initialize_matrix(n_hidden, n_output, 'out_mat', rng)
hidden_bias = theano.shared(np.zeros((n_hidden,), dtype=theano.config.floatX))
out_bias = theano.shared(np.zeros((n_output,), dtype=theano.config.floatX))
parameters = [h_0, V, W, out_mat, hidden_bias, out_bias]
def recurrence(x_t, y_t, h_prev, cost_prev, acc_prev, V, W, hidden_bias, out_mat, out_bias):
if loss_function == 'CE':
data_lin_output = V[x_t]
else:
data_lin_output = T.dot(x_t, V)
h_t = T.nnet.relu(T.dot(h_prev, W) + data_lin_output + hidden_bias.dimshuffle('x', 0))
if out_every_t:
lin_output = T.dot(h_t, out_mat) + out_bias.dimshuffle('x', 0)
cost_t, acc_t = compute_cost_t(lin_output, loss_function, y_t)
else:
cost_t = theano.shared(np.float32(0.0))
acc_t = theano.shared(np.float32(0.0))
return h_t, cost_t, acc_t
non_sequences = [V, W, hidden_bias, out_mat, out_bias]
h_0_batch = T.tile(h_0, [x.shape[1], 1])
if out_every_t:
sequences = [x, y]
else:
sequences = [x, T.tile(theano.shared(np.zeros((1,1), dtype=theano.config.floatX)), [x.shape[0], 1, 1])]
outputs_info = [h_0_batch, theano.shared(np.float32(0.0)), theano.shared(np.float32(0.0))]
[hidden_states, cost_steps, acc_steps], updates = theano.scan(fn=recurrence,
sequences=sequences,
non_sequences=non_sequences,
outputs_info = outputs_info)
if not out_every_t:
lin_output = T.dot(hidden_states[-1,:,:], out_mat) + out_bias.dimshuffle('x', 0)
costs = compute_cost_t(lin_output, loss_function, y)
else:
cost = cost_steps.mean()
accuracy = acc_steps.mean()
costs = [cost, accuracy]
return inputs, parameters, costs
def tanhRNN(n_input, n_hidden, n_output, input_type='real', out_every_t=False, loss_function='CE'):
np.random.seed(1234)
rng = np.random.RandomState(1234)
x, y = initialize_data_nodes(loss_function, input_type, out_every_t)
inputs = [x, y]
h_0 = theano.shared(np.zeros((1, n_hidden), dtype=theano.config.floatX))
V = initialize_matrix(n_input, n_hidden, 'V', rng)
W = initialize_matrix(n_hidden, n_hidden, 'W', rng)
out_mat = initialize_matrix(n_hidden, n_output, 'out_mat', rng)
hidden_bias = theano.shared(np.zeros((n_hidden,), dtype=theano.config.floatX))
out_bias = theano.shared(np.zeros((n_output,), dtype=theano.config.floatX))
parameters = [h_0, V, W, out_mat, hidden_bias, out_bias]
def recurrence(x_t, y_t, h_prev, cost_prev, acc_prev, V, W, hidden_bias, out_mat, out_bias):
if loss_function == 'CE':
data_lin_output = V[x_t]
else:
data_lin_output = T.dot(x_t, V)
h_t = T.tanh(T.dot(h_prev, W) + data_lin_output + hidden_bias.dimshuffle('x', 0))
if out_every_t:
lin_output = T.dot(h_t, out_mat) + out_bias.dimshuffle('x', 0)
cost_t, acc_t = compute_cost_t(lin_output, loss_function, y_t)
else:
cost_t = theano.shared(np.float32(0.0))
acc_t = theano.shared(np.float32(0.0))
return h_t, cost_t, acc_t
non_sequences = [V, W, hidden_bias, out_mat, out_bias]
h_0_batch = T.tile(h_0, [x.shape[1], 1])
if out_every_t:
sequences = [x, y]
else:
sequences = [x, T.tile(theano.shared(np.zeros((1,1), dtype=theano.config.floatX)), [x.shape[0], 1, 1])]
outputs_info = [h_0_batch, theano.shared(np.float32(0.0)), theano.shared(np.float32(0.0))]
[hidden_states, cost_steps, acc_steps], updates = theano.scan(fn=recurrence,
sequences=sequences,
non_sequences=non_sequences,
outputs_info=outputs_info)
if not out_every_t:
lin_output = T.dot(hidden_states[-1,:,:], out_mat) + out_bias.dimshuffle('x', 0)
costs = compute_cost_t(lin_output, loss_function, y)
else:
cost = cost_steps.mean()
accuracy = acc_steps.mean()
costs = [cost, accuracy]
return inputs, parameters, costs
def LSTM(n_input, n_hidden, n_output, input_type='real', out_every_t=False, loss_function='CE',flag_use_mask=False,flag_return_lin_output=False,flag_return_hidden_states=False,cost_weight=None,cost_transform=None,seed=1234):
np.random.seed(seed)
rng = np.random.RandomState(seed)
W_i = initialize_matrix(n_input, n_hidden, 'W_i', rng)
W_f = initialize_matrix(n_input, n_hidden, 'W_f', rng)
W_c = initialize_matrix(n_input, n_hidden, 'W_c', rng)
W_o = initialize_matrix(n_input, n_hidden, 'W_o', rng)
U_i = initialize_matrix(n_hidden, n_hidden, 'U_i', rng)
U_f = initialize_matrix(n_hidden, n_hidden, 'U_f', rng)
U_c = initialize_matrix(n_hidden, n_hidden, 'U_c', rng)
U_o = initialize_matrix(n_hidden, n_hidden, 'U_o', rng)
V_o = initialize_matrix(n_hidden, n_hidden, 'V_o', rng)
b_i = theano.shared(np.zeros((n_hidden,), dtype=theano.config.floatX))
b_f = theano.shared(np.ones((n_hidden,), dtype=theano.config.floatX))
b_c = theano.shared(np.zeros((n_hidden,), dtype=theano.config.floatX))
b_o = theano.shared(np.zeros((n_hidden,), dtype=theano.config.floatX))
h_0 = theano.shared(np.zeros((1, n_hidden), dtype=theano.config.floatX))
state_0 = theano.shared(np.zeros((1, n_hidden), dtype=theano.config.floatX))
out_mat = initialize_matrix(n_hidden, n_output, 'out_mat', rng)
out_bias = theano.shared(np.zeros((n_output,), dtype=theano.config.floatX))
parameters = [W_i, W_f, W_c, W_o, U_i, U_f, U_c, U_o, V_o, b_i, b_f, b_c, b_o, h_0, state_0, out_mat, out_bias]
x, y = initialize_data_nodes(loss_function, input_type, out_every_t)
if flag_use_mask:
if loss_function == 'CE':
ymask = T.matrix(dtype='int8') if out_every_t else T.vector(dtype='int8')
else:
# y will be n_fram x n_output x n_utt
ymask = T.tensor3(dtype='int8') if out_every_t else T.matrix(dtype='int8')
def recurrence(x_t, y_t, ymask_t, h_prev, state_prev, cost_prev, acc_prev,
W_i, W_f, W_c, W_o, U_i, U_f, U_c, U_o, V_o, b_i, b_f, b_c, b_o, out_mat, out_bias):
if (loss_function == 'CE') and (input_type=='categorical'):
x_t_W_i = W_i[x_t]
x_t_W_c = W_c[x_t]
x_t_W_f = W_f[x_t]
x_t_W_o = W_o[x_t]
else:
x_t_W_i = T.dot(x_t, W_i)
x_t_W_c = T.dot(x_t, W_c)
x_t_W_f = T.dot(x_t, W_f)
x_t_W_o = T.dot(x_t, W_o)
input_t = T.nnet.sigmoid(x_t_W_i + T.dot(h_prev, U_i) + b_i.dimshuffle('x', 0))
candidate_t = T.tanh(x_t_W_c + T.dot(h_prev, U_c) + b_c.dimshuffle('x', 0))
forget_t = T.nnet.sigmoid(x_t_W_f + T.dot(h_prev, U_f) + b_f.dimshuffle('x', 0))
state_t = input_t * candidate_t + forget_t * state_prev
output_t = T.nnet.sigmoid(x_t_W_o + T.dot(h_prev, U_o) + T.dot(state_t, V_o) + b_o.dimshuffle('x', 0))
h_t = output_t * T.tanh(state_t)
if out_every_t:
lin_output = T.dot(h_t, out_mat) + out_bias.dimshuffle('x', 0)
if flag_use_mask:
cost_t, acc_t = compute_cost_t(lin_output, loss_function, y_t, ymask_t=ymask_t)
else:
cost_t, acc_t = compute_cost_t(lin_output, loss_function, y_t)
else:
cost_t = theano.shared(np.float32(0.0))
acc_t = theano.shared(np.float32(0.0))
return h_t, state_t, cost_t, acc_t
non_sequences = [W_i, W_f, W_c, W_o, U_i, U_f, U_c, U_o, V_o, b_i, b_f, b_c, b_o, out_mat, out_bias]
h_0_batch = T.tile(h_0, [x.shape[1], 1])
state_0_batch = T.tile(state_0, [x.shape[1], 1])
if out_every_t:
if flag_use_mask:
sequences = [x, y, ymask]
else:
sequences = [x, y, T.tile(theano.shared(np.ones((1,1),dtype=theano.config.floatX)), [x.shape[0], 1, 1])]
else:
if flag_use_mask:
sequences = [x, T.tile(theano.shared(np.zeros((1,1), dtype=theano.config.floatX)), [x.shape[0], 1, 1]), T.tile(theano.shared(np.ones((1,1),dtype=theano.config.floatX)), [x.shape[0], 1, 1])]
else:
sequences = [x, T.tile(theano.shared(np.zeros((1,1), dtype=theano.config.floatX)), [x.shape[0], 1, 1]), T.tile(theano.shared(np.ones((1,1),dtype=theano.config.floatX)),[x.shape[0], 1, 1])]
outputs_info = [h_0_batch, state_0_batch, theano.shared(np.float32(0.0)), theano.shared(np.float32(0.0))]
[hidden_states, states, cost_steps, acc_steps], updates = theano.scan(fn=recurrence,
sequences=sequences,
non_sequences=non_sequences,
outputs_info=outputs_info)
if flag_return_lin_output:
#if output_type=='complex':
# lin_output = T.dot(hidden_states, out_mat) + out_bias.dimshuffle('x',0)
#elif output_type=='real':
lin_output = T.dot(hidden_states, out_mat) + out_bias.dimshuffle('x',0)
if not out_every_t:
lin_output = T.dot(hidden_states[-1,:,:], out_mat) + out_bias.dimshuffle('x', 0)
costs = compute_cost_t(lin_output, loss_function, y)
cost=costs[0]
accuracy=costs[1]
else:
if (cost_transform=='magTimesPhase'):
cosPhase=T.cos(lin_output)
sinPhase=T.sin(lin_output)
linMag=np.sqrt(10**(x/10.0)-1e-5)
yest_real=linMag*cosPhase
yest_imag=linMag*sinPhase
yest=T.concatenate([yest_real,yest_imag],axis=2)
mse=(yest-y)**2
cost_steps=T.mean(mse*ymask[:,:,0].dimshuffle(0,1,'x'),axis=2)
elif cost_transform is not None:
# assume that cost_transform is an inverse DFT followed by synthesis windowing
lin_output_real=lin_output[:,:,:n_output//2]
lin_output_imag=lin_output[:,:,n_output//2:]
lin_output_sym_real=T.concatenate([lin_output_real,lin_output_real[:,:,n_output//2-2:0:-1]],axis=2)
lin_output_sym_imag=T.concatenate([-lin_output_imag,lin_output_imag[:,:,n_output//2-2:0:-1]],axis=2)
lin_output_sym=T.concatenate([lin_output_sym_real,lin_output_sym_imag],axis=2)
yest_xform=T.dot(lin_output_sym,cost_transform)
# apply synthesis window
yest_xform=yest_xform*cost_weight.dimshuffle('x','x',0)
y_real=y[:,:,:n_output//2]
y_imag=y[:,:,n_output//2:]
y_sym_real=T.concatenate([y_real,y_real[:,:,n_output//2-2:0:-1]],axis=2)
y_sym_imag=T.concatenate([-y_imag,y_imag[:,:,n_output//2-2:0:-1]],axis=2)
y_sym=T.concatenate([y_sym_real,y_sym_imag],axis=2)
y_xform=T.dot(y_sym,cost_transform)
# apply synthesis window
y_xform=y_xform*cost_weight.dimshuffle('x','x',0)
mse=(y_xform-yest_xform)**2
cost_steps=T.mean(mse*ymask[:,:,0].dimshuffle(0,1,'x'),axis=2)
cost = cost_steps.mean()
accuracy = acc_steps.mean()
costs = [cost, accuracy]
if (loss_function=='CE_of_sum'):
yest = T.sum(lin_output,axis=0) #sum over time_steps, yest is Nseq x n_output
yest_softmax = T.nnet.softmax(yest)
cost = T.nnet.categorical_crossentropy(yest_softmax, y[0,:]).mean()
accuracy = T.eq(T.argmax(yest, axis=-1), y[0,:]).mean(dtype=theano.config.floatX)
costs = [cost,accuracy]
if flag_return_lin_output:
costs = [cost, accuracy, lin_output]
if flag_return_hidden_states:
costs = costs + [hidden_states]
#nmse_local = ymask.dimshuffle(0,1)*( (lin_output-y)**2 )/( 1e-5 + y**2 )
nmse_local = theano.shared(np.float32(0.0))
costs = costs + [nmse_local]
costs = costs + [cost_steps]
if flag_use_mask:
return [x, y, ymask], parameters, costs
else:
return [x, y], parameters, costs
def initialize_unitary(n,impl,rng,name_suffix='',n_Givens=0,init='rand'):
if (impl == 'adhoc'):
# ad-hoc parameterization of Arjovsky, Shah, and Bengio 2015
reflection = initialize_matrix(2, 2*n, 'reflection'+name_suffix, rng)
theta = theano.shared(np.asarray(rng.uniform(low=-np.pi,
high=np.pi,
size=(3, n)),
dtype=theano.config.floatX),
name='theta'+name_suffix)
index_permute = rng.permutation(n)
index_permute_long = np.concatenate((index_permute, index_permute + n))
Wparams = [theta,reflection,index_permute_long]
elif (impl == 'full'):
"""
# fixed full unitary matrix
Z=rng.randn(n,n).astype(np.complex64)+1j*rng.randn(n,n).astype(np.complex64)
UZ, SZ, VZ=np.linalg.svd(Z)
Wc=np.dot(UZ,VZ)
WcRe=np.transpose(np.real(Wc))
WcIm=np.transpose(np.imag(Wc))
Waug = theano.shared(np.concatenate( [np.concatenate([WcRe,WcIm],axis=1),np.concatenate([(-1)*WcIm,WcRe],axis=1)], axis=0),name='Waug'+name_suffix)
"""
if (init=='rand'):
# use ad-hoc for initialization
reflection = initialize_matrix(2, 2*n, 'reflection'+name_suffix, rng)
theta = theano.shared(np.asarray(rng.uniform(low=-np.pi,
high=np.pi,
size=(3, n)),
dtype=theano.config.floatX),
name='theta'+name_suffix)
index_permute = rng.permutation(n)
index_permute_long = np.concatenate((index_permute, index_permute + n))
WcRe=np.eye(n).astype(np.float32)
WcIm=np.zeros((n,n)).astype(np.float32)
Waug=np.concatenate( [np.concatenate([WcRe,WcIm],axis=1),np.concatenate([WcIm,WcRe],axis=1)], axis=0)
swap_re_im = np.concatenate((np.arange(n, 2*n), np.arange(n)))
Waug_variable=times_unitary(Waug,n,swap_re_im,[theta,reflection,index_permute_long],'adhoc')
Waug=theano.shared(Waug_variable.eval().astype(np.float32),name='Waug'+name_suffix)
elif (init=='identity'):
WcRe=np.eye(n).astype(np.float32)
WcIm=np.zeros((n,n)).astype(np.float32)
Waug_np=np.concatenate( [np.concatenate([WcRe,WcIm],axis=1),np.concatenate([WcIm,WcRe],axis=1)], axis=0)
Waug=theano.shared(Waug_np,name='Waug'+name_suffix)
Wparams = [Waug]
elif (impl == 'givens'):
# composition of Givens rotations
gphipsi = theano.shared(np.asarray(rng.uniform(low=-np.pi,
high=np.pi,
size=(n_Givens, 1, 2)),
dtype=theano.config.floatX),
name='gphipsi')
gchi = theano.shared(np.asarray(np.arccos(rng.uniform(low=0,
high=1,
size=(n_Givens, 1, 1))),
dtype=theano.config.floatX),
name='gchi')
#galp = theano.shared(np.asarray(rng.uniform(low=-np.pi,
# high=np.pi,
# size=(1, 1)),
# dtype=theano.config.floatX),
# name='galp')
# build indices for Givens rotations:
Nchoose2=(n)*(n-1)/2;
# generate a random permutation of 1:(N choose 2)
Nchoose2perm=rng.permutation(Nchoose2)
# take the first n_Givens values
Nchoose2perm=Nchoose2perm[:n_Givens]
# initialize Givens indices
gidx_np=np.zeros((n_Givens,1,2),dtype=np.int32)
ig=0 #absolute Givens index
ig_sel=0 #indices for selected Givens indices
for ig1 in range(0,n):
for ig2 in range(ig1+1,n):
if ig in Nchoose2perm:
ig_sel=np.where(Nchoose2perm==ig)
ig_sel=ig_sel[0][0]
gidx_np[ig_sel,0,:]=np.reshape([ig1,ig2],(1,1,2))
ig=ig+1
gidx=theano.shared(gidx_np)
Wparams = [gphipsi, gchi, gidx]
return Wparams
def initialize_complex_RNN_layer(n_hidden,Wimpl,rng,hidden_bias_mean,name_suffix='',n_Givens=0,hidden_bias_init='rand',h_0_init='rand',W_init='rand'):
# hidden bias
if (hidden_bias_init=='rand'):
hidden_bias = theano.shared(np.asarray(hidden_bias_mean+rng.uniform(low=-0.01,
high=0.01,
size=(n_hidden,)),
dtype=theano.config.floatX),
name='hidden_bias'+name_suffix)
elif (hidden_bias_init=='zero'):
hidden_bias = theano.shared(np.zeros((n_hidden,)).astype(theano.config.floatX),name='hidden_bias'+name_suffix)
else:
raise ValueError("Unknown initialization method %s for hidden_bias" % hidden_bias_init)
# initial state h_0
h_0_size=(1,2*n_hidden)
if (h_0_init=='rand'):
bucket = np.sqrt(3. / 2 / n_hidden)
h_0 = theano.shared(np.asarray(rng.uniform(low=-bucket,
high=bucket,
size=h_0_size),
dtype=theano.config.floatX),
name='h_0'+name_suffix)
elif (h_0_init=='zero'):
h_0 = theano.shared(np.zeros(h_0_size).astype(theano.config.floatX),name='h_0'+name_suffix)
else:
raise ValueError("Unknown initialization method %s for h_0" % h_0_init)
# unitary transition matrix W
Wparams = initialize_unitary(n_hidden,Wimpl,rng,name_suffix=name_suffix,n_Givens=n_Givens,init=W_init)
"""
if (Wimpl == 'adhoc'):
# ad-hoc parameterization of Arjovsky, Shah, and Bengio 2015
reflection = initialize_matrix(2, 2*n_hidden, 'reflection'+name_suffix, rng)
theta = theano.shared(np.asarray(rng.uniform(low=-np.pi,
high=np.pi,
size=(3, n_hidden)),
dtype=theano.config.floatX),
name='theta'+name_suffix)
index_permute = np.random.permutation(n_hidden)
index_permute_long = np.concatenate((index_permute, index_permute + n_hidden))
Wparams = [theta,reflection,index_permute_long]
elif (Wimpl == 'full'):
# fixed full unitary matrix
Z=prng_Givens.randn(n_hidden,n_hidden).astype(np.complex64)+1j*prng_Givens.randn(n_hidden,n_hidden).astype(np.complex64)
UZ, SZ, VZ=np.linalg.svd(Z)
Wc=np.dot(UZ,VZ)
WcRe=np.transpose(np.real(Wc))
WcIm=np.transpose(np.imag(Wc))
Waug = theano.shared(np.concatenate( [np.concatenate([WcRe,WcIm],axis=1),np.concatenate([(-1)*WcIm,WcRe],axis=1)], axis=0),name='Waug'+name_suffix)
Wparams = [Waug]
elif (Wimpl == 'givens'):
# composition of Givens rotations
gphipsi = theano.shared(np.asarray(rng.uniform(low=-np.pi,
high=np.pi,
size=(n_Givens, 1, 2)),
dtype=theano.config.floatX),
name='gphipsi')
gchi = theano.shared(np.asarray(np.arccos(rng.uniform(low=0,
high=1,
size=(n_Givens, 1, 1))),
dtype=theano.config.floatX),
name='gchi')
#galp = theano.shared(np.asarray(rng.uniform(low=-np.pi,
# high=np.pi,
# size=(1, 1)),
# dtype=theano.config.floatX),
# name='galp')
# build indices for Givens rotations:
Nchoose2=(n_hidden)*(n_hidden-1)/2;
# generate a random permutation of 1:(N choose 2)
Nchoose2perm=prng_Givens.permutation(Nchoose2)
# take the first n_Givens values
Nchoose2perm=Nchoose2perm[:n_Givens]
# initialize Givens indices
gidx_np=np.zeros((n_Givens,1,2),dtype=np.int32)
ig=0 #absolute Givens index
ig_sel=0 #indices for selected Givens indices
for ig1 in range(0,n_hidden):
for ig2 in range(ig1+1,n_hidden):
if ig in Nchoose2perm:
ig_sel=np.where(Nchoose2perm==ig)
ig_sel=ig_sel[0][0]
gidx_np[ig_sel,0,:]=np.reshape([ig1,ig2],(1,1,2))
ig=ig+1
gidx=theano.shared(gidx_np)
Wparams = [gphipsi, gchi, gidx]
"""
return hidden_bias, h_0, Wparams
def times_unitary(x,n,swap_re_im,Wparams,Wimpl):
# multiply tensor x on the right by the unitary matrix W parameterized by Wparams
if (Wimpl == 'adhoc'):
theta=Wparams[0]
reflection=Wparams[1]
index_permute_long=Wparams[2]
step1 = times_diag(x, n, theta[0,:], swap_re_im)
step2 = do_fft(step1, n)
step3 = times_reflection(step2, n, reflection[0,:])
step4 = vec_permutation(step3, index_permute_long)
step5 = times_diag(step4, n, theta[1,:], swap_re_im)
step6 = do_ifft(step5, n)
step7 = times_reflection(step6, n, reflection[1,:])
step8 = times_diag(step7, n, theta[2,:], swap_re_im)
y = step8
elif (Wimpl == 'full'):
Waug=Wparams[0]
y = T.dot(x,Waug)
elif (Wimpl == 'givens'):
gphipsi=Wparams[0]
gchi=Wparams[1]
gidx=Wparams[2]
# scan method for composing Givens rotations
givens_steps=h_prev #output of this inner scan should be I x 2*n
givens_outputs, updates = theano.scan(fn=lambda gphipsi,
gchi,
gidx,
Gh_prev:
times_givens(Gh_prev,
n,
T.reshape(T.concatenate([gphipsi,gchi],axis=1),[3]),
T.reshape(gidx,[2])),
sequences=[gphipsi,gchi,gidx],
outputs_info=givens_steps)
# output of composition of Givens rotations:
y=T.reshape(givens_outputs[-1,:,:],(givens_outputs.shape[1],givens_outputs.shape[2]))
return y
def complex_RNN(n_input, n_hidden, n_output, input_type='real', out_every_t=False, loss_function='CE', output_type='real', fidx=None, flag_return_lin_output=False,name_suffix='',x_spec=None,flag_feed_forward=False,flag_use_mask=False,hidden_bias_mean=0.0,lam=0.0,Wimpl="adhoc",n_Givens=None,prng_Givens=np.random.RandomState(),Vnorm=0.0,Unorm=0.0,flag_return_hidden_states=False,n_layers=1,cost_weight=None,cost_transform=None,flag_noComplexConstraint=0,seed=1234,V_init='rand',U_init='rand',W_init='rand',h_0_init='rand',out_bias_init='rand',hidden_bias_init='rand',flag_add_input_to_output=False,flag_connect_input_to_layers=False,flag_broadcast_silo=False):
np.random.seed(seed)
rng = np.random.RandomState(seed)
# Initialize input and output parameters: V, U, out_bias0
# input matrix V
if flag_noComplexConstraint and (input_type=='complex'):
V = initialize_matrix(2*n_input, 2*n_hidden, 'V'+name_suffix, rng, init=V_init)
Vaug = V
else:
V = initialize_matrix(n_input, 2*n_hidden, 'V'+name_suffix, rng, init=V_init)
if (Vnorm>0.0):
# normalize the rows of V by the L2 norm (note that the variable V here is actually V^T, so we normalize the columns)
Vr = V[:,:n_hidden]
Vi = V[:,n_hidden:]
Vnorms = T.sqrt(1e-5 + T.sum(Vr**2,axis=0,keepdims=True) + T.sum(Vi**2,axis=0,keepdims=True))
Vn = T.concatenate( [Vr/(1e-5 + Vnorms), Vi/(1e-5 + Vnorms)], axis=1)
# scale so row norms are desired number
Vn = V*T.sqrt(Vnorm)
else:
Vn = V
if input_type=='complex':
Vim = T.concatenate([ (-1)*Vn[:,n_hidden:], Vn[:,:n_hidden] ],axis=1) #concatenate along columns to make [-V_I, V_R]
Vaug = T.concatenate([ Vn, Vim ],axis=0) #concatenate along rows to make [V_R, V_I; -V_I, V_R]
# output matrix U
if flag_noComplexConstraint and (input_type=='complex'):
U = initialize_matrix(2*n_hidden,2*n_output,'U'+name_suffix,rng, init=U_init)
Uaug=U
else:
U = initialize_matrix(2 * n_hidden, n_output, 'U'+name_suffix, rng, init=U_init)
if (Unorm > 0.0):
# normalize the cols of U by the L2 norm (note that the variable U here is actually U^H, so we normalize the rows)
Ur = U[:n_hidden,:]
Ui = U[n_hidden:,:]
Unorms = T.sqrt(1e-5 + T.sum(Ur**2,axis=1,keepdims=True) + T.sum(Ui**2,axis=1,keepdims=True))
Un = T.concatenate([ Ur/(1e-5 + Unorms), Ui/(1e-5 + Unorms) ], axis=0)
# scale so col norms are desired number
Un = Un*T.sqrt(Unorm)
else:
Un = U
if output_type=='complex':
Uim = T.concatenate([ (-1)*Un[n_hidden:,:], Un[:n_hidden,:] ],axis=0) #concatenate along rows to make [-U_I; U_R]
Uaug = T.concatenate([ Un,Uim ],axis=1) #concatante along cols to make [U_R, -U_I; U_I, U_R]
# note that this is a little weird compared to the convention elsewhere in this code that
# right-multiplication real-composite form is [A, B; -B, A]. The weirdness is because of the original
# implementation, which initialized U for real-valued outputs as U=[A; B], which really should have
# been U=[A; -B]
# output bias out_bias
if output_type=='complex':
out_bias = theano.shared(np.zeros((2*n_output,), dtype=theano.config.floatX), name='out_bias'+name_suffix)
else:
out_bias = theano.shared(np.zeros((n_output,), dtype=theano.config.floatX), name='out_bias'+name_suffix)
# initialize layer 1 parameters
hidden_bias, h_0, Wparams = initialize_complex_RNN_layer(n_hidden,Wimpl,rng,hidden_bias_mean,name_suffix=name_suffix,n_Givens=n_Givens,hidden_bias_init=hidden_bias_init,h_0_init=h_0_init,W_init=W_init)
# extract recurrent parameters into this namespace
if flag_feed_forward:
# just doing feed-foward, so remove any recurrent parameters
if (Wimpl == 'adhoc'):
#theta = theano.shared(np.float32(0.0))
h_0_size=(1,2*n_hidden)
h_0 = theano.shared(np.asarray(np.zeros(h_0_size),dtype=theano.config.floatX))
parameters = [V, U, hidden_bias, out_bias]
else:
if (Wimpl == 'adhoc'):
# ad-hoc parameterization of Arjovsky, Shah, and Bengio 2015
theta = Wparams[0]
reflection = Wparams[1]
index_permute_long = Wparams[2]
parameters = [V, U, hidden_bias, reflection, out_bias, theta, h_0]
#Wparams = [theta]
elif (Wimpl == 'full'):
# fixed full unitary matrix
Waug=Wparams[0]
parameters = [V, U, hidden_bias, out_bias, h_0, Waug]
#Wparams = [Waug]
elif (Wimpl == 'givens'):
# composition of Givens rotations
gphipsi = Wparams[0]
gchi = Wparams[1]
gidx = Wparams[2]
parameters = [V,U, hidden_bias, out_bias, h_0, gphipsi, gchi]
#Wparams = [gphipsi, gchi, gidx]
h_0_all_layers = h_0
# initialize additional layer parameters
addl_layers_params=[]
addl_layers_params_optim=[]
for i_layer in range(2,n_layers+1):
betw_layer_suffix='_L%d_to_L%d' % (i_layer-1,i_layer)
layer_suffix='_L%d' % i_layer
Wvparams_cur = initialize_unitary(n_hidden,Wimpl,rng,name_suffix=(name_suffix+betw_layer_suffix),n_Givens=n_Givens,init=W_init)
hidden_bias_cur, h_0_cur, Wparams_cur = initialize_complex_RNN_layer(n_hidden,Wimpl,rng,hidden_bias_mean,name_suffix=(name_suffix + layer_suffix),n_Givens=n_Givens,hidden_bias_init=hidden_bias_init,h_0_init=h_0_init,W_init=W_init)
addl_layers_params = addl_layers_params + Wvparams_cur + [hidden_bias_cur, h_0_cur, ] + Wparams_cur
if (Wimpl=='adhoc'):
# don't include permutation indices in the list of parameters to be optimized
addl_layers_params_optim = addl_layers_params_optim + Wvparams_cur[0:2] + [hidden_bias_cur, h_0_cur] + Wparams_cur[0:2]
else:
addl_layers_params_optim = addl_layers_params
if flag_connect_input_to_layers:
Vk = initialize_matrix(n_input, 2*n_hidden, 'V'+name_suffix+layer_suffix, rng, init=V_init)
if (Vnorm>0.0):
# normalize the rows of V by the L2 norm (note that the variable V here is actually V^T, so we normalize the columns)
Vkr = Vk[:,:n_hidden]
Vki = Vk[:,n_hidden:]
Vknorms = T.sqrt(1e-5 + T.sum(Vkr**2,axis=0,keepdims=True) + T.sum(Vki**2,axis=0,keepdims=True))
Vkn = T.concatenate( [Vkr/(1e-5 + Vknorms), Vki/(1e-5 + Vknorms)], axis=1)
# scale so row norms are desired number
Vkn = Vk*T.sqrt(Vknorm)
else:
Vkn = Vk
if input_type=='complex':
Vkim = T.concatenate([ (-1)*Vkn[:,n_hidden:], Vkn[:,:n_hidden] ],axis=1) #concatenate along columns to make [-V_I, V_R]
Vkaug = T.concatenate([ Vkn, Vkim ],axis=0) #concatenate along rows to make [V_R, V_I; -V_I, V_R]
addl_layers_params = addl_layers_params + [Vkaug]
else:
addl_layers_params = addl_layers_params + [Vkn]
addl_layers_params_optim = addl_layers_params_optim + [Vk]
h_0_all_layers = T.concatenate([h_0_all_layers,h_0_cur],axis=1)
parameters = parameters + addl_layers_params_optim
# initialize data nodes
x, y = initialize_data_nodes(loss_function, input_type, out_every_t)
if flag_use_mask:
if 'CE' in loss_function:
ymask = T.matrix(dtype='int8') if out_every_t else T.vector(dtype='int8')
else:
# y will be n_fram x n_output x n_utt
ymask = T.tensor3(dtype='int8') if out_every_t else T.matrix(dtype='int8')
if x_spec is not None:
# x is specified, set x to this:
x = x_spec
swap_re_im = np.concatenate((np.arange(n_hidden, 2*n_hidden), np.arange(n_hidden)))
# define the recurrence used by theano.scan
def recurrence(x_t, y_t, ymask_t, h_prev, cost_prev, acc_prev, V, hidden_bias, out_bias, U, *argv):
# h_prev is of size n_batch x n_layers*2*n_hidden
# strip W parameters off variable arguments list
if (Wimpl=='full'):
Wparams=argv[0:1]
argv=argv[1:]
else:
Wparams=argv[0:3]
argv=argv[3:]
if not flag_feed_forward:
# Compute hidden linear transform: W h_{t-1}
h_prev_layer1 = h_prev[:,0:2*n_hidden]
hidden_lin_output = times_unitary(h_prev_layer1,n_hidden,swap_re_im,Wparams,Wimpl)
# Compute data linear transform
if ('CE' in loss_function) and (input_type=='categorical'):
# inputs are categorical, so just use them as indices into V
data_lin_output = V[T.cast(x_t, 'int32')]
else:
# second dimension of real-valued x_t should be of size n_input, first dimension of V should be of size n_input
# (or augmented, where the dimension of summation is 2*n_input and V is of real/imag. augmented form)
data_lin_output = T.dot(x_t, V)
# Total linear output
if not flag_feed_forward:
lin_output = hidden_lin_output + data_lin_output
else:
lin_output = data_lin_output
# Apply non-linearity ----------------------------
# scale RELU nonlinearity
# add a little bit to sqrt argument to ensure stable gradients,
# since gradient of sqrt(x) is -0.5/sqrt(x)
modulus = T.sqrt(1e-9+lin_output**2 + lin_output[:, swap_re_im]**2)
rescale = T.maximum(modulus + T.tile(hidden_bias, [2]).dimshuffle('x', 0), 0.) / (modulus)
h_t = lin_output * rescale
h_t_all_layers = h_t
# Compute additional recurrent layers
for i_layer in range(2,n_layers+1):
# strip Wv parameters off variable arguments list
if (Wimpl=='full'):
Wvparams_cur=argv[0:1]
argv=argv[1:]
else:
Wvparams_cur=argv[0:3]
argv=argv[3:]
# strip hidden_bias for this layer off argv
hidden_bias_cur = argv[0]
argv=argv[1:]
# strip h_0 for this layer off argv
#h_0_cur = argv[0] #unused, since h_0_all_layers is all layers' h_0s concatenated
argv=argv[1:]
# strip W parameters off variable arguments list
if (Wimpl=='full'):
Wparams_cur=argv[0:1]
argv=argv[1:]
else:
Wparams_cur=argv[0:3]
argv=argv[3:]
if flag_connect_input_to_layers:
# strip layer-dependent input transforms off variable arugments list
Vk=argv[0]
argv=argv[1:]
# Compute the linear parts of the layer ----------
if not flag_feed_forward:
# get previous hidden state h_{t-1} for this layer:
if flag_broadcast_silo:
# use top of the previous iteration stack for h_{t-1}
h_prev_cur = h_prev[:,(n_layers-1)*2*n_hidden:n_layers*2*n_hidden]
else:
h_prev_cur = h_prev[:,(i_layer-1)*2*n_hidden:i_layer*2*n_hidden]
# Compute hidden linear transform: W h_{t-1}
hidden_lin_output_cur = times_unitary(h_prev_cur,n_hidden,swap_re_im,Wparams_cur,Wimpl)
# Compute "data linear transform", which for this intermediate layer is the previous layer's h_t transformed by Wv
data_lin_output_cur = times_unitary(h_t,n_hidden,swap_re_im,Wvparams_cur,Wimpl)
# Total linear output
if not flag_feed_forward:
lin_output_cur = hidden_lin_output_cur + data_lin_output_cur
else:
lin_output_cur = data_lin_output_cur
if flag_connect_input_to_layers:
lin_output_cur = lin_output_cur + T.dot(x_t,Vk)
# Apply non-linearity ----------------------------
# scale RELU nonlinearity
# add a little bit to sqrt argument to ensure stable gradients,
# since gradient of sqrt(x) is -0.5/sqrt(x)
modulus = T.sqrt(1e-9+lin_output_cur**2 + lin_output_cur[:, swap_re_im]**2)
rescale = T.maximum(modulus + T.tile(hidden_bias_cur, [2]).dimshuffle('x', 0), 0.) / (modulus)
h_t = lin_output_cur * rescale
h_t_all_layers = T.concatenate([h_t_all_layers,h_t],axis=1)
# assume we aren't passing any preactivation to compute_cost
z_t = None
if loss_function == 'MSEplusL1':
z_t = h_t
if out_every_t:
lin_output = T.dot(h_t, U) + out_bias.dimshuffle('x', 0)
if flag_add_input_to_output:
lin_output=lin_output + x_t
if flag_use_mask:
cost_t, acc_t = compute_cost_t(lin_output, loss_function, y_t, ymask_t=ymask_t, z_t=z_t, lam=lam)
else:
cost_t, acc_t = compute_cost_t(lin_output, loss_function, y_t, z_t=z_t, lam=lam)
else:
cost_t = theano.shared(np.float32(0.0))
acc_t = theano.shared(np.float32(0.0))
return h_t_all_layers, cost_t, acc_t
def recurrence_Givens(x_t, y_t, ymask_t, h_prev, cost_prev, acc_prev, V, hidden_bias, out_bias, U, gphipsi, gchi, gidx):
if not flag_feed_forward:
# scan method for composing Givens rotations
givens_steps=h_prev #output of this inner scan should be I x 2*n_hidden
givens_outputs, updates = theano.scan(fn=lambda gphipsi,
gchi,
gidx,
Gh_prev:
times_givens(Gh_prev,
n_hidden,
T.reshape(T.concatenate([gphipsi,gchi],axis=1),[3]),
T.reshape(gidx,[2])),
sequences=[gphipsi,gchi,gidx],
outputs_info=givens_steps)
# output of composition of Givens rotations:
hidden_lin_output=T.reshape(givens_outputs[-1,:,:],(givens_outputs.shape[1],givens_outputs.shape[2]))
# Compute data linear transform
if ('CE' in loss_function) and (input_type=='categorical'):
# inputs are categorical, so just use them as indices into V
data_lin_output = V[T.cast(x_t, 'int32')]
else:
# second dimension of real-valued x_t should be of size n_input, first dimension of V should be of size n_input
# (or augmented, where the dimension of summation is 2*n_input and V is of real/imag. augmented form)
data_lin_output = T.dot(x_t, V)
# Total linear output
if not flag_feed_forward:
lin_output = hidden_lin_output + data_lin_output
else:
lin_output = data_lin_output
# Apply non-linearity ----------------------------
# scale RELU nonlinearity
# add a little bit to sqrt argument to ensure stable gradients,
# since gradient of sqrt(x) is -0.5/sqrt(x)
modulus = T.sqrt(1e-9+lin_output**2 + lin_output[:, swap_re_im]**2)
rescale = T.maximum(modulus + T.tile(hidden_bias, [2]).dimshuffle('x', 0), 0.) / (modulus)
h_t = lin_output * rescale
# assume we aren't passing any preactivation to compute_cost
z_t = None
if loss_function == 'MSEplusL1':
z_t = h_t
if out_every_t:
lin_output = T.dot(h_t, U) + out_bias.dimshuffle('x', 0)
if flag_use_mask:
cost_t, acc_t = compute_cost_t(lin_output, loss_function, y_t, ymask_t=ymask_t, z_t=z_t, lam=lam)
else:
cost_t, acc_t = compute_cost_t(lin_output, loss_function, y_t, z_t=z_t, lam=lam)
else:
cost_t = theano.shared(np.float32(0.0))
acc_t = theano.shared(np.float32(0.0))
return h_t, cost_t, acc_t
# compute hidden states
# h_0_batch should be n_utt x n_layers*2*n_hidden, since scan goes over first dimension of x, which is the maximum STFT length in frames
h_0_batch = T.tile(h_0_all_layers, [x.shape[1], 1])
if (Wimpl=='givens'):
if input_type=='complex' and output_type=='complex':
# pass in augmented input and output transformations
non_sequences = [Vaug, hidden_bias, out_bias, Uaug, gphipsi, gchi, gidx]
elif input_type=='complex':
non_sequences = [Vaug, hidden_bias, out_bias, Un, gphipsi, gchi, gidx]
elif output_type=='complex':
non_sequences = [Vn , hidden_bias, out_bias, Uaug, gphipsi, gchi, gidx]
else:
non_sequences = [Vn , hidden_bias, out_bias, Un, gphipsi, gchi, gidx]
else:
if input_type=='complex' and output_type=='complex':
# pass in augmented input and output transformations
non_sequences = [Vaug, hidden_bias, out_bias, Uaug] + Wparams + addl_layers_params
elif input_type=='complex':
non_sequences = [Vaug, hidden_bias, out_bias, Un] + Wparams + addl_layers_params
elif output_type=='complex':
non_sequences = [Vn , hidden_bias, out_bias, Uaug] + Wparams + addl_layers_params
else:
non_sequences = [Vn , hidden_bias, out_bias, Un] + Wparams + addl_layers_params
if out_every_t:
if flag_use_mask:
sequences = [x, y, ymask]
else:
sequences = [x, y, T.tile(theano.shared(np.ones((1,1),dtype=theano.config.floatX)), [x.shape[0], 1, 1])]
else:
if flag_use_mask:
sequences = [x, T.tile(theano.shared(np.zeros((1,1), dtype=theano.config.floatX)), [x.shape[0], 1, 1]), T.tile(theano.shared(np.ones((1,1),dtype=theano.config.floatX)), [x.shape[0], 1, 1])]
else:
sequences = [x, T.tile(theano.shared(np.zeros((1,1), dtype=theano.config.floatX)), [x.shape[0], 1, 1]), T.tile(theano.shared(np.ones((1,1),dtype=theano.config.floatX)),[x.shape[0], 1, 1])]
outputs_info=[h_0_batch, theano.shared(np.float32(0.0)), theano.shared(np.float32(0.0))]
if (Wimpl=='givens'):
[hidden_states_all_layers, cost_steps, acc_steps], updates = theano.scan(fn=recurrence_Givens,
sequences=sequences,
non_sequences=non_sequences,
outputs_info=outputs_info)
else:
[hidden_states_all_layers, cost_steps, acc_steps], updates = theano.scan(fn=recurrence,
sequences=sequences,
non_sequences=non_sequences,
outputs_info=outputs_info)
# get hidden states of last layer
hidden_states = hidden_states_all_layers[:,:,(n_layers-1)*2*n_hidden:]
if flag_return_lin_output:
if output_type=='complex':
lin_output = T.dot(hidden_states, Uaug) + out_bias.dimshuffle('x',0)
else:
lin_output = T.dot(hidden_states, Un) + out_bias.dimshuffle('x',0)
if flag_add_input_to_output:
lin_output = lin_output + x
if not out_every_t:
#TODO: here, if flag_use_mask is set, need to use a for-loop to select the desired time-step for each utterance
lin_output = T.dot(hidden_states[-1,:,:], Un) + out_bias.dimshuffle('x', 0)
z_t = None
if loss_function == 'MSEplusL1':
z_t = hidden_states[-1,:,:]
costs = compute_cost_t(lin_output, loss_function, y, z_t=z_t, lam=lam)
cost=costs[0]
accuracy=costs[1]
else:
if (cost_transform=='magTimesPhase'):
cosPhase=T.cos(lin_output)
sinPhase=T.sin(lin_output)
linMag=np.sqrt(10**(x/10.0)-1e-5)
yest_real=linMag*cosPhase
yest_imag=linMag*sinPhase
yest=T.concatenate([yest_real,yest_imag],axis=2)
mse=(yest-y)**2
cost_steps=T.mean(mse*ymask[:,:,0].dimshuffle(0,1,'x'),axis=2)
elif cost_transform is not None:
# assume that cost_transform is an inverse DFT followed by synthesis windowing
lin_output_real=lin_output[:,:,:n_output]
lin_output_imag=lin_output[:,:,n_output:]
lin_output_sym_real=T.concatenate([lin_output_real,lin_output_real[:,:,n_output-2:0:-1]],axis=2)
lin_output_sym_imag=T.concatenate([-lin_output_imag,lin_output_imag[:,:,n_output-2:0:-1]],axis=2)
lin_output_sym=T.concatenate([lin_output_sym_real,lin_output_sym_imag],axis=2)
yest_xform=T.dot(lin_output_sym,cost_transform)
# apply synthesis window
yest_xform=yest_xform*cost_weight.dimshuffle('x','x',0)
y_real=y[:,:,:n_output]
y_imag=y[:,:,n_output:]
y_sym_real=T.concatenate([y_real,y_real[:,:,n_output-2:0:-1]],axis=2)
y_sym_imag=T.concatenate([-y_imag,y_imag[:,:,n_output-2:0:-1]],axis=2)
y_sym=T.concatenate([y_sym_real,y_sym_imag],axis=2)
y_xform=T.dot(y_sym,cost_transform)
# apply synthesis window
y_xform=y_xform*cost_weight.dimshuffle('x','x',0)
mse=(y_xform-yest_xform)**2
cost_steps=T.mean(mse*ymask[:,:,0].dimshuffle(0,1,'x'),axis=2)
cost = cost_steps.mean()
accuracy = acc_steps.mean()
if (loss_function=='CE_of_sum'):
yest = T.sum(lin_output,axis=0) #sum over time_steps, yest is Nseq x n_output
yest_softmax = T.nnet.softmax(yest)
cost = T.nnet.categorical_crossentropy(yest_softmax, y[0,:]).mean()
accuracy = T.eq(T.argmax(yest, axis=-1), y[0,:]).mean(dtype=theano.config.floatX)
if flag_return_lin_output:
costs = [cost, accuracy, lin_output]
if flag_return_hidden_states:
costs = costs + [hidden_states]
#nmse_local = ymask.dimshuffle(0,1)*( (lin_output-y)**2 )/( 1e-5 + y**2 )
nmse_local = theano.shared(np.float32(0.0))
costs = costs + [nmse_local]
costs = costs + [cost_steps]
else:
costs = [cost, accuracy]
if flag_use_mask:
return [x,y,ymask], parameters, costs
else:
return [x, y], parameters, costs
def Givens_RNN(n_input, n_hidden, n_output, input_type='real', out_every_t=False, loss_function='CE', output_type='real', fidx=None, flag_return_lin_output=False, flag_useGivensForLoop=False):
# composes {n_hidden}\choose{2} Givens rotations to form W, which is guaranteed
# to cover the entire unitary group U(n_hidden) [<NAME>, <NAME>, "Random Unitary Matrices", 1994]
np.random.seed(1234)
rng = np.random.RandomState(1234)
# Initialize parameters: theta, V_re, V_im, hidden_bias, U, out_bias, h_0
if input_type=='complex':
V = initialize_matrix(n_input, 2*n_hidden, 'V', rng)
Vim = T.concatenate([ (-1)*V[:,n_hidden:], V[:,:n_hidden] ],axis=1) #concatenate along columns to make [-V_I, V_R]
Vaug = T.concatenate([ V, Vim ],axis=0) #concatenate along rows to make [V_R, V_I; -V_I, V_R]
else:
V = initialize_matrix(n_input, 2*n_hidden, 'V', rng)
if output_type=='complex':
U = initialize_matrix(2 * n_hidden, n_output, 'U', rng)
Uim = T.concatenate([ (-1)*U[n_hidden:,:], U[:n_hidden,:] ],axis=0) #concatenate along rows to make [-U_I; U_R]
Uaug = T.concatenate([ U,Uim ],axis=1) #concatante along columns to make [U_R, U_I; -U_I, U_R]
else:
U = initialize_matrix(2 * n_hidden, n_output, 'U', rng)
hidden_bias = theano.shared(np.asarray(rng.uniform(low=-0.01,
high=0.01,
size=(n_hidden,)),
dtype=theano.config.floatX),
name='hidden_bias')
if output_type=='complex':
out_bias = theano.shared(np.zeros((2*n_output,), dtype=theano.config.floatX), name='out_bias')
else:
out_bias = theano.shared(np.zeros((n_output,), dtype=theano.config.floatX), name='out_bias')
Nchoose2=(n_hidden)*(n_hidden-1)/2;
gphipsi = theano.shared(np.asarray(rng.uniform(low=-np.pi,
high=np.pi,
size=(Nchoose2, 1, 2)),
dtype=theano.config.floatX),
name='gphipsi')
gchi = theano.shared(np.asarray(np.arccos(rng.uniform(low=0,
high=1,
size=(Nchoose2, 1, 1))),
dtype=theano.config.floatX),
name='gchi')
#galp = theano.shared(np.asarray(rng.uniform(low=-np.pi,
# high=np.pi,
# size=(1, 1)),
# dtype=theano.config.floatX),
# name='galp')
# build indices for Givens rotations:
gidx=np.zeros((Nchoose2,1,2),dtype=np.int32)
ig=0
for ig1 in range(0,n_hidden):
for ig2 in range(ig1+1,n_hidden):
gidx[ig,0,:]=np.reshape([ig1,ig2],(1,1,2))
ig=ig+1
bucket = np.sqrt(3. / 2 / n_hidden)
h_0_size=(1,2*n_hidden)
h_0 = theano.shared(np.asarray(rng.uniform(low=-bucket,
high=bucket,
size=h_0_size),
dtype=theano.config.floatX),
name='h_0')
parameters = [V, U, hidden_bias, out_bias, h_0, gphipsi, gchi]
x, y = initialize_data_nodes(loss_function, input_type, out_every_t)
swap_re_im = np.concatenate((np.arange(n_hidden, 2*n_hidden), np.arange(n_hidden)))
# define the recurrence used by theano.scan
def recurrence(x_t, y_t, h_prev, cost_prev, acc_prev, V, hidden_bias, out_bias, U, gphipsi, gchi, gidx):
# h_prev is nutt x 2*n_hidden
# Compute hidden linear transform
##complex_RNN steps
#step1 = times_diag(h_prev, n_hidden, theta[0,:], swap_re_im)
#step2 = do_fft(step1, n_hidden)
#step3 = times_reflection(step2, n_hidden, reflection[0,:])
#step4 = vec_permutation(step3, index_permute_long)
#step5 = times_diag(step4, n_hidden, theta[1,:], swap_re_im)
#step6 = do_ifft(step5, n_hidden)
#step7 = times_reflection(step6, n_hidden, reflection[1,:])
#step8 = times_diag(step7, n_hidden, theta[2,:], swap_re_im)
#
#hidden_lin_output = step8
if flag_useGivensForLoop:
# for loop method
hidden_lin_output=h_prev
ig=0; #absolute matrix index
for ig1 in range(0,n_hidden):
for ig2 in range(ig1+1,n_hidden):
hidden_lin_output=T.set_subtensor(hidden_lin_output[:,[ig1,ig2,ig1+n_hidden,ig2+n_hidden]],
times_givens(hidden_lin_output[:,[ig1,ig2,ig1+n_hidden,ig2+n_hidden]],
2,
T.reshape(T.concatenate([gphipsi[ig,:],gchi[ig,:]],axis=1),[3]),
np.asarray([1,2],dtype=np.int32)))
else:
# scan method for composing Givens rotations
givens_steps=h_prev #output of this inner scan should be I x 2*n_hidden
givens_outputs, updates = theano.scan(fn=lambda gphipsi,
gchi,
gidx,
Gh_prev:
times_givens(Gh_prev,
n_hidden,
T.reshape(T.concatenate([gphipsi,gchi],axis=1),[3]),
T.reshape(gidx,[2])),
sequences=[gphipsi,gchi,gidx],
outputs_info=[givens_steps])
# output of composition of Givens rotations:
hidden_lin_output=T.reshape(givens_outputs[-1,:,:],(givens_outputs.shape[1],givens_outputs.shape[2]))
# Compute data linear transform
if loss_function == 'CE':
# inputs are categorical, so just use them as indices into V
data_lin_output = V[T.cast(x_t, 'int32')]
# elif input_type=='complex':
# # second dimension of complex-valued x_t should be of size 2*n_input, with 0:(n_input-1) the real part and
# # n_input:end the imag. part
# data_lin_output = T.dot(x_t, V)
else:
# second dimension of real-valued x_t should be of size n_input, first dimension of V should be of size n_input
# (or augmented, where the dimension of summation is 2*n_input and V is of real/imag. augmented form)
data_lin_output = T.dot(x_t, V)
# Total linear output
lin_output = hidden_lin_output + data_lin_output
# Apply non-linearity ----------------------------
# scale RELU nonlinearity
modulus = T.sqrt(lin_output**2 + lin_output[:, swap_re_im]**2)
rescale = T.maximum(modulus + T.tile(hidden_bias, [2]).dimshuffle('x', 0), 0.) / (modulus + 1e-5)
h_t = lin_output * rescale
if out_every_t:
lin_output = T.dot(h_t, U) + out_bias.dimshuffle('x', 0)
cost_t, acc_t = compute_cost_t(lin_output, loss_function, y_t)
else:
cost_t = theano.shared(np.float32(0.0))
acc_t = theano.shared(np.float32(0.0))
return h_t, cost_t, acc_t
# compute hidden states
# h_0_batch should be n_utt x 2*n_hidden, since scan goes over first dimension of x, which is the maximum STFT length in frames
h_0_batch = T.tile(h_0, [x.shape[1], 1])
if input_type=='complex' and output_type=='complex':
# pass in augmented input and output transformations
non_sequences = [Vaug, hidden_bias, out_bias, Uaug, gphipsi, gchi, gidx]
elif input_type=='complex':
non_sequences = [Vaug, hidden_bias, out_bias, U, gphipsi, gchi, gidx]
elif output_type=='complex':
non_sequences = [V , hidden_bias, out_bias, Uaug, gphipsi, gchi, gidx]
else:
non_sequences = [V, hidden_bias, out_bias, U, gphipsi, gchi, gidx]
if out_every_t:
sequences = [x, y]
else:
sequences = [x, T.tile(theano.shared(np.zeros((1,1), dtype=theano.config.floatX)), [x.shape[0], 1, 1])]
outputs_info=[h_0_batch, theano.shared(np.float32(0.0)), theano.shared(np.float32(0.0))]
[hidden_states, cost_steps, acc_steps], updates = theano.scan(fn=recurrence,
sequences=sequences,
non_sequences=non_sequences,
outputs_info=outputs_info)
if not out_every_t:
lin_output = T.dot(hidden_states[-1,:,:], U) + out_bias.dimshuffle('x', 0)
costs = compute_cost_t(lin_output, loss_function, y)
else:
cost = cost_steps.mean()
accuracy = acc_steps.mean()
if flag_return_lin_output:
if output_type=='complex':
lin_outputs = T.dot(hidden_states, Uaug) + out_bias.dimshuffle('x',0)
elif output_type=='real':
lin_outputs = T.dot(hidden_states, U) + out_bias.dimshuffle('x',0)
costs = [cost, accuracy, lin_outputs]
else:
costs = [cost, accuracy]
return [x, y], parameters, costs
def cue_RNN(n_input, n_hidden, n_output, input_type='real', out_every_t=False, loss_function='CE', n_reflections=None, flag_telescope=True):
# composes n_reflections Householder reflection matrices to make W, defaults to telescoping
# Householder matrices, which is related to the subgroup algorithm.
if n_reflections is None:
# use n_hidden reflections by default (samples entire unitary group)
n_reflections=n_hidden
np.random.seed(1234)
rng = np.random.RandomState(1234)
# Initialize parameters: theta, V_re, V_im, hidden_bias, U, out_bias, h_0
V = initialize_matrix(n_input, 2*n_hidden, 'V', rng)
U = initialize_matrix(2 * n_hidden, n_output, 'U', rng)
hidden_bias = theano.shared(np.asarray(rng.uniform(low=-0.01,
high=0.01,
size=(n_hidden,)),
dtype=theano.config.floatX),
name='hidden_bias')
reflection = initialize_matrix(n_reflections, 2*n_hidden, 'reflection', rng)
out_bias = theano.shared(np.zeros((n_output,), dtype=theano.config.floatX), name='out_bias')
bucket = np.sqrt(3. / 2 / n_hidden)
h_0 = theano.shared(np.asarray(rng.uniform(low=-bucket,
high=bucket,
size=(1, 2 * n_hidden)),
dtype=theano.config.floatX),
name='h_0')
parameters = [V, U, hidden_bias, reflection, out_bias, h_0]
x, y = initialize_data_nodes(loss_function, input_type, out_every_t)
swap_re_im = np.concatenate((np.arange(n_hidden, 2*n_hidden), np.arange(n_hidden)))
# define the recurrence used by theano.scan
def recurrence(x_t, y_t, h_prev, cost_prev, acc_prev, V, hidden_bias, out_bias, U):
# Compute hidden linear transform
# def apply_reflection(ireflection, rinput, n_hidden, reflection):
# return times_reflection(rinput, n_hidden, reflection[ireflection,:])
#
# outputs_info=[h_prev]
# sequences=[np.arange(n_reflections)]
# non_sequences=[n_hidden,reflection]
#
# hidden_lin_output = theano.scan(fn=apply_reflection,
# outputs_info=outputs_info,
# sequences=sequences,
# non_sequences=non_sequences)
# hidden_lin_output = hidden_lin_output[-1]
step=h_prev
#for ii in range(0,n_reflections):
# step=times_reflection(step, n_hidden, reflection[ii,:])
for ii in range(n_hidden,n_hidden-n_reflections,-1):
if flag_telescope:
step=times_reflection_sub(step, n_hidden, ii, reflection[ii-1,:])
else:
step=times_reflection(step, n_hidden, reflection[ii-1,:])
hidden_lin_output = step
# Compute data linear transform
if loss_function == 'CE':
data_lin_output = V[T.cast(x_t, 'int32')]
else:
data_lin_output = T.dot(x_t, V)
# Total linear output
lin_output = hidden_lin_output + data_lin_output
# Apply non-linearity ----------------------------
# scale RELU nonlinearity
modulus = T.sqrt(lin_output**2 + lin_output[:, swap_re_im]**2)
rescale = T.maximum(modulus + T.tile(hidden_bias, [2]).dimshuffle('x', 0), 0.) / (modulus + 1e-5)
h_t = lin_output * rescale
if out_every_t:
lin_output = T.dot(h_t, U) + out_bias.dimshuffle('x', 0)
cost_t, acc_t = compute_cost_t(lin_output, loss_function, y_t)
else:
cost_t = theano.shared(np.float32(0.0))
acc_t = theano.shared(np.float32(0.0))
return h_t, cost_t, acc_t
# compute hidden states
h_0_batch = T.tile(h_0, [x.shape[1], 1])
non_sequences = [V, hidden_bias, out_bias, U]
if out_every_t:
sequences = [x, y]
else:
sequences = [x, T.tile(theano.shared(np.zeros((1,1), dtype=theano.config.floatX)), [x.shape[0], 1, 1])]
outputs_info=[h_0_batch, theano.shared(np.float32(0.0)), theano.shared(np.float32(0.0))]
[hidden_states, cost_steps, acc_steps], updates = theano.scan(fn=recurrence,
sequences=sequences,
non_sequences=non_sequences,
outputs_info=outputs_info)
if not out_every_t:
lin_output = T.dot(hidden_states[-1,:,:], U) + out_bias.dimshuffle('x', 0)
costs = compute_cost_t(lin_output, loss_function, y)
else:
cost = cost_steps.mean()
accuracy = acc_steps.mean()
costs = [cost, accuracy]
return [x, y], parameters, costs
|
462702
|
from numpy.random import random, normal
figure(4)
clf()
axis([-10, 10, -10, 10])
# Define properties of the "bouncing balls"
n = 10
pos = (20 * random(n*2) - 10).reshape(n, 2)
vel = (0.3 * normal(size=n*2)).reshape(n, 2)
sizes = normal(200, 100, size=n)
# Colors where each row is (Red, Green, Blue, Alpha). Each can go
# from 0 to 1. Alpha is the transparency.
colors = random([n, 4])
# Draw all the circles and return an object ``circles`` that allows
# manipulation of the plotted circles.
circles=scatter(pos[:,0], pos[:,1], marker=(5,0,1), s=sizes, c=colors)
for i in range(100):
pos = pos + vel
bounce = abs(pos) > 10 # Find balls that are outside walls
vel[bounce] = -vel[bounce] # Bounce if outside the walls
clf()
axis([-10, 10, -10, 10])
scatter(pos[:,0], pos[:,1], marker=(5,0,i), s=sizes, c=colors)
draw()
# circles.set_offsets(pos) # Change the positions
# draw()
|
462808
|
from rest_framework.pagination import PageNumberPagination
class PageSizeNumberPagination(PageNumberPagination):
page_size_query_param = 'page_size'
|
462862
|
import pytest
from stake.watchlist import AddToWatchlistRequest, RemoveFromWatchlistRequest
# flake8: noqa
@pytest.mark.asyncio
async def test_add_to_watchlist(tracing_client):
added = await tracing_client.watchlist.add(AddToWatchlistRequest(symbol="SPOT"))
assert added.watching
@pytest.mark.asyncio
async def test_remove_from_watchlist(tracing_client):
removed = await tracing_client.watchlist.remove(
RemoveFromWatchlistRequest(symbol="SPOT")
)
assert not removed.watching
@pytest.mark.asyncio
async def test_list_watchlist(tracing_client):
watched = await tracing_client.watchlist.list()
assert len(watched) == 6
|
462868
|
E = EuclideanSpace(3)
x, y, z = E.default_chart()[:]
v = E.vector_field(-y, x, sin(x*y*z), name='v')
sphinx_plot(v.plot(max_range=1.5, scale=0.5))
|
462891
|
import torch
import torch.nn as nn
from deepblast.ops import operators
import numba
import numpy as np
use_numba = True
@numba.njit
def _soft_max_numba(X):
M = X[0]
for i in range(1, 3):
M = X[i] if X[i] > M else M
A = np.empty_like(X)
S = 0.0
for i in range(3):
A[i] = np.exp(X[i] - M)
S += A[i]
for i in range(3):
A[i] /= S
M += np.log(S)
return M, A
@numba.njit
def _soft_max_hessian_product_numba(P, Z):
prod = P * Z
prod = np.empty_like(P)
for i in range(3):
prod[i] = P[i] * Z[i]
res = np.empty_like(P)
total = np.sum(prod)
for i in range(3):
res[i] = prod[i] - P[i] * total
return res
@numba.njit
def _forward_pass_numba(theta, A):
N, M = theta.shape
V = np.zeros((N + 1, M + 1)) # N x M
Q = np.zeros((N + 2, M + 2, 3)) # N x M x S
Q[N + 1, M + 1] = 1
m, x, y = 1, 0, 2
maxargs = np.empty(3)
for i in range(1, N + 1):
for j in range(1, M + 1):
maxargs[x] = A[i - 1, j - 1] + V[i - 1, j] # x
maxargs[m] = V[i - 1, j - 1] # m
maxargs[y] = A[i - j, 1 - 1] + V[i, j - 1] # y
v, Q[i, j] = _soft_max_numba(maxargs)
V[i, j] = theta[i - 1, j - 1] + v
Vt = V[N, M]
return Vt, Q
def _forward_pass(theta, A, operator='softmax'):
""" Forward pass to calculate DP alignment matrix
Parameters
----------
theta : torch.Tensor
Input potentials of dimension N x M.
This represents the pairwise residue match scores.
A : torch.Tensor
Gap penality (scalar valued)
operator : str
The smoothed maximum operator.
Returns
-------
Vt : torch.Tensor
Terminal alignment score (just 1 dimension)
Q : torch.Tensor
Derivatives of max theta + v of dimension N x M x S.
"""
if not use_numba or operator != 'softmax':
operator = operators[operator]
new = theta.new
N, M = theta.size()
V = new(N + 1, M + 1).zero_() # N x M
Q = new(N + 2, M + 2, 3).zero_() # N x M x S
Q[N + 1, M + 1] = 1
for i in range(1, N + 1):
for j in range(1, M + 1):
tmp = torch.Tensor([
A[i - 1, j - 1] + V[i - 1, j],
V[i - 1, j - 1],
A[i - 1, j - 1] + V[i, j - 1]
])
v, Q[i, j] = operator.max(tmp)
V[i, j] = theta[i - 1, j - 1] + v
Vt = V[N, M]
else:
Vt, Q = _forward_pass_numba(
theta.detach().cpu().numpy(),
A.detach().cpu().numpy())
Vt = torch.tensor(Vt, dtype=theta.dtype)
Q = torch.from_numpy(Q)
return Vt, Q
@numba.njit
def _backward_pass_numba(Et, Q):
m, x, y = 1, 0, 2
n_1, m_1, _ = Q.shape
N, M = n_1 - 2, m_1 - 2
E = np.zeros((N + 2, M + 2))
E[N + 1, M + 1] = Et
Q[N + 1, M + 1] = 1
for ir in range(1, N + 1):
i = N + 1 - ir
for jr in range(1, M + 1):
j = M + 1 - jr
E[i, j] = Q[i + 1, j, x] * E[i + 1, j] + \
Q[i + 1, j + 1, m] * E[i + 1, j + 1] + \
Q[i, j + 1, y] * E[i, j + 1]
return E
def _backward_pass(Et, Q):
""" Backward pass to calculate grad DP
Parameters
----------
Et : torch.Tensor
Terminal alignment edge (scalar valued).
Q : torch.Tensor
Derivatives of max (theta + v) of dimension N x M x S.
Returns
-------
E : torch.Tensor
Traceback matrix of dimension N x M x S
"""
if not use_numba:
m, x, y = 1, 0, 2
n_1, m_1, _ = Q.shape
new = Q.new
N, M = n_1 - 2, m_1 - 2
E = new(N + 2, M + 2).zero_()
E[N + 1, M + 1] = 1 * Et
Q[N + 1, M + 1] = 1
for i in reversed(range(1, N + 1)):
for j in reversed(range(1, M + 1)):
E[i, j] = Q[i + 1, j, x] * E[i + 1, j] + \
Q[i + 1, j + 1, m] * E[i + 1, j + 1] + \
Q[i, j + 1, y] * E[i, j + 1]
else:
import collections
if isinstance(Et, collections.abc.Sequence):
Et_float = float(Et[0])
else:
Et_float = float(Et)
E = torch.from_numpy(_backward_pass_numba(
Et_float, Q.detach().cpu().numpy()))
return E
@numba.njit
def _adjoint_forward_pass_numba(Q, Ztheta, ZA):
N, M = Ztheta.shape
N, M = N - 2, M - 2
Vd = np.zeros((N + 1, M + 1)) # N x M
Qd = np.zeros((N + 2, M + 2, 3)) # N x M x S
m, x, y = 1, 0, 2
maxargs = np.empty(3)
for i in range(1, N + 1):
for j in range(1, M + 1):
# Note: the indexing of ZA doesn't match Ztheta
# See forward_pass method.
maxargs[x] = ZA[i - 1, j - 1] + Vd[i - 1, j]
maxargs[m] = Vd[i - 1, j - 1]
maxargs[y] = ZA[i - 1, j - 1] + Vd[i, j - 1]
Vd[i, j] = Ztheta[i, j] + \
Q[i, j, x] * maxargs[0] + \
Q[i, j, m] * maxargs[1] + \
Q[i, j, y] * maxargs[2]
Qd[i, j] = _soft_max_hessian_product_numba(
Q[i, j], maxargs)
return Vd[N, M], Qd
def _adjoint_forward_pass(Q, Ztheta, ZA, operator='softmax'):
""" Calculate directional derivatives and Hessians.
Parameters
----------
Q : torch.Tensor
Derivatives of max theta + v of dimension N x M x S
Ztheta : torch.Tensor
Derivative of theta of dimension N x M
ZA : torch.Tensor
Derivative of gap score.
operator : str
The smoothed maximum operator.
Returns
-------
Vd : torch.Tensor
Derivatives of V of dimension N x M
Qd : torch.Tensor
Derivatives of Q of dimension N x M x S
"""
if not use_numba or operator != 'softmax':
m, x, y = 1, 0, 2
operator = operators[operator]
new = Ztheta.new
N, M = Ztheta.size()
N, M = N - 2, M - 2
Vd = new(N + 1, M + 1).zero_() # N x M
Qd = new(N + 2, M + 2, 3).zero_() # N x M x S
for i in range(1, N + 1):
for j in range(1, M + 1):
Vd[i, j] = Ztheta[i, j] + \
Q[i, j, x] * (ZA[i - 1, j - 1] + Vd[i - 1, j]) + \
Q[i, j, m] * Vd[i - 1, j - 1] + \
Q[i, j, y] * (ZA[i - 1, j - 1] + Vd[i, j - 1])
vd = torch.Tensor([(ZA[i - 1, j - 1] + Vd[i - 1, j]),
Vd[i - 1, j - 1],
(ZA[i - 1, j - 1] + Vd[i, j - 1])])
Qd[i, j] = operator.hessian_product(Q[i, j], vd)
return Vd[N, M], Qd
else:
Vd, Qd = _adjoint_forward_pass_numba(
Q.detach().cpu().numpy(), Ztheta.detach().cpu().numpy(),
ZA.detach().cpu().numpy())
Vd = torch.tensor(Vd, dtype=Ztheta.dtype)
Qd = torch.from_numpy(Qd)
return Vd, Qd
@numba.njit
def _adjoint_backward_pass_numba(E, Q, Qd):
m, x, y = 1, 0, 2
n_1, m_1, _ = Q.shape
N, M = n_1 - 2, m_1 - 2
Ed = np.zeros((N + 2, M + 2))
for ir in range(1, N + 1):
i = N + 1 - ir
for jr in range(1, M + 1):
j = M + 1 - jr
Ed[i, j] = Qd[i + 1, j, x] * E[i + 1, j] + \
Q[i + 1, j, x] * Ed[i + 1, j] + \
Qd[i + 1, j + 1, m] * E[i + 1, j + 1] + \
Q[i + 1, j + 1, m] * Ed[i + 1, j + 1] + \
Qd[i, j + 1, y] * E[i, j + 1] + \
Q[i, j + 1, y] * Ed[i, j + 1]
return Ed
def _adjoint_backward_pass(E, Q, Qd):
""" Calculate directional derivatives and Hessians.
Parameters
----------
E : torch.Tensor
Traceback matrix of dimension N x M
Q : torch.Tensor
Derivatives of max theta + v of dimension N x M x S
Qd : torch.Tensor
Derivatives of Q of dimension N x M
Returns
-------
Ed : torch.Tensor
Derivative of traceback matrix of dimension N x M.
Notes
-----
Careful with Ztheta, it actually has dimensions (N + 2) x (M + 2).
The border elements aren't useful, only need Ztheta[1:-1, 1:-1]
"""
if not use_numba:
m, x, y = 1, 0, 2
n_1, m_1, _ = Q.shape
new = Q.new
N, M = n_1 - 2, m_1 - 2
Ed = new(N + 2, M + 2).zero_()
for i in reversed(range(1, N + 1)):
for j in reversed(range(1, M + 1)):
Ed[i, j] = Qd[i + 1, j, x] * E[i + 1, j] + \
Q[i + 1, j, x] * Ed[i + 1, j] + \
Qd[i + 1, j + 1, m] * E[i + 1, j + 1] + \
Q[i + 1, j + 1, m] * Ed[i + 1, j + 1] + \
Qd[i, j + 1, y] * E[i, j + 1] + \
Q[i, j + 1, y] * Ed[i, j + 1]
else:
Ed = _adjoint_backward_pass_numba(
E.detach().cpu().numpy(), Q.detach().cpu().numpy(),
Qd.detach().cpu().numpy())
Ed = torch.tensor(Ed)
return Ed
class NeedlemanWunschFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, theta, A, operator):
# Return both the alignment matrix
Vt, Q = _forward_pass(theta, A, operator)
ctx.save_for_backward(theta, A, Q)
ctx.others = operator
return Vt
@staticmethod
def backward(ctx, Et):
"""
Parameters
----------
ctx : ?
Some autograd context object
Et : torch.Tensor
Last alignment trace (scalar value)
"""
theta, A, Q = ctx.saved_tensors
operator = ctx.others
E, A = NeedlemanWunschFunctionBackward.apply(
theta, A, Et, Q, operator)
return E[1:-1, 1:-1], A, None, None, None
class NeedlemanWunschFunctionBackward(torch.autograd.Function):
@staticmethod
def forward(ctx, theta, A, Et, Q, operator):
E = _backward_pass(Et, Q)
ctx.save_for_backward(E, Q)
ctx.others = operator
return E, A
@staticmethod
def backward(ctx, Ztheta, ZA):
"""
Parameters
----------
ctx : ?
Some autograd context object
Ztheta : torch.Tensor
Derivative of theta of dimension N x M
ZA : torch.Tensor
Derivative of affine gap matrix
"""
E, Q = ctx.saved_tensors
operator = ctx.others
Vtd, Qd = _adjoint_forward_pass(Q, Ztheta, ZA, operator)
Ed = _adjoint_backward_pass(E, Q, Qd)
Ed = Ed[1:-1, 1:-1]
return Ed, None, Vtd, None, None, None
class NeedlemanWunschDecoder(nn.Module):
def __init__(self, operator):
super().__init__()
self.operator = operator
def forward(self, theta, A):
theta = theta.cpu()
A = A.cpu()
return NeedlemanWunschFunction.apply(
theta, A, self.operator)
def traceback(self, grad):
""" Computes traceback
Parameters
----------
grad : torch.Tensor
Gradients of the alignment matrix.
Returns
-------
states : list of tuple
Indices representing matches.
"""
m, x, y = 1, 0, 2
N, M = grad.shape
states = torch.zeros(max(N, M))
i, j = N - 1, M - 1
states = [(i, j, m)]
max_ = -100000
while True:
idx = torch.Tensor([[i - 1, j], [i - 1, j - 1], [i, j - 1]]).long()
left = max_ if i <= 0 else grad[i - 1, j]
diag = max_ if (i <= 0 and j <= 0) else grad[i - 1, j - 1]
upper = max_ if j <= 0 else grad[i, j - 1]
if diag == max_ and upper == max_ and left == max_:
break
ij = torch.argmax(torch.Tensor([left, diag, upper]))
xmy = torch.Tensor([x, m, y])
i, j = int(idx[ij][0]), int(idx[ij][1])
s = int(xmy[ij])
states.append((i, j, s))
# take care of any outstanding gaps
while i > 0:
i = i - 1
s = x
states.append((i, j, s))
while j > 0:
j = j - 1
s = y
states.append((i, j, s))
return states[::-1]
def decode(self, theta, A):
""" Shortcut for doing inference. """
# data, batch_sizes = theta
theta = theta.cpu()
A = A.cpu()
with torch.enable_grad():
# data.requires_grad_()
nll = self.forward(theta, A)
v = torch.sum(nll)
v_grad, _ = torch.autograd.grad(
v, (theta, A),
create_graph=True)
return v_grad
|
462901
|
from unittest import TestCase
from bot.duel_links_runtime import DuelLinkRunTimeOptions
from bot.utils.data import read_json_file, write_data_file
class TestDuelLinkRunTimeOptions(TestCase):
def setUp(self):
file = r'D:\Sync\OneDrive\Yu-gi-oh_bot\run_at_test.json'
self.runtimeoptions = DuelLinkRunTimeOptions(file)
def test_update(self):
self.runtimeoptions.update()
self.runtimeoptions.run_now = True
self.runtimeoptions.dump()
tmp_data = read_json_file(self.runtimeoptions._file)
runtimedict = self.runtimeoptions.dump_options()
self.assertTrue(tmp_data == runtimedict, "Expecting them to be the same")
tmp_data['run_now'] = False
write_data_file(tmp_data, self.runtimeoptions._file)
self.runtimeoptions.update()
runtimedict = self.runtimeoptions.dump_options()
self.assertTrue(tmp_data == runtimedict, "Expecting them to be the same")
def test_dump(self):
self.runtimeoptions.dump()
tmp_data = read_json_file(self.runtimeoptions._file)
runtimedict = self.runtimeoptions.dump_options()
self.assertTrue(tmp_data == runtimedict, "Expecting them to be the same")
def test_runtimeerrors(self):
self.runtimeoptions.update()
self.runtimeoptions.stop = 'Yes'
self.assertTrue(self.runtimeoptions.stop != 'Yes', 'Cannot change to type string')
self.runtimeoptions.next_run_at = 'Try'
self.assertTrue(self.runtimeoptions.next_run_at != 'Try', 'Cannot change from datetime to string')
|
462904
|
import re
from functools import partial
import markdown
from veripress.helpers import to_list
class Parser(object):
"""Base parser class."""
# this should be overridden in subclasses,
# and should be a compiled regular expression
_read_more_exp = None
def __init__(self):
if self._read_more_exp is not None and \
isinstance(self._read_more_exp, str):
# compile the regular expression
# make the regex require new lines above and below the sep flag
self._read_more_exp = re.compile(
r'\r?\n\s*?' + self._read_more_exp + r'\s*?\r?\n',
re.IGNORECASE
)
def parse_preview(self, raw_content):
"""
Parse the preview part of the content,
and return the parsed string and whether there is more content or not.
If the preview part is equal to the whole part,
the second element of the returned tuple will be False, else True.
:param raw_content: raw content
:return: tuple(parsed string, whether there is more content or not)
"""
if self._read_more_exp is None:
return self.parse_whole(raw_content), False
sp = self._read_more_exp.split(raw_content, maxsplit=1)
if len(sp) == 2 and sp[0]:
has_more_content = True
result = sp[0].rstrip()
else:
has_more_content = False
result = raw_content
# since the preview part contains no read_more_sep,
# we can safely use the parse_whole method
return self.parse_whole(result), has_more_content
def parse_whole(self, raw_content):
"""
Parse the whole part of the content.
Should be overridden in subclasses.
"""
raise NotImplementedError
def remove_read_more_sep(self, raw_content):
"""
Removes the first read_more_sep that occurs in raw_content.
Subclasses should call this method to preprocess raw_content.
"""
if self._read_more_exp is None:
return raw_content
sp = self._read_more_exp.split(raw_content, maxsplit=1)
if len(sp) == 2 and sp[0]:
result = '\n\n'.join((sp[0].rstrip(), sp[1].lstrip()))
else:
result = raw_content
return result
# key: extension name, value: standard format name
_ext_format_mapping = {}
# key: standard format name, value: parser instance
_format_parser_mapping = {}
def get_standard_format_name(ext_name):
"""
Get the standard format name of the given extension.
:param ext_name: extension name
:return: standard format name
"""
return _ext_format_mapping.get(ext_name.lower())
def get_parser(format_name):
"""
Get parser of the given format.
:param format_name: standard format name
:return: the parser instance
"""
return _format_parser_mapping.get(format_name.lower())
def parser(format_name, ext_names=None):
"""
Decorate a parser class to register it.
:param format_name: standard format name
:param ext_names: supported extension name
"""
def decorator(cls):
format_name_lower = format_name.lower()
if ext_names is None:
_ext_format_mapping[format_name_lower] = format_name_lower
else:
for ext in to_list(ext_names):
_ext_format_mapping[ext.lower()] = format_name_lower
_format_parser_mapping[format_name_lower] = cls()
return cls
return decorator
@parser('txt', ext_names=['txt'])
class TxtParser(Parser):
"""Txt content parser."""
_read_more_exp = r'-{3,}[ \t]*more[ \t]*-{3,}'
def parse_whole(self, raw_content):
raw_content = self.remove_read_more_sep(raw_content)
return '<pre class="txt">{}</pre>'.format(raw_content)
@parser('markdown', ext_names=['md', 'mdown', 'markdown'])
class MarkdownParser(Parser):
"""Markdown content parser."""
_read_more_exp = r'<!--\s*more\s*-->'
_markdown = partial(
markdown.markdown,
output_format='html5',
extensions=[
'markdown.extensions.extra',
'markdown.extensions.codehilite'
],
extension_configs={
'markdown.extensions.codehilite': {
'guess_lang': False,
'css_class': 'highlight',
'use_pygments': True
}
},
)
def parse_whole(self, raw_content):
raw_content = self.remove_read_more_sep(raw_content)
return self._markdown(raw_content).strip()
|
462915
|
import logging
import os
from django import forms
from django.utils.translation import ugettext_lazy as _
from mayan.apps.views.forms import DetailForm
from ..models.document_models import Document
from ..settings import setting_language
from ..utils import get_language, get_language_choices
__all__ = ('DocumentForm', 'DocumentPropertiesForm',)
logger = logging.getLogger(name=__name__)
class DocumentForm(forms.ModelForm):
"""
Base form for the minimal document properties. Meant to be subclassed.
"""
class Meta:
fields = ('label', 'description', 'language')
model = Document
def __init__(self, *args, **kwargs):
document_type = kwargs.pop('document_type', None)
super().__init__(*args, **kwargs)
# Is a document (documents app edit) and has been saved (sources
# app upload)?
if self.instance and self.instance.pk:
document_type = self.instance.document_type
else:
self.initial.update({'language': setting_language.value})
filenames_queryset = document_type.filenames.filter(enabled=True)
if filenames_queryset:
self.fields[
'document_type_available_filenames'
] = forms.ModelChoiceField(
queryset=filenames_queryset,
required=False,
label=_('Quick document rename'),
widget=forms.Select(
attrs={
'class': 'select2'
}
)
)
self.fields['preserve_extension'] = forms.BooleanField(
label=_('Preserve extension'), required=False,
help_text=_(
'Takes the file extension and moves it to the end of the '
'filename allowing operating systems that rely on file '
'extensions to open document correctly.'
)
)
self.fields['language'].widget = forms.Select(
choices=get_language_choices(), attrs={
'class': 'select2'
}
)
def clean(self):
self.cleaned_data['label'] = self.get_final_label(
# Fallback to the instance label if there is no label key or
# there is a label key and is an empty string
filename=self.cleaned_data.get('label') or self.instance.label
)
return self.cleaned_data
def get_final_label(self, filename):
if 'document_type_available_filenames' in self.cleaned_data:
if self.cleaned_data['document_type_available_filenames']:
if self.cleaned_data['preserve_extension']:
filename, extension = os.path.splitext(filename)
filename = '{}{}'.format(
self.cleaned_data[
'document_type_available_filenames'
].filename, extension
)
else:
filename = self.cleaned_data[
'document_type_available_filenames'
].filename
return filename
class DocumentPropertiesForm(DetailForm):
"""
Detail class form to display a document file based properties
"""
def __init__(self, *args, **kwargs):
document = kwargs['instance']
extra_fields = [
{
'label': _('Date created'),
'field': 'datetime_created',
'widget': forms.widgets.DateTimeInput
},
{'label': _('UUID'), 'field': 'uuid'},
{
'label': _('Language'),
'func': lambda x: get_language(
language_code=document.language
)
},
]
kwargs['extra_fields'] = extra_fields
super().__init__(*args, **kwargs)
class Meta:
fields = ('document_type', 'description')
model = Document
|
462918
|
import os, glob, platform
#find out if we're running on mac or linux and set the dynamic library extension
dylib_ext = ""
if platform.system().lower() == "darwin":
dylib_ext = ".dylib"
else:
dylib_ext = ".so"
print("Running on " + platform.system())
#make sure the release folder exists, and clean out any .o/.so file if there are any
if not os.path.exists( "release" ):
os.makedirs( "release" )
os.chdir( "release" )
o_files = glob.glob( "*.o" )
o_files.extend( glob.glob( "*" + dylib_ext ) )
for o_file in o_files:
os.remove( o_file )
os.chdir( ".." )
#make sure the debug folder exists, and clean out any .o/.so files if there are any
if not os.path.exists( "debug" ):
os.makedirs( "debug" )
os.chdir( "debug" )
o_files = glob.glob( "*.o" );
o_files.extend( glob.glob( "*" + dylib_ext ) )
for o_file in o_files:
os.remove( o_file )
os.chdir( ".." )
#find all the cpp files in /source. We'll compile all of them
os.chdir( "source" )
cpp_files = glob.glob( "*.cpp" );
os.chdir( ".." )
#specify the search paths/dependencies/options for gcc
include_paths = [ "../include" ]
link_paths = [ "../lib" ]
link_dependencies = [ "-lAnalyzer64" ] #refers to libAnalyzer.dylib or libAnalyzer.so
debug_compile_flags = "-O0 -w -c -fpic -g"
release_compile_flags = "-O3 -w -c -fpic"
#loop through all the cpp files, build up the gcc command line, and attempt to compile each cpp file
for cpp_file in cpp_files:
#g++
command = "g++ "
#include paths
for path in include_paths:
command += "-I\"" + path + "\" "
release_command = command
release_command += release_compile_flags
release_command += " -o\"release/" + cpp_file.replace( ".cpp", ".o" ) + "\" " #the output file
release_command += "\"" + "source/" + cpp_file + "\"" #the cpp file to compile
debug_command = command
debug_command += debug_compile_flags
debug_command += " -o\"debug/" + cpp_file.replace( ".cpp", ".o" ) + "\" " #the output file
debug_command += "\"" + "source/" + cpp_file + "\"" #the cpp file to compile
#run the commands from the command line
print(release_command)
os.system( release_command )
print(debug_command)
os.system( debug_command )
#lastly, link
#g++
command = "g++ "
#add the library search paths
for link_path in link_paths:
command += "-L\"" + link_path + "\" "
#add libraries to link against
for link_dependency in link_dependencies:
command += link_dependency + " "
#make a dynamic (shared) library (.so/.dylib)
if dylib_ext == ".dylib":
command += "-dynamiclib "
else:
command += "-shared "
#figgure out what the name of this analyzer is
analyzer_name = ""
for cpp_file in cpp_files:
if cpp_file.endswith( "Analyzer.cpp" ):
analyzer_name = cpp_file.replace( "Analyzer.cpp", "" )
break
#the files to create (.so/.dylib files)
if dylib_ext == ".dylib":
release_command = command + "-o release/lib" + analyzer_name + "Analyzer.dylib "
debug_command = command + "-o debug/lib" + analyzer_name + "Analyzer.dylib "
else:
release_command = command + "-o\"release/lib" + analyzer_name + "Analyzer.so\" "
debug_command = command + "-o\"debug/lib" + analyzer_name + "Analyzer.so\" "
#add all the object files to link
for cpp_file in cpp_files:
release_command += "release/" + cpp_file.replace( ".cpp", ".o" ) + " "
debug_command += "debug/" + cpp_file.replace( ".cpp", ".o" ) + " "
#run the commands from the command line
print(release_command)
os.system( release_command )
print(debug_command)
os.system( debug_command )
|
462931
|
import datetime
import ipaddress
from tests.common import constants
class TrafficPorts(object):
""" Generate a list of ports needed for the PFC Watchdog test"""
def __init__(self, mg_facts, neighbors, vlan_nw):
"""
Args:
mg_facts (dict): parsed minigraph info
neighbors (list): 'device_conn' info from connection graph facts
vlan_nw (string): ip in the vlan range specified in the DUT
"""
self.mg_facts = mg_facts
self.bgp_info = self.mg_facts['minigraph_bgp']
self.port_idx_info = self.mg_facts['minigraph_port_indices']
self.pc_info = self.mg_facts['minigraph_portchannels']
self.vlan_info = self.mg_facts['minigraph_vlans']
self.neighbors = neighbors
self.vlan_nw = vlan_nw
self.test_ports = dict()
self.pfc_wd_rx_port = None
self.pfc_wd_rx_port_addr = None
self.pfc_wd_rx_neighbor_addr = None
self.pfc_wd_rx_port_id = None
def build_port_list(self):
"""
Generate a list of ports to be used for the test
For T0 topology, the port list is built parsing the portchannel and vlan info and for T1,
port list is constructed from the interface info
"""
if self.mg_facts['minigraph_interfaces']:
self.parse_intf_list()
elif self.mg_facts['minigraph_portchannels']:
self.parse_pc_list()
elif 'minigraph_vlan_sub_interfaces' in self.mg_facts:
self.parse_vlan_sub_interface_list()
if self.mg_facts['minigraph_vlans']:
self.test_ports.update(self.parse_vlan_list())
return self.test_ports
def parse_intf_list(self):
"""
Built the port info from the ports in 'minigraph_interfaces'
The constructed port info is a dict with a port as the key (transmit port) and value contains
all the info associated with this port (its fanout neighbor, receive port, receive ptf id,
transmit ptf id, neighbor addr etc). The first port in the list is assumed to be the Rx port.
The rest of the ports will use this port as the Rx port while populating their dict
info. The selected Rx port when used as a transmit port will use the next port in
the list as its associated Rx port
"""
pfc_wd_test_port = None
first_pair = False
for intf in self.mg_facts['minigraph_interfaces']:
if ipaddress.ip_address(unicode(intf['addr'])).version != 4:
continue
# first port
if not self.pfc_wd_rx_port:
self.pfc_wd_rx_port = intf['attachto']
self.pfc_wd_rx_port_addr = intf['addr']
self.pfc_wd_rx_port_id = self.port_idx_info[self.pfc_wd_rx_port]
elif not pfc_wd_test_port:
# second port
first_pair = True
# populate info for all ports except the first one
if first_pair or pfc_wd_test_port:
pfc_wd_test_port = intf['attachto']
pfc_wd_test_port_addr = intf['addr']
pfc_wd_test_port_id = self.port_idx_info[pfc_wd_test_port]
pfc_wd_test_neighbor_addr = None
for item in self.bgp_info:
if ipaddress.ip_address(unicode(item['addr'])).version != 4:
continue
if not self.pfc_wd_rx_neighbor_addr and item['peer_addr'] == self.pfc_wd_rx_port_addr:
self.pfc_wd_rx_neighbor_addr = item['addr']
if item['peer_addr'] == pfc_wd_test_port_addr:
pfc_wd_test_neighbor_addr = item['addr']
self.test_ports[pfc_wd_test_port] = {'test_neighbor_addr': pfc_wd_test_neighbor_addr,
'rx_port': [self.pfc_wd_rx_port],
'rx_neighbor_addr': self.pfc_wd_rx_neighbor_addr,
'peer_device': self.neighbors[pfc_wd_test_port]['peerdevice'],
'test_port_id': pfc_wd_test_port_id,
'rx_port_id': [self.pfc_wd_rx_port_id],
'test_port_type': 'interface'
}
# populate info for the first port
if first_pair:
self.test_ports[self.pfc_wd_rx_port] = {'test_neighbor_addr': self.pfc_wd_rx_neighbor_addr,
'rx_port': [pfc_wd_test_port],
'rx_neighbor_addr': pfc_wd_test_neighbor_addr,
'peer_device': self.neighbors[self.pfc_wd_rx_port]['peerdevice'],
'test_port_id': self.pfc_wd_rx_port_id,
'rx_port_id': [pfc_wd_test_port_id],
'test_port_type': 'interface'
}
first_pair = False
def parse_pc_list(self):
"""
Built the port info from the ports in portchannel
The constructed port info is a dict with a port as the key (transmit port) and value contains
all the info associated with this port (its fanout neighbor, receive ports, receive
ptf ids, transmit ptf ids, neighbor portchannel addr, its own portchannel addr etc).
The first port in the list is assumed to be the Rx port. The rest
of the ports will use this port as the Rx port while populating their dict
info. The selected Rx port when used as a transmit port will use the next port in
the list as its associated Rx port
"""
pfc_wd_test_port = None
first_pair = False
for item in self.mg_facts['minigraph_portchannel_interfaces']:
if ipaddress.ip_address(unicode(item['addr'])).version != 4:
continue
pc = item['attachto']
# first port
if not self.pfc_wd_rx_port:
self.pfc_wd_rx_portchannel = pc
self.pfc_wd_rx_port = self.pc_info[pc]['members']
self.pfc_wd_rx_port_addr = item['addr']
self.pfc_wd_rx_port_id = [self.port_idx_info[port] for port in self.pfc_wd_rx_port]
elif not pfc_wd_test_port:
# second port
first_pair = True
# populate info for all ports except the first one
if first_pair or pfc_wd_test_port:
pfc_wd_test_portchannel = pc
pfc_wd_test_port = self.pc_info[pc]['members']
pfc_wd_test_port_addr = item['addr']
pfc_wd_test_port_id = [self.port_idx_info[port] for port in pfc_wd_test_port]
pfc_wd_test_neighbor_addr = None
for bgp_item in self.bgp_info:
if ipaddress.ip_address(unicode(bgp_item['addr'])).version != 4:
continue
if not self.pfc_wd_rx_neighbor_addr and bgp_item['peer_addr'] == self.pfc_wd_rx_port_addr:
self.pfc_wd_rx_neighbor_addr = bgp_item['addr']
if bgp_item['peer_addr'] == pfc_wd_test_port_addr:
pfc_wd_test_neighbor_addr = bgp_item['addr']
for port in pfc_wd_test_port:
self.test_ports[port] = {'test_neighbor_addr': pfc_wd_test_neighbor_addr,
'rx_port': self.pfc_wd_rx_port,
'rx_neighbor_addr': self.pfc_wd_rx_neighbor_addr,
'peer_device': self.neighbors[port]['peerdevice'],
'test_port_id': self.port_idx_info[port],
'rx_port_id': self.pfc_wd_rx_port_id,
'test_portchannel_members': pfc_wd_test_port_id,
'test_port_type': 'portchannel'
}
# populate info for the first port
if first_pair:
for port in self.pfc_wd_rx_port:
self.test_ports[port] = {'test_neighbor_addr': self.pfc_wd_rx_neighbor_addr,
'rx_port': pfc_wd_test_port,
'rx_neighbor_addr': pfc_wd_test_neighbor_addr,
'peer_device': self.neighbors[port]['peerdevice'],
'test_port_id': self.port_idx_info[port],
'rx_port_id': pfc_wd_test_port_id,
'test_portchannel_members': self.pfc_wd_rx_port_id,
'test_port_type': 'portchannel'
}
first_pair = False
def parse_vlan_list(self):
"""
Add vlan specific port info to the already populated port info dict.
Each vlan interface will be the key and value contains all the info associated with this port
(receive fanout neighbor, receive port receive ptf id, transmit ptf id, neighbor addr etc).
Args:
None
Returns:
temp_ports (dict): port info constructed from the vlan interfaces
"""
temp_ports = dict()
vlan_details = self.vlan_info.values()[0]
vlan_members = vlan_details['members']
vlan_type = vlan_details.get('type')
vlan_id = vlan_details['vlanid']
rx_port = self.pfc_wd_rx_port if isinstance(self.pfc_wd_rx_port, list) else [self.pfc_wd_rx_port]
rx_port_id = self.pfc_wd_rx_port_id if isinstance(self.pfc_wd_rx_port_id, list) else [self.pfc_wd_rx_port_id]
for item in vlan_members:
temp_ports[item] = {'test_neighbor_addr': self.vlan_nw,
'rx_port': rx_port,
'rx_neighbor_addr': self.pfc_wd_rx_neighbor_addr,
'peer_device': self.neighbors[item]['peerdevice'],
'test_port_id': self.port_idx_info[item],
'rx_port_id': rx_port_id,
'test_port_type': 'vlan'
}
if hasattr(self, 'pfc_wd_rx_port_vlan_id'):
temp_ports[item]['rx_port_vlan_id'] = self.pfc_wd_rx_port_vlan_id
if vlan_type is not None and vlan_type == 'Tagged':
temp_ports[item]['test_port_vlan_id'] = vlan_id
return temp_ports
def parse_vlan_sub_interface_list(self):
"""Build the port info from the vlan sub-interfaces."""
pfc_wd_test_port = None
first_pair = False
for sub_intf in self.mg_facts['minigraph_vlan_sub_interfaces']:
if ipaddress.ip_address(unicode(sub_intf['addr'])).version != 4:
continue
intf_name, vlan_id = sub_intf['attachto'].split(constants.VLAN_SUB_INTERFACE_SEPARATOR)
# first port
if not self.pfc_wd_rx_port:
self.pfc_wd_rx_port = intf_name
self.pfc_wd_rx_port_addr = sub_intf['addr']
self.pfc_wd_rx_port_id = self.port_idx_info[self.pfc_wd_rx_port]
self.pfc_wd_rx_port_vlan_id = vlan_id
elif not pfc_wd_test_port:
# second port
first_pair = True
# populate info for all ports except the first one
if first_pair or pfc_wd_test_port:
pfc_wd_test_port = intf_name
pfc_wd_test_port_addr = sub_intf['addr']
pfc_wd_test_port_id = self.port_idx_info[pfc_wd_test_port]
pfc_wd_test_neighbor_addr = None
for item in self.bgp_info:
if ipaddress.ip_address(unicode(item['addr'])).version != 4:
continue
if not self.pfc_wd_rx_neighbor_addr and item['peer_addr'] == self.pfc_wd_rx_port_addr:
self.pfc_wd_rx_neighbor_addr = item['addr']
if item['peer_addr'] == pfc_wd_test_port_addr:
pfc_wd_test_neighbor_addr = item['addr']
self.test_ports[pfc_wd_test_port] = {'test_neighbor_addr': pfc_wd_test_neighbor_addr,
'rx_port': [self.pfc_wd_rx_port],
'rx_neighbor_addr': self.pfc_wd_rx_neighbor_addr,
'peer_device': self.neighbors[pfc_wd_test_port]['peerdevice'],
'test_port_id': pfc_wd_test_port_id,
'rx_port_id': [self.pfc_wd_rx_port_id],
'rx_port_vlan_id': self.pfc_wd_rx_port_vlan_id,
'test_port_vlan_id': vlan_id,
'test_port_type': 'interface'
}
# populate info for the first port
if first_pair:
self.test_ports[self.pfc_wd_rx_port] = {'test_neighbor_addr': self.pfc_wd_rx_neighbor_addr,
'rx_port': [pfc_wd_test_port],
'rx_neighbor_addr': pfc_wd_test_neighbor_addr,
'peer_device': self.neighbors[self.pfc_wd_rx_port]['peerdevice'],
'test_port_id': self.pfc_wd_rx_port_id,
'rx_port_id': [pfc_wd_test_port_id],
'rx_port_vlan_id': vlan_id,
'test_port_vlan_id': self.pfc_wd_rx_port_vlan_id,
'test_port_type': 'interface'
}
first_pair = False
def set_pfc_timers():
"""
Set PFC timers
Args:
None
Returns:
pfc_timers (dict)
"""
pfc_timers = {'pfc_wd_detect_time': 400,
'pfc_wd_restore_time': 400,
'pfc_wd_restore_time_large': 3000,
'pfc_wd_poll_time': 400
}
return pfc_timers
def select_test_ports(test_ports):
"""
Select a subset of ports from the generated port info
Args:
test_ports (dict): Constructed port info
Returns:
selected_ports (dict): random port info or set of ports matching seed
"""
selected_ports = dict()
rx_ports = set()
seed = int(datetime.datetime.today().day)
for port, port_info in test_ports.items():
rx_port = port_info["rx_port"]
if isinstance(rx_port, (list, tuple)):
rx_ports.update(rx_port)
else:
rx_ports.add(rx_port)
if (int(port_info['test_port_id']) % 15) == (seed % 15):
selected_ports[port] = port_info
# filter out selected ports that also act as rx ports
selected_ports = {p: pi for p, pi in selected_ports.items()
if p not in rx_port}
if not selected_ports:
random_port = test_ports.keys()[0]
selected_ports[random_port] = test_ports[random_port]
return selected_ports
def start_wd_on_ports(duthost, port, restore_time, detect_time, action="drop"):
"""
Starts PFCwd on ports
Args:
port (string): single port or space separated list of ports
restore_time (int): PFC storm restoration time
detect_time (int): PFC storm detection time
action (string): PFCwd action. values include 'drop', 'forward'
"""
duthost.command("pfcwd start --action {} --restoration-time {} {} {}"
.format(action, restore_time, port, detect_time))
|
462972
|
class BaseData(object):
def __init__(self, unit):
self.unit = unit
def change_units(self, new_units):
self.unit = new_units
|
463005
|
import logging
from collections import deque
from teether.cfg.bb import BB
from teether.cfg.instruction import Instruction
from teether.cfg.opcodes import opcodes
class ArgumentTooShort(Exception):
pass
def disass(code, i=0):
assert isinstance(code, bytes)
while i < len(code):
loc = i
op = code[i]
arg = None
inslen = 1
if not op in opcodes:
break
# raise IllegalInstruction('%02x at %d'%(op, i))
if 0x60 <= op <= 0x7f:
arglen = op - 0x5f
inslen += arglen
arg = code[i + 1:i + 1 + arglen]
if len(arg) < arglen:
raise ArgumentTooShort
i += arglen
i += 1
yield Instruction(loc, op, arg)
# End basic block on STOP, JUMP, JUMPI, RETURN, REVERT, RAISE, or if the following instruction is a JUMPDEST
if op in (0x00, 0x56, 0x57, 0xf3, 0xfd, 0xfe, 0xff) or (i < len(code) and code[i] == 0x5b):
break
def generate_BBs(code):
fallthrough_locs = [i + 1 for i, c in enumerate(code) if c == 0x57]
jumpdest_locs = [i for i, c in enumerate(code) if c == 0x5b]
leader_candidates = {0} | set(fallthrough_locs) | set(jumpdest_locs)
for l in sorted(leader_candidates):
try:
instructions = list(disass(code, l))
if instructions:
yield BB(instructions)
except:
continue
|
463026
|
from enum import Enum
from typing import Any, Dict, Optional
from eth2._utils.bls import bls
from eth2._utils.bls.backends import MilagroBackend
from eth2.beacon.tools.fixtures.test_part import TestPart
from eth2.configs import Eth2Config
from .test_handler import Input, Output, TestHandler
class BLSSetting(Enum):
OPTIONAL = 0
ENABLED = 1
DISABLED = 2
def _select_bls_backend(bls_setting: BLSSetting) -> None:
if bls_setting == BLSSetting.DISABLED:
bls.use_noop_backend()
elif bls_setting == BLSSetting.ENABLED:
bls.use(MilagroBackend)
elif bls_setting == BLSSetting.OPTIONAL:
# do not verify BLS to save time
bls.use_noop_backend()
# META_KEY is the prefix of the filename of the YAML file storing metadata about a test case.
# e.g. in the context of a test case file tree, there is a file `meta.yaml`.
META_KEY = "meta"
BLS_SETTING_KEY = "bls_setting"
class TestCase:
name: str
handler: TestHandler[Any, Any]
test_case_parts: Dict[str, TestPart]
config: Optional[Eth2Config]
def __init__(
self,
name: str,
handler: TestHandler[Input, Output],
test_case_parts: Dict[str, TestPart],
config: Optional[Eth2Config],
) -> None:
self.name = name
self.handler = handler
self.test_case_parts = test_case_parts
self.config = config
self.metadata = self._load_metadata()
self._process_meta(self.metadata)
def _load_metadata(self) -> Dict[str, Any]:
if META_KEY not in self.test_case_parts:
return {}
metadata_test_part = self.test_case_parts[META_KEY]
return metadata_test_part.load()
def _process_meta(self, metadata: Dict[str, Any]) -> None:
self.bls_setting = BLSSetting(metadata.get(BLS_SETTING_KEY, 0))
def valid(self) -> bool:
return self.handler.valid(self.test_case_parts)
def execute(self) -> None:
_select_bls_backend(self.bls_setting)
inputs = self.handler.parse_inputs(self.test_case_parts, self.metadata)
outputs = self.handler.run_with(inputs, self.config)
# NOTE: parse outputs after running the handler as we may trigger
# an exception due to an invalid test case that should raise before
# invalid decoding of empty output we expect to be missing.
expected_outputs = self.handler.parse_outputs(self.test_case_parts)
self.handler.condition(outputs, expected_outputs)
|
463048
|
import numpy as np
import numpy.testing as npt
from stumpy import scrump, stump, config
from stumpy.scrump import prescrump
import pytest
import naive
test_data = [
(
np.array([9, 8100, -60, 7], dtype=np.float64),
np.array([584, -11, 23, 79, 1001, 0, -19], dtype=np.float64),
),
(
np.random.uniform(-1000, 1000, [8]).astype(np.float64),
np.random.uniform(-1000, 1000, [64]).astype(np.float64),
),
]
window_size = [8, 16, 32]
substitution_locations = [(slice(0, 0), 0, -1, slice(1, 3), [0, 3])]
substitution_values = [np.nan, np.inf]
percentages = [(0.01, 0.1, 1.0)]
@pytest.mark.parametrize("T_A, T_B", test_data)
def test_prescrump_self_join(T_A, T_B):
m = 3
zone = int(np.ceil(m / 4))
for s in range(1, zone + 1):
seed = np.random.randint(100000)
np.random.seed(seed)
ref_P, ref_I = naive.prescrump(T_B, m, T_B, s=s, exclusion_zone=zone)
np.random.seed(seed)
comp_P, comp_I = prescrump(T_B, m, s=s)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
@pytest.mark.parametrize("T_A, T_B", test_data)
def test_prescrump_A_B_join(T_A, T_B):
m = 3
zone = int(np.ceil(m / 4))
for s in range(1, zone + 1):
seed = np.random.randint(100000)
np.random.seed(seed)
ref_P, ref_I = naive.prescrump(T_A, m, T_B, s=s)
np.random.seed(seed)
comp_P, comp_I = prescrump(T_A, m, T_B=T_B, s=s)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
@pytest.mark.parametrize("T_A, T_B", test_data)
def test_prescrump_A_B_join_swap(T_A, T_B):
m = 3
zone = int(np.ceil(m / 4))
for s in range(1, zone + 1):
seed = np.random.randint(100000)
np.random.seed(seed)
ref_P, ref_I = naive.prescrump(T_B, m, T_A, s=s)
np.random.seed(seed)
comp_P, comp_I = prescrump(T_B, m, T_B=T_A, s=s)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
@pytest.mark.parametrize("T_A, T_B", test_data)
@pytest.mark.parametrize("m", window_size)
def test_prescrump_self_join_larger_window(T_A, T_B, m):
if len(T_B) > m:
zone = int(np.ceil(m / 4))
for s in range(1, zone + 1):
seed = np.random.randint(100000)
np.random.seed(seed)
ref_P, ref_I = naive.prescrump(T_B, m, T_B, s=s, exclusion_zone=zone)
np.random.seed(seed)
comp_P, comp_I = prescrump(T_B, m, s=s)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
def test_scrump_int_input():
with pytest.raises(TypeError):
scrump(np.arange(10), 5, ignore_trivial=True, percentage=1.0, pre_scrump=False)
@pytest.mark.parametrize("T_A, T_B", test_data)
@pytest.mark.parametrize("percentages", percentages)
def test_scrump_self_join(T_A, T_B, percentages):
m = 3
zone = int(np.ceil(m / 4))
for percentage in percentages:
seed = np.random.randint(100000)
np.random.seed(seed)
ref_mp = naive.scrump(T_B, m, T_B, percentage, zone, False, None)
ref_P = ref_mp[:, 0]
ref_I = ref_mp[:, 1]
ref_left_I = ref_mp[:, 2]
ref_right_I = ref_mp[:, 3]
np.random.seed(seed)
approx = scrump(
T_B, m, ignore_trivial=True, percentage=percentage, pre_scrump=False
)
approx.update()
comp_P = approx.P_
comp_I = approx.I_
comp_left_I = approx.left_I_
comp_right_I = approx.right_I_
naive.replace_inf(ref_P)
naive.replace_inf(comp_P)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
npt.assert_almost_equal(ref_left_I, comp_left_I)
npt.assert_almost_equal(ref_right_I, comp_right_I)
@pytest.mark.parametrize("T_A, T_B", test_data)
@pytest.mark.parametrize("percentages", percentages)
def test_scrump_A_B_join(T_A, T_B, percentages):
m = 3
for percentage in percentages:
seed = np.random.randint(100000)
np.random.seed(seed)
ref_mp = naive.scrump(T_A, m, T_B, percentage, None, False, None)
ref_P = ref_mp[:, 0]
ref_I = ref_mp[:, 1]
ref_left_I = ref_mp[:, 2]
ref_right_I = ref_mp[:, 3]
np.random.seed(seed)
approx = scrump(
T_A, m, T_B, ignore_trivial=False, percentage=percentage, pre_scrump=False
)
approx.update()
comp_P = approx.P_
comp_I = approx.I_
comp_left_I = approx.left_I_
comp_right_I = approx.right_I_
naive.replace_inf(ref_P)
naive.replace_inf(comp_P)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
npt.assert_almost_equal(ref_left_I, comp_left_I)
npt.assert_almost_equal(ref_right_I, comp_right_I)
@pytest.mark.parametrize("T_A, T_B", test_data)
@pytest.mark.parametrize("percentages", percentages)
def test_scrump_A_B_join_swap(T_A, T_B, percentages):
m = 3
for percentage in percentages:
seed = np.random.randint(100000)
np.random.seed(seed)
ref_mp = naive.scrump(T_B, m, T_A, percentage, None, False, None)
ref_P = ref_mp[:, 0]
# ref_I = ref_mp[:, 1]
ref_left_I = ref_mp[:, 2]
ref_right_I = ref_mp[:, 3]
np.random.seed(seed)
approx = scrump(
T_B, m, T_A, ignore_trivial=False, percentage=percentage, pre_scrump=False
)
approx.update()
comp_P = approx.P_
# comp_I = approx.I_
comp_left_I = approx.left_I_
comp_right_I = approx.right_I_
naive.replace_inf(ref_P)
naive.replace_inf(comp_P)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_left_I, comp_left_I)
npt.assert_almost_equal(ref_right_I, comp_right_I)
@pytest.mark.parametrize("T_A, T_B", test_data)
@pytest.mark.parametrize("m", window_size)
@pytest.mark.parametrize("percentages", percentages)
def test_scrump_self_join_larger_window(T_A, T_B, m, percentages):
if len(T_B) > m:
zone = int(np.ceil(m / 4))
for percentage in percentages:
seed = np.random.randint(100000)
np.random.seed(seed)
ref_mp = naive.scrump(T_B, m, T_B, percentage, zone, False, None)
ref_P = ref_mp[:, 0]
ref_I = ref_mp[:, 1]
ref_left_I = ref_mp[:, 2]
ref_right_I = ref_mp[:, 3]
np.random.seed(seed)
approx = scrump(
T_B, m, ignore_trivial=True, percentage=percentage, pre_scrump=False
)
approx.update()
comp_P = approx.P_
comp_I = approx.I_
comp_left_I = approx.left_I_
comp_right_I = approx.right_I_
naive.replace_inf(ref_P)
naive.replace_inf(comp_P)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
npt.assert_almost_equal(ref_left_I, comp_left_I)
npt.assert_almost_equal(ref_right_I, comp_right_I)
@pytest.mark.parametrize("T_A, T_B", test_data)
def test_scrump_self_join_full(T_A, T_B):
m = 3
zone = int(np.ceil(m / 4))
ref_mp = naive.stamp(T_B, m, exclusion_zone=zone)
ref_P = ref_mp[:, 0]
ref_I = ref_mp[:, 1]
ref_left_I = ref_mp[:, 2]
ref_right_I = ref_mp[:, 3]
approx = scrump(T_B, m, ignore_trivial=True, percentage=1.0, pre_scrump=False)
approx.update()
comp_P = approx.P_
comp_I = approx.I_
comp_left_I = approx.left_I_
comp_right_I = approx.right_I_
naive.replace_inf(ref_P)
naive.replace_inf(comp_P)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
npt.assert_almost_equal(ref_left_I, comp_left_I)
npt.assert_almost_equal(ref_right_I, comp_right_I)
ref_mp = stump(T_B, m, ignore_trivial=True)
ref_P = ref_mp[:, 0]
ref_I = ref_mp[:, 1]
ref_left_I = ref_mp[:, 2]
ref_right_I = ref_mp[:, 3]
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
npt.assert_almost_equal(ref_left_I, comp_left_I)
npt.assert_almost_equal(ref_right_I, comp_right_I)
@pytest.mark.parametrize("T_A, T_B", test_data)
def test_scrump_A_B_join_full(T_A, T_B):
m = 3
ref_mp = naive.stamp(T_A, m, T_B=T_B)
ref_P = ref_mp[:, 0]
ref_I = ref_mp[:, 1]
ref_left_I = ref_mp[:, 2]
ref_right_I = ref_mp[:, 3]
approx = scrump(T_A, m, T_B, ignore_trivial=False, percentage=1.0, pre_scrump=False)
approx.update()
comp_P = approx.P_
comp_I = approx.I_
comp_left_I = approx.left_I_
comp_right_I = approx.right_I_
naive.replace_inf(ref_P)
naive.replace_inf(comp_P)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
npt.assert_almost_equal(ref_left_I, comp_left_I)
npt.assert_almost_equal(ref_right_I, comp_right_I)
ref_mp = stump(T_A, m, T_B=T_B, ignore_trivial=False)
ref_P = ref_mp[:, 0]
ref_I = ref_mp[:, 1]
ref_left_I = ref_mp[:, 2]
ref_right_I = ref_mp[:, 3]
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
npt.assert_almost_equal(ref_left_I, comp_left_I)
npt.assert_almost_equal(ref_right_I, comp_right_I)
@pytest.mark.parametrize("T_A, T_B", test_data)
def test_scrump_A_B_join_full_swap(T_A, T_B):
m = 3
ref_mp = naive.stamp(T_B, m, T_B=T_A)
ref_P = ref_mp[:, 0]
ref_I = ref_mp[:, 1]
ref_left_I = ref_mp[:, 2]
ref_right_I = ref_mp[:, 3]
approx = scrump(T_B, m, T_A, ignore_trivial=False, percentage=1.0, pre_scrump=False)
approx.update()
comp_P = approx.P_
comp_I = approx.I_
comp_left_I = approx.left_I_
comp_right_I = approx.right_I_
naive.replace_inf(ref_P)
naive.replace_inf(comp_P)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
npt.assert_almost_equal(ref_left_I, comp_left_I)
npt.assert_almost_equal(ref_right_I, comp_right_I)
@pytest.mark.parametrize("T_A, T_B", test_data)
@pytest.mark.parametrize("m", window_size)
def test_scrump_self_join_full_larger_window(T_A, T_B, m):
if len(T_B) > m:
zone = int(np.ceil(m / 4))
ref_mp = naive.stamp(T_B, m, exclusion_zone=zone)
ref_P = ref_mp[:, 0]
ref_I = ref_mp[:, 1]
ref_left_I = ref_mp[:, 2]
ref_right_I = ref_mp[:, 3]
approx = scrump(T_B, m, ignore_trivial=True, percentage=1.0, pre_scrump=False)
approx.update()
comp_P = approx.P_
comp_I = approx.I_
comp_left_I = approx.left_I_
comp_right_I = approx.right_I_
naive.replace_inf(ref_P)
naive.replace_inf(comp_P)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
npt.assert_almost_equal(ref_left_I, comp_left_I)
npt.assert_almost_equal(ref_right_I, comp_right_I)
@pytest.mark.parametrize("T_A, T_B", test_data)
@pytest.mark.parametrize("percentages", percentages)
def test_scrump_plus_plus_self_join(T_A, T_B, percentages):
m = 3
zone = int(np.ceil(m / 4))
for s in range(1, zone + 1):
for percentage in percentages:
seed = np.random.randint(100000)
np.random.seed(seed)
ref_P, ref_I = naive.prescrump(T_B, m, T_B, s=s, exclusion_zone=zone)
ref_mp = naive.scrump(T_B, m, T_B, percentage, zone, True, s)
for i in range(ref_mp.shape[0]):
if ref_P[i] < ref_mp[i, 0]:
ref_mp[i, 0] = ref_P[i]
ref_mp[i, 1] = ref_I[i]
ref_P = ref_mp[:, 0]
ref_I = ref_mp[:, 1]
# ref_left_I = ref_mp[:, 2]
# ref_right_I = ref_mp[:, 3]
np.random.seed(seed)
approx = scrump(
T_B, m, ignore_trivial=True, percentage=percentage, pre_scrump=True, s=s
)
approx.update()
comp_P = approx.P_
comp_I = approx.I_
# comp_left_I = approx.left_I_
# comp_right_I = approx.right_I_
naive.replace_inf(ref_P)
naive.replace_inf(comp_I)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
# npt.assert_almost_equal(ref_left_I, comp_left_I)
# npt.assert_almost_equal(ref_right_I, comp_right_I)
@pytest.mark.parametrize("T_A, T_B", test_data)
@pytest.mark.parametrize("percentages", percentages)
def test_scrump_plus_plus_A_B_join(T_A, T_B, percentages):
m = 3
zone = int(np.ceil(m / 4))
for s in range(1, zone + 1):
for percentage in percentages:
seed = np.random.randint(100000)
np.random.seed(seed)
ref_P, ref_I = naive.prescrump(T_A, m, T_B, s=s)
ref_mp = naive.scrump(T_A, m, T_B, percentage, None, False, None)
for i in range(ref_mp.shape[0]):
if ref_P[i] < ref_mp[i, 0]:
ref_mp[i, 0] = ref_P[i]
ref_mp[i, 1] = ref_I[i]
ref_P = ref_mp[:, 0]
ref_I = ref_mp[:, 1]
ref_left_I = ref_mp[:, 2]
ref_right_I = ref_mp[:, 3]
approx = scrump(
T_A,
m,
T_B,
ignore_trivial=False,
percentage=percentage,
pre_scrump=True,
s=s,
)
approx.update()
comp_P = approx.P_
comp_I = approx.I_
comp_left_I = approx.left_I_
comp_right_I = approx.right_I_
naive.replace_inf(ref_P)
naive.replace_inf(comp_P)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
npt.assert_almost_equal(ref_left_I, comp_left_I)
npt.assert_almost_equal(ref_right_I, comp_right_I)
@pytest.mark.parametrize("T_A, T_B", test_data)
def test_scrump_plus_plus_self_join_full(T_A, T_B):
m = 3
zone = int(np.ceil(m / 4))
ref_mp = naive.stamp(T_B, m, exclusion_zone=zone)
ref_P = ref_mp[:, 0]
ref_I = ref_mp[:, 1]
ref_left_I = ref_mp[:, 2]
ref_right_I = ref_mp[:, 3]
approx = scrump(
T_B, m, ignore_trivial=True, percentage=1.0, pre_scrump=True, s=zone
)
approx.update()
comp_P = approx.P_
comp_I = approx.I_
comp_left_I = approx.left_I_
comp_right_I = approx.right_I_
naive.replace_inf(ref_P)
naive.replace_inf(comp_P)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
npt.assert_almost_equal(ref_left_I, comp_left_I)
npt.assert_almost_equal(ref_right_I, comp_right_I)
@pytest.mark.parametrize("T_A, T_B", test_data)
def test_scrump_plus_plus_A_B_join_full(T_A, T_B):
m = 3
zone = int(np.ceil(m / 4))
ref_mp = naive.stamp(T_A, m, T_B=T_B)
ref_P = ref_mp[:, 0]
ref_I = ref_mp[:, 1]
ref_left_I = ref_mp[:, 2]
ref_right_I = ref_mp[:, 3]
approx = scrump(
T_A, m, T_B=T_B, ignore_trivial=False, percentage=1.0, pre_scrump=True, s=zone
)
approx.update()
comp_P = approx.P_
comp_I = approx.I_
comp_left_I = approx.left_I_
comp_right_I = approx.right_I_
naive.replace_inf(ref_P)
naive.replace_inf(comp_P)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
npt.assert_almost_equal(ref_left_I, comp_left_I)
npt.assert_almost_equal(ref_right_I, comp_right_I)
@pytest.mark.parametrize("T_A, T_B", test_data)
def test_scrump_plus_plus_A_B_join_full_swap(T_A, T_B):
m = 3
zone = int(np.ceil(m / 4))
ref_mp = naive.stamp(T_B, m, T_B=T_A)
ref_P = ref_mp[:, 0]
ref_I = ref_mp[:, 1]
ref_left_I = ref_mp[:, 2]
ref_right_I = ref_mp[:, 3]
approx = scrump(
T_B, m, T_B=T_A, ignore_trivial=False, percentage=1.0, pre_scrump=True, s=zone
)
approx.update()
comp_P = approx.P_
comp_I = approx.I_
comp_left_I = approx.left_I_
comp_right_I = approx.right_I_
naive.replace_inf(ref_P)
naive.replace_inf(comp_P)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
npt.assert_almost_equal(ref_left_I, comp_left_I)
npt.assert_almost_equal(ref_right_I, comp_right_I)
@pytest.mark.parametrize("percentages", percentages)
def test_scrump_constant_subsequence_self_join(percentages):
T = np.concatenate((np.zeros(20, dtype=np.float64), np.ones(5, dtype=np.float64)))
m = 3
zone = int(np.ceil(m / 4))
for percentage in percentages:
seed = np.random.randint(100000)
np.random.seed(seed)
ref_mp = naive.scrump(T, m, T, percentage, zone, False, None)
ref_P = ref_mp[:, 0]
ref_I = ref_mp[:, 1]
ref_left_I = ref_mp[:, 2]
ref_right_I = ref_mp[:, 3]
np.random.seed(seed)
approx = scrump(
T, m, ignore_trivial=True, percentage=percentage, pre_scrump=False
)
approx.update()
comp_P = approx.P_
comp_I = approx.I_
comp_left_I = approx.left_I_
comp_right_I = approx.right_I_
naive.replace_inf(ref_P)
naive.replace_inf(comp_P)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
npt.assert_almost_equal(ref_left_I, comp_left_I)
npt.assert_almost_equal(ref_right_I, comp_right_I)
@pytest.mark.parametrize("percentages", percentages)
def test_scrump_identical_subsequence_self_join(percentages):
identical = np.random.rand(8)
T = np.random.rand(20)
T[1 : 1 + identical.shape[0]] = identical
T[11 : 11 + identical.shape[0]] = identical
m = 3
zone = int(np.ceil(m / 4))
for percentage in percentages:
seed = np.random.randint(100000)
np.random.seed(seed)
ref_mp = naive.scrump(T, m, T, percentage, zone, False, None)
ref_P = ref_mp[:, 0]
# ref_I = ref_mp[:, 1]
# ref_left_I = ref_mp[:, 2]
# ref_right_I = ref_mp[:, 3]
np.random.seed(seed)
approx = scrump(
T, m, ignore_trivial=True, percentage=percentage, pre_scrump=False
)
approx.update()
comp_P = approx.P_
# comp_I = approx.I_
# comp_left_I = approx.left_I_
# comp_right_I = approx.right_I_
naive.replace_inf(ref_P)
naive.replace_inf(comp_P)
npt.assert_almost_equal(ref_P, comp_P, decimal=config.STUMPY_TEST_PRECISION)
# npt.assert_almost_equal(ref_I, comp_I)
# npt.assert_almost_equal(ref_left_I, comp_left_I)
# npt.assert_almost_equal(ref_right_I, comp_right_I)
@pytest.mark.parametrize("T_A, T_B", test_data)
@pytest.mark.parametrize("substitute", substitution_values)
@pytest.mark.parametrize("substitution_locations", substitution_locations)
@pytest.mark.parametrize("percentages", percentages)
def test_scrump_nan_inf_self_join(
T_A, T_B, substitute, substitution_locations, percentages
):
m = 3
T_B_sub = T_B.copy()
for substitution_location in substitution_locations:
T_B_sub[:] = T_B[:]
T_B_sub[substitution_location] = substitute
zone = int(np.ceil(m / 4))
for percentage in percentages:
seed = np.random.randint(100000)
np.random.seed(seed)
ref_mp = naive.scrump(T_B_sub, m, T_B_sub, percentage, zone, False, None)
ref_P = ref_mp[:, 0]
ref_I = ref_mp[:, 1]
ref_left_I = ref_mp[:, 2]
ref_right_I = ref_mp[:, 3]
np.random.seed(seed)
approx = scrump(T_B_sub, m, percentage=percentage, pre_scrump=False)
approx.update()
comp_P = approx.P_
comp_I = approx.I_
comp_left_I = approx.left_I_
comp_right_I = approx.right_I_
naive.replace_inf(ref_P)
naive.replace_inf(comp_P)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
npt.assert_almost_equal(ref_left_I, comp_left_I)
npt.assert_almost_equal(ref_right_I, comp_right_I)
@pytest.mark.parametrize("percentages", percentages)
def test_scrump_nan_zero_mean_self_join(percentages):
T = np.array([-1, 0, 1, np.inf, 1, 0, -1])
m = 3
zone = int(np.ceil(m / 4))
for percentage in percentages:
seed = np.random.randint(100000)
np.random.seed(seed)
ref_mp = naive.scrump(T, m, T, percentage, zone, False, None)
ref_P = ref_mp[:, 0]
ref_I = ref_mp[:, 1]
ref_left_I = ref_mp[:, 2]
ref_right_I = ref_mp[:, 3]
np.random.seed(seed)
approx = scrump(T, m, percentage=percentage, pre_scrump=False)
approx.update()
comp_P = approx.P_
comp_I = approx.I_
comp_left_I = approx.left_I_
comp_right_I = approx.right_I_
naive.replace_inf(ref_P)
naive.replace_inf(comp_P)
npt.assert_almost_equal(ref_P, comp_P)
npt.assert_almost_equal(ref_I, comp_I)
npt.assert_almost_equal(ref_left_I, comp_left_I)
npt.assert_almost_equal(ref_right_I, comp_right_I)
|
463071
|
from NIENV import *
# GENERAL
# self.input(index) <- access to input data
# self.outputs[index].set_val(val) <- set output data port value
# self.main_widget <- access to main widget
# self.exec_output(index) <- executes an execution output
# EDITING
# self.create_new_input(type_, label, widget_name=None, widget_pos='under', pos=-1)
# self.delete_input(input or index)
# self.create_new_output(type_, label, pos=-1)
# self.delete_output(output or index)
# LOGGING
# mylog = self.new_log('Example Log')
# mylog.log('I\'m alive!!')
# self.log_message('hello global!', 'global')
# self.log_message('that\'s not good', 'error')
class %CLASS%(NodeInstance):
def __init__(self, params):
super(%CLASS%, self).__init__(params)
self.special_actions['add target option'] = {'method': M(self.action_add_target_option)}
self.log = self.new_log('Log Node Log')
self.default_target = 'personal'
self.showing_target_option = False
self.target = self.default_target
def action_add_target_option(self):
del self.special_actions['add target option']
self.add_target_option()
def add_target_option(self):
self.special_actions['remove target option'] = {'method': M(self.action_remove_target_option)}
self.create_new_input('data', 'target', widget_name='LogTargetComboBox', widget_pos='besides')
self.showing_target_option = True
def action_remove_target_option(self):
del self.special_actions['remove target option']
self.remove_target_option()
def remove_target_option(self):
self.special_actions['add target option'] = {'method': M(self.action_add_target_option)}
self.delete_input(-1)
self.target = self.default_target
self.showing_target_option = False
def update_event(self, input_called=-1):
if input_called == 0:
if self.target == 'personal':
self.log.log(self.input(1))
else:
self.log_message(self.input(1), target=self.target)
self.exec_output(0)
def get_data(self):
data = {'target': self.target,
'showing target': self.showing_target_option}
return data
def set_data(self, data):
self.target = data['target']
self.showing_target_option = data['showing target']
def remove_event(self):
pass
|
463081
|
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.font_manager
matplotlib.font_manager._rebuild()
import matplotlib.pyplot as plt
import copy
import pickle
import pdb
from matplotlib import rc
# rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
filehandler = open('lmpc_object.pkl', 'rb')
lmpc = pickle.load(filehandler)
# =========================================================
# Plot closed-loop trajectories at iteration j
# =========================================================
it = 19
plt.figure()
xcl = np.array(lmpc.SS[0]).T
plt.plot(xcl[0,:], xcl[1,:], 'sr', label='sampled Safe Set')
for i in range(1,it-1):
xcl = np.array(lmpc.SS[i]).T
plt.plot(xcl[0,:], xcl[1,:], 'sr')
i = it-1
xcl = np.array(lmpc.SS[i]).T
plt.plot(xcl[0,:], xcl[1,:], '-ob', label='LMPC closed-loop')
plt.plot(lmpc.xOpt[0,:], lmpc.xOpt[1,:], '--*k', label='Optimal trajectory')
plt.legend(fontsize=16)
plt.xlabel('$x_1$', fontsize=20)
plt.ylabel('$x_2$', fontsize=20)
plt.xlim([-16,1])
plt.ylim([-0.5,7])
plt.show()
# =========================================================
# Plot closed-loop trajectories
# =========================================================
it = lmpc.it
plt.figure()
xcl = np.array(lmpc.SS[0]).T
plt.plot(xcl[0,:], xcl[1,:], '-dg', label='Initial feasible trajectory')
for i in range(1,it-1):
xcl = np.array(lmpc.SS[i]).T
plt.plot(xcl[0,:], xcl[1,:], 'sr')
plt.plot(0, 0, 'sr', label='Stored data')
i = it-1
xcl = np.array(lmpc.SS[i]).T
plt.plot(xcl[0,:], xcl[1,:], '-ob', label='LMPC closed-loop')
plt.plot(lmpc.xOpt[0,:], lmpc.xOpt[1,:], '--*k', label='Optimal trajectory')
plt.legend(fontsize=16)
plt.xlabel('$x_1$', fontsize=20)
plt.ylabel('$x_2$', fontsize=20)
# =========================================================
# Plot iteration cost
# =========================================================
plt.figure()
totCost = []
for i in range(0,it):
xcl = np.array(lmpc.SS[i]).T
totCost.append(lmpc.Qfun[i][0])
plt.plot(totCost, '-ob', label='Iteration Cost')
plt.plot([0, it-1], [lmpc.optCost, lmpc.optCost], '--k', label='Optimal cost')
plt.xlabel('$\mathrm{Iteration}$', fontsize=20)
plt.legend(fontsize=16)
# =========================================================
# Plot iteration cost just LMPC
# =========================================================
plt.figure()
totCost = []
for i in range(1,it):
xcl = np.array(lmpc.SS[i]).T
totCost.append(lmpc.Qfun[i][0])
plt.plot(range(1, it, 1),totCost, '-ob', label='Iteration Cost')
plt.plot([0, it-1], [lmpc.optCost, lmpc.optCost], '--k', label='Optimal cost')
plt.xlabel('$\mathrm{Iteration}$', fontsize=20)
plt.legend(fontsize=16)
print("Percentage deviation: ", np.abs((lmpc.optCost-totCost[-1])/lmpc.optCost)*100)
plt.show()
|
463094
|
import numpy as np
import cv2
def blend_map(img, map, factor, colormap=cv2.COLORMAP_JET):
"""
Function to blend an image and a probability map.
:param img: The image
:param map: The map
:param factor: factor * img + (1-factor) * map
:param colormap: a cv2 colormap.
:return: The blended image.
"""
assert 0 < factor < 1, 'factor must satisfy 0 < factor < 1'
map = np.float32(map)
map /= map.max()
map *= 255
map = map.astype(np.uint8)
blend = cv2.addWeighted(src1=img, alpha=factor,
src2=cv2.applyColorMap(map, colormap), beta=(1-factor),
gamma=0)
return blend
palette = np.array([[128, 64, 128],
[244, 35, 232],
[70, 70, 70],
[102, 102, 156],
[190, 153, 153],
[153, 153, 153],
[250, 170, 30],
[220, 220, 0],
[107, 142, 35],
[152, 251, 152],
[70, 130, 180],
[220, 20, 60],
[255, 0, 0],
[0, 0, 142],
[0, 0, 70],
[0, 60, 100],
[0, 80, 100],
[0, 0, 230],
[119, 11, 32]], dtype=np.uint8)
def seg_to_rgb(segm):
prediction = np.argmax(segm, axis=0)
h, w = prediction.shape
rgb = np.reshape(palette[prediction.ravel()], newshape=(h, w, 3))
return rgb
|
463107
|
import cloudsight
def call_vision_api(image_filename, api_keys):
api_key = api_keys['cloudsight']['api_key']
api_secret = api_keys['cloudsight']['api_secret']
# Via example found here:
# https://github.com/cloudsight/cloudsight-python
auth = cloudsight.SimpleAuth(api_key)
api = cloudsight.API(auth)
with open(image_filename, 'rb') as image_file:
response = api.image_request(image_file, image_filename)
response = api.wait(response['token'], timeout=60)
return response
def get_standardized_result(api_result):
output = {
'captions' : [],
}
if api_result['status'] == 'completed':
output['captions'].append((api_result["name"], None))
elif api_result['status'] == 'skipped':
output['captions'].append(("error_skipped_because_" + api_result["reason"], None))
else:
output['captions'].append(("error_" + api_result["status"], None))
return output
|
463110
|
from pythonwarrior.abilities.base import AbilityBase
class DirectionOfStairs(AbilityBase):
def description(self):
return ("Returns the direction ('left', 'right', 'forward',"
"'backward') the stairs are from your location")
def perform(self):
return self._unit.position.relative_direction_of_stairs()
|
463129
|
import logging
from .mem import Ram, Registers, Uniques
from .arch import instantiate_architecture
logger = logging.getLogger(__name__)
class State(object):
def __init__(self, api_base):
self.api_base = api_base
self.arch = instantiate_architecture(self.api_base)
if self.arch is None:
raise RuntimeError("No supported architectures found")
self.registers = Registers(self.api_base, self.arch)
self.ram = Ram(self.api_base, self.arch)
self.uniques = None
def execute_cur_location(self):
return self._step_cur_loc(True)
def inspect_cur_location(self):
return self._step_cur_loc(False)
def _step_cur_loc(self, do_execute):
self.uniques = Uniques(self.api_base, self.arch)
# Get the instructions and instruction size
instrs, instr_size = self.ram.get_code(self.get_pc())
# Step the prog counter before any branches might update it
self.step_pc()
# Execute each instruction
run_type = "Executing" if do_execute else "Instruction"
log_type = logger.debug if do_execute else logger.info
for instr in instrs:
log_type("{} {}".format(run_type, instr))
if do_execute:
instr.execute(self)
logger.debug(self)
return self.get_pc()
def __str__(self):
return "Registers {}\nRam {}\nUniques {}".format(self.registers,
self.ram, self.uniques)
def get_pc(self):
return self.registers.load(self.arch.pc_offset, self.arch.reg_len)
def set_pc(self, location):
self.registers.store(self.arch.pc_offset, self.arch.reg_len, location)
def step_pc(self):
cur_loc = self.get_pc()
_, instr_size = self.ram.get_code(cur_loc)
self.set_pc(cur_loc + instr_size)
def set_varnode(self, varnode, value):
if varnode.isRegister():
self.registers.store(varnode.offset, varnode.size, value)
elif varnode.isUnique():
self.uniques.store(varnode.offset, varnode.size, value)
elif varnode.isAddress():
self.ram.store(varnode.offset, varnode.size, value)
elif varnode.getAddress().isStackAddress():
addr = self.arch.resolve_stack_address(self, varnode.offset)
self.ram.store(addr, varnode.size, value)
else:
raise RuntimeError("Invalid varnode for setting: {}"
"".format(varnode))
def read_varnode(self, varnode):
if varnode.isRegister():
return self.registers.load(varnode.offset, varnode.size)
elif varnode.isUnique():
return self.uniques.load(varnode.offset, varnode.size)
elif varnode.isAddress():
return self.ram.load(varnode.offset, varnode.size)
elif varnode.isConstant():
return varnode.offset
elif varnode.getAddress().isStackAddress():
addr = self.arch.resolve_stack_address(self, varnode.offset)
return self.ram.load(addr, varnode.size)
else:
raise RuntimeError("Unknown varnode type: {}".format(varnode))
def setup_stack(self):
self.arch.setup_stack(self)
def fake_function_call(self, func_addr):
self.arch.fake_function_call(self, func_addr)
|
463161
|
from office365.runtime.client_path import ClientPath
from office365.runtime.odata.odata_path_builder import ODataPathBuilder
class ServiceOperationPath(ClientPath):
""" Resource path to address Service Operations which
represents simple functions exposed by an OData service"""
def __init__(self, name, parameters=None, parent=None):
"""
:type parameters: list or dict or office365.runtime.client_value.ClientValue or None
:type name: str
:type parent: office365.runtime.client_path.ClientPath
"""
super(ServiceOperationPath, self).__init__(parent)
self._name = name
self._parameters = parameters
@property
def segments(self):
return [self.delimiter, ODataPathBuilder.from_operation(self._name, self._parameters)]
|
463184
|
width = int(input())
while width % 2 == 0:
text = input()
totalDots = chr(46) * (width - len(text))
halfDots = int(width / 2)
halfLen = len(text) / 2
firstDots = chr(46) * (halfDots - int(halfLen))
secondDots = chr(46) * (halfDots - int(halfLen))
if text == "END":
break
elif len(text) % 2 != 0:
secondDots = chr(46) * (halfDots - int(halfLen) - 1)
print(firstDots+text+secondDots)
elif len(text) % 2 == 0:
print(firstDots+text+secondDots)
while width % 2 != 0:
text = input()
totalDots = chr(46) * (width - len(text))
halfDots = int(width / 2)
halfLen = len(text) / 2
firstDots = chr(46) * (halfDots - int(halfLen))
secondDots = chr(46) * (halfDots - int(halfLen))
if text == "END":
break
elif len(text) % 2 != 0:
print(firstDots+text+secondDots)
elif len(text) % 2 == 0:
firstDots = chr(46) * (halfDots - int(halfLen) + 1)
print(firstDots+text+secondDots)
|
463217
|
from .modules import Transformer, TransformerEncoderLayer, TransformerDecoderLayer, ScaledDotProductAttention, \
MultiHeadAttention, PositionalEmbedding, PositionWise
|
463228
|
import string
def key_generation(key):
# initializing all and generating key_matrix
main=string.ascii_lowercase.replace('j','.')
# convert all alphabets to lower
key=key.lower()
key_matrix=['' for i in range(5)]
# if we have spaces in key, those are ignored automatically
i=0;j=0
for c in key:
if c in main:
# putting into matrix
key_matrix[i]+=c
# to make sure repeated characters in key
# doesnt include in the key_matrix, we replace the
# alphabet into . in the main, whenever comes in iteration
main=main.replace(c,'.')
# counting column change
j+=1
# if column count exceeds 5
if(j>4):
# row count is increased
i+=1
# column count is set again to zero
j=0
# to place other alphabets in the key_matrix
# the i and j values returned from the previous loop
# are again used in this loop, continuing the values in them
for c in main:
if c!='.':
key_matrix[i]+=c
j+=1
if j>4:
i+=1
j=0
return(key_matrix)
# Now plaintext is to be converted into cipher text
def conversion(plain_text):
# seggrigating the maeesage into pairs
plain_text_pairs=[]
# replacing repeated characters in pair with other letter, x
cipher_text_pairs=[]
# remove spaces
plain_text=plain_text.replace(" ","")
# convert to lower case
plain_text=plain_text.lower()
# RULE1: if both letters in the pair are same or one letter is left at last,
# replace second letter with x or add x, else continue with normal pairing
i=0
# let plain_text be abhi
while i<len(plain_text):
# i=0,1,2,3
a=plain_text[i]
b=''
if((i+1)==len(plain_text)):
# if the chosen letter is last and doesnt have pair
# then the pai will be x
b='x'
else:
# else the next letter will be pair with the previous letter
b=plain_text[i+1]
if(a!=b):
plain_text_pairs.append(a+b)
# if not equal then leave the next letter,
# as it became pair with previous alphabet
i+=2
else:
plain_text_pairs.append(a+'x')
# else dont leave the next letter and put x
# in place of repeated letter and conitnue with the next letter
# which is repeated (according to algo)
i+=1
print("plain text pairs: ",plain_text_pairs)
for pair in plain_text_pairs:
# RULE2: if the letters are in the same row, replace them with
# letters to their immediate right respectively
flag=False
for row in key_matrix:
if(pair[0] in row and pair[1] in row):
# find will return index of a letter in string
j0=row.find(pair[0])
j1=row.find(pair[1])
cipher_text_pair=row[(j0+1)%5]+row[(j1+1)%5]
cipher_text_pairs.append(cipher_text_pair)
flag=True
if flag:
continue
# RULE3: if the letters are in the same column, replace them with
# letters to their immediate below respectively
for j in range(5):
col="".join([key_matrix[i][j] for i in range(5)])
if(pair[0] in col and pair[1] in col):
# find will return index of a letter in string
i0=col.find(pair[0])
i1=col.find(pair[1])
cipher_text_pair=col[(i0+1)%5]+col[(i1+1)%5]
cipher_text_pairs.append(cipher_text_pair)
flag=True
if flag:
continue
#RULE:4 if letters are not on the same row or column,
# replace with the letters on the same row respectively but
# at the other pair of corners of rectangle,
# which is defined by the original pair
i0=0
i1=0
j0=0
j1=0
for i in range(5):
row=key_matrix[i]
if(pair[0] in row):
i0=i
j0=row.find(pair[0])
if(pair[1] in row):
i1=i
j1=row.find(pair[1])
cipher_text_pair=key_matrix[i0][j1]+key_matrix[i1][j0]
cipher_text_pairs.append(cipher_text_pair)
print("cipher text pairs: ",cipher_text_pairs)
# final statements
print('plain text: ',plain_text)
print('cipher text: ',"".join(cipher_text_pairs))
key=input("Enter the key: ")
# calling first function
key_matrix=key_generation(key)
print("Key Matrix for encryption:")
print(key_matrix)
plain_text=input("Enter the message: ")
# calling second function
conversion(plain_text)
'''
----------OUTPUT----------
Enter the key: Make my day beautiful
Key Matrix for encryption:
['makey', 'dbuti', 'flcgh', 'nopqr', 'svwxz']
Enter the message: hi there my name is abhiram
plain text pairs: ['hi', 'th', 'er', 'em', 'yn', 'am', 'ei', 'sa', 'bh', 'ir', 'am']
cipher text pairs: ['rh', 'ig', 'yq', 'ya', 'mr', 'ka', 'yt', 'vm', 'il', 'hz', 'ka']
plain text: hitheremynameisabhiram
cipher text: rhigyqyamrkaytvmilhzka
>>>
'''
'''
Took help from:
1. https://www.youtube.com/watch?v=U_J2xnhblPg
2. https://www.youtube.com/watch?v=O8MxWNfrzho&t=4s
3. https://www.youtube.com/watch?v=66K1tplwYqg&t=5s
4. https://www.youtube.com/watch?v=2PUInSjhxNs
Thanks for the help !!!
'''
|
463233
|
import unittest
from py.game_logic.Research import Research
class Research_test(unittest.TestCase):
def test_add_and_check_researched_nodes(self):
res = Research()
node= 'advanced spam canning'
self.assertFalse(res.isUnlocked(node))
res.unlock(node)
self.assertTrue(res.isUnlocked(node))
|
463237
|
from interpretador.interpretador import Interpretador
class ConfigurarInterpretador:
def __init__(self):
pass
def gerar_regex_compilado_interpretador(self, dicLetras:dict, dic_comandos:dict, idioma:str) -> tuple:
"""Compila todos os regex que o interpretador poderá usar
Args:
Returns: (regex_compilado, regex_comandos)
"""
diretorio_base = ''
bool_ignorar_todos_breakpoints = True
bool_logs = False
dic_regex_compilado = None
re_comandos = None
instancia = Interpretador(
bool_logs,
[],
bool_ignorar_todos_breakpoints,
diretorio_base,
dicLetras,
dic_comandos,
idioma,
dic_regex_compilado,
re_comandos)
dic_regex_compilado = instancia.dic_regex_compilado
re_comandos = instancia.re_comandos
del instancia
del diretorio_base
del bool_ignorar_todos_breakpoints
del bool_logs
return (dic_regex_compilado, re_comandos)
def carregar_dicionario_letra(self, dic_comandos:dict) -> dict:
"""
Carrega um dicionário com as primeiras letras de todos os comandos disponíveis
"""
dic_letras = {}
# Anda por todos os comandos
for k, v in dic_comandos.items():
# Cria uma lista pela chave de cada comando
dic_letras[k] = []
# Para cada subcomando
for valor in v["comando"]:
# Pega a primeira letra do subcomando
valor = valor[0].strip()
# Adiona no dicionário a primeira letra do comando
if valor == "":
dic_letras[k].append(valor)
else:
valor = valor.lower()
if valor[0] not in dic_letras[k]:
dic_letras[k].append(valor[0])
return dic_letras
|
463243
|
from time import gmtime, strftime
import os
import reporter
def getTimeStamp():
return strftime("%Y/%m/%d | %H:%M:%S", gmtime())
def info(message, sendReport=False):
logAndWrite(getTimeStamp(), " | INFO | ", message)
if sendReport:
reporter.report('info', message)
def warn(message, sendReport=False):
logAndWrite(getTimeStamp(), " | WARN | ", message)
if sendReport:
reporter.report('warn', message)
def crit(message, sendReport=False):
logAndWrite(getTimeStamp(), " | CRIT | ", message)
if sendReport:
reporter.report('crit', message)
def logAndWrite(timestamp, code, message):
print(timestamp + code + message)
f = open(logFile, 'a+')
f.write(timestamp + code + message + '\n')
f.close()
def announceLogFile(sendReport = True):
info("Logging to: " + logFileName, sendReport)
logDir = "logs"
if not os.path.exists(logDir):
os.makedirs(logDir)
logFileName = "ucscresults.monitor." + strftime("%Y%m%d.%H%M%S", gmtime()) + ".log"
logFile = logDir + '/' + logFileName
|
463279
|
import errno
import json
import logging
import os
__all__ = ['get_config', 'get_default_config_filename', 'get_application_config', 'expand_env_vars']
logger = logging.getLogger(__name__)
def get_default_config_filename():
config_filename = os.path.join(os.path.abspath(os.getcwd()), "application.cfg")
return config_filename
def _load_secrets(filename='/secrets'): # pragma: no cover
try:
with open(filename, 'r') as secrets_file:
secrets = json.load(secrets_file)
except IOError as e:
if e.errno in (errno.ENOENT, errno.EISDIR):
return {}
e.strerror = 'Unable to load configuration file (%s)' % e.strerror
raise
return secrets
def get_config(config_filename=None, secrets_file='/secrets'):
config_filename = config_filename or get_default_config_filename()
logger.debug('config filename: {}'.format(config_filename))
with open(config_filename, 'r') as cfg:
config = json.load(cfg)
secrets = _load_secrets(filename=secrets_file)
if secrets: # pragma: no cover
try:
import secure_config.secrets as sec
config = sec.load_secret_dict(password=secrets['encryption_key'], config_dict=config)
except ImportError as e:
logger.debug('secure_config not installed')
return config
def get_application_config(config):
try:
return config['application']
except KeyError:
return []
def get_meta_db_config_path(config):
username = get_user(config)
password = get_password(config)
db_path = 'postgresql://{db_username}:{db_pwd}@{host}:{port}/{db_name}'.format(
db_name=config['metadb']['db_name'],
db_username=username,
db_pwd=password,
host=config['metadb']['host'],
port=config['metadb']['port']
)
return db_path
def get_user(config):
try:
server = config['metadb']['server']
username = '@'.join([config['metadb']['db_username'], server])
except KeyError:
username = config['metadb']['db_username']
return username
def get_password(config):
try:
password = config['metadb']['db_pwd'].decrypt()
except AttributeError:
password = config['metadb']['db_pwd']
return password
|
463308
|
function diginto(thestruct, level)
if nargin < 2
level = 0;
end
fn = fieldnames(thestruct);
for n = 1:length(fn)
tabs = '';
for m = 1:level
tabs = [tabs ' '];
end
disp([tabs fn{n}])
fn2 = getfield(thestruct,fn{n});
if isstruct(fn2)
diginto(fn2, level+1);
end
end
end
|
463341
|
import os,sys
import gzip
review_file = sys.argv[1]
output_path = sys.argv[2]
min_count = int(sys.argv[3])
output_path += 'min_count' + str(min_count) + '/'
if not os.path.exists(output_path):
os.makedirs(output_path)
#read all words, users, products
word_count_map = {}
user_set = set()
product_set = set()
with gzip.open(review_file, 'r') as g:
for l in g:
l = eval(l)
user = l['reviewerID']
product = l['asin']
review_text = l['reviewText']
summary = l['summary']
user_set.add(user)
product_set.add(product)
for term in review_text.strip().split(' '):
if term not in word_count_map:
word_count_map[term] = 0
word_count_map[term] += 1
for term in summary.strip().split(' '):
if term not in word_count_map:
word_count_map[term] = 0
word_count_map[term] += 1
#filter vocabulary by min_count
delete_key = set()
for key in word_count_map:
if word_count_map[key] < min_count:
delete_key.add(key)
#output word, user, product indexes
word_list = list(set(word_count_map.keys()) - delete_key)
with gzip.open(output_path + 'vocab.txt.gz','w') as fout:
for word in word_list:
fout.write(word + '\n')
user_list = list(user_set)
with gzip.open(output_path + 'users.txt.gz','w') as fout:
for user in user_list:
fout.write(user + '\n')
product_list = list(product_set)
with gzip.open(output_path + 'product.txt.gz','w') as fout:
for product in product_list:
fout.write(product + '\n')
#read and output indexed reviews
def index_set(s):
i = 0
s_map = {}
for key in s:
s_map[key] = str(i)
i += 1
return s_map
word_map = index_set(word_list)
user_map = index_set(user_list)
product_map = index_set(product_list)
with gzip.open(output_path + 'review_text.txt.gz', 'w') as fout_text, gzip.open(output_path + 'review_u_p.txt.gz', 'w') as fout_u_p:
with gzip.open(output_path + 'review_id.txt.gz', 'w') as fout_id:
with gzip.open(review_file, 'r') as g:
index = 0
for l in g:
l = eval(l)
user = l['reviewerID']
product = l['asin']
review_text = l['reviewText']
summary = l['summary']
count_words = 0
for term in summary.strip().split(' '):
if term in word_map:
fout_text.write(word_map[term] + ' ')
count_words += 1
for term in review_text.strip().split(' '):
if term in word_map:
fout_text.write(word_map[term] + ' ')
count_words += 1
if count_words > 0:
fout_text.write('\n')
fout_u_p.write(user_map[user] + ' ' + product_map[product] + '\n')
fout_id.write('line_' + str(index) + '\n')
index += 1
|
463345
|
import tensorwatch as tw
import random, time
def static_hist():
w = tw.Watcher()
s = w.create_stream()
v = tw.Visualizer(s, vis_type='histogram', bins=6)
v.show()
for _ in range(100):
s.write(random.random()*10)
tw.plt_loop()
def dynamic_hist():
w = tw.Watcher()
s = w.create_stream()
v = tw.Visualizer(s, vis_type='histogram', bins=6, clear_after_each=True)
v.show()
for _ in range(100):
s.write([random.random()*10 for _ in range(100)])
tw.plt_loop(count=3)
dynamic_hist()
|
463351
|
import torch
import torch.nn as nn
from models.word_model import CaptionModel
class Seq2SeqAttention(nn.Module):
def __init__(self, hs_enc, hs_dec, attn_size):
"""
Args:
hs_enc: encoder hidden size
hs_dec: decoder hidden size
attn_size: attention vector size
"""
super(Seq2SeqAttention, self).__init__()
self.h2attn = nn.Linear(hs_enc + hs_dec, attn_size)
self.v = nn.Parameter(torch.randn(attn_size))
nn.init.kaiming_uniform_(self.h2attn.weight)
def forward(self, h_dec, h_enc, src_lens):
"""
Args:
h_dec: decoder hidden state, [N, hs_dec]
h_enc: encoder hiddens/outputs, [N, src_max_len, hs_enc]
src_lens: source (encoder input) lengths, [N, ]
"""
N = h_enc.size(0)
src_max_len = h_enc.size(1)
h_dec = h_dec.unsqueeze(1).repeat(1, src_max_len, 1) # [N, src_max_len, hs_dec]
attn_input = torch.cat((h_dec, h_enc), dim=-1)
attn_out = torch.tanh(self.h2attn(attn_input)) # [N, src_max_len, attn_size]
v = self.v.repeat(N, 1).unsqueeze(1) # [N, 1, attn_size]
# score = torch.bmm(v, attn_out.permute(0, 2, 1)).squeeze(1) # [N, src_max_len]
score = (v@attn_out.permute(0, 2, 1)).squeeze(1) # [N, src_max_len]
idxs = torch.arange(src_max_len).repeat(N).view(N, src_max_len)
mask = (idxs < src_lens.view(-1, 1)).to(h_dec.device)
score = score.masked_fill(mask == 0, -1e10)
weights = torch.softmax(score, dim=-1) # [N, src_max_len]
# ctx = torch.bmm(weights.unsqueeze(1), h_enc).squeeze(1) # [N, hs_enc]
ctx = (weights.unsqueeze(1)@h_enc).squeeze(1) # [N, hs_enc]
return ctx, weights
class Seq2SeqAttnModel(CaptionModel):
def __init__(self, encoder, decoder, **kwargs):
super(Seq2SeqAttnModel, self).__init__(encoder, decoder, **kwargs)
def train_forward(self, encoded, caps, cap_lens, **kwargs):
# Bahdanau attention only supports step-by-step implementation, so we implement forward in
# step-by-step manner whether in training or evaluation
return self.stepwise_forward(encoded, caps, cap_lens, **kwargs)
def prepare_output(self, encoded, output, max_length):
super(Seq2SeqAttnModel, self).prepare_output(encoded, output, max_length)
attn_weights = torch.empty(output["seqs"].size(0), max(encoded["audio_embeds_lens"]), max_length)
output["attn_weights"] = attn_weights
def prepare_decoder_input(self, decoder_input, encoded, caps, output, t, **kwargs):
super(Seq2SeqAttnModel, self).prepare_decoder_input(decoder_input, encoded, caps, output, t, **kwargs)
if t == 0:
decoder_input["enc_mem"] = encoded["audio_embeds"]
decoder_input["enc_mem_lens"] = encoded["audio_embeds_lens"]
if encoded["state"] is None:
state = self.decoder.init_hidden(output["seqs"].size(0))
state = state.to(encoded["audio_embeds"].device)
decoder_input["state"] = state
# decoder_input: { "word": ..., "state": ..., "enc_mem": ..., "enc_mem_lens": ... }
def stepwise_process_step(self, output, output_t, t, sampled):
super(Seq2SeqAttnModel, self).stepwise_process_step(output, output_t, t, sampled)
output["attn_weights"][:, :, t] = output_t["weights"]
def prepare_beamsearch_output(self, output, beam_size, encoded, max_length):
super(Seq2SeqAttnModel, self).prepare_beamsearch_output(output, beam_size, encoded, max_length)
output["attn_weights"] = torch.empty(beam_size, max(encoded["audio_embeds_lens"]), max_length)
def prepare_beamsearch_decoder_input(self, decoder_input, encoded, output, i, t, beam_size):
super(Seq2SeqAttnModel, self).prepare_beamsearch_decoder_input(decoder_input, encoded, output, i, t, beam_size)
if t == 0:
enc_mem = encoded["audio_embeds"][i]
decoder_input["enc_mem"] = enc_mem.unsqueeze(0).repeat(beam_size, 1, 1)
enc_mem_lens = encoded["audio_embeds_lens"][i]
decoder_input["enc_mem_lens"] = enc_mem_lens.repeat(beam_size)
if decoder_input["state"] is None:
decoder_input["state"] = self.decoder.init_hidden(beam_size)
decoder_input["state"] = decoder_input["state"].to(decoder_input["enc_mem"].device)
def beamsearch_step(self, decoder_input, encoded, output, i, t, beam_size):
output_t = super(Seq2SeqAttnModel, self).beamsearch_step(decoder_input, encoded, output, i, t, beam_size)
output["attn_weights"][:, :, t] = output_t["weights"]
return output_t
def beamsearch_process_step(self, output, output_t):
super().beamsearch_process_step(output, output_t)
output["attn_weights"] = output["attn_weights"][output["prev_word_inds"], :, :]
def beamsearch_process(self, output, output_i, i):
output["seqs"][i] = output_i["seqs"][0]
output["attn_weights"][i] = output_i["attn_weights"][0]
class Seq2SeqAttnEnsemble():
def __init__(self, models, max_length=20) -> None:
self.models = models
self.max_length = max_length
self.end_idx = models[0].end_idx
def inference(self, feats, feat_lens):
encoded = []
for model in self.models:
encoded.append(model.encoder(feats, feat_lens))
N = feats.size(0)
output_seqs = torch.empty(N, self.max_length, dtype=torch.long).fill_(self.end_idx)
|
463361
|
from sdk import *
def delegate(node, account, amount):
newDelegation = NetWorkDelegate(account, amount, node + "/keystore/")
newDelegation.send_network_Delegate()
def check_rewards(result, balance, pending):
if balance != '':
balance = str(balance) + '0' * 18
if int(result['balance']) < int(balance):
sys.exit(-1)
if pending != None:
if len(result['pending']) != len(pending):
sys.exit(-1)
for i, amt in enumerate(pending):
if amt != result['pending'][i]['amount']:
sys.exit(-1)
def check_total_rewards(result, expected_exclude_withdrawn):
if result < expected_exclude_withdrawn:
sys.exit(-1)
if __name__ == "__main__":
# create validator account
funder = addValidatorWalletAccounts(node_0)
# create delegator account
delegator = createAccount(node_0, 2500000, funder)
# delegates some OLT and wait for rewards distribution
delegation_amt = 2000000
delegation_amt_long = str(delegation_amt) + '0' * 18
delegate(node_0, delegator, delegation_amt_long)
wait_for(4)
# query and check balance
res = query_rewards(delegator)
check_rewards(res, '6', [])
# overdraw MUST fail
overdraw_amount = '100' + '0' * 18
withdraw = WithdrawRewards(delegator, overdraw_amount, node_0 + "/keystore/")
withdraw.send(exit_on_err=False, mode=TxSync)
print bcolors.OKGREEN + "#### Overdraw rewards failed as expected" + bcolors.ENDC
# initiate 2 withdrawals
pending = []
total = 0
for i in range(2):
amt = i + 2
amt_long = str(amt) + '0' * 18
withdraw = WithdrawRewards(delegator, amt_long, node_0 + "/keystore/")
withdraw.send(exit_on_err=True, mode=TxSync)
pending.append(amt_long)
total += amt
wait_for(2)
# query account balance before mature
balance_before = query_balance(delegator)
# query and check pending withdrawal
res = query_rewards(delegator)
check_rewards(res, '0', pending)
print bcolors.OKGREEN + "#### Successfully withdrawn delegator rewards" + bcolors.ENDC
# query and check again after maturity
wait_for(4)
res1 = query_rewards(delegator)
check_rewards(res1, '', [])
print bcolors.OKGREEN + "#### Successfully matured delegator rewards" + bcolors.ENDC
# fully undelegate
newDelegation = NetWorkDelegate(delegator, delegation_amt_long, node_0 + "/keystore/")
newDelegation.send_network_undelegate(delegation_amt_long)
wait_for(4)
# withdraw all balance
res2 = query_rewards(delegator)
withdraw = WithdrawRewards(delegator, res2['balance'], node_0 + "/keystore/")
withdraw.send(exit_on_err=True, mode=TxSync)
# test query ListDelegation when there is no delegation and no rewards balance, only pending rewards
wait_for(2)
query_result = query_delegation()
expected_delegation = 0
expected_pending_delegation = 0
expected_pending_rewards = int(res2['balance'])
check_query_delegation(query_result, 0, expected_delegation, expected_pending_delegation, False, expected_pending_rewards)
print bcolors.OKGREEN + "#### Successfully tested query ListDelegation with pending rewards" + bcolors.ENDC
print bcolors.OKGREEN + "#### Successfully withdrawn all rewards" + bcolors.ENDC
# query and check account balance
balance_after = query_balance(delegator)
check_balance(balance_before, balance_after, total + delegation_amt)
# below is to test total rewards query
# create another delegator account
funder1 = addValidatorWalletAccounts(node_1)
delegator1 = createAccount(node_1, 8000000, funder1)
# delegates some OLT and wait for rewards distribution
delegation_amt = '5000000' + '0' * 18
delegate(node_1, delegator1, delegation_amt_long)
wait_for(4)
# initiate 1 withdrawal
amt1 = 3
amt1_long = str(amt1) + '0' * 18
withdraw1 = WithdrawRewards(delegator1, amt1_long, node_1 + "/keystore/")
withdraw1.send(True)
wait_for(7)
# query total rewards and check
res = query_rewards(delegator)
res1 = query_rewards(delegator1)
total = query_total_rewards()
check_total_rewards(total['totalRewards'], int(res['balance']) * pow(10, 18) + int(res1['balance']) * pow(10, 18))
print bcolors.OKGREEN + "#### Successfully tested query total rewards" + bcolors.ENDC
|
463396
|
import argparse
import logging
import sys
import Queue
from migrator.Migrator import Migrator
from migrator.ArtifactoryDockerAccess import ArtifactoryDockerAccess
from migrator.DockerRegistryAccess import DockerRegistryAccess
from migrator.QuayAccess import QuayAccess
from migrator.DTRAccess import DTRAccess
import os
import shutil
dir_path = os.path.dirname(os.path.realpath(__file__))
'''
Entry point and argument parser for Docker to Artifactory migrator
Supports:
generic - Migrate from a generic, token based registry.
ecr - Migrate from an Amazon Elastic Container Registry
quay - Migrate from a SaaS Quay registry.
quayee - Migrate from Quay Enterprise.
'''
# Globals
NUM_OF_WORKERS = 2
MIN_NUM_OF_WORKERS = 1
MAX_NUM_OF_WORKERS = 16
def add_extra_args(parser):
parser.add_argument('--ignore-certs', dest='ignore_cert', action='store_const', const=True, default=False,
help='Ignore any certificate errors from both source and destination')
parser.add_argument('--overwrite', action='store_true',
help='Overwrite existing image/tag on the destination')
parser.add_argument('--num-of-workers', dest='workers', type=int, default=NUM_OF_WORKERS,
help='Number of worker threads. Defaults to %d.' % NUM_OF_WORKERS)
parser.add_argument('-v', '--verbose', action='store_true', help='Make the operation more talkative')
# Provide a predefined set of images to import
parser.add_argument('--image-file', dest='image_file',
help='Limit the import to a set of images in the provided file. '
'Format of new line separated file: \'<image-name>:<tag>\' OR '
'\'<image-name>\' to import all tags of that repository.')
def add_art_access(parser):
art_group = parser.add_argument_group('artifactory')
art_group.add_argument('artifactory', help='The destination Artifactory URL')
art_group.add_argument('username', help='The username to use for authentication to Artifactory')
art_group.add_argument('password', help='The password to use for authentication to Artifactory')
art_group.add_argument('repo', help='The docker repository in Artifactory to store the images')
# Sets up the argument parser for the application
def get_arg_parser():
parser = argparse.ArgumentParser(prog='python DockerMigrator.py', description='Docker registry to Artifactory migrator.')
# Generic Registry Parser
subparsers = parser.add_subparsers(help='sub-command help')
parser_generic = subparsers.add_parser('generic', help='A generic tool to migrate a single registry')
# Source registry access
source_group = parser_generic.add_argument_group('source')
source_group.add_argument('source', help='The source registry URL')
source_group.add_argument('--source-username', help='The username to use for authentication to the source')
source_group.add_argument('--source-password', help='The password to use for authentication to the source')
# Artifactory access
add_art_access(parser_generic)
# Extra options
add_extra_args(parser_generic)
parser_generic.set_defaults(func=generic_migration)
# ECR
parser_ecr = subparsers.add_parser('ecr', help='A tool to migrate from Amazon Elastic Container Registry (ECR)')
# Source registry access
source_group = parser_ecr.add_argument_group('source')
source_group.add_argument('source', help='The source registry URL')
source_group.add_argument('token', help='The token generated by the aws tool')
# Artifactory access
add_art_access(parser_ecr)
# Extra options
add_extra_args(parser_ecr)
parser_ecr.set_defaults(func=ecr_migration)
# DTR
parser_dtr = subparsers.add_parser('dtr', help='A tool to migrate from Docker Trusted Registry (DTR)')
# Source registry access
source_group = parser_dtr.add_argument_group('source')
source_group.add_argument('source', help='The DTR registry URL')
source_group.add_argument('dtr_username', help='The username of a DTR admin')
source_group.add_argument('dtr_password', help='The DTR admin password or token')
# Artifactory access
add_art_access(parser_dtr)
# Extra options
add_extra_args(parser_dtr)
parser_dtr.set_defaults(func=dtr_migration)
# GCR
parser_gcr = subparsers.add_parser('gcr', help='A tool to migrate from Google Container Registry (GCR)')
# Source registry access
source_group = parser_gcr.add_argument_group('source')
source_group.add_argument('--source', help='The source registry URL (defaults to https://gcr.io)',
default='https://gcr.io')
source_group.add_argument('keyfile', help='The Google JSON key file')
# Artifactory access
add_art_access(parser_gcr)
# Extra options
add_extra_args(parser_gcr)
parser_gcr.set_defaults(func=gcr_migration)
# QUAY
parser_quay = subparsers.add_parser('quay', help='A tool specifically for Quay SaaS')
quay = parser_quay.add_argument_group('source')
quay.add_argument('namespace', help='The username or organization to import repositories from')
quay.add_argument('token', help='The OAuth2 Access Token')
# Artifactory access
add_art_access(parser_quay)
# Extra options
add_extra_args(parser_quay)
parser_quay.set_defaults(func=quay_migration)
# Quay enterprise
parser_quay_ee = subparsers.add_parser('quayee', help='A tool specifically for Quay Enterprise')
quay_ee = parser_quay_ee.add_argument_group('source')
quay_ee.add_argument('source', help='The source registry URL')
quay_ee.add_argument('--source-username', help='The super user username')
quay_ee.add_argument('--source-password', help='The super user password')
quay_ee.add_argument('--token', help='The OAuth2 Access Token')
# Artifactory access
add_art_access(parser_quay_ee)
# Extra options
add_extra_args(parser_quay_ee)
parser_quay_ee.set_defaults(func=quay_ee_migration)
return parser
'''
Parse image file
Returns two different lists, one with just image names and one with image/tag tuple.
Example:
Input file:
image_name1
image_name2,
image_name3:tag1
image_name4:tag2
Result:
[image_name1, image_name2,...], [(image_name3, tag1), (image_name4, tag2),...]
'''
def parse_image_file(file_path):
image_names = []
images = []
try:
with open(file_path) as f:
content = f.readlines()
for unprocessed_line in content:
line = unprocessed_line.strip()
if ':' in line:
name, tag = line.split(':')
if name and tag:
images.append((name, tag))
elif len(line) > 0:
image_names.append(line)
return image_names, images
except Exception as ex:
logging.error("Unable to read in image file '%s' due to %s" % (file_path, str(ex)))
return [], []
def parse_key_file(file_path):
try:
with open(file_path) as f:
content = f.read()
return content
except Exception as ex:
logging.error("Unable to read in key file '%s' due to %s" % (file_path, str(ex)))
return None
'''
Generic migration for a V2 token based Docker registry
@param args - The user provided arguments
@param work_dir - The temporary work directory
@registry - The source registry (for info only)
'''
def generic_migration(args, work_dir, registry="generic"):
# Verify the more intricate argument requirements
if bool(args.source_username) != bool(args.source_password):
parser.error("--source-username and --source-password must both be provided or neither.")
if args.workers < MIN_NUM_OF_WORKERS or args.workers > MAX_NUM_OF_WORKERS:
parser.error("--num-of-workers must be between %d and %d." % (MIN_NUM_OF_WORKERS, MAX_NUM_OF_WORKERS))
# Set up and verify the connection to the source registry
source = DockerRegistryAccess(url=args.source, username=args.source_username, password=args.source_password,
ignore_cert=args.ignore_cert)
common_migration(args, work_dir, source, registry)
'''
ECR migration
@param args - The user provided arguments
@param work_dir - The temporary work directory
'''
def ecr_migration(args, work_dir):
if args.workers < MIN_NUM_OF_WORKERS or args.workers > MAX_NUM_OF_WORKERS:
parser.error("--num-of-workers must be between %d and %d." % (MIN_NUM_OF_WORKERS, MAX_NUM_OF_WORKERS))
# Set up and verify the connection to the source registry
source = DockerRegistryAccess(url=args.source, username='AWS', password=args.token, method='basic',
ignore_cert=args.ignore_cert)
common_migration(args, work_dir, source, "ecr")
'''
GCR migration
@param args - The user provided arguments
@param work_dir - The temporary work directory
'''
def gcr_migration(args, work_dir):
if args.workers < MIN_NUM_OF_WORKERS or args.workers > MAX_NUM_OF_WORKERS:
parser.error("--num-of-workers must be between %d and %d." % (MIN_NUM_OF_WORKERS, MAX_NUM_OF_WORKERS))
password = parse_key_file(args.keyfile)
if not password:
sys.exit("Unable to read key file or key is empty.")
# Set up and verify the connection to the source registry
source = DockerRegistryAccess(url=args.source, username='_json_key', password=password, method='basic',
ignore_cert=args.ignore_cert)
common_migration(args, work_dir, source, "gcr")
'''
DTR migration
@param args - The user provided arguments
@param work_dir - The temporary work directory
'''
def dtr_migration(args, work_dir):
if args.workers < MIN_NUM_OF_WORKERS or args.workers > MAX_NUM_OF_WORKERS:
parser.error("--num-of-workers must be between %d and %d." % (MIN_NUM_OF_WORKERS, MAX_NUM_OF_WORKERS))
# Set up and verify the connection to the source registry
source = DTRAccess(url=args.source, username=args.dtr_username, password=args.dtr_password,
ignore_cert=args.ignore_cert)
common_migration(args, work_dir, source, "ecr")
'''
Common migration procedure
@param args - The user provided arguments
@param work_dir - The temporary work directory
@param source - The source access
@registry - The source registry (for info only)
'''
def common_migration(args, work_dir, source, registry="NA"):
if not source.verify_is_v2():
sys.exit("The provided URL does not appear to be a valid V2 repository.")
# Set up and verify the connection to Artifactory
art_access = setup_art_access(args.artifactory, args.username, args.password, args.repo, args.ignore_cert)
image_names = []
q = Queue.Queue()
# Build the list of image/tags
# If the user provides a set of images, don't query the upstream
if 'image_file' in args and args.image_file:
image_names, images = parse_image_file(args.image_file)
for image_name, tag in images:
q.put_nowait((image_name, tag))
else:
logging.info("Requesting catalog from source registry.")
image_names = source.get_catalog()
if not image_names:
print "Found no repositories."
if image_names:
print "Found %d repositories." % len(image_names)
populate_tags(image_names, source, q)
if not q.empty():
# Perform the migration
perform_migration(source, art_access, q, work_dir, registry)
else:
print "Nothing to migrate."
'''
Set up and verify the connection to Artifactory
@param artifactory_url - The URL to the Artifactory instance
@param username - The username to access Artifactory
@param password - The password (API Key, encrypted password, token) to access Artifactory
@param repo - The repo name
@param ignore_cert - True if the certificate to this instance should be ignored
'''
def setup_art_access(artifactory_url, username, password, repo, ignore_cert):
art_access = ArtifactoryDockerAccess(url=artifactory_url, username=username,
password=password, repo=repo, ignore_cert=ignore_cert)
if not art_access.is_valid():
sys.exit("The provided Artifactory URL or credentials do not appear valid.")
if not art_access.is_valid_version():
sys.exit("The provided Artifactory instance is version %s but only 4.4.3+ is supported." %
art_access.get_version())
if not art_access.is_valid_docker_repo():
sys.exit("The repo %s does not appear to be a valid V2 Docker repository." % args.repo)
return art_access
'''
Finds and populates the tags for a set of image names
@param image_names - A list of images names
@param source - Access to the source registry
@param q - The queue to populate with (image_name, tag) tuples
'''
def populate_tags(image_names, source, q):
print "Populating set of image/tags..."
for image_name in image_names:
image_name = str(image_name)
tags = source.get_tags(image_name)
if tags:
print "Found %d tags for repository %s." % (len(tags), image_name)
for tag in tags:
tag = str(tag)
q.put_nowait((image_name, tag))
'''
Perform the migration
@param source - Access to the source registry
@param art_access - Access to the Artifactory destination
@param q - The queue of (image, tag) tuples that have to be migrated
@param work_dir - The temporary working directory
@registry - The source registry (for info only)
'''
def perform_migration(source, art_access, q, work_dir, registry="NA"):
print "Performing migration for %d image/tags." % q.qsize()
art_access.report_usage(registry)
m = Migrator(source, art_access, q, args.workers, args.overwrite, work_dir)
m.migrate()
print "Migration finished."
# Report any skipped images
skipped_list = list(m.get_skipped_queue().queue)
skipped_count = len(skipped_list)
if skipped_list and skipped_count > 0:
print "Skipped %d images because they already exist in Artifactory." % skipped_count
# Report on any failures
failure_list = list(m.get_failure_queue().queue)
failure_count = len(failure_list)
if failure_list and failure_count > 0:
print "Failed to migrate the following %d images: " % failure_count
for image, tag in failure_list:
print " %s/%s" % (image, tag)
def quay_migration(args, work_dir):
# Set up and verify the connection to Artifactory
art_access = setup_art_access(args.artifactory, args.username, args.password, args.repo, args.ignore_cert)
q = Queue.Queue()
# If the user provides a set of images, don't query the upstream
if 'image_file' in args and args.image_file:
image_names, images = parse_image_file(args.image_file)
for image_name, tag in images:
q.put_nowait((image_name, tag))
else:
quay = QuayAccess(args.namespace, args.token)
image_names = quay.get_catalog()
if not image_names:
logging.error("Failed to retrieve catalog.")
# Set up the token based connection to Quay
source = DockerRegistryAccess(url="https://quay.io", username="$oauthtoken", password=args.token,
ignore_cert=args.ignore_cert)
if image_names:
print "Found %d repositories." % len(image_names)
populate_tags(image_names, source, q)
if not q.empty():
# Perform the migration
perform_migration(source, art_access, q, work_dir, "quay")
else:
print "Nothing to migrate."
def quay_ee_migration(args, work_dir):
# Verify arguments
if bool(args.source_username) != bool(args.source_password):
parser.error("--source-username and --source-password must both be provided or neither.")
if bool(args.token) and bool(args.source_username):
parser.error("The token and source username/password arguments are mutually exclusive.")
if not(bool(args.token) or bool(args.source_username)):
parser.error("The token or source username/password arguments must be specified.")
if bool(args.token):
# Transform the token into username/password
args.source_username = "$oauthtoken"
args.source_password = args.token
generic_migration(args, work_dir, "quayee")
def setup_logging(level):
fmt = "%(asctime)s [%(threadName)s] [%(levelname)s]"
fmt += " (%(name)s:%(lineno)d) - %(message)s"
formatter = logging.Formatter(fmt)
stdouth = logging.StreamHandler(sys.stdout)
stdouth.setFormatter(formatter)
logger = logging.getLogger()
logger.setLevel(level)
logger.handlers = []
logger.addHandler(stdouth)
if __name__ == '__main__':
# Argument parsing
logging.info("Parsing and verifying user provided arguments.")
parser = get_arg_parser()
args = parser.parse_args()
# Set log level
if args.verbose:
setup_logging(logging.INFO)
else:
setup_logging(logging.WARN)
# Create temp dir
work_dir = os.path.join(dir_path, 'workdir')
if not os.path.exists(work_dir):
try:
os.makedirs(work_dir)
except:
sys.exit("Failed to create work directory '%s'" % work_dir)
# Calls the appropriate function based on user's selected operation
args.func(args, work_dir)
# Delete temp dir
if os.path.exists(work_dir):
shutil.rmtree(work_dir, ignore_errors=True)
|
463410
|
from torch.nn import Module
from getalp.wsd.torch_fix import *
import math
class PositionalEncoding(Module):
def __init__(self, input_embeddings_size, max_len=5000):
super().__init__()
pe = torch_zeros(max_len, input_embeddings_size) # max_len x input_embeddings_size
position = torch_arange(start=0, end=max_len, step=1).unsqueeze(1) # max_len x 1
div_term = torch_exp((torch_arange(start=0, end=input_embeddings_size, step=2, dtype=torch_float32) * -(math.log(10000.0) / input_embeddings_size)))
pe[:, 0::2] = torch_sin(position.float() * div_term)
pe[:, 1::2] = torch_cos(position.float() * div_term)
pe = pe.unsqueeze(0)
self.register_buffer('pe', pe)
self.pe = pe
self.input_embeddings_size = input_embeddings_size
# inputs:
# - int (seq)
# output:
# - FloatTensor (1 x seq x hidden)
def forward(self, seq: int, full: bool = True):
if full:
return self.pe[:, :seq, :]
else:
return self.pe[:, seq, :]
|
463445
|
import sys
sys.path.append("../")
from settings import (NES_PALETTE_HEX, animation_settings)
from core import sprite
RiderRightStandard01 = sprite(
palette = {
"b":NES_PALETTE_HEX[0, 13],
"w":NES_PALETTE_HEX[3, 0],
"r":NES_PALETTE_HEX[0, 6],
},
matrix = [
"x8w4x8",
"x7w5r1x7",
"x7w4r3x6",
"x7r3b3x7",
"x7w4b1w1x7",
"x7b1r2w4x6",
"x6w2r3x9",
"x5w2b1r2w1x9",
"x5w1b1w1r5x1b1x5",
"x5w1b1w2r3b1r1b1x5",
"x5w1b2w1x3w2b1x5",
"x2r3w2b2w1x1r2w1r4x2",
"x5b2w1b1w2r2w2x3r1x1",
"x2b2r3b1w1b1w1r3w2b2x2",
"x1b2x1r3b1w3r2x1w2x1b2x1",
"b2x2r2x1w1r3b1x1b2w1x2b2",
"b1x2b1x2w2r3b1x1b1x1w2x2b1",
"b1x2w4x1r3x2b1x2w1x2b1",
"b2x3b2x1r4x1b2x3b2",
"x1b2x1b2x4b1x3b2x1b2x1",
"x2b3x10b3x2",
]
)
RiderRightStandard02 = sprite(
palette = {
"b":NES_PALETTE_HEX[0, 13],
"w":NES_PALETTE_HEX[3, 0],
"r":NES_PALETTE_HEX[0, 6],
},
matrix = [
"x7w4x8",
"x6w5r1x7",
"x6w4r3x6",
"x6r3b3x7",
"x6w4b1w1x7",
"x6b1r2w4x6",
"x5w2r3x9",
"x4w2b1r2w1x9",
"x4w1b1w1r2w1x9",
"x4w1b1w1r3x9",
"x4w1b2w1r4x1b1x5",
"x5w1b2w1r2b1r1b1x5",
"x6w1b1w2x1w2b1x5",
"x1r3b3w1b1w1r2w1r4x2",
"x2b5w3r2w3b1x1r1x1",
"x1b1x1r3b1r3b1r2w2x1b1x2",
"b1x2r3w1r3b1r1x1b1w2x1b1x1",
"b1x1w1r2w2r3b1x1b1x1w2x2b1",
"b1x5b1r4x1b1x5b1",
"b2x2b2x3b1x2b2x3b2",
"x1b4x8b4x2",
]
)
RiderRightWheelie01 = sprite(
palette = {
"b":NES_PALETTE_HEX[0, 13],
"w":NES_PALETTE_HEX[3, 0],
"r":NES_PALETTE_HEX[0, 6],
},
matrix = [
"x6w4x10",
"x5w5r1x9",
"x5w4r3x8",
"x5r3b3x9",
"x5w4b1w1x9",
"x5b1r2w4x8",
"x5w1r3x11",
"x4w2r6x1b1x6",
"x4w1b1w1r4b1r1b1x6",
"x4w1b1w2x3w2b1r3x3",
"x4w1b2w2x1r2w2x6",
"x4w3b1w2r3w2b3x2",
"x2r2b2w2b1w1r3w2b1x1b2x1",
"x1r1x2r3b1w1b1w1r2b1w1x3b2",
"x2b2r3b1w2r1x2b1w3x2b1",
"x1b2x1r2w1b1r3x2b2x1w1x2b1",
"b2x3b1w1x1r3x2b2x3b2",
"b1x2b1w3x1r4x2b2x1b2x1",
"b1x2w2x1b1x2r1b1x4b3x2",
"b2x3b2x13",
"x1b2x1b2x14",
"x2b3x15",
]
)
RiderRightWheelie02 = sprite(
palette = {
"b":NES_PALETTE_HEX[0, 13],
"w":NES_PALETTE_HEX[3, 0],
"r":NES_PALETTE_HEX[0, 6],
},
matrix = [
"x3w4x12",
"x2w5r1x11",
"x2w4r3x10",
"x2r3b3x11",
"x2w4b1w1x11",
"x2b1r2w4x1b1x8",
"x2w1r3b1x3b1x2r1x5",
"x2w1r6b1r1b1r2x5",
"x2w1b1r5x1w1r1x2b3x2",
"x2w1b2w1x3r1w3b2x1b2x1",
"x2w2b1w3x1r3w2x3b2",
"x3w1b3w2r3b1w1x4b1",
"x3w4b1w1b1r1x1b1w3x2b1",
"x3b3w3r1x2b2x3b2",
"r2b2r1b1w1r3x3b2x1b2x1",
"x2r3x1r5x3b3x2",
"x1b1r3b1w1r5x7",
"b2x1r2w2x1r2b1x8",
"b1x4w1b1x12",
"b1x2b1w2b1x12",
"b2x3b2x12",
"x1b2x1b2x13",
"x2b3x14",
]
)
RiderRightWheelie03 = sprite(
palette = {
"b":NES_PALETTE_HEX[0, 13],
"w":NES_PALETTE_HEX[3, 0],
"r":NES_PALETTE_HEX[0, 6],
},
matrix = [
"x3w4x11",
"x2w5r1x10",
"x2w4r3x9",
"x2r3b3x10",
"x2w4b1w1x10",
"x2b1r2w4b1x3r1x4",
"x1w2r2b1x3b1x2r1x5",
"x1w2r5b1r1b1r2b3x2",
"x1w1b1r5x1w2r1b2x1b2x1",
"x1w1b1w1r2x2r2w4x2b2",
"x1w1b1w4b1r3b1x1w2x2b1",
"x1w2b3w3r2b1x2w1x2b1",
"x2w4b2w1b1x1b2x3b2",
"x3b2w3r2x2b2x1b2x1",
"x1r1b2r2b1r4x2b3x2",
"x1r1x1r3b1r5x6",
"r1x2r3b1w1r5x5",
"x2b1r2b1w2x1r1b1x7",
"x1b2x3w1b1x10",
"x1b1x3w2b1x10",
"x1b1x2b1w1x1b1x10",
"x1b2x3b2x10",
"x2b2x1b2x11",
"x3b3x12",
]
)
RiderRightWheelie04 = sprite(
palette = {
"b":NES_PALETTE_HEX[0, 13],
"w":NES_PALETTE_HEX[3, 0],
"r":NES_PALETTE_HEX[0, 6],
},
matrix = [
"x2w4x13",
"x1w5r1x12",
"x1w4r3x4r1x6",
"x1r3b3x4r1x2b3x2",
"x1w4b1w1x1b1x2r1x1b2x1b2x1",
"x1b1r2w4b2r1x1b2x3b2",
"w2r2b1x3r1w5x4b1",
"w2r5b1x2w6x2b1",
"w1b1r5x2r2x1b2x3b2",
"w2b1r2w3r4x1b2x1b2x1",
"x1w2b3w3b1r1x3b3x2",
"x2w4b2w1r1b2x7",
"x5w4r2b1r1x6",
"x4b3w1r5x6",
"x4b4r3b1x7",
"x3r1b1r3b1w1r1x8",
"x2r2x1r3w2x9",
"x2r1x2r2x1w1b1x9",
"x1r1x2b2r1x1w1b2x8",
"x4b1x3w1x1b1x8",
"x4b1x2b1w1x1b1x8",
"x4b2x3b2x8",
"x5b2x1b2x9",
"x6b3x10",
]
)
RiderRightWheelie05 = sprite(
palette = {
"b":NES_PALETTE_HEX[0, 13],
"w":NES_PALETTE_HEX[3, 0],
"r":NES_PALETTE_HEX[0, 6],
},
matrix = [
"x2w4x14",
"x1w5r1x13",
"x1w4r3x5r1x6",
"x1r3b3x5r2x1b3x2",
"x1w4b1w1x2b1x2r1x1b2x1b2x1",
"x1b1r2w4x2b1r1x1b2x3b2",
"w2r3b1x3r1w7x2b1",
"w1b1r3x2r2b1w1x2b1x2w1x2b1",
"w2b1r6x1r3b2x3b2",
"x1w2r5w2r3x1b2x1b2x1",
"x1w2b1w2b1w1b1w2b1r1x2b3x2",
"x2w1b3w5r1b1x7",
"x2w5b2w1r3x7",
"x3w3b3r5x6",
"x5b3r1b1r5x5",
"x5b2r2w2r1b1x7",
"x4r1x1r3b1w1x9",
"x4r1x1r3x1w1b1x8",
"x3r2x1b1r1x2w1b2x7",
"x6b1x3w1x1b1x7",
"x6b1x3w1x1b1x7",
"x6b2x3b2x7",
"x7b2x1b2x8",
"x8b3x9",
]
)
RiderRightWheelie06 = sprite(
palette = {
"b":NES_PALETTE_HEX[0, 13],
"w":NES_PALETTE_HEX[3, 0],
"r":NES_PALETTE_HEX[0, 6],
},
matrix = [
"x2w4x12",
"x1w5r1x6b3x2",
"x1w4r3x4b2x1b2x1",
"x1r3b3x2r1x1b2x3b2",
"x1w4b1w1x2r1x1b1x1w2x2b1",
"x1b1r2w4x1r1x1w4x2b1",
"w2r3b1x3r1x1w1b1x3b2",
"w2r4x1b2w3b2x1b2x1",
"w2r3x3r1w1r1x2b3x2",
"w2b1r5b1r4x5",
"w2b1w1r4w2r1b4x3",
"x1w1b2w3b2w2r5x2",
"x1w3b3w3r5x3",
"x2w8r4b1x3",
"x3w4x2b3r2x4",
"x9b2r1w2x4",
"x9b2r2w2b1x2",
"x9b2r2w2b2x1",
"x9r1x1r2x1w1x1b2",
"x9r1x1b1x2w1x2b1",
"x9r1x1b1x2w1x2b1",
"x9r1x1b2x3b2",
"x12b2x1b2x1",
"x13b3x2",
]
)
ExciteBikeBG01 = sprite(
palette = {
"d":NES_PALETTE_HEX[0, 8],
"r":NES_PALETTE_HEX[2, 8],
"g":NES_PALETTE_HEX[2, 9],
"p":NES_PALETTE_HEX[3, 13],
},
matrix = [
"d3g8d8g8d5",
"d3g8d8g8d5",
"g32",
"g32",
"g32",
"g32",
"g32",
"g32",
"g32",
"g32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r2d2r1d2r3d2r1d2r3d2r1d2r3d2r1d2r1",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
]
)
ExciteBikeBG02 = sprite(
palette = {
"d":NES_PALETTE_HEX[0, 10],
"r":NES_PALETTE_HEX[2, 9],
"g":NES_PALETTE_HEX[0, 2],
"p":NES_PALETTE_HEX[3, 9],
},
matrix = [
"d3g8d8g8d5",
"d3g8d8g8d5",
"g32",
"g32",
"g32",
"g32",
"g32",
"g32",
"g32",
"g32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r2d2r1d2r3d2r1d2r3d2r1d2r3d2r1d2r1",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
"r32",
]
)
#Doesn't contrast well with rider's helmet
# ExciteBikeBG02 = sprite(
# palette = {
# "d":NES_PALETTE_HEX[0, 8],
# "r":NES_PALETTE_HEX[2, 8],
# "g":NES_PALETTE_HEX[2, 9],
# "p":NES_PALETTE_HEX[3, 13],
# },
# matrix = [
# "g32",
# "g32",
# "g32",
# "g32",
# "p2g10p6g10p4",
# "p3g8p8g8p5",
# "r1p2g8r1p1r1p2r1p2g8r1p1r1p2",
# "d1r1p1g8r2d1r2d1r1p1g8r2d1r2",
# "d1r2g8d1r1d1r2d1r2g8d1r1d1r2",
# "d1r1d1g8d3r2d1r1d1g8d3r2",
# "d3g8d8g8d5",
# "d3g8d8g8d5",
# "g32",
# "g32",
# "g32",
# "g32",
# "g32",
# "g32",
# "g32",
# "g32",
# "r32",
# "r32",
# "r32",
# "r32",
# "r32",
# "r32",
# "r32",
# "r32",
# "r32",
# "r32",
# "r32",
# "r2d2r1d2r3d2r1d2r3d2r1d2r3d2r1d2r1",
# ]
# )
excitebike_animation = animation_settings(
sprite_list=[
[RiderRightStandard01,
RiderRightStandard02],
[RiderRightWheelie01,
RiderRightWheelie01,
RiderRightWheelie02,
RiderRightWheelie02,
RiderRightWheelie03,
RiderRightWheelie03,
RiderRightWheelie04,
RiderRightWheelie04,
RiderRightWheelie05,
RiderRightWheelie05,
RiderRightWheelie06,
RiderRightWheelie06,
RiderRightWheelie05,
RiderRightWheelie05,
RiderRightWheelie04,
RiderRightWheelie04,
RiderRightWheelie03,
RiderRightWheelie03,
RiderRightWheelie02,
RiderRightWheelie02,
],
],
bg_sprites=[ExciteBikeBG01,
ExciteBikeBG02],
xoffs=[
[0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
],
yoffs=[
[0, 0],
[1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,],
],
frame_time=0.03,
spbg_ratio=2,
center=True,
bg_scroll_speed=(1, 0),
cycles_per_char=5,
reversible=False,
)
|
463497
|
from django.contrib import admin
from .models import Location, State, RegionalLead
class LocationAdmin(admin.ModelAdmin):
list_per_page = 10
list_display = (
'name',
'state')
search_fields = ('name',)
list_filter = (
'name',
'state')
class StateAdmin(admin.ModelAdmin):
list_per_page = 10
search_fields = ('name',)
admin.site.register(Location, LocationAdmin)
admin.site.register(State, StateAdmin)
admin.site.register(RegionalLead)
|
463500
|
from os import getcwd
from sys import path
from cv2 import resize
from foo.pictureR import pictureFind
class Booty:
def __init__(self, cwd):
self.cwd = cwd
self.bootyPicPath = cwd + '/res/booty/pics'
self.bootyList = {'RMA70-12':pictureFind.picRead(self.bootyPicPath + '/RMA70-12.png'),
'RMA70-24':pictureFind.picRead(self.bootyPicPath + '/RMA70-24.png' ),
'白马醇':pictureFind.picRead(self.bootyPicPath + '/白马醇.png'),
'炽合金':pictureFind.picRead(self.bootyPicPath + '/炽合金.png'),
'炽合金块':pictureFind.picRead(self.bootyPicPath + '/炽合金块.png'),
'代糖':pictureFind.picRead(self.bootyPicPath + '/代糖.png'),
'改量装置':pictureFind.picRead(self.bootyPicPath + '/改量装置.png'),
'固源岩':pictureFind.picRead(self.bootyPicPath + '/固源岩.png'),
'固源岩组':pictureFind.picRead(self.bootyPicPath + '/固源岩组.png'),
'聚合凝胶':pictureFind.picRead(self.bootyPicPath + '/聚合凝胶.png'),
'聚酸酯':pictureFind.picRead(self.bootyPicPath + '/聚酸酯.png'),
'聚酸酯块':pictureFind.picRead(self.bootyPicPath + '/聚酸酯块.png'),
'聚酸酯组':pictureFind.picRead(self.bootyPicPath + '/聚酸酯组.png'),
'凝胶':pictureFind.picRead(self.bootyPicPath + '/凝胶.png'),
'扭转醇':pictureFind.picRead(self.bootyPicPath + '/扭转醇.png'),
'破损装置':pictureFind.picRead(self.bootyPicPath + '/破损装置.png'),
'轻锰矿':pictureFind.picRead(self.bootyPicPath + '/轻锰矿.png'),
'全新装置':pictureFind.picRead(self.bootyPicPath + '/全新装置.png'),
'三水锰矿':pictureFind.picRead(self.bootyPicPath + '/三水锰矿.png'),
'双酮':pictureFind.picRead(self.bootyPicPath + '/双酮.png'),
'糖':pictureFind.picRead(self.bootyPicPath + '/糖.png'),
'糖聚块':pictureFind.picRead(self.bootyPicPath + '/糖聚块.png'),
'糖组':pictureFind.picRead(self.bootyPicPath + '/糖组.png'),
'提纯源岩':pictureFind.picRead(self.bootyPicPath + '/提纯源岩.png'),
'酮凝集':pictureFind.picRead(self.bootyPicPath + '/酮凝集.png'),
'酮凝集组':pictureFind.picRead(self.bootyPicPath + '/酮凝集组.png'),
'酮阵列':pictureFind.picRead(self.bootyPicPath + '/酮阵列.png'),
'五水研磨石':pictureFind.picRead(self.bootyPicPath + '/五水研磨石.png'),
'研磨石':pictureFind.picRead(self.bootyPicPath + '/研磨石.png'),
'异铁':pictureFind.picRead(self.bootyPicPath + '/异铁.png'),
'异铁块':pictureFind.picRead(self.bootyPicPath + '/异铁块.png'),
'异铁碎片':pictureFind.picRead(self.bootyPicPath + '/异铁碎片.png'),
'异铁组':pictureFind.picRead(self.bootyPicPath + '/异铁组.png'),
'源岩':pictureFind.picRead(self.bootyPicPath + '/源岩.png'),
'酯原料':pictureFind.picRead(self.bootyPicPath + '/酯原料.png'),
'装置':pictureFind.picRead(self.bootyPicPath + '/装置.png'),
'晶体元件':pictureFind.picRead(self.bootyPicPath + '/晶体元件.png'),
'晶体电子单元':pictureFind.picRead(self.bootyPicPath + '/晶体电子单元.png'),
'晶体电路':pictureFind.picRead(self.bootyPicPath + '/晶体电路.png'),
'辅助芯片':pictureFind.picRead(self.bootyPicPath + '/辅助芯片.png'),
'近卫芯片':pictureFind.picRead(self.bootyPicPath + '/近卫芯片.png'),
'狙击芯片':pictureFind.picRead(self.bootyPicPath + '/狙击芯片.png'),
'术师芯片':pictureFind.picRead(self.bootyPicPath + '/术师芯片.png'),
'特种芯片':pictureFind.picRead(self.bootyPicPath + '/特种芯片.png'),
'先锋芯片':pictureFind.picRead(self.bootyPicPath + '/先锋芯片.png'),
'医疗芯片':pictureFind.picRead(self.bootyPicPath + '/医疗芯片.png'),
'重装芯片':pictureFind.picRead(self.bootyPicPath + '/重装芯片.png'),
'辅助芯片组':pictureFind.picRead(self.bootyPicPath + '/辅助芯片组.png'),
'近卫芯片组':pictureFind.picRead(self.bootyPicPath + '/近卫芯片组.png'),
'狙击芯片组':pictureFind.picRead(self.bootyPicPath + '/狙击芯片组.png'),
'术师芯片组':pictureFind.picRead(self.bootyPicPath + '/术师芯片组.png'),
'特种芯片组':pictureFind.picRead(self.bootyPicPath + '/特种芯片组.png'),
'先锋芯片组':pictureFind.picRead(self.bootyPicPath + '/先锋芯片组.png'),
'医疗芯片组':pictureFind.picRead(self.bootyPicPath + '/医疗芯片组.png'),
'重装芯片组':pictureFind.picRead(self.bootyPicPath + '/重装芯片组.png')}
self.one = pictureFind.picRead(self.cwd + '/res/booty/num/1.png')
self.two = pictureFind.picRead(self.cwd + '/res/booty/num/2.png')
def bootyCheck(self, bootyName, screenshot):
scs = pictureFind.imreadCH(screenshot)
scs = resize(scs, (1920, 1080))
scs = scs[770:1080, 710:1920]
bootyInfo = pictureFind.matchImg(scs, self.bootyList[bootyName], confidencevalue=0.5, targetSize=(0,0))
if bootyInfo == None:
return 0
else:
rdPos = bootyInfo['rectangle'][3]
if '芯片组' in bootyName:
corpX1 = rdPos[0] - 20
corpX2 = rdPos[0] + 25
corpY1 = rdPos[1] + 15
corpY2 = rdPos[1] + 60
elif '芯片' in bootyName:
corpX1 = rdPos[0] - 15
corpX2 = rdPos[0] + 25
corpY1 = rdPos[1] + 15
corpY2 = rdPos[1] + 60
else:
corpX1 = rdPos[0] - 30
corpX2 = rdPos[0] + 10
corpY1 = rdPos[1] + 5
corpY2 = rdPos[1] + 50
if corpX1 < 0 or corpX2 > 1210 or corpY1 < 0 or corpY2 > 310:
return 0
bootyNumPic = scs[corpY1:corpY2, corpX1:corpX2]
oneCheck = pictureFind.matchImg(bootyNumPic, self.one, targetSize=(0,0))
twoCheck = pictureFind.matchImg(bootyNumPic, self.two, targetSize=(0,0))
if oneCheck != None:
return 1
elif twoCheck != None:
return 2
else:
return 0
|
463553
|
from smp_manifold_learning.scripts.proj_ecmnn import eval_projection
import numpy as np
import argparse
parser = argparse.ArgumentParser(allow_abbrev=False)
parser.add_argument("-d", "--dataset_option", default=1, type=int)
if __name__ == '__main__':
n_data_samples = 100
tolerance = 1e-1 # threshold for points to be considered on the manifold
step_size = 0.25
extrapolation_factor = 1.0 # describes extrapolation of sampled data from dataset
rand_seed = 1
plot_results = False
use_sign = False
np.random.seed(rand_seed)
args = parser.parse_args()
dataset_option = args.dataset_option
manifold = {1: "3Dsphere", 2: "3Dcircle", 3: "3dof_v2_traj", 4: "6dof_traj"}
expmode = {0: "normal", 1: "wo_augmentation", 2: "wo_rand_combination_normaleigvecs",
3: "wo_siamese_losses", 4: "wo_nspace_alignment", 5: "noisy_normal",
6: "no_siam_reflection", 7: "no_siam_frac_aug", 8: "no_siam_same_levelvec",
9: "aug_variation"}
epoch = 25
for expmode_id in [0, 1, 3, 4, 5, 6, 7, 8]:
if dataset_option == 4:
hidden_sizes = [128, 64, 32, 16]
else:
hidden_sizes = [36, 24, 18, 10]
if expmode_id == 9:
aug_vars = [1, 2, 3, 4, 5, 6, 7]
else:
aug_vars = [9]
for N_aug in aug_vars:
if expmode_id == 9:
expname = 'normal%d' % N_aug
else:
expname = expmode[expmode_id]
proj_success_frac_list = list()
for randseed in range(3):
log_dir = '/%s/%s/r%02d/best/' % (manifold[dataset_option], expname, randseed)
proj_success_frac = eval_projection(dataset_option, n_data_samples, tolerance,
extrapolation_factor, epoch, hidden_sizes, step_size,
use_sign, log_dir, plot_results)
proj_success_frac_list.append(proj_success_frac)
proj_success_frac_mean = np.mean(np.array(proj_success_frac_list))
proj_success_frac_std = np.std(np.array(proj_success_frac_list))
print('dataset %s , exp mode %s:' % (manifold[dataset_option], expmode[expmode_id]))
print(' proj_success_frac = %f +- %f' % (proj_success_frac_mean, proj_success_frac_std))
|
463558
|
from __future__ import print_function
import numpy as np
import os
class NpzDataset(object):
'''
Write out NPZ datasets one file at a time, with information in filenames
for easy access and data aggregation.
This is a fairly slow way to do things but prevents a lot of the problems
with massive amounts of data being held in memory.
'''
def __init__(self, name):
'''
Create a folder to hold different archives in
'''
self.name = os.path.expanduser(name)
try:
os.mkdir(name)
except OSError:
pass
def write(self, example, i, r, image_type=None):
'''
Write an example out to disk.
'''
if r > 0.:
status = "success"
else:
status = "failure"
filename = "example%06d.%s.npz"%(i,status)
filename = os.path.join(self.name, filename)
if image_type is not None:
example["image_type"] = image_type
np.savez(filename, **example)
def load(self,success_only=False):
'''
Read a whole set of data files in. This part could definitely be
faster/more efficient.
Parameters:
-----------
success_only: exclude examples without the "success" tag in their
filename when loading. Good when learning certain types
of models.
Returns:
--------
data: dict of features and other information.
'''
files = os.listdir(self.name)
files.sort()
data = {}
i = 0
for f in files:
if not f[0] == '.':
i += 1
print("%d:"%i, f)
if success_only:
name = f.split('.')
if name[0] == 'failure':
continue
fdata = np.load(os.path.join(self.name,f))
for key, value in fdata.items():
if key not in data:
data[key] = value
if value.shape[0] == 0:
continue
data[key] = np.concatenate([data[key],value],axis=0)
return data
def preprocess(self, train=0.6, val=0.2):
'''
TODO(cpaxton)
Create train/val/test splits
'''
assert train+val <= 1.0 and train+val > 0.
test = 1.0 - train - val
|
463584
|
import importlib
from django.conf import settings
from auction.utils.loader import load_class
LOT_MODEL = getattr(settings, 'AUCTION_LOT_MODEL',
'auction.models.defaults.Lot')
Lot = load_class(LOT_MODEL, 'AUCTION_LOT_MODEL')
|
463600
|
import unittest
from six import StringIO
import sys
import re
import pandas as pd
from auditai import misc
def pass_fail_count(output):
pass_cnt = len(re.findall('pass', output))
fail_cnt = len(re.findall('fail', output))
return pass_cnt, fail_cnt
class TestMisc(unittest.TestCase):
def setUp(self):
self.labels = [0, 0, 0, 0,
1, 1, 1, 1, 1, 1]
self.results = [0.25, 0.25, 0.75, 0.75,
0.25, 0.25, 0.25, 0.75, 0.75, 0.75]
def test_bias_test_check_all_pass(self):
"""
Testing unbias results.
Default test_thresh = 0.50 and all tests pass.
"""
capturedOutput = StringIO()
sys.stdout = capturedOutput
misc.bias_test_check(self.labels, self.results, category='test_group')
sys.stdout = sys.__stdout__
pass_cnt, fail_cnt = pass_fail_count(capturedOutput.getvalue())
self.assertEqual(pass_cnt, 5)
self.assertEqual(fail_cnt, 0)
def test_bias_test_check_below_min_thresh(self):
"""
Testing unbias results at a test_threshold below min(results).
Unable to run all tests all labels are classified into one group.
"""
capturedOutput = StringIO()
sys.stdout = capturedOutput
misc.bias_test_check(self.labels, self.results, category='test_group',
test_thresh=0.20)
sys.stdout = sys.__stdout__
pass_cnt, fail_cnt = pass_fail_count(capturedOutput.getvalue())
self.assertEqual(pass_cnt, 0)
self.assertEqual(fail_cnt, 0)
def test_bias_test_completely_bias(self):
"""
Testing bias results at a test_threshold of 0.50. All tests will fail.
"""
labels = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
results = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
capturedOutput = StringIO()
sys.stdout = capturedOutput
misc.bias_test_check(labels, results, category='test_group')
sys.stdout = sys.__stdout__
pass_cnt, fail_cnt = pass_fail_count(capturedOutput.getvalue())
self.assertEqual(pass_cnt, 0)
self.assertEqual(fail_cnt, 5)
def test_one_way_mi(self):
df = pd.DataFrame({'feat1': [1, 2, 3, 2, 1],
'feat2': [3, 2, 1, 2, 3],
'feat3': [1, 2, 3, 2, 1],
'feat4': [1, 2, 3, 2, 1],
'group': [1, 1, 3, 4, 5],
'y': [1, 2, 1, 1, 2]})
expected_output = {
'feature': {0: 'feat1', 1: 'feat2', 2: 'feat3', 3: 'feat4'},
'group': {0: 0.12, 1: 0.12, 2: 0.12, 3: 0.12},
'group_scaled': {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0},
'y': {0: 0.12, 1: 0.12, 2: 0.12, 3: 0.12},
'y_scaled': {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0}}
features = ['feat1', 'feat2', 'feat3', 'feat4']
group_column = 'group'
y_var = 'y'
output = misc.one_way_mi(df, features, group_column, y_var, (4, 2))
for col in [group_column, y_var,
group_column+'_scaled', y_var+'_scaled']:
output[col] = output[col].round(2)
self.assertEqual(output.to_dict(), expected_output)
|
463729
|
import pathlib
from setuptools import setup
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
requirements = ["click", "fabric", "numpy", "pyYAML", "click-config-file"]
setup(
name="shepherd_herd",
version="0.2.6",
description="Synchronized Energy Harvesting Emulator and Recorder CLI",
long_description=README,
long_description_content_type="text/markdown",
packages=["shepherd_herd"],
license="MIT",
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Information Technology",
"Programming Language :: Python :: 3",
],
install_requires=requirements,
author="<NAME>",
author_email="<EMAIL>",
entry_points={"console_scripts": ["shepherd-herd=shepherd_herd:main"]},
)
|
463768
|
from lie_logger.application import LoggerComponent
from mdstudio.runner import main
if __name__ == '__main__':
main(LoggerComponent)
|
463820
|
from __future__ import print_function, unicode_literals
core_store_students_programs = False
core_store_students_programs_path = 'files_stored'
core_experiment_poll_time = 350 # seconds
# Ports
core_facade_port = 18341
core_facade_server_route = 'testing-route'
core_server_url = 'http://127.0.0.1:%s/weblab/' % core_facade_port
# Scheduling
core_coordinator_db_name = 'WebLabCoordination'
core_coordinator_db_username = 'weblab'
core_coordinator_db_password = '<PASSWORD>'
core_coordinator_laboratory_servers = {
"mylab:myprocess2@myhost" : {
"exp1|dummy1|Dummy experiments" : "dummy1@dummy1",
"exp1|dummy2|Dummy experiments" : "dummy2@dummy2",
}
}
core_coordinator_external_servers = {}
core_scheduling_systems = {
"dummy1" : ("PRIORITY_QUEUE", {}),
"dummy2" : ("PRIORITY_QUEUE", {}),
}
|
463830
|
from typing import List
from calyx.py_ast import *
from dahlia_utils import *
from calyx.gen_exp import generate_exp_taylor_series_approximation
### Dahlia Implementations for Relay Call Nodes ###
# Context: While implementing a Relay frontend for
# Calyx, we decided it would be easier to implement
# the Relay calls, e.g. `nn.softmax`, in Dahlia, and
# then lower the corresponding function definition
# to a Calyx program. Perhaps one day these will
# be replaced directly with Calyx components.
#
# In some cases, there is an effort to allow certain
# functions take on varying dimensionality, which
# trades off code readability for minimizing duplication.
#
# Local variables declared in each Dahlia implementation
# should use the `__` prefix, e.g. `x` should be named `__x`
# to avoid name collisions.
def broadcast(fd: DahliaFuncDef) -> str:
"""Implements array broadcasting:
Two dimensions are compatible when either (1) they're equal,
or (2) one of them is `1`. It is not required that both
operands have the same number of dimensions either. When
lowering from Relay IR, we are guaranteed the arrays are
compatible for broadcasting.
Example:
first operand: 64 x 1 x 32
second operand: 16 x 1
result: 64 x 16 x 32
->
for (i = 0...64) {
for (j = 0..16) {
for (k = 0..32) {
result[i][j][k] := op1[i][0][k] op op2[j][0];
...
Reference: https://numpy.org/doc/stable/user/basics.broadcasting.html
"""
op1, op2, res = fd.args[0], fd.args[1], fd.dest
op1_dims, op2_dims, res_dims = (
get_dims(op1.comp),
get_dims(op2.comp),
get_dims(res.comp),
)
# Get memory sizes in reversed order.
op1_sizes, op2_sizes, res_sizes = [], [], []
for i in reversed(range(0, op1_dims)):
op1_sizes.append(op1.comp.args[i + 1])
for i in reversed(range(0, op2_dims)):
op2_sizes.append(op2.comp.args[i + 1])
for i in reversed(range(0, res_dims)):
res_sizes.append(res.comp.args[i + 1])
# Gets the last variable name for indexing, since
# we will compare sizes in the reverse direction.
index_var = chr(ord(CHARACTER_I) + res_dims - 1)
# Determine the value address value at each index.
# This will either be a variable name or `0`.
index_zero = "[0]"
op1_indices, op2_indices, res_indices = [], [], []
for i in range(0, len(res_sizes)):
current_dimension = f"[__{index_var}]"
res_indices.append(current_dimension)
if op1_dims > op2_dims and len(op2_sizes) <= i:
op1_indices.append(current_dimension)
elif op2_dims > op1_dims and len(op1_sizes) <= i:
op2_indices.append(current_dimension)
elif op1_sizes[i] == op2_sizes[i]:
op1_indices.append(current_dimension)
op2_indices.append(current_dimension)
elif op1_sizes[i] > op2_sizes[i]:
op1_indices.append(current_dimension)
op2_indices.append(index_zero)
else:
# op2_sizes[i] < op1_sizes[i]
op1_indices.append(index_zero)
op2_indices.append(current_dimension)
index_var = next_character(index_var, -1)
# Resulting index in the nested for loop,
# e.g. for `op1[i][j][0][k]`, this is `[i][j][0][k]`.
op1_index = "".join(reversed(op1_indices))
op2_index = "".join(reversed(op2_indices))
res_index = "".join(reversed(res_indices))
loop_body = (
f"{res.id.name}{res_index} := {op1.id.name}{op1_index} "
f"{BinaryOps[fd.function_id]} {op2.id.name}{op2_index};"
)
return emit_dahlia_definition(fd, emit_dahlia_loop(res, loop_body))
def dropout(fd: DahliaFuncDef) -> str:
"""https://tvm.apache.org/docs/api/python/relay/nn.html#tvm.relay.nn.dropout"""
p = fd.attributes.get_str("rate")
data, res = fd.args[0], fd.dest
data_type = fd.data_type
num_dims = get_dims(res.comp)
inverse_rate = 1 / (1 - p)
indices = []
var_name = CHARACTER_I
for n in range(num_dims):
# Determine loop body indices.
indices.append(f"[__{var_name}]")
var_name = next_character(var_name)
indices = "".join(indices)
loop_body = f"{res.id.name}{indices} := {data.id.name}{indices} * ({inverse_rate} as {data_type});"
return emit_dahlia_definition(fd, emit_dahlia_loop(res, loop_body))
# https://github.com/cucapra/calyx/issues/401
# Please read the issue above before trying
# to lower this using `relay.fromtext`.
def expand_dims(fd: DahliaFuncDef) -> str:
"""tvm.apache.org/docs/api/python/relay/index.html#tvm.relay.expand_dims"""
axis = fd.attributes.get_int("axis")
data, res = fd.args[0], fd.dest
res_indices, data_indices = "", ""
var_name = CHARACTER_I
num_dims = get_dims(data.comp)
for n in range(num_dims):
# Determine loop body indices.
index = f"[__{var_name}]"
res_indices += index
data_indices += index
if axis == n + 1:
# Append expanded dimensions.
res_indices += "[0]" * fd.attributes.get_int("num_newaxis")
var_name = next_character(var_name)
loop_body = f"{res.id.name}{res_indices} := {data.id.name}{data_indices};"
return emit_dahlia_definition(fd, emit_dahlia_loop(data, loop_body))
def negative(fd: DahliaFuncDef) -> str:
"""tvm.apache.org/docs/api/python/relay/index.html#tvm.relay.negative"""
inp, res = fd.args[0], fd.dest
var_name = CHARACTER_I
indices = ""
num_dims = get_dims(inp.comp)
for _ in range(num_dims):
# Determine loop body indices.
indices += f"[__{var_name}]"
var_name = next_character(var_name)
zero = f"(0.0 as {fd.data_type})" if "fix" in fd.data_type else "0"
loop_body = f"{res.id.name}{indices} := {zero} - {inp.id.name}{indices};"
return emit_dahlia_definition(fd, emit_dahlia_loop(res, loop_body))
def batch_flatten(fd: DahliaFuncDef) -> str:
"""tvm.apache.org/docs/api/python/relay/nn.html#tvm.relay.nn.batch_flatten"""
data, res = fd.args[0], fd.dest
var_name = CHARACTER_I
args = data.comp.args
data_indices = ""
res_indices = f"[__{var_name}]"
num_dims = get_dims(data.comp)
for i in range(num_dims):
index = f"[__{var_name}]"
data_indices += index
var_name = next_character(var_name)
var_name = f"__{var_name}"
res_indices += f"[{var_name}]"
loop_body = f"""{res.id.name}{res_indices} := \
{data.id.name}{data_indices}; \
{var_name} := {var_name} + 1;"""
return emit_dahlia_definition(
fd,
(
# Uses the index after the batch dimension.
f"let {var_name}: ubit<{res.comp.args[4]}> = 0;",
emit_dahlia_loop(data, loop_body),
),
)
def bias_add(fd: DahliaFuncDef) -> str:
"""tvm.apache.org/docs/api/python/relay/nn.html#tvm.relay.nn.bias_add"""
data, bias, res = fd.args[0], fd.args[1], fd.dest
axis_attribute = fd.attributes.get_int("axis")
num_dims = get_dims(data.comp)
axis = num_dims - 1 if axis_attribute == -1 else axis_attribute
var_name = CHARACTER_I
data_indices = ""
args = data.comp.args
for i in range(num_dims):
# Determine loop body indices based on `axis` provided.
size = args[i + 1]
index_size = args[i + 1 + num_dims]
index = f"[__{var_name}]"
if axis == i:
# Determine which `var_name` is
# associated with the bias index.
bias_index = index
data_indices += index
var_name = next_character(var_name)
loop_body = f"""{res.id.name}{data_indices} :=
{data.id.name}{data_indices} + {bias.id.name}{bias_index};"""
return emit_dahlia_definition(fd, emit_dahlia_loop(data, loop_body))
def max_pool2d(fd: DahliaFuncDef) -> str:
"""tvm.apache.org/docs/api/python/relay/nn.html#tvm.relay.nn.max_pool2d"""
data, res = fd.args[0], fd.dest
strides = fd.attributes.get_int_tuple("strides")
pool_size = fd.attributes.get_int_tuple("pool_size")
layout = fd.attributes.get_str("layout")
ceil_mode = fd.attributes.get_int("ceil_mode")
assert (
layout == "NCHW"
), f"""Layout \'{layout}\' is not currently supported for
nn.max_pool2d; please use `NCHW`."""
assert (
ceil_mode == False
), "`ceil_mode` is not currently supported for nn.max_pool2d"
args = res.comp.args
width = args[0]
data_type = fd.data_type
size0, size1, size2, size3 = args[1:5]
return emit_dahlia_definition(
fd,
f"""for (let __b: ubit<{width}> = 0..{size0}) {{
for (let __c: ubit<{width}> = 0..{size1}) {{
for (let __y: ubit<{width}> = 0..{size2}) {{
for (let __x: ubit<{width}> = 0..{size3}) {{
let __stride_y: ubit<{width}> = __y * {strides[0]}/*strides[0]*/;
let __stride_x: ubit<{width}> = __x * {strides[1]}/*strides[1]*/;
let __max: {data_type} = {data.id.name}[__b][__c][__stride_y][__stride_x];
for (let __m: ubit<{width}> = 0..{pool_size[0]}/*pool_size[0]*/) {{
for (let __n: ubit<{width}> = 0..{pool_size[1]}/*pool_size[1]*/) {{
let __pool_y: ubit<{width}> = __stride_y + __m;
let __pool_x: ubit<{width}> = __stride_x + __n;
let __current: {data_type} = {data.id.name}[__b][__c][__pool_y][__pool_x];
if (__current > __max) {{ __max := __current; }}
}}
}}
{res.id.name}[__b][__c][__y][__x] := __max;
}}
}}
}}
}}
""",
)
def relu(fd: DahliaFuncDef) -> str:
"""tvm.apache.org/docs/api/python/relay/nn.html#tvm.relay.nn.relu"""
data, res = fd.args[0], fd.dest
num_dims = get_dims(data.comp)
args = data.comp.args
indices = ""
var_name = CHARACTER_I
for _ in range(num_dims):
indices += f"[__{var_name}]"
var_name = next_character(var_name)
data_type = fd.data_type
zero = f'({"0.0" if "fix" in data_type else "0"} as {data_type})'
input = f"{data.id.name}{indices}"
result = f"{res.id.name}{indices}"
loop_body = f"""if ({input} > {zero}) {{ {result} := {input}; }}
else {{ {result} := {zero}; }}"""
return emit_dahlia_definition(fd, emit_dahlia_loop(data, loop_body))
def sqrt(fd: DahliaFuncDef) -> str:
"""tvm.apache.org/docs/api/python/relay/index.html#tvm.relay.sqrt"""
data, res = fd.args[0], fd.dest
num_dims = get_dims(data.comp)
args = data.comp.args
indices = ""
var_name = CHARACTER_I
for _ in range(num_dims):
indices += f"[__{var_name}]"
var_name = next_character(var_name)
loop_body = f"""let __tmp = sqrt({data.id.name}{indices});
{res.id.name}{indices} := __tmp;"""
return emit_dahlia_definition(fd, emit_dahlia_loop(data, loop_body))
def batch_matmul(fd: DahliaFuncDef) -> str:
"""tvm.apache.org/docs/api/python/relay/nn.html#tvm.relay.nn.batch_matmul"""
a, b, res = fd.args[0], fd.args[1], fd.dest
type = fd.data_type
bitwidth, M1_size0, M1_size1, M1_size2 = a.comp.args[0:4]
M1_index_size0, M1_index_size1, M1_index_size2 = a.comp.args[4:7]
M2_size0, M2_size1, M2_size2 = b.comp.args[1:4]
M2_index_size0, M2_index_size1, M2_index_size2 = b.comp.args[4:7]
return emit_dahlia_definition(
fd,
f"""let __transpose_{b.id.name}: {type}[{M2_size0}][{M2_size2}][{M2_size1}];
for (let __batch: ubit<{M1_index_size0}> = 0..{M1_size0}) {{
for (let __i: ubit<{M2_index_size1}> = 0..{M2_size1}) {{
for (let __j: ubit<{M2_index_size2}> = 0..{M2_size2}) {{
__transpose_{b.id.name}[__batch][__j][__i] := {b.id.name}[__batch][__i][__j];
}}
}}
}}
---
for (let __batch: ubit<{M1_index_size0}> = 0..{M1_size0}) {{
for (let __i: ubit<{M1_index_size1}> = 0..{M1_size1}) {{
for (let __j: ubit<{M2_index_size1}> = 0..{M2_size1}) {{
for (let __k: ubit<{M2_index_size2}> = 0..{M2_size2}) {{
let __product = {a.id.name}[__batch][__i][__k] * __transpose_{b.id.name}[__batch][__k][__j];
}} combine {{ {res.id.name}[__batch][__i][__j] += __product; }}
}}
}}
}}
""",
)
def dense(fd: DahliaFuncDef) -> str:
"""tvm.apache.org/docs/api/python/relay/nn.html#tvm.relay.nn.dense"""
a, b, res = fd.args[0], fd.args[1], fd.dest
type = fd.data_type
M1_size0, M1_size1 = a.comp.args[1:3]
M1_index_size0, M1_index_size1 = a.comp.args[3:5]
M2_size0, M2_size1, M2_index_size0, M2_index_size1 = b.comp.args[1:5]
return emit_dahlia_definition(
fd,
f"""let __transpose_{b.id.name}: {type}[{M2_size1}][{M2_size0}];
for (let __i: ubit<{M2_index_size0}> = 0..{M2_size0}) {{
for (let __j: ubit<{M2_index_size1}> = 0..{M2_size1}) {{
__transpose_{b.id.name}[__j][__i] := {b.id.name}[__i][__j];
}}
}}
for (let __i: ubit<{M1_index_size0}> = 0..{M1_size0}) {{
for (let __j: ubit<{M2_index_size0}> = 0..{M2_size0}) {{
for (let __k: ubit<{M1_index_size1}> = 0..{M1_size1}) {{
let __product = {a.id.name}[__i][__k] * __transpose_{b.id.name}[__k][__j];
}} combine {{ {res.id.name}[__i][__j] += __product; }}
}}
}}
""",
)
def conv2d(fd: DahliaFuncDef) -> str:
"""tvm.apache.org/docs/api/python/relay/nn.html#tvm.relay.nn.conv2d"""
data, weight, res = fd.args[0], fd.args[1], fd.dest
data_type = fd.data_type
strides = fd.attributes.get_int_tuple("strides")
kernel_size = fd.attributes.get_int_tuple("kernel_size")
size0, size1, size2, size3 = res.comp.args[1:5]
# If no channels provided, inferred from second dimension of the data.
channels = fd.attributes.get_int("channels") or data.comp.args[2]
return emit_dahlia_definition(
fd,
f"""for (let __b: ubit<32> = 0..{size0}) {{
for (let __c: ubit<32> = 0..{size1}) {{
for (let __y: ubit<32> = 0..{size2}) {{
for (let __x: ubit<32> = 0..{size3}) {{
let __sum: {data_type} = {'0.0' if 'fix' in data_type else '0'};
for (let __k: ubit<32> = 0..{channels}) {{
for (let __dy: ubit<32> = 0..{kernel_size[1]}/*kernel_size[1]*/) {{
for (let __dx: ubit<32> = 0..{kernel_size[0]}/*kernel_size[0]*/) {{
let __kernel_y: ubit<32> = (/*strides[0]*/{strides[0]} * __y) + __dy;
let __kernel_x: ubit<32> = (/*strides[1]*/{strides[1]} * __x) + __dx;
}} combine {{
__sum += {data.id.name}[__b][__k][__kernel_y][__kernel_x] *
{weight.id.name}[__c][__k][__dy][__dx];
}}
}}
}}
{res.id.name}[__b][__c][__y][__x] := __sum;
}}
}}
}}
}}
""",
)
def reshape(fd: DahliaFuncDef) -> str:
"""https://tvm.apache.org/docs/api/python/relay/index.html#tvm.relay.reshape"""
data, res = fd.args[0], fd.dest
newshape = fd.attributes.get_int_tuple("newshape")
ddims = get_dims(data.comp)
rdims = get_dims(res.comp)
assert (
# See the TVM Relay API for significance of `newshape` values.
newshape[0] == -1
and rdims == 2
), f"""Only supports a subset of `reshape` functionality (i.e. where the dimensions are inferred).
E.g.
let %x: Tensor[(1, 2, 2, 2), float32] = ...;
let %x1: Tensor[(1, 8), float32] = reshape(%x, newshape[-1, 8]);
---
[Actual] newshape[0]: {newshape[0]}, rdims: {rdims}"""
data_indices, res_indices = "", ""
var_name = CHARACTER_I
for _ in range(ddims):
data_indices += f"[__{var_name}]"
var_name = next_character(var_name)
data_type = fd.data_type
input = f"{data.id.name}{data_indices}"
result = f"{res.id.name}[0][__m]"
loop_body = f"""{result} := {input}; __m += (1 as ubit<{res.comp.args[4]}>);"""
program = (
f"let __m: ubit<{res.comp.args[4]}> = 0;",
emit_dahlia_loop(data, loop_body),
)
return emit_dahlia_definition(fd, program)
def softmax(fd: DahliaFuncDef) -> str:
"""tvm.apache.org/docs/api/python/relay/nn.html#tvm.relay.nn.softmax"""
data, res = fd.args[0], fd.dest
axis = fd.attributes.get_int("axis")
assert axis == -1 or axis == 1, f"nn.softmax with axis = {axis} is not supported."
data_type = fd.data_type
size0, size1, index_size0, index_size1 = data.comp.args[1:5]
return emit_dahlia_definition(
fd,
f"""
let __max :{data_type} = {data.id.name}[0][0];
for (let __i: ubit<{index_size0}> = 0..{size0}) {{
for (let __j: ubit<{index_size1}> = 0..{size1}) {{
if ({data.id.name}[__i][__j] > __max) {{ __max := {data.id.name}[__i][__j]; }}
}}
}}
for (let __i: ubit<{index_size0}> = 0..{size0}) {{
let __exp_sum: {data_type} = {'0.0' if 'fix' in data_type else '0'};
for (let __j: ubit<{index_size1}> = 0..{size1}) {{
let __t0 = {data.id.name}[__i][__j] - __max;
let __t1 = exp(__t0);
__exp_sum += __t1;
}}
for (let __k: ubit<{index_size1}> = 0..{size1}) {{
let __t2 = {data.id.name}[__i][__k] - __max;
let __t3 = exp(__t2);
{res.id.name}[__i][__k] := __t3 / __exp_sum;
}}
}}""",
)
# Mapping from Relay function names to their respective Dahlia lowering.
RelayCallNodes = {
"expand_dims": expand_dims,
"negative": negative,
"batch_flatten": batch_flatten,
"batch_matmul": batch_matmul,
"bias_add": bias_add,
"conv2d": conv2d,
"dense": dense,
"dropout": dropout,
"reshape": reshape,
"max_pool2d": max_pool2d,
"relu": relu,
"softmax": softmax,
"sqrt": sqrt,
}
# Mapping from Relay binary calls to
# the respective Dahlia operator.
BinaryOps = {"add": "+", "divide": "/", "multiply": "*", "subtract": "-"}
def emit_components(func_defs: List[DahliaFuncDef]) -> str:
"""Returns a string containing all the components
created from the list of Dahlia function definitions.
This does not include the import statement.
"""
if not func_defs:
return ""
dahlia_definitions = []
for func_def in func_defs:
id = func_def.function_id
assert (
id in RelayCallNodes or id in BinaryOps
), f"{id} not supported for lowering."
# If the function is a binary operation, use broadcasting.
# Otherwise, use the associated Relay function.
apply = broadcast if id in BinaryOps else RelayCallNodes[id]
dahlia_definitions.append(apply(func_def))
type = func_defs[0].data_type
imports = [
f"""import futil("primitives/math.futil")
{{
def exp(x: {type}): {type};
def sqrt(in: {type}): {type};
def fp_sqrt(in: {type}): {type};
}}"""
]
exp_components = ""
if any(f.function_id == "softmax" for f in func_defs):
# Import `exp` operator for softmax.
sep = type.find(",")
width = int(type[type.find("<") + 1 : sep])
int_width = int(type[sep + 1 : type.find(">")])
exp_components = generate_exp_taylor_series_approximation(
degree=8,
width=width,
int_width=int_width,
is_signed="u" not in type,
)
exp_components = "\n".join(c.doc() for c in exp_components)
return dahlia_to_calyx(imports, dahlia_definitions) + exp_components
|
463835
|
import autograd.numpy as np
import tensorflow as tf
import theano.tensor as T
import torch
from examples._tools import ExampleRunner
from numpy import linalg as la, random as rnd
import pymanopt
from pymanopt.manifolds import FixedRankEmbedded
from pymanopt.solvers import ConjugateGradient
SUPPORTED_BACKENDS = (
"Autograd", "Callable", "PyTorch", "TensorFlow", "Theano"
)
def create_cost_egrad(backend, A, rank):
m, n = A.shape
egrad = None
if backend == "Autograd":
@pymanopt.function.Autograd
def cost(u, s, vt):
X = u @ np.diag(s) @ vt
return np.linalg.norm(X - A) ** 2
elif backend == "Callable":
@pymanopt.function.Callable
def cost(u, s, vt):
X = u @ np.diag(s) @ vt
return la.norm(X - A) ** 2
@pymanopt.function.Callable
def egrad(u, s, vt):
X = u @ np.diag(s) @ vt
S = np.diag(s)
gu = 2 * (X - A) @ (S @ vt).T
gs = 2 * np.diag(u.T @ (X - A) @ vt.T)
gvt = 2 * (u @ S).T @ (X - A)
return gu, gs, gvt
elif backend == "PyTorch":
A_ = torch.from_numpy(A)
@pymanopt.function.PyTorch
def cost(u, s, vt):
X = torch.matmul(u, torch.matmul(torch.diag(s), vt))
return torch.norm(X - A_) ** 2
elif backend == "TensorFlow":
u = tf.Variable(tf.zeros((m, rank), dtype=np.float64), name="u")
s = tf.Variable(tf.zeros(rank, dtype=np.float64), name="s")
vt = tf.Variable(tf.zeros((rank, n), dtype=np.float64), name="vt")
@pymanopt.function.TensorFlow
def cost(u, s, vt):
X = tf.matmul(u, tf.matmul(tf.linalg.diag(s), vt))
return tf.norm(X - A) ** 2
elif backend == "Theano":
u = T.matrix()
s = T.vector()
vt = T.matrix()
@pymanopt.function.Theano(u, s, vt)
def cost(u, s, vt):
X = T.dot(T.dot(u, T.diag(s)), vt)
return (X - A).norm(2) ** 2
else:
raise ValueError("Unsupported backend '{:s}'".format(backend))
return cost, egrad
def run(backend=SUPPORTED_BACKENDS[0], quiet=True):
m, n, rank = 5, 4, 2
matrix = rnd.randn(m, n)
cost, egrad = create_cost_egrad(backend, matrix, rank)
manifold = FixedRankEmbedded(m, n, rank)
problem = pymanopt.Problem(manifold, cost=cost, egrad=egrad)
if quiet:
problem.verbosity = 0
solver = ConjugateGradient()
left_singular_vectors, singular_values, right_singular_vectors = \
solver.solve(problem)
low_rank_approximation = (left_singular_vectors @
np.diag(singular_values) @
right_singular_vectors)
if not quiet:
u, s, vt = la.svd(matrix, full_matrices=False)
indices = np.argsort(s)[-rank:]
low_rank_solution = (u[:, indices] @
np.diag(s[indices]) @
vt[indices, :])
print("Analytic low-rank solution:")
print()
print(low_rank_solution)
print()
print("Rank-{} approximation:".format(rank))
print()
print(low_rank_approximation)
print()
print("Frobenius norm error:",
la.norm(low_rank_approximation - low_rank_solution))
print()
if __name__ == "__main__":
runner = ExampleRunner(run, "Low-rank matrix approximation",
SUPPORTED_BACKENDS)
runner.run()
|
463851
|
import tensorflow as tf
from .op import linear, batch_norm, flatten
from .output import OutputType, Normalization
import numpy as np
from enum import Enum
import os
class Network(object):
def __init__(self, scope_name):
self.scope_name = scope_name
def build(self, input):
raise NotImplementedError
@property
def all_vars(self):
return tf.get_collection(
tf.GraphKeys.GLOBAL_VARIABLES,
scope=self.scope_name)
@property
def trainable_vars(self):
return tf.get_collection(
tf.GraphKeys.TRAINABLE_VARIABLES,
scope=self.scope_name)
def print_layers(self):
print("Layers of {}".format(self.scope_name))
print(self.all_vars)
def save(self, sess, folder):
saver = tf.train.Saver(self.all_vars)
path = os.path.join(folder, "model.ckpt")
saver.save(sess, path)
def load(self, sess, folder):
saver = tf.train.Saver(self.all_vars)
path = os.path.join(folder, "model.ckpt")
saver.restore(sess, path)
class Discriminator(Network):
def __init__(self,
num_layers=5, num_units=200,
scope_name="discriminator", *args, **kwargs):
super(Discriminator, self).__init__(
scope_name=scope_name, *args, **kwargs)
self.num_layers = num_layers
self.num_units = num_units
def build(self, input_feature, input_attribute, train):
with tf.variable_scope(self.scope_name, reuse=tf.AUTO_REUSE):
input_feature = flatten(input_feature)
input_attribute = flatten(input_attribute)
input_ = tf.concat([input_feature, input_attribute], 1)
layers = [input_feature, input_attribute, input_]
for i in range(self.num_layers - 1):
with tf.variable_scope("layer{}".format(i)):
layers.append(linear(layers[-1], self.num_units))
layers.append(tf.nn.relu(layers[-1]))
# if (i > 0):
# layers.append(batch_norm()(layers[-1], train=train))
with tf.variable_scope("layer{}".format(self.num_layers - 1)):
layers.append(linear(layers[-1], 1))
# batch_size * 1
layers.append(tf.squeeze(layers[-1], 1))
# batch_size
return layers[-1]
class AttrDiscriminator(Network):
def __init__(self,
num_layers=5, num_units=200,
scope_name="attrDiscriminator", *args, **kwargs):
super(AttrDiscriminator, self).__init__(
scope_name=scope_name, *args, **kwargs)
self.num_layers = num_layers
self.num_units = num_units
def build(self, input_attribute, train):
with tf.variable_scope(self.scope_name, reuse=tf.AUTO_REUSE):
input_attribute = flatten(input_attribute)
layers = [input_attribute]
for i in range(self.num_layers - 1):
with tf.variable_scope("layer{}".format(i)):
layers.append(linear(layers[-1], self.num_units))
layers.append(tf.nn.relu(layers[-1]))
# if (i > 0):
# layers.append(batch_norm()(layers[-1], train=train))
with tf.variable_scope("layer{}".format(self.num_layers - 1)):
layers.append(linear(layers[-1], 1))
# batch_size * 1
layers.append(tf.squeeze(layers[-1], 1))
# batch_size
return layers[-1]
class RNNInitialStateType(Enum):
ZERO = "ZERO"
RANDOM = "RANDOM"
VARIABLE = "VARIABLE"
class DoppelGANgerGenerator(Network):
def __init__(self, feed_back, noise,
feature_outputs, attribute_outputs, real_attribute_mask,
sample_len,
attribute_num_units=100, attribute_num_layers=3,
feature_num_units=100, feature_num_layers=1,
initial_state=RNNInitialStateType.RANDOM,
initial_stddev=0.02,
scope_name="DoppelGANgerGenerator", *args, **kwargs):
super(DoppelGANgerGenerator, self).__init__(
scope_name=scope_name, *args, **kwargs)
self.feed_back = feed_back
self.noise = noise
self.attribute_num_units = attribute_num_units
self.attribute_num_layers = attribute_num_layers
self.feature_num_units = feature_num_units
self.feature_outputs = feature_outputs
self.attribute_outputs = attribute_outputs
self.real_attribute_mask = real_attribute_mask
self.feature_num_layers = feature_num_layers
self.sample_len = sample_len
self.initial_state = initial_state
self.initial_stddev = initial_stddev
self.feature_out_dim = (np.sum([t.dim for t in feature_outputs]) *
self.sample_len)
self.attribute_out_dim = np.sum([t.dim for t in attribute_outputs])
if not self.noise and not self.feed_back:
raise Exception("noise and feed_back should have at least "
"one True")
self.real_attribute_outputs = []
self.addi_attribute_outputs = []
self.real_attribute_out_dim = 0
self.addi_attribute_out_dim = 0
for i in range(len(self.real_attribute_mask)):
if self.real_attribute_mask[i]:
self.real_attribute_outputs.append(
self.attribute_outputs[i])
self.real_attribute_out_dim += self.attribute_outputs[i].dim
else:
self.addi_attribute_outputs.append(
self.attribute_outputs[i])
self.addi_attribute_out_dim += \
self.attribute_outputs[i].dim
for i in range(len(self.real_attribute_mask) - 1):
if (self.real_attribute_mask[i] == False and
self.real_attribute_mask[i + 1] == True):
raise Exception("Real attribute should come first")
self.gen_flag_id = None
for i in range(len(self.feature_outputs)):
if self.feature_outputs[i].is_gen_flag:
self.gen_flag_id = i
break
if self.gen_flag_id is None:
raise Exception("cannot find gen_flag_id")
if self.feature_outputs[self.gen_flag_id].dim != 2:
raise Exception("gen flag output's dim should be 2")
self.STR_REAL = "real"
self.STR_ADDI = "addi"
def build(self, attribute_input_noise, addi_attribute_input_noise,
feature_input_noise, feature_input_data, train,
attribute=None):
with tf.variable_scope(self.scope_name, reuse=tf.AUTO_REUSE):
batch_size = tf.shape(feature_input_noise)[0]
if attribute is None:
all_attribute = []
all_discrete_attribute = []
if len(self.addi_attribute_outputs) > 0:
all_attribute_input_noise = \
[attribute_input_noise,
addi_attribute_input_noise]
all_attribute_outputs = \
[self.real_attribute_outputs,
self.addi_attribute_outputs]
all_attribute_part_name = \
[self.STR_REAL, self.STR_ADDI]
all_attribute_out_dim = \
[self.real_attribute_out_dim,
self.addi_attribute_out_dim]
else:
all_attribute_input_noise = [attribute_input_noise]
all_attribute_outputs = [self.real_attribute_outputs]
all_attribute_part_name = [self.STR_REAL]
all_attribute_out_dim = [self.real_attribute_out_dim]
else:
all_attribute = [attribute]
all_discrete_attribute = [attribute]
if len(self.addi_attribute_outputs) > 0:
all_attribute_input_noise = \
[addi_attribute_input_noise]
all_attribute_outputs = \
[self.addi_attribute_outputs]
all_attribute_part_name = \
[self.STR_ADDI]
all_attribute_out_dim = [self.addi_attribute_out_dim]
else:
all_attribute_input_noise = []
all_attribute_outputs = []
all_attribute_part_name = []
all_attribute_out_dim = []
for part_i in range(len(all_attribute_input_noise)):
with tf.variable_scope(
"attribute_{}".format(all_attribute_part_name[part_i]),
reuse=tf.AUTO_REUSE):
if len(all_discrete_attribute) > 0:
layers = [tf.concat(
[all_attribute_input_noise[part_i]] +
all_discrete_attribute,
axis=1)]
else:
layers = [all_attribute_input_noise[part_i]]
for i in range(self.attribute_num_layers - 1):
with tf.variable_scope("layer{}".format(i)):
layers.append(
linear(layers[-1], self.attribute_num_units))
layers.append(tf.nn.relu(layers[-1]))
layers.append(batch_norm()(
layers[-1], train=train))
with tf.variable_scope(
"layer{}".format(self.attribute_num_layers - 1),
reuse=tf.AUTO_REUSE):
part_attribute = []
part_discrete_attribute = []
for i in range(len(all_attribute_outputs[part_i])):
with tf.variable_scope("output{}".format(i),
reuse=tf.AUTO_REUSE):
output = all_attribute_outputs[part_i][i]
sub_output_ori = linear(layers[-1], output.dim)
if (output.type_ == OutputType.DISCRETE):
sub_output = tf.nn.softmax(sub_output_ori)
sub_output_discrete = tf.one_hot(
tf.argmax(sub_output, axis=1),
output.dim)
elif (output.type_ == OutputType.CONTINUOUS):
if (output.normalization ==
Normalization.ZERO_ONE):
sub_output = tf.nn.sigmoid(
sub_output_ori)
elif (output.normalization ==
Normalization.MINUSONE_ONE):
sub_output = tf.nn.tanh(sub_output_ori)
else:
raise Exception("unknown normalization"
" type")
sub_output_discrete = sub_output
else:
raise Exception("unknown output type")
part_attribute.append(sub_output)
part_discrete_attribute.append(
sub_output_discrete)
part_attribute = tf.concat(part_attribute, axis=1)
part_discrete_attribute = tf.concat(
part_discrete_attribute, axis=1)
part_attribute = tf.reshape(
part_attribute,
[batch_size, all_attribute_out_dim[part_i]])
part_discrete_attribute = tf.reshape(
part_discrete_attribute,
[batch_size, all_attribute_out_dim[part_i]])
# batch_size * dim
part_discrete_attribute = tf.stop_gradient(
part_discrete_attribute)
all_attribute.append(part_attribute)
all_discrete_attribute.append(part_discrete_attribute)
all_attribute = tf.concat(all_attribute, axis=1)
all_discrete_attribute = tf.concat(all_discrete_attribute, axis=1)
all_attribute = tf.reshape(
all_attribute,
[batch_size, self.attribute_out_dim])
all_discrete_attribute = tf.reshape(
all_discrete_attribute,
[batch_size, self.attribute_out_dim])
with tf.variable_scope("feature", reuse=tf.AUTO_REUSE):
all_cell = []
for i in range(self.feature_num_layers):
with tf.variable_scope("unit{}".format(i),
reuse=tf.AUTO_REUSE):
cell = tf.nn.rnn_cell.LSTMCell(
num_units=self.feature_num_units,
state_is_tuple=True)
all_cell.append(cell)
rnn_network = tf.nn.rnn_cell.MultiRNNCell(all_cell)
feature_input_data_dim = \
len(feature_input_data.get_shape().as_list())
if feature_input_data_dim == 3:
feature_input_data_reshape = tf.transpose(
feature_input_data, [1, 0, 2])
feature_input_noise_reshape = tf.transpose(
feature_input_noise, [1, 0, 2])
# time * batch_size * ?
if self.initial_state == RNNInitialStateType.ZERO:
initial_state = rnn_network.zero_state(
batch_size, tf.float32)
elif self.initial_state == RNNInitialStateType.RANDOM:
initial_state = tf.random_normal(
shape=(self.feature_num_layers,
2,
batch_size,
self.feature_num_units),
mean=0.0, stddev=1.0)
initial_state = tf.unstack(initial_state, axis=0)
initial_state = tuple(
[tf.nn.rnn_cell.LSTMStateTuple(
initial_state[idx][0], initial_state[idx][1])
for idx in range(self.feature_num_layers)])
elif self.initial_state == RNNInitialStateType.VARIABLE:
initial_state = []
for i in range(self.feature_num_layers):
sub_initial_state1 = tf.get_variable(
"layer{}_initial_state1".format(i),
(1, self.feature_num_units),
initializer=tf.random_normal_initializer(
stddev=self.initial_stddev))
sub_initial_state1 = tf.tile(
sub_initial_state1, (batch_size, 1))
sub_initial_state2 = tf.get_variable(
"layer{}_initial_state2".format(i),
(1, self.feature_num_units),
initializer=tf.random_normal_initializer(
stddev=self.initial_stddev))
sub_initial_state2 = tf.tile(
sub_initial_state2, (batch_size, 1))
sub_initial_state = tf.nn.rnn_cell.LSTMStateTuple(
sub_initial_state1, sub_initial_state2)
initial_state.append(sub_initial_state)
initial_state = tuple(initial_state)
else:
raise NotImplementedError
time = feature_input_noise.get_shape().as_list()[1]
if time is None:
time = tf.shape(feature_input_noise)[1]
def compute(i, state, last_output, all_output,
gen_flag, all_gen_flag, all_cur_argmax,
last_cell_output):
input_all = [all_discrete_attribute]
if self.noise:
input_all.append(feature_input_noise_reshape[i])
if self.feed_back:
if feature_input_data_dim == 3:
input_all.append(feature_input_data_reshape[i])
else:
input_all.append(last_output)
input_all = tf.concat(input_all, axis=1)
cell_new_output, new_state = rnn_network(input_all, state)
new_output_all = []
id_ = 0
for j in range(self.sample_len):
for k in range(len(self.feature_outputs)):
with tf.variable_scope("output{}".format(id_),
reuse=tf.AUTO_REUSE):
output = self.feature_outputs[k]
sub_output = linear(
cell_new_output, output.dim)
if (output.type_ == OutputType.DISCRETE):
sub_output = tf.nn.softmax(sub_output)
elif (output.type_ == OutputType.CONTINUOUS):
if (output.normalization ==
Normalization.ZERO_ONE):
sub_output = tf.nn.sigmoid(sub_output)
elif (output.normalization ==
Normalization.MINUSONE_ONE):
sub_output = tf.nn.tanh(sub_output)
else:
raise Exception("unknown normalization"
" type")
else:
raise Exception("unknown output type")
new_output_all.append(sub_output)
id_ += 1
new_output = tf.concat(new_output_all, axis=1)
for j in range(self.sample_len):
all_gen_flag = all_gen_flag.write(
i * self.sample_len + j, gen_flag)
cur_gen_flag = tf.to_float(tf.equal(tf.argmax(
new_output_all[(j * len(self.feature_outputs) +
self.gen_flag_id)],
axis=1), 0))
cur_gen_flag = tf.reshape(cur_gen_flag, [-1, 1])
all_cur_argmax = all_cur_argmax.write(
i * self.sample_len + j,
tf.argmax(
new_output_all[(j * len(self.feature_outputs) +
self.gen_flag_id)],
axis=1))
gen_flag = gen_flag * cur_gen_flag
return (i + 1,
new_state,
new_output,
all_output.write(i, new_output),
gen_flag,
all_gen_flag,
all_cur_argmax,
cell_new_output)
(i, state, _, feature, _, gen_flag, cur_argmax,
cell_output) = \
tf.while_loop(
lambda a, b, c, d, e, f, g, h:
tf.logical_and(a < time,
tf.equal(tf.reduce_max(e), 1)),
compute,
(0,
initial_state,
feature_input_data if feature_input_data_dim == 2
else feature_input_data_reshape[0],
tf.TensorArray(tf.float32, time),
tf.ones((batch_size, 1)),
tf.TensorArray(tf.float32, time * self.sample_len),
tf.TensorArray(tf.int64, time * self.sample_len),
tf.zeros((batch_size, self.feature_num_units))))
def fill_rest(i, all_output, all_gen_flag, all_cur_argmax):
all_output = all_output.write(
i, tf.zeros((batch_size, self.feature_out_dim)))
for j in range(self.sample_len):
all_gen_flag = all_gen_flag.write(
i * self.sample_len + j,
tf.zeros((batch_size, 1)))
all_cur_argmax = all_cur_argmax.write(
i * self.sample_len + j,
tf.zeros((batch_size,), dtype=tf.int64))
return (i + 1,
all_output,
all_gen_flag,
all_cur_argmax)
_, feature, gen_flag, cur_argmax = tf.while_loop(
lambda a, b, c, d: a < time,
fill_rest,
(i, feature, gen_flag, cur_argmax))
feature = feature.stack()
# time * batch_size * (dim * sample_len)
gen_flag = gen_flag.stack()
# (time * sample_len) * batch_size * 1
cur_argmax = cur_argmax.stack()
gen_flag = tf.transpose(gen_flag, [1, 0, 2])
# batch_size * (time * sample_len) * 1
cur_argmax = tf.transpose(cur_argmax, [1, 0])
# batch_size * (time * sample_len)
length = tf.reduce_sum(gen_flag, [1, 2])
# batch_size
feature = tf.transpose(feature, [1, 0, 2])
# batch_size * time * (dim * sample_len)
gen_flag_t = tf.reshape(
gen_flag,
[batch_size, time, self.sample_len])
# batch_size * time * sample_len
gen_flag_t = tf.reduce_sum(gen_flag_t, [2])
# batch_size * time
gen_flag_t = tf.to_float(gen_flag_t > 0.5)
gen_flag_t = tf.expand_dims(gen_flag_t, 2)
# batch_size * time * 1
gen_flag_t = tf.tile(
gen_flag_t,
[1, 1, self.feature_out_dim])
# batch_size * time * (dim * sample_len)
# zero out the parts after sequence ends
feature = feature * gen_flag_t
feature = tf.reshape(
feature,
[batch_size,
time * self.sample_len,
self.feature_out_dim / self.sample_len])
# batch_size * (time * sample_len) * dim
return feature, all_attribute, gen_flag, length, cur_argmax
|
463854
|
import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.hvac_templates import HvactemplateSystemUnitaryHeatPumpAirToAir
log = logging.getLogger(__name__)
class TestHvactemplateSystemUnitaryHeatPumpAirToAir(unittest.TestCase):
def setUp(self):
self.fd, self.path = tempfile.mkstemp()
def tearDown(self):
os.remove(self.path)
def test_create_hvactemplatesystemunitaryheatpumpairtoair(self):
pyidf.validation_level = ValidationLevel.error
obj = HvactemplateSystemUnitaryHeatPumpAirToAir()
# alpha
var_name = "Name"
obj.name = var_name
# object-list
var_system_availability_schedule_name = "object-list|System Availability Schedule Name"
obj.system_availability_schedule_name = var_system_availability_schedule_name
# object-list
var_control_zone_or_thermostat_location_name = "object-list|Control Zone or Thermostat Location Name"
obj.control_zone_or_thermostat_location_name = var_control_zone_or_thermostat_location_name
# real
var_cooling_supply_air_flow_rate = 0.0001
obj.cooling_supply_air_flow_rate = var_cooling_supply_air_flow_rate
# real
var_heating_supply_air_flow_rate = 0.0001
obj.heating_supply_air_flow_rate = var_heating_supply_air_flow_rate
# real
var_no_load_supply_air_flow_rate = 0.0
obj.no_load_supply_air_flow_rate = var_no_load_supply_air_flow_rate
# object-list
var_supply_fan_operating_mode_schedule_name = "object-list|Supply Fan Operating Mode Schedule Name"
obj.supply_fan_operating_mode_schedule_name = var_supply_fan_operating_mode_schedule_name
# alpha
var_supply_fan_placement = "BlowThrough"
obj.supply_fan_placement = var_supply_fan_placement
# real
var_supply_fan_total_efficiency = 0.50005
obj.supply_fan_total_efficiency = var_supply_fan_total_efficiency
# real
var_supply_fan_delta_pressure = 0.0
obj.supply_fan_delta_pressure = var_supply_fan_delta_pressure
# real
var_supply_fan_motor_efficiency = 0.50005
obj.supply_fan_motor_efficiency = var_supply_fan_motor_efficiency
# real
var_supply_fan_motor_in_air_stream_fraction = 0.5
obj.supply_fan_motor_in_air_stream_fraction = var_supply_fan_motor_in_air_stream_fraction
# alpha
var_cooling_coil_type = "SingleSpeedDX"
obj.cooling_coil_type = var_cooling_coil_type
# object-list
var_cooling_coil_availability_schedule_name = "object-list|Cooling Coil Availability Schedule Name"
obj.cooling_coil_availability_schedule_name = var_cooling_coil_availability_schedule_name
# real
var_cooling_design_supply_air_temperature = 15.15
obj.cooling_design_supply_air_temperature = var_cooling_design_supply_air_temperature
# real
var_cooling_coil_gross_rated_total_capacity = 16.16
obj.cooling_coil_gross_rated_total_capacity = var_cooling_coil_gross_rated_total_capacity
# real
var_cooling_coil_gross_rated_sensible_heat_ratio = 0.75
obj.cooling_coil_gross_rated_sensible_heat_ratio = var_cooling_coil_gross_rated_sensible_heat_ratio
# real
var_cooling_coil_gross_rated_cop = 0.0001
obj.cooling_coil_gross_rated_cop = var_cooling_coil_gross_rated_cop
# alpha
var_heat_pump_heating_coil_type = "SingleSpeedDXHeatPump"
obj.heat_pump_heating_coil_type = var_heat_pump_heating_coil_type
# object-list
var_heat_pump_heating_coil_availability_schedule_name = "object-list|Heat Pump Heating Coil Availability Schedule Name"
obj.heat_pump_heating_coil_availability_schedule_name = var_heat_pump_heating_coil_availability_schedule_name
# real
var_heating_design_supply_air_temperature = 21.21
obj.heating_design_supply_air_temperature = var_heating_design_supply_air_temperature
# real
var_heat_pump_heating_coil_gross_rated_capacity = 0.0001
obj.heat_pump_heating_coil_gross_rated_capacity = var_heat_pump_heating_coil_gross_rated_capacity
# real
var_heat_pump_heating_coil_rated_cop = 0.0001
obj.heat_pump_heating_coil_rated_cop = var_heat_pump_heating_coil_rated_cop
# real
var_heat_pump_heating_minimum_outdoor_drybulb_temperature = -20.0
obj.heat_pump_heating_minimum_outdoor_drybulb_temperature = var_heat_pump_heating_minimum_outdoor_drybulb_temperature
# real
var_heat_pump_defrost_maximum_outdoor_drybulb_temperature = 3.61
obj.heat_pump_defrost_maximum_outdoor_drybulb_temperature = var_heat_pump_defrost_maximum_outdoor_drybulb_temperature
# alpha
var_heat_pump_defrost_strategy = "ReverseCycle"
obj.heat_pump_defrost_strategy = var_heat_pump_defrost_strategy
# alpha
var_heat_pump_defrost_control = "Timed"
obj.heat_pump_defrost_control = var_heat_pump_defrost_control
# real
var_heat_pump_defrost_time_period_fraction = 0.0
obj.heat_pump_defrost_time_period_fraction = var_heat_pump_defrost_time_period_fraction
# alpha
var_supplemental_heating_coil_type = "Electric"
obj.supplemental_heating_coil_type = var_supplemental_heating_coil_type
# object-list
var_supplemental_heating_coil_availability_schedule_name = "object-list|Supplemental Heating Coil Availability Schedule Name"
obj.supplemental_heating_coil_availability_schedule_name = var_supplemental_heating_coil_availability_schedule_name
# real
var_supplemental_heating_coil_capacity = 31.31
obj.supplemental_heating_coil_capacity = var_supplemental_heating_coil_capacity
# real
var_supplemental_heating_coil_maximum_outdoor_drybulb_temperature = 21.0
obj.supplemental_heating_coil_maximum_outdoor_drybulb_temperature = var_supplemental_heating_coil_maximum_outdoor_drybulb_temperature
# real
var_supplemental_gas_heating_coil_efficiency = 0.5
obj.supplemental_gas_heating_coil_efficiency = var_supplemental_gas_heating_coil_efficiency
# real
var_supplemental_gas_heating_coil_parasitic_electric_load = 0.0
obj.supplemental_gas_heating_coil_parasitic_electric_load = var_supplemental_gas_heating_coil_parasitic_electric_load
# real
var_maximum_outdoor_air_flow_rate = 0.0
obj.maximum_outdoor_air_flow_rate = var_maximum_outdoor_air_flow_rate
# real
var_minimum_outdoor_air_flow_rate = 0.0
obj.minimum_outdoor_air_flow_rate = var_minimum_outdoor_air_flow_rate
# object-list
var_minimum_outdoor_air_schedule_name = "object-list|Minimum Outdoor Air Schedule Name"
obj.minimum_outdoor_air_schedule_name = var_minimum_outdoor_air_schedule_name
# alpha
var_economizer_type = "FixedDryBulb"
obj.economizer_type = var_economizer_type
# alpha
var_economizer_lockout = "NoLockout"
obj.economizer_lockout = var_economizer_lockout
# real
var_economizer_maximum_limit_drybulb_temperature = 40.4
obj.economizer_maximum_limit_drybulb_temperature = var_economizer_maximum_limit_drybulb_temperature
# real
var_economizer_maximum_limit_enthalpy = 41.41
obj.economizer_maximum_limit_enthalpy = var_economizer_maximum_limit_enthalpy
# real
var_economizer_maximum_limit_dewpoint_temperature = 42.42
obj.economizer_maximum_limit_dewpoint_temperature = var_economizer_maximum_limit_dewpoint_temperature
# real
var_economizer_minimum_limit_drybulb_temperature = 43.43
obj.economizer_minimum_limit_drybulb_temperature = var_economizer_minimum_limit_drybulb_temperature
# object-list
var_supply_plenum_name = "object-list|Supply Plenum Name"
obj.supply_plenum_name = var_supply_plenum_name
# object-list
var_return_plenum_name = "object-list|Return Plenum Name"
obj.return_plenum_name = var_return_plenum_name
# alpha
var_night_cycle_control = "StayOff"
obj.night_cycle_control = var_night_cycle_control
# object-list
var_night_cycle_control_zone_name = "object-list|Night Cycle Control Zone Name"
obj.night_cycle_control_zone_name = var_night_cycle_control_zone_name
# alpha
var_heat_recovery_type = "None"
obj.heat_recovery_type = var_heat_recovery_type
# real
var_sensible_heat_recovery_effectiveness = 0.5
obj.sensible_heat_recovery_effectiveness = var_sensible_heat_recovery_effectiveness
# real
var_latent_heat_recovery_effectiveness = 0.5
obj.latent_heat_recovery_effectiveness = var_latent_heat_recovery_effectiveness
# alpha
var_humidifier_type = "None"
obj.humidifier_type = var_humidifier_type
# object-list
var_humidifier_availability_schedule_name = "object-list|Humidifier Availability Schedule Name"
obj.humidifier_availability_schedule_name = var_humidifier_availability_schedule_name
# real
var_humidifier_rated_capacity = 0.0
obj.humidifier_rated_capacity = var_humidifier_rated_capacity
# real
var_humidifier_rated_electric_power = 0.0
obj.humidifier_rated_electric_power = var_humidifier_rated_electric_power
# object-list
var_humidifier_control_zone_name = "object-list|Humidifier Control Zone Name"
obj.humidifier_control_zone_name = var_humidifier_control_zone_name
# real
var_humidifier_setpoint = 50.0
obj.humidifier_setpoint = var_humidifier_setpoint
# alpha
var_return_fan = "Yes"
obj.return_fan = var_return_fan
# real
var_return_fan_total_efficiency = 0.50005
obj.return_fan_total_efficiency = var_return_fan_total_efficiency
# real
var_return_fan_delta_pressure = 0.0
obj.return_fan_delta_pressure = var_return_fan_delta_pressure
# real
var_return_fan_motor_efficiency = 0.50005
obj.return_fan_motor_efficiency = var_return_fan_motor_efficiency
# real
var_return_fan_motor_in_air_stream_fraction = 0.5
obj.return_fan_motor_in_air_stream_fraction = var_return_fan_motor_in_air_stream_fraction
idf = IDF()
idf.add(obj)
idf.save(self.path, check=False)
with open(self.path, mode='r') as f:
for line in f:
log.debug(line.strip())
idf2 = IDF(self.path)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].name, var_name)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].system_availability_schedule_name, var_system_availability_schedule_name)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].control_zone_or_thermostat_location_name, var_control_zone_or_thermostat_location_name)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].cooling_supply_air_flow_rate, var_cooling_supply_air_flow_rate)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].heating_supply_air_flow_rate, var_heating_supply_air_flow_rate)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].no_load_supply_air_flow_rate, var_no_load_supply_air_flow_rate)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].supply_fan_operating_mode_schedule_name, var_supply_fan_operating_mode_schedule_name)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].supply_fan_placement, var_supply_fan_placement)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].supply_fan_total_efficiency, var_supply_fan_total_efficiency)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].supply_fan_delta_pressure, var_supply_fan_delta_pressure)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].supply_fan_motor_efficiency, var_supply_fan_motor_efficiency)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].supply_fan_motor_in_air_stream_fraction, var_supply_fan_motor_in_air_stream_fraction)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].cooling_coil_type, var_cooling_coil_type)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].cooling_coil_availability_schedule_name, var_cooling_coil_availability_schedule_name)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].cooling_design_supply_air_temperature, var_cooling_design_supply_air_temperature)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].cooling_coil_gross_rated_total_capacity, var_cooling_coil_gross_rated_total_capacity)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].cooling_coil_gross_rated_sensible_heat_ratio, var_cooling_coil_gross_rated_sensible_heat_ratio)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].cooling_coil_gross_rated_cop, var_cooling_coil_gross_rated_cop)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].heat_pump_heating_coil_type, var_heat_pump_heating_coil_type)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].heat_pump_heating_coil_availability_schedule_name, var_heat_pump_heating_coil_availability_schedule_name)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].heating_design_supply_air_temperature, var_heating_design_supply_air_temperature)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].heat_pump_heating_coil_gross_rated_capacity, var_heat_pump_heating_coil_gross_rated_capacity)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].heat_pump_heating_coil_rated_cop, var_heat_pump_heating_coil_rated_cop)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].heat_pump_heating_minimum_outdoor_drybulb_temperature, var_heat_pump_heating_minimum_outdoor_drybulb_temperature)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].heat_pump_defrost_maximum_outdoor_drybulb_temperature, var_heat_pump_defrost_maximum_outdoor_drybulb_temperature)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].heat_pump_defrost_strategy, var_heat_pump_defrost_strategy)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].heat_pump_defrost_control, var_heat_pump_defrost_control)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].heat_pump_defrost_time_period_fraction, var_heat_pump_defrost_time_period_fraction)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].supplemental_heating_coil_type, var_supplemental_heating_coil_type)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].supplemental_heating_coil_availability_schedule_name, var_supplemental_heating_coil_availability_schedule_name)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].supplemental_heating_coil_capacity, var_supplemental_heating_coil_capacity)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].supplemental_heating_coil_maximum_outdoor_drybulb_temperature, var_supplemental_heating_coil_maximum_outdoor_drybulb_temperature)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].supplemental_gas_heating_coil_efficiency, var_supplemental_gas_heating_coil_efficiency)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].supplemental_gas_heating_coil_parasitic_electric_load, var_supplemental_gas_heating_coil_parasitic_electric_load)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].maximum_outdoor_air_flow_rate, var_maximum_outdoor_air_flow_rate)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].minimum_outdoor_air_flow_rate, var_minimum_outdoor_air_flow_rate)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].minimum_outdoor_air_schedule_name, var_minimum_outdoor_air_schedule_name)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].economizer_type, var_economizer_type)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].economizer_lockout, var_economizer_lockout)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].economizer_maximum_limit_drybulb_temperature, var_economizer_maximum_limit_drybulb_temperature)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].economizer_maximum_limit_enthalpy, var_economizer_maximum_limit_enthalpy)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].economizer_maximum_limit_dewpoint_temperature, var_economizer_maximum_limit_dewpoint_temperature)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].economizer_minimum_limit_drybulb_temperature, var_economizer_minimum_limit_drybulb_temperature)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].supply_plenum_name, var_supply_plenum_name)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].return_plenum_name, var_return_plenum_name)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].night_cycle_control, var_night_cycle_control)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].night_cycle_control_zone_name, var_night_cycle_control_zone_name)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].heat_recovery_type, var_heat_recovery_type)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].sensible_heat_recovery_effectiveness, var_sensible_heat_recovery_effectiveness)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].latent_heat_recovery_effectiveness, var_latent_heat_recovery_effectiveness)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].humidifier_type, var_humidifier_type)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].humidifier_availability_schedule_name, var_humidifier_availability_schedule_name)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].humidifier_rated_capacity, var_humidifier_rated_capacity)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].humidifier_rated_electric_power, var_humidifier_rated_electric_power)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].humidifier_control_zone_name, var_humidifier_control_zone_name)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].humidifier_setpoint, var_humidifier_setpoint)
self.assertEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].return_fan, var_return_fan)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].return_fan_total_efficiency, var_return_fan_total_efficiency)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].return_fan_delta_pressure, var_return_fan_delta_pressure)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].return_fan_motor_efficiency, var_return_fan_motor_efficiency)
self.assertAlmostEqual(idf2.hvactemplatesystemunitaryheatpumpairtoairs[0].return_fan_motor_in_air_stream_fraction, var_return_fan_motor_in_air_stream_fraction)
|
463859
|
from torch.nn import Module
from torch.autograd import Function
import torch.nn.functional as F
from torch.autograd import Variable
import math
import shapely
from shapely.geometry import Polygon, MultiPoint
import pixel_weights_cpu
import pixel_weights_cuda
import torch
import numpy as np
import cv2
class PiousFunction(Function):
@staticmethod
def forward(ctx, loc_p, loc_t, grid, k, is_hard):
ctx.k = k
if loc_p.is_cuda:
ctx.grad_loc_memory = torch.zeros(
(loc_p.size(0), 5), dtype=torch.float32).cuda()
pious = pixel_weights_cuda.forward_cuda(
loc_p, loc_t, grid, k, is_hard, ctx.grad_loc_memory)
else:
pious = pixel_weights_cpu.forward_cpu(loc_p, loc_t, grid, k)
return pious
@staticmethod
def backward(ctx, grad_pious):
grad_loc_memory = ctx.grad_loc_memory
if grad_pious.is_cuda:
grad_loc_p = pixel_weights_cuda.backward_cuda(
grad_pious, grad_loc_memory)
return grad_loc_p, None, None, None, None
else:
return None, None, None, None, None
class Pious(Module):
def __init__(self, k=10, is_hard=False):
super(Pious, self).__init__()
self.k = k
self.is_hard = is_hard
def forward(self, loc_p, loc_t, grid):
pious = PiousFunction.apply(
loc_p, loc_t, grid, self.k, self.is_hard)
return pious
class JaccardRFunction(Function):
@staticmethod
def forward(ctx, loc_p, loc_t, grid):
if loc_p.is_cuda:
pious = pixel_weights_cuda.overlap_r_cuda(
loc_p, loc_t, grid)
return pious
else:
assert 1==0, 'Not Support'
class JaccardR(Module):
def forward(self, loc_p, loc_t, grid):
pious = JaccardRFunction.apply(
loc_p, loc_t, grid)
return pious
def template_pixels(height, width):
xv, yv = torch.meshgrid(
[torch.arange(-100, width + 100), torch.arange(-100, height + 100)])
xy = torch.stack((xv, yv), -1)
grid_xy = xy.reshape(-1, 2).float() + 0.5
return grid_xy
def rbox2corners(rboxes):
w_sin = 0.5 * rboxes[:, 2:3] * torch.sin(rboxes[:, 4:5])
w_cos = 0.5 * rboxes[:, 2:3] * torch.cos(rboxes[:, 4:5])
h_sin = 0.5 * rboxes[:, 3:4] * torch.sin(rboxes[:, 4:5])
h_cos = 0.5 * rboxes[:, 3:4] * torch.cos(rboxes[:, 4:5])
cornerx0 = rboxes[:, :1] + w_cos + h_sin
cornery0 = rboxes[:, 1:2] - w_sin + h_cos
cornerx1 = rboxes[:, :1] - w_cos + h_sin
cornery1 = rboxes[:, 1:2] + w_sin + h_cos
cornerx2 = rboxes[:, :1] - w_cos - h_sin
cornery2 = rboxes[:, 1:2] + w_sin - h_cos
cornerx3 = rboxes[:, :1] + w_cos - h_sin
cornery3 = rboxes[:, 1:2] - w_sin - h_cos
corners = torch.cat([cornerx0, cornery0, cornerx1,
cornery1, cornerx2, cornery2, cornerx3, cornery3], -1)
return corners
def template_w_pixels(width):
x = torch.tensor(torch.arange(-100, width + 100))
grid_x = x.float() + 0.5
return grid_x
def rbox2corners_torch(loc):
cos_w = 0.5 * loc[:, 2:3] * torch.cos(loc[:, 4:5])
sin_w = 0.5 * loc[:, 2:3] * torch.sin(loc[:, 4:5])
cos_h = 0.5 * loc[:, 3:4] * torch.cos(loc[:, 4:5])
sin_h = 0.5 * loc[:, 3:4] * torch.sin(loc[:, 4:5])
x0 = loc[:, 0:1] + cos_w + sin_h
y0 = loc[:, 1:2] - sin_w + cos_h
x1 = loc[:, 0:1] - cos_w + sin_h
y1 = loc[:, 1:2] + sin_w + cos_h
x2 = loc[:, 0:1] - cos_w - sin_h
y2 = loc[:, 1:2] + sin_w - cos_h
x3 = loc[:, 0:1] + cos_w - sin_h
y3 = loc[:, 1:2] - sin_w - cos_h
rbox = torch.cat((x0, y0, x1, y1, x2, y2, x3, y3), -1)
return rbox
def rbox2corners_cpu(cx, cy, cwidth, cheight, angle):
x0 = cx + 0.5 * cwidth * math.cos(angle) + 0.5 * cheight * math.sin(angle)
y0 = cy - 0.5 * cwidth * math.sin(angle) + 0.5 * cheight * math.cos(angle)
x1 = cx - 0.5 * cwidth * math.cos(angle) + 0.5 * cheight * math.sin(angle)
y1 = cy + 0.5 * cwidth * math.sin(angle) + 0.5 * cheight * math.cos(angle)
x2 = cx - 0.5 * cwidth * math.cos(angle) - 0.5 * cheight * math.sin(angle)
y2 = cy + 0.5 * cwidth * math.sin(angle) - 0.5 * cheight * math.cos(angle)
x3 = cx + 0.5 * cwidth * math.cos(angle) - 0.5 * cheight * math.sin(angle)
y3 = cy - 0.5 * cwidth * math.sin(angle) - 0.5 * cheight * math.cos(angle)
rbox = np.array([[x0, y0], [x1, y1], [x2, y2], [x3, y3]], dtype=np.float32)
return rbox
# loc --> num x dim x 5
# grid_xy --> num x dim x 2
def kernel_function(dis, k, t):
# clamp to avoid nan
factor = torch.clamp(-k * (dis - t), -50, 50)
return 1.0 - 1.0 / (torch.exp(factor) + 1)
# loc --> num x dim x 5
# grid_xy --> num x dim x 2
def pixel_weights(loc, grid_xy, k):
xx = torch.pow(loc[:, :, 0:2], 2).sum(2)
yy = torch.pow(grid_xy, 2).sum(2)
dis = xx + yy
# dis - 2 * x * yT
dis.addmm_(1, -2, loc[:, 0, 0:2], grid_xy[0].t())
dis = dis.clamp(min=1e-9).sqrt() # for numerical stability
a1 = loc[:, :, -1] - torch.acos((grid_xy[:, :, 0] - loc[:, :, 0]) / dis)
a2 = loc[:, :, -1] + torch.acos((grid_xy[:, :, 0] - loc[:, :, 0]) / dis)
a = torch.where(loc[:, :, 1] > grid_xy[:, :, 1], a1, a2)
dis_w = dis * torch.abs(torch.cos(a))
dis_h = dis * torch.abs(torch.sin(a))
# return dis_h
pixel_weights = kernel_function(
dis_w, k, loc[:, :, 2] / 2.) * kernel_function(dis_h, k, loc[:, :, 3] / 2.)
return pixel_weights
def PIoU(loc_p, loc_t, grid_xy, k=10):
num = loc_p.size(0)
dim = grid_xy.size(0)
loc_pp = loc_p.unsqueeze(1).expand(num, dim, 5)
loc_tt = loc_t.unsqueeze(1).expand(num, dim, 5)
grid_xyxy = grid_xy.unsqueeze(0).expand(num, dim, 2)
pixel_p_weights = pixel_weights(loc_pp, grid_xyxy, k)
pixel_t_weights = pixel_weights(loc_tt, grid_xyxy, k)
inter_pixel_area = pixel_p_weights * pixel_t_weights
intersection_area = torch.sum(inter_pixel_area, 1)
union_pixel_area = pixel_p_weights + \
pixel_t_weights - inter_pixel_area
union_area = torch.sum(union_pixel_area, 1)
pious = intersection_area / (union_area + 1e-9)
return torch.sum(1 - pious), pious
def HPIoU(loc_p, loc_t, grid_xy, k=10):
num = loc_p.size(0)
dim = grid_xy.size(0)
loc_pp = loc_p.unsqueeze(1).expand(num, dim, 5)
loc_tt = loc_t.unsqueeze(1).expand(num, dim, 5)
grid_xyxy = grid_xy.unsqueeze(0).expand(num, dim, 2)
area_p = loc_p[:, 2] * loc_p[:, 3]
area_t = loc_t[:, 2] * loc_t[:, 3]
pixel_p_weights = pixel_weights(loc_pp, grid_xyxy, k)
pixel_t_weights = pixel_weights(loc_tt, grid_xyxy, k)
inter_pixel_area = pixel_p_weights * pixel_t_weights
intersection_area = torch.sum(inter_pixel_area, 1)
union_area = area_p + area_t - intersection_area
pious = intersection_area / (union_area + 1e-9)
return torch.sum(1 - pious), pious
def intersect(box_a, box_b):
""" We resize both tensors to [A,B,2] without new malloc:
[A,2] -> [A,1,2] -> [A,B,2]
[B,2] -> [1,B,2] -> [A,B,2]
Then we compute the area of intersect between box_a and box_b when the angles is same: 0.
Args:
box_a: (tensor) bounding boxes, Shape: [A, 5].
box_b: (tensor) bounding boxes, Shape: [B, 5].
Return:
(tensor) intersection area, Shape: [A,B].
"""
A = box_a.size(0)
B = box_b.size(0)
max_xy = torch.min(box_a[:, 2:4].unsqueeze(1).expand(A, B, 2),
box_b[:, 2:4].unsqueeze(0).expand(A, B, 2))
min_xy = torch.max(box_a[:, :2].unsqueeze(1).expand(A, B, 2),
box_b[:, :2].unsqueeze(0).expand(A, B, 2))
inter = torch.clamp((max_xy - min_xy), min=0)
return inter[:, :, 0] * inter[:, :, 1]
def get_grid(box_a, box_b):
""" We resize both tensors to [A,B,2] without new malloc:
[A,2] -> [A,1,2] -> [A,B,2]
[B,2] -> [1,B,2] -> [A,B,2]
Then we compute the area of intersect between box_a and box_b when the angles is same: 0.
Args:
box_a: (tensor) bounding boxes, Shape: [A, 5].
box_b: (tensor) bounding boxes, Shape: [B, 5].
Return:
(tensor) intersection area, Shape: [A,B].
"""
A = box_a.size(0)
B = box_b.size(0)
max_xy = torch.min(box_a[:, 2:4].unsqueeze(1).expand(A, B, 2),
box_b[:, 2:4].unsqueeze(0).expand(A, B, 2))
min_xy = torch.max(box_a[:, :2].unsqueeze(1).expand(A, B, 2),
box_b[:, :2].unsqueeze(0).expand(A, B, 2))
grid = torch.cat((min_xy, max_xy), -1)
inter = torch.clamp((max_xy - min_xy), min=0)
return grid, inter[:, :, 0] * inter[:, :, 1]
def point_form(boxes):
""" Convert prior_boxes to (xmin, ymin, xmax, ymax)
representation for comparison to point form ground truth data.
Args:
boxes: (tensor) center-size default boxes from priorbox layers.
Return:
boxes: (tensor) Converted xmin, ymin, xmax, ymax form of boxes.
"""
return torch.cat((boxes[:, :2] - boxes[:, 2:4] / 2, # xmin, ymin
boxes[:, :2] + boxes[:, 2:4] / 2,
boxes[:, 4:5]), 1) # xmax, ymax
def jaccard(box_a, box_b):
inter = intersect(box_a, box_b)
print('inter: ', inter)
area_a = ((box_a[:, 2]-box_a[:, 0]) *
(box_a[:, 3]-box_a[:, 1])).unsqueeze(1).expand_as(inter) # [A,B]
area_b = ((box_b[:, 2]-box_b[:, 0]) *
(box_b[:, 3]-box_b[:, 1])).unsqueeze(0).expand_as(inter) # [A,B]
union = area_a + area_b - inter
return inter / (union + 1e-9)
def test_jaccardr():
jaccardr_f = JaccardR()
for item in range(100):
print('item: ', item)
loc_pxy = torch.randint(10, 300, [10, 2]).float()
loc_pwh = torch.randint(10, 200, [10, 2]).float()
loc_pa = torch.randint(-180, 180, [10, 1]) / 180.0 * 3.141593
loc_p = torch.cat((loc_pxy, loc_pwh, loc_pa), -1)
loc_txy = torch.randint(10, 300, [20, 2]).float()
loc_twh = torch.randint(10, 200, [20, 2]).float()
loc_ta = torch.randint(-180, 180, [20, 1]) / 180.0 * 3.141593
loc_t = torch.cat((loc_txy, loc_twh, loc_ta), -1)
loc_p = loc_p.float()
loc_t = loc_t.float()
corners_p = rbox2corners_torch(loc_p)
corners_t = rbox2corners_torch(loc_t)
if torch.cuda.is_available():
print('------------pixel_weights_gpu test on gpu------------')
corners_p = corners_p.cuda()
corners_t = corners_t.cuda()
# print('corners_p: ', corners_p.shape)
# print('corners_t: ', corners_t.shape)
jaccard_r_gpu = jaccardr_f(corners_p, corners_t)
# print('jaccard_r_gpu: ', jaccard_r_gpu[jaccard_r_gpu > 0.001])
else:
print('You device have not a GPU')
print('..................polygon................')
loc_p = loc_p.cpu().numpy()
loc_t = loc_t.cpu().numpy()
pious = []
for i in range(loc_p.shape[0]):
for j in range(loc_t.shape[0]):
corners_p = rbox2corners_cpu(loc_p[i][0], loc_p[i][1], loc_p[i]
[2], loc_p[i][3], loc_p[i][4])
corners_t = rbox2corners_cpu(loc_t[j][0], loc_t[j][1], loc_t[j]
[2], loc_t[j][3], loc_t[j][4])
p1 = Polygon(corners_p)
p2 = Polygon(corners_t)
inter_area = p1.intersection(p2).area
iou = inter_area / (loc_p[i][2] * loc_p[i]
[3] + loc_t[j][2] * loc_t[j][3] - inter_area)
pious.append(round(iou, 4))
pious_np = np.array(pious)
pious_np = pious_np.reshape(loc_p.shape[0], -1)
# print('pious: ', pious_np[pious_np > 0.001])
gap = np.sum(np.abs(pious_np - jaccard_r_gpu.cpu().numpy()))
if gap < 0.005:
print('-------------->pass gap: ', gap)
else:
print('-------------->error gap')
assert 1 == 0, gap
def test_hiou():
jaccardr_f = JaccardR()
loc_pxy = torch.randint(10, 300, [3, 2]).float()
loc_pwh = torch.randint(10, 200, [3, 2]).float()
loc_pa = torch.randint(-180, 180, [3, 1]) / 180.0 * 3.141593
loc_p = torch.cat((loc_pxy, loc_pwh, loc_pa), -1)
loc_txy = torch.randint(10, 300, [4, 2]).float()
loc_twh = torch.randint(10, 200, [4, 2]).float()
loc_ta = torch.randint(-180, 180, [4, 1]) / 180.0 * 3.141593
loc_t = torch.cat((loc_txy, loc_twh, loc_ta), -1)
loc_p = loc_p.float()
loc_t = loc_t.float()
corners_p = rbox2corners_torch(loc_p)
corners_t = rbox2corners_torch(loc_t)
xmin_p, _ = torch.min(corners_p[:, 0::2], -1, keepdim=True)
ymin_p, _ = torch.min(corners_p[:, 1::2], -1, keepdim=True)
xmax_p, _ = torch.max(corners_p[:, 0::2], -1, keepdim=True)
ymax_p, _ = torch.max(corners_p[:, 1::2], -1, keepdim=True)
xmin_t, _ = torch.min(corners_t[:, 0::2], -1, keepdim=True)
ymin_t, _ = torch.min(corners_t[:, 1::2], -1, keepdim=True)
xmax_t, _ = torch.max(corners_t[:, 0::2], -1, keepdim=True)
ymax_t, _ = torch.max(corners_t[:, 1::2], -1, keepdim=True)
box_p = torch.cat((xmin_p, ymin_p, xmax_p, ymax_p), -1)
print('ymin_p: ', ymin_p)
print('corners_p: ', corners_p)
box_t = torch.cat((xmin_t, ymin_t, xmax_t, ymax_t), -1)
print('box_t: ', (box_t[:, 3] - box_t[:, 1]) * (box_t[:, 2] - box_t[:, 0]))
overlaps = jaccard(box_p, box_t)
corners_p = corners_p.cuda()
corners_t = corners_t.cuda()
jaccard_r_gpu = jaccardr_f(corners_p, corners_t)
print('jaccard_r_gpu: ', jaccard_r_gpu)
print('overlaps: ', overlaps)
def corners_box_form(corners):
xmin, _ = torch.min(corners[:, 0::2], -1, keepdim=True)
ymin, _ = torch.min(corners[:, 1::2], -1, keepdim=True)
xmax, _ = torch.max(corners[:, 0::2], -1, keepdim=True)
ymax, _ = torch.max(corners[:, 1::2], -1, keepdim=True)
corners_box = torch.cat((xmin, ymin, xmax, ymax), -1)
return corners_box
def jaccard_fast(box_a, box_b):
"""Compute the jaccard overlap of two sets of boxes. The jaccard overlap
is simply the intersection over union of two boxes. Here we operate on
ground truth boxes and default boxes.
E.g.:
A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B)
Args:
box_a: (tensor) Ground truth bounding boxes, Shape: [num_objects,5]
box_b: (tensor) Prior boxes from priorbox layers, Shape: [num_priors,5]
Return:
jaccard overlap: (tensor) Shape: [box_a.size(0), box_b.size(0)]
"""
A = box_a.size(0)
B = box_b.size(0)
max_xy = torch.min(box_a[:, 2:4].unsqueeze(1).expand(A, B, 2),
box_b[:, 2:4].unsqueeze(0).expand(A, B, 2))
min_xy = torch.max(box_a[:, :2].unsqueeze(1).expand(A, B, 2),
box_b[:, :2].unsqueeze(0).expand(A, B, 2))
grid = torch.cat((min_xy, max_xy), -1)
inter = torch.clamp((max_xy - min_xy), min=0)
inter_area = inter[:, :, 0] * inter[:, :, 1]
area_a = ((box_a[:, 2]-box_a[:, 0]) *
(box_a[:, 3]-box_a[:, 1])).unsqueeze(1).expand_as(inter_area) # [A,B]
area_b = ((box_b[:, 2]-box_b[:, 0]) *
(box_b[:, 3]-box_b[:, 1])).unsqueeze(0).expand_as(inter_area) # [A,B]
union = area_a + area_b - inter_area
h_iou = inter_area / union # [A,B]
return torch.cat((grid, h_iou.reshape(h_iou.size(0), -1, 1)), -1)
def test_pious_fast():
jaccardr_f = JaccardR()
loc_pxy = torch.randint(10, 300, [3, 2]).float()
loc_pwh = torch.randint(10, 200, [3, 2]).float()
loc_pa = torch.randint(-180, 180, [3, 1]) / 180.0 * 3.141593
loc_p = torch.cat((loc_pxy, loc_pwh, loc_pa), -1)
loc_txy = torch.randint(10, 300, [4, 2]).float()
loc_twh = torch.randint(10, 200, [4, 2]).float()
loc_ta = torch.randint(-180, 180, [4, 1]) / 180.0 * 3.141593
loc_t = torch.cat((loc_txy, loc_twh, loc_ta), -1)
loc_p = loc_p.float()
loc_t = loc_t.float()
corners_p = rbox2corners_torch(loc_p)
corners_t = rbox2corners_torch(loc_t)
grid = jaccard_fast(corners_box_form(corners_p), corners_box_form(corners_t))
overlaps = jaccardr_f(loc_p.cuda(), loc_t.cuda(), grid.cuda())
print('grid: ', grid.shape)
print('overlaps: ', overlaps)
print('..................polygon................')
loc_p = loc_p.cpu().numpy()
loc_t = loc_t.cpu().numpy()
pious = []
for i in range(loc_p.shape[0]):
for j in range(loc_t.shape[0]):
corners_p = rbox2corners_cpu(loc_p[i][0], loc_p[i][1], loc_p[i]
[2], loc_p[i][3], loc_p[i][4])
corners_t = rbox2corners_cpu(loc_t[j][0], loc_t[j][1], loc_t[j]
[2], loc_t[j][3], loc_t[j][4])
p1 = Polygon(corners_p)
p2 = Polygon(corners_t)
inter_area = p1.intersection(p2).area
iou = inter_area / (loc_p[i][2] * loc_p[i]
[3] + loc_t[j][2] * loc_t[j][3] - inter_area)
pious.append(round(iou, 4))
pious_np = np.array(pious)
pious_np = pious_np.reshape(loc_p.shape[0], -1)
print('pious: ', pious_np)
def test_pious():
for item in range(100):
print('item: ', item)
loc_pxy = torch.randint(10, 300, [10, 2]).float()
loc_pwh = torch.randint(20, 200, [10, 2]).float()
loc_pa = torch.randint(-180, 180, [10, 1]) / 180.0 * 3.141593
loc_p = torch.cat((loc_pxy, loc_pwh, loc_pa), -1)
loc_txy = torch.randint(10, 300, [10, 2]).float()
loc_twh = torch.randint(20, 200, [10, 2]).float()
loc_ta = torch.randint(-180, 180, [10, 1]) / 180.0 * 3.141593
loc_t = torch.cat((loc_txy, loc_twh, loc_ta), -1)
grid_xy = template_pixels(512, 512)
grid_x = template_w_pixels(512)
num = loc_p.size(0)
dim = grid_xy.size(0)
loc_p = loc_p.float()
loc_t = loc_t.float()
grid_xy = grid_xy.float()
loc_p = Variable(loc_p, requires_grad=True)
piou_loss, pious_big = PIoU(loc_p, loc_t.data, grid_xy.data, 10)
piou_loss.backward()
grad_loc_p_big = loc_p.grad
PiousF = Pious(10)
# print('pious_big: ', pious_big)
# print('grad_loc_p_big: ', grad_loc_p_big)
if torch.cuda.is_available():
print('------------pixel_weights_gpu test on gpu------------')
loc_p = loc_p.cuda()
loc_t = loc_t.cuda()
grid_xy = grid_xy.cuda()
grid_x = grid_x.cuda()
loc_p = Variable(loc_p, requires_grad=True)
pious_gpu = PiousF(loc_p, loc_t, grid_x)
# # print('pious_gpu: ', pious_gpu)
piou = torch.sum(1 - pious_gpu)
piou.backward()
loc_p_grad = loc_p.grad
print('gap piou: ', torch.sum(pious_big.cuda() - pious_gpu) / 10)
# # print('gap: ', grad_loc_p_big, loc_p_grad)
print('gap grad piou: ', torch.sum(grad_loc_p_big.cuda() - loc_p_grad) / 10)
# print('grad: ')
# print('grad: ', loc_p_grad)
else:
print('You device have not a GPU')
def test_hpious():
for item in range(10):
print('item: ', item)
loc_pxy = torch.randint(10, 300, [10, 2]).float()
loc_pwh = torch.randint(20, 200, [10, 2]).float()
loc_pa = torch.randint(-180, 180, [10, 1]) / 180.0 * 3.141593
loc_p = torch.cat((loc_pxy, loc_pwh, loc_pa), -1)
loc_txy = torch.randint(10, 300, [10, 2]).float()
loc_twh = torch.randint(20, 200, [10, 2]).float()
loc_ta = torch.randint(-180, 180, [10, 1]) / 180.0 * 3.141593
loc_t = torch.cat((loc_txy, loc_twh, loc_ta), -1)
grid_xy = template_pixels(512, 512)
grid_x = template_w_pixels(512)
num = loc_p.size(0)
dim = grid_xy.size(0)
loc_p = loc_p.float()
loc_t = loc_t.float()
grid_xy = grid_xy.float()
loc_p = Variable(loc_p, requires_grad=True)
hpiou_loss, hpious_big = HPIoU(loc_p, loc_t.data, grid_xy.data, 10)
# print('hpious_big: ', hpious_big)
hpiou_loss.backward()
grad_loc_p_big = loc_p.grad
HPiousF = Pious(k=10, is_hard=True)
if torch.cuda.is_available():
print('------------pixel_weights_gpu test on gpu------------')
loc_p = loc_p.cuda()
loc_t = loc_t.cuda()
grid_xy = grid_xy.cuda()
grid_x = grid_x.cuda()
loc_p = Variable(loc_p, requires_grad=True)
hpious_gpu = HPiousF(loc_p, loc_t, grid_x)
# print('hpious_gpu: ', hpious_gpu)
piou = torch.sum(1 - hpious_gpu)
piou.backward()
loc_p_grad = loc_p.grad
print('gap piou: ', torch.sum(hpious_big.cuda() - hpious_gpu) / 10)
print('gap grad: ', grad_loc_p_big, loc_p_grad)
print('gap grad piou: ', torch.sum(grad_loc_p_big.cuda() - loc_p_grad) / 10)
# print('grad: ')
# print('grad: ', loc_p_grad)
else:
print('You device have not a GPU')
# print('..................polygon................')
# loc_p = loc_p.detach().cpu().numpy()
# loc_t = loc_t.detach().cpu().numpy()
# pious = []
# for i in range(loc_p.shape[0]):
# corners_p = rbox2corners_cpu(loc_p[i][0], loc_p[i][1], loc_p[i]
# [2], loc_p[i][3], loc_p[i][4])
# corners_t = rbox2corners_cpu(loc_t[i][0], loc_t[i][1], loc_t[i]
# [2], loc_t[i][3], loc_t[i][4])
# p1 = Polygon(corners_p)
# p2 = Polygon(corners_t)
# inter_area = p1.intersection(p2).area
# iou = inter_area / (loc_p[i][2] * loc_p[i]
# [3] + loc_t[i][2] * loc_t[i][3] - inter_area)
# pious.append(round(iou, 4))
# print('pious: ', pious)
def test_corners():
loc_pxy = torch.randint(10, 300, [3, 2]).float()
loc_pwh = torch.randint(20, 200, [3, 2]).float()
loc_pa = torch.randint(-180, 180, [3, 1]) / 180.0 * 3.141593
loc_p = torch.cat((loc_pxy, loc_pwh, loc_pa), -1)
corners_p = rbox2corners_torch(loc_p)
print('corners_p: ', corners_p)
rbox = loc_p.cpu().numpy()
for item in range(3):
point = cv2.boxPoints(((rbox[item][0], rbox[item][1]), (rbox[item][2], rbox[item][3]), rbox[item][4]))
print('point: ', point)
def test_resize():
loc_pxy = torch.randint(10, 300, [3, 2]).float()
loc_pwh = torch.randint(20, 200, [3, 2]).float()
loc_pa = torch.randint(-180, 180, [3, 1]) / 180.0 * 3.141593
loc_p = torch.cat((loc_pxy, loc_pwh, loc_pa), -1)
corners_p = rbox2corners_torch(loc_p)
loc_p_resize = loc_p[:, 0:4] * 0.25
print('loc_p_resize: ', loc_p_resize)
corners_p_s = corners_p * 0.25
corners_p_s = corners_p_s.numpy()
for item in range(3):
box = np.int0([corners_p_s[item][0], corners_p_s[item][1],
corners_p_s[item][2], corners_p_s[item][3],
corners_p_s[item][4], corners_p_s[item][5],
corners_p_s[item][6], corners_p_s[item][7]])
box = box.reshape([-1, 2])
rect = cv2.minAreaRect(box)
rwidth, rheight = rect[1]
rangle = rect[2]
if rwidth > rheight:
rangle = np.abs(rangle)
else:
temp = rwidth
rwidth = rheight
rheight = temp
rangle = np.abs(rangle) + 90
rbox = [rect[0][0], rect[0][1], rwidth, rheight, rangle / 180.0 * 3.141593]
print('rbox: ', rbox)
if __name__ == '__main__':
# test_jaccardr()
# test_hiou()
test_pious()
# PIoU()
# test_pious_fast()
# test_hpious()
# test_corners()
# test_resize()
|
463860
|
import os
import sublime
from PHPUnitKit.plugin import _get_php_executable
from PHPUnitKit.tests import unittest
class TestGetPHPExecutable(unittest.TestCase):
def setUp(self):
super().setUp()
self.versions_path = unittest.fixtures_path(os.path.join('get_php_executable', 'versions'))
def test_returns_none_when_no_executable_found(self):
self.assertIsNone(_get_php_executable(unittest.fixtures_path('foobar'), self.versions_path))
def test_can_retrieve_from_setting(self):
expected = unittest.fixtures_path(os.path.join('get_php_executable', 'php'))
actual = _get_php_executable(unittest.fixtures_path('foobar'), self.versions_path, expected)
self.assertEqual(actual, expected)
def test_setting_not_found_raises_exeption(self):
with self.assertRaisesRegex(ValueError, 'phpunit\\.php_executable.*is not an executable file'):
_get_php_executable(
unittest.fixtures_path('foobar'),
self.versions_path,
unittest.fixtures_path(os.path.join('get_php_executable', 'foobar'))
)
@unittest.mock.patch('PHPUnitKit.plugin.platform')
def test_linux_get_from_php_version_file(self, platform):
platform.return_value = 'linux'
expected = unittest.fixtures_path(os.path.join('get_php_executable', 'versions', '7.3.0', 'bin', 'php'))
actual = _get_php_executable(
unittest.fixtures_path('get_php_executable'),
self.versions_path,
unittest.fixtures_path('get_php_executable')
)
self.assertEqual(actual, expected)
@unittest.mock.patch('PHPUnitKit.plugin.platform')
def test_windows_get_from_php_version_file(self, platform):
platform.return_value = 'windows'
expected = unittest.fixtures_path(os.path.join('get_php_executable', 'versions', '7.3.0', 'php.exe'))
actual = _get_php_executable(
unittest.fixtures_path('get_php_executable'),
self.versions_path,
unittest.fixtures_path('get_php_executable')
)
self.assertEqual(actual, expected)
def test_invalid_version_file_number_raises_exception(self):
with self.assertRaisesRegex(ValueError, 'not a valid version number'):
_get_php_executable(unittest.fixtures_path('get_php_executable/invalid'), self.versions_path)
def test_no_versions_path_raises_exception(self):
with self.assertRaisesRegex(ValueError, 'is not set'):
_get_php_executable(unittest.fixtures_path('get_php_executable'), None)
def test_invalid_versions_path_raises_exception(self):
with self.assertRaisesRegex(ValueError, 'does not exist or is not a valid directory'):
_get_php_executable(unittest.fixtures_path('get_php_executable'), unittest.fixtures_path('foobar'))
def test_non_executable_raises_exeption(self):
if sublime.platform() == 'windows':
actual = _get_php_executable(
unittest.fixtures_path(os.path.join('get_php_executable', 'not_executable')),
self.versions_path)
expected = unittest.fixtures_path(os.path.join('get_php_executable', 'versions', '7.2.0', 'php.exe'))
self.assertEqual(actual, expected)
else:
with self.assertRaisesRegex(ValueError, 'is not an executable file'):
_get_php_executable(
unittest.fixtures_path(os.path.join('get_php_executable', 'not_executable')),
self.versions_path)
|
463952
|
import unittest
import click
from biolinkml.generators import graphqlgen
from tests.test_scripts.environment import env
from tests.utils.clicktestcase import ClickTestCase
class GenGraphqlTestCase(ClickTestCase):
testdir = "gengraphql"
click_ep = graphqlgen.cli
prog_name = "gen-graphql"
env = env
def test_help(self):
self.do_test("--help", 'help')
def test_meta(self):
self.do_test([], 'meta.graphql')
self.do_test('-f xsv', 'meta_error', expected_error=click.exceptions.BadParameter)
if __name__ == '__main__':
unittest.main()
|
463963
|
from houdini.data import AbstractDataCollection, db
class BuddyList(db.Model):
__tablename__ = 'buddy_list'
penguin_id = db.Column(db.ForeignKey('penguin.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True,
nullable=False)
buddy_id = db.Column(db.ForeignKey('penguin.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True,
nullable=False, index=True)
best_buddy = db.Column(db.Boolean, nullable=False, server_default=db.text("false"))
class BuddyRequest(db.Model):
__tablename__ = 'buddy_request'
penguin_id = db.Column(db.ForeignKey('penguin.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True,
nullable=False)
requester_id = db.Column(db.ForeignKey('penguin.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True,
nullable=False)
class IgnoreList(db.Model):
__tablename__ = 'ignore_list'
penguin_id = db.Column(db.ForeignKey('penguin.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True,
nullable=False)
ignore_id = db.Column(db.ForeignKey('penguin.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True,
nullable=False, index=True)
class Character(db.Model):
__tablename__ = 'character'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30), nullable=False)
gift_id = db.Column(db.ForeignKey('item.id', ondelete='CASCADE', onupdate='CASCADE'))
stamp_id = db.Column(db.ForeignKey('stamp.id', ondelete='CASCADE', onupdate='CASCADE'))
class CharacterBuddy(db.Model):
__tablename__ = 'character_buddy'
penguin_id = db.Column(db.ForeignKey('penguin.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True,
nullable=False)
character_id = db.Column(db.ForeignKey('character.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True,
nullable=False)
best_buddy = db.Column(db.Boolean, nullable=False, server_default=db.text("false"))
class BuddyListCollection(AbstractDataCollection):
__model__ = BuddyList
__filterby__ = 'penguin_id'
__indexby__ = 'buddy_id'
class IgnoreListCollection(AbstractDataCollection):
__model__ = IgnoreList
__filterby__ = 'penguin_id'
__indexby__ = 'ignore_id'
class BuddyRequestCollection(AbstractDataCollection):
__model__ = BuddyRequest
__filterby__ = 'penguin_id'
__indexby__ = 'requester_id'
class CharacterCollection(AbstractDataCollection):
__model__ = Character
__filterby__ = 'id'
__indexby__ = 'id'
class CharacterBuddyCollection(AbstractDataCollection):
__model__ = CharacterBuddy
__filterby__ = 'penguin_id'
__indexby__ = 'character_id'
|
464003
|
class JenkinsMetadata(object):
""" This class is the model of the Jenkins data relating to the build that ran the tests or collected the metrics.
This class is how the model is represented in the HTTP API """
def __init__(self, jenkins_job_id):
self.jenkins_job_id = jenkins_job_id
|
464009
|
from django.test import TestCase
class SampleTest(TestCase):
def test_1_equals_1(self):
self.assertEquals(1, 1)
|
464013
|
from opyoid.provider import Provider
from opyoid.utils import InjectedT
class FromInstanceProvider(Provider[InjectedT]):
def __init__(self, instance: InjectedT) -> None:
self._instance = instance
def get(self) -> InjectedT:
return self._instance
|
464040
|
from threading import Thread
def my_function():
print("printing from thread")
if __name__ == "__main__":
threads = [Thread(target=my_function) for _ in range(10)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
|
464128
|
import os
import mindmeld
from telegram.ext import (
Updater,
CommandHandler,
MessageHandler,
Filters,
ConversationHandler,
CallbackContext,
)
import logging
import requests
from dotenv import load_dotenv
url = "http://localhost:7150/parse"
load_dotenv()
updater = Updater(token=os.getenv('BOT_TOKEN'), use_context=True)
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
dispatcher = updater.dispatcher
def start(update, context):
context.bot.send_message(chat_id=update.effective_chat.id, text="Hello, I'm Journey. What can I do for you?")
def message_received(update: Updater, context: CallbackContext):
msg = update.message.text
body = {"text": msg}
response = requests.post(url, json=body)
print(response.json())
context.bot.send_message(chat_id=update.effective_chat.id, text=response.json()["directives"][0].payload.text)
message_handler = MessageHandler(Filters.text, message_received)
dispatcher.add_handler(message_handler)
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)
updater.start_polling()
|
464154
|
import os
import json
import datetime
from django.http import HttpResponse
from django.views.generic import TemplateView
from django.utils.safestring import mark_safe
from django.utils import timezone
from django.template.loader import render_to_string
from person.models import Person
from document.models import Dossier
from document.models import Submitter
from document.models import Kamervraag
from document.models import Kamerstuk
from document.views import TimelineKamervraagItem
from document.views import TimelineKamerstukItem
from government.models import Government
from website import settings
from stats.views import get_example_plot_html
class HomeView(TemplateView):
template_name = "website/index.html"
context_object_name = "homepage"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
class ContactView(TemplateView):
template_name = "website/contact.html"
context_object_name = "contact"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['contact_email'] = settings.CONTACT_EMAIL
return context
def create_timeline_date(date):
return {
'year': date.year,
'month': date.month,
'day': date.day
}
def get_dossier_timeline_json(request):
governments = Government.objects.all()
eras = []
for government in governments:
if government.date_dissolved:
end_date = government.date_dissolved
else:
end_date = timezone.now()
text = {
'headline': government.name,
'text': government.name
}
era = {
'start_date': create_timeline_date(government.date_formed),
'end_date': create_timeline_date(end_date),
'text': text
}
eras.append(era)
events = []
if 'dossier_pk' in request.GET:
dossier = Dossier.objects.get(id=request.GET['dossier_pk'])
for kamerstuk in dossier.kamerstukken:
text = {
'headline': kamerstuk.type_short,
'text': kamerstuk.type_long
}
event = {
'start_date': create_timeline_date(kamerstuk.document.date_published),
'text': text
}
events.append(event)
timeline_info = {
'events': events,
'eras': eras
}
timeline_json = json.dumps(timeline_info, sort_keys=True, indent=4)
# print(timeline_json)
return HttpResponse(timeline_json, content_type='application/json')
class PlotExampleView(TemplateView):
template_name = "website/plot_examples.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['plot_html'] = mark_safe(get_example_plot_html())
return context
class DatabaseDumpsView(TemplateView):
template_name = "website/database_dumps.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
backup_files = self.get_files(settings.DBBACKUP_STORAGE_OPTIONS['location'])
context['backup_files'] = sorted(backup_files, key=lambda backup: backup['datetime_created'], reverse=True)
return context
@staticmethod
def get_files(path):
files = []
for (dirpath, dirnames, filenames) in os.walk(path):
for file in filenames:
if '.gitignore' in file or 'readme.txt' in file:
continue
filepath = os.path.join(dirpath, file)
size = os.path.getsize(filepath)
datetime_created = os.path.getctime(filepath)
files.append({
'file': file,
'size': int(size)/1024/1024,
'datetime_created': datetime.datetime.fromtimestamp(datetime_created)
})
return files
class CSVExportsView(TemplateView):
template_name = "website/csv_exports.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
files = DatabaseDumpsView.get_files(settings.CSV_EXPORT_PATH)
context['files'] = sorted(files, key=lambda file: file['datetime_created'], reverse=True)
return context
class PersonTimelineView(TemplateView):
template_name = "website/items/person_timeline.html"
@staticmethod
def get_timeline_items(person, year=None):
if year:
year = int(year)
submitters = Submitter.objects.filter(person=person, document__date_published__range=[datetime.date(year=year, day=1, month=1), datetime.date(year=year, day=31, month=12)])
else:
submitters = Submitter.objects.filter(person=person)
submitter_ids = list(submitters.values_list('id', flat=True))
timeline_items = []
kamervragen = Kamervraag.objects.filter(document__submitter__in=submitter_ids).select_related('document', 'kamerantwoord')
for kamervraag in kamervragen:
timeline_items.append(TimelineKamervraagItem(kamervraag))
kamerstukken = Kamerstuk.objects.filter(document__submitter__in=submitter_ids).select_related('document')
for kamerstuk in kamerstukken:
timeline_items.append(TimelineKamerstukItem(kamerstuk))
timeline_items = sorted(timeline_items, key=lambda items: items.date, reverse=True)
return timeline_items
def get_context_data(self, slug, year, **kwargs):
year = int(year)
context = super().get_context_data(**kwargs)
person = Person.objects.get(slug=slug)
timeline_items = []
has_next = True
while len(timeline_items) == 0:
timeline_items = PersonTimelineView.get_timeline_items(person, year)
if timeline_items:
break
if year < 1996:
has_next = False
break
year -= 1
if year == datetime.date.today().year:
next_year = None
else:
next_year = year + 1
context['timeline_items'] = timeline_items
context['person'] = person
context['is_person_timeline'] = True
context['previous_year'] = year - 1
context['next_year'] = next_year
context['has_next'] = has_next
return context
def get_person_timeline_html(request):
person = Person.objects.get(id=request.GET['person_id'])
year = int(request.GET['year'])
timeline_items = PersonTimelineView.get_timeline_items(person, year)
if year == datetime.date.today().year:
next_year = None
else:
next_year = year + 1
html = render_to_string('website/items/person_timeline.html', {
'timeline_items': timeline_items,
'person': person,
'is_person_timeline': True,
'previous_year': year-1,
'year': next_year,
'has_next': True
})
response = json.dumps({'html': html})
return HttpResponse(response, content_type='application/json')
|
464181
|
def test_enter(player, limo):
player.perform("enter limo")
assert player.saw("You enter a fancy limo")
assert player.saw("electric")
def test_enter_and_exit(player, limo):
player.perform("enter limo")
player.forget()
player.perform("go out")
assert player.saw("Antechamber")
|
464205
|
from abc import ABC, abstractmethod
from typing import Optional, Tuple
import torch
from torch import Tensor, nn
from torch.distributions import Bernoulli, Categorical, Distribution, Normal
from torch.nn import functional as F
from ..prelude import Array, Index, Self
from ..utils import Device
class Policy(ABC):
"""Represents parameterized stochastic policies."""
def __init__(self, dist: Distribution) -> None:
self.dist = dist
self._action: Optional[Tensor] = None
self._baction: Optional[Tensor] = None
def action(self) -> Tensor:
"""Sample actions or returns cached actions."""
if self._action is None:
self._action = self.sample()
# If batch size == 1, flatten the action
return self._action.squeeze(dim=0)
def baction(self) -> Tensor:
"""Sample 'backwardable' actions by PyTorch's ``rsample``."""
if self._baction is None:
self._baction = self.rsample()
return self._baction.squeeze(dim=0)
def set_action(self, action: Tensor) -> None:
"""Set cached actions."""
self._action = action
@torch.no_grad()
def sample(self) -> Tensor:
"""Sample actions with ``requires_grad=True``."""
return self.dist.sample()
def rsample(self) -> Tensor:
"""Sample with reparameterization trick. Returned tensor is backwardable."""
return self.dist.rsample()
def eval_action(self, deterministic: bool = False, to_numpy: bool = True) -> Array:
"""Sample actions for evaluation without setting cached actions."""
if deterministic:
act = self.best_action()
else:
act = self.sample()
if to_numpy:
return act.squeeze_().cpu().numpy()
else:
return act.squeeze_()
@abstractmethod
def __getitem__(self, idx: Index) -> Self:
pass
@abstractmethod
def best_action(self) -> Tensor:
pass
@abstractmethod
def log_prob(
self,
action: Optional[Tensor] = None,
use_baction: bool = False,
) -> Tensor:
pass
@abstractmethod
def entropy(self) -> Tensor:
pass
@abstractmethod
def detach(self) -> Self:
pass
class BernoulliPolicy(Policy):
def __init__(self, *args, **kwargs) -> None:
super().__init__(Bernoulli(*args, **kwargs))
self.dist: Bernoulli
def best_action(self) -> Tensor:
return self.dist.probs > 0.5
def log_prob(
self,
action: Optional[Tensor] = None,
use_baction: bool = False,
) -> Tensor:
if action is None:
action = self.bactions() if use_baction else self.action()
return self.dist.log_prob(action)
def entropy(self) -> Tensor:
return self.dist.entropy()
def __getitem__(self, idx: Index) -> Self:
return self.__class__(logits=self.dist.logits[idx])
def detach(self) -> Self:
return self.__class__(logits=self.dist.logits.detach())
class CategoricalPolicy(Policy):
def __init__(self, *args, **kwargs) -> None:
super().__init__(Categorical(*args, **kwargs))
self.dist: Categorical
def best_action(self) -> Tensor:
return self.dist.probs.argmax(dim=-1)
def log_prob(
self,
action: Optional[Tensor] = None,
use_baction: bool = False,
) -> Tensor:
if action is None:
action = self.bactions() if use_baction else self.action()
return self.dist.log_prob(action)
def entropy(self) -> Tensor:
return self.dist.entropy()
def __getitem__(self, idx: Index) -> Self:
return self.__class__(logits=self.dist.logits[idx])
def detach(self) -> Self:
return self.__class__(logits=self.dist.logits.detach())
class GaussianPolicy(Policy):
def __init__(self, *args, **kwargs) -> None:
super().__init__(Normal(*args, **kwargs))
self.dist: Normal
def best_action(self) -> Tensor:
return self.dist.mean
def entropy(self) -> Tensor:
return self.dist.entropy().sum(-1)
def log_prob(
self,
action: Optional[Tensor] = None,
use_baction: bool = False,
) -> Tensor:
if action is None:
action = self.bactions() if use_baction else self.action()
return self.dist.log_prob(action).sum(-1)
def __getitem__(self, idx: Index) -> Self:
return self.__class__(self.dist.mean[idx], self.dist.stddev[idx])
def detach(self) -> Self:
return self.__class__(self.dist.mean.detach(), self.dist.stddev.detach())
class TanhGaussianPolicy(GaussianPolicy):
def __init__(self, *args, epsilon: float = 1e-6, **kwargs) -> None:
super().__init__(*args, **kwargs)
self._pre_tanh: Optional[Tensor] = None
self.epsilon = epsilon
def sample(self) -> Tensor:
pre_tanh = self.dist.sample().detach()
self._pre_tanh = pre_tanh
return torch.tanh(pre_tanh)
def rsample(self) -> Tensor:
res = self.dist.rsample()
self._pre_tanh = res
return torch.tanh(res)
def best_action(self) -> Tensor:
return torch.tanh(self.dist.mean)
def log_prob(
self,
action: Optional[Tensor] = None,
use_baction: bool = False,
) -> Tensor:
if action is None:
action = self._baction if use_baction else self.action()
if self._pre_tanh is None:
pre_tanh = torch.log((1.0 + action) / (1.0 - action)) / 2
else:
pre_tanh = self._pre_tanh
log_n = self.dist.log_prob(pre_tanh).sum(-1)
log_da_du = torch.log(1.0 - action ** 2 + self.epsilon).sum(-1)
return log_n - log_da_du
class PolicyDist(ABC, nn.Module):
def __init__(self, action_dim: int, *args, **kwargs) -> None:
super().__init__()
self.action_dim = action_dim
@property
def input_dim(self) -> int:
return self.action_dim
@abstractmethod
def forward(self, t: Tensor) -> Policy:
pass
class BernoulliDist(PolicyDist):
"""Bernoulli policy with no learnable parameter"""
def __init__(self, action_dim: int = 1, *args, **kwargs) -> None:
super().__init__(action_dim)
def forward(self, x: Tensor) -> Policy:
return BernoulliPolicy(logits=x)
class CategoricalDist(PolicyDist):
"""Categorical policy with no learnable parameter"""
def forward(self, x: Tensor) -> Policy:
return CategoricalPolicy(logits=x)
class GaussinanDist(PolicyDist):
"""Gaussian policy which takes both mean and stdev as inputs."""
@property
def input_dim(self) -> int:
return self.action_dim * 2
def forward(self, x: Tensor) -> Policy:
size = x.size(1) // 2
mean, stddev = x[:, :size], x[:, size:]
return GaussianPolicy(mean, F.softplus(stddev))
class TanhGaussianDist(GaussinanDist):
"""Tanh clipped Gaussian policy."""
def __init__(
self,
action_dim: int,
*args,
logstd_range: Tuple[float, float] = (-20.0, 2.0),
**kwargs,
) -> None:
super().__init__(action_dim)
self.logstd_range = logstd_range
def forward(self, x: Tensor) -> Policy:
size = x.size(1) // 2
mu, logstd = x[:, :size], x[:, size:]
std = torch.exp(logstd.clamp_(*self.logstd_range))
return TanhGaussianPolicy(mu, std)
class SeparateStdGaussianDist(PolicyDist):
"""Gaussian policy which takes only mean as an input, and has a standard deviation
independent with states, as a lernable parameter.
"""
def __init__(self, action_dim: int, device: Device, *args, **kwargs) -> None:
super().__init__(action_dim)
self.stddev = nn.Parameter(device.zeros(action_dim))
def forward(self, x: Tensor) -> Policy:
return GaussianPolicy(x, F.softplus(self.stddev))
class PerOptionStdGaussianDist(PolicyDist):
"""The same as `SeparateStdGaussianDist`, but has a dimention for options"""
def __init__(
self, action_dim: int, device: Device, *args, noptions: int = 1, **kwargs
) -> None:
super().__init__(action_dim)
self.stddev = nn.Parameter(device.zeros((noptions, action_dim)))
def forward(self, x: Tensor) -> Policy:
return GaussianPolicy(x, F.softplus(self.stddev))
|
464211
|
import torch.nn as nn
import torch.nn.functional as F
from sodium.utils import setup_logger
from sodium.base import BaseModel
logger = setup_logger(__name__)
class MNISTModel(BaseModel):
def __init__(self, dropout_value=0.08):
self.dropout_value = dropout_value # dropout value
super(MNISTModel, self).__init__()
# Input Block
self.convblock1 = nn.Sequential(
nn.Conv2d(in_channels=1, out_channels=14,
kernel_size=(3, 3), padding=0, bias=False),
nn.BatchNorm2d(14),
nn.ReLU(),
nn.Dropout(self.dropout_value)
) # output_size = 26
# CONVOLUTION BLOCK 1
self.convblock2 = nn.Sequential(
nn.Conv2d(in_channels=14, out_channels=30,
kernel_size=(3, 3), padding=0, bias=False),
nn.BatchNorm2d(30),
nn.ReLU(),
nn.Dropout(self.dropout_value)
) # output_size = 24
# TRANSITION BLOCK 1
self.convblock3 = nn.Sequential(
nn.Conv2d(in_channels=30, out_channels=10,
kernel_size=(1, 1), padding=0, bias=False),
) # output_size = 24
self.pool1 = nn.MaxPool2d(2, 2) # output_size = 12
# CONVOLUTION BLOCK 2
self.convblock4 = nn.Sequential(
nn.Conv2d(in_channels=10, out_channels=14,
kernel_size=(3, 3), padding=0, bias=False),
nn.BatchNorm2d(14),
nn.ReLU(),
nn.Dropout(self.dropout_value)
) # output_size = 10
self.convblock5 = nn.Sequential(
nn.Conv2d(in_channels=14, out_channels=15,
kernel_size=(3, 3), padding=0, bias=False),
nn.BatchNorm2d(15),
nn.ReLU(),
nn.Dropout(self.dropout_value)
) # output_size = 8
self.convblock6 = nn.Sequential(
nn.Conv2d(in_channels=15, out_channels=15,
kernel_size=(3, 3), padding=0, bias=False),
nn.BatchNorm2d(15),
nn.ReLU(),
nn.Dropout(self.dropout_value)
) # output_size = 6
# OUTPUT BLOCK
self.gap = nn.Sequential(
nn.AvgPool2d(kernel_size=6)
) # output_size = 1
self.convblock7 = nn.Sequential(
nn.Conv2d(in_channels=15, out_channels=15,
kernel_size=(1, 1), padding=0, bias=False),
nn.ReLU(),
nn.BatchNorm2d(15),
nn.Dropout(self.dropout_value)
)
self.convblock8 = nn.Sequential(
nn.Conv2d(in_channels=15, out_channels=10,
kernel_size=(1, 1), padding=0, bias=False),
)
self.dropout = nn.Dropout(self.dropout_value)
def forward(self, x):
x = self.convblock1(x)
x = self.convblock2(x)
x = self.convblock3(x)
x = self.pool1(x)
x = self.convblock4(x)
x = self.convblock5(x)
x = self.convblock6(x)
x = self.gap(x)
x = self.convblock7(x)
x = self.convblock8(x)
x = x.view(-1, 10)
return F.log_softmax(x, dim=-1)
class CIFAR10Model(BaseModel):
def __init__(self, dropout_value=0.25):
self.dropout_value = dropout_value # dropout value
super(CIFAR10Model, self).__init__()
# Input Block
self.convblock1 = nn.Sequential(
nn.Conv2d(in_channels=3, out_channels=32,
kernel_size=(3, 3), padding=1, bias=False),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.Dropout(self.dropout_value)
) # output_size = 32
# CONVOLUTION BLOCK 1
self.convblock2 = nn.Sequential(
nn.Conv2d(in_channels=32, out_channels=64,
kernel_size=(3, 3), padding=1, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Dropout(self.dropout_value)
) # output_size = 32
# TRANSITION BLOCK 1
self.convblock3 = nn.Sequential(
nn.Conv2d(in_channels=64, out_channels=32,
kernel_size=(1, 1), padding=0, bias=False),
) # output_size = 32
self.pool1 = nn.MaxPool2d(2, 2) # output_size = 16
# CONVOLUTION BLOCK 2
# DEPTHWISE CONVOLUTION AND POINTWISE CONVOLUTION
self.depthwise1 = nn.Sequential(
nn.Conv2d(in_channels=32, out_channels=64,
kernel_size=(3, 3), padding=0, groups=32, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.Dropout(self.dropout_value)
) # output_size = 16
self.convblock4 = nn.Sequential(
nn.Conv2d(in_channels=64, out_channels=128,
kernel_size=(1, 1), padding=0, bias=False),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.Dropout(self.dropout_value)
) # output_size = 16
# TRANSITION BLOCK 2
self.pool2 = nn.MaxPool2d(2, 2) # output_size = 8
# CONVOLUTION BLOCK 3
self.convblock5 = nn.Sequential(
nn.Conv2d(in_channels=128, out_channels=128,
kernel_size=(3, 3), padding=4, dilation=2, bias=False),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.Dropout(self.dropout_value)
) # output_size = 11
self.convblock6 = nn.Sequential(
nn.Conv2d(in_channels=128, out_channels=128,
kernel_size=(3, 3), padding=1, bias=False),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.Dropout(self.dropout_value)
) # output_size = 11
# TRANSITION BLOCK 3
self.pool3 = nn.MaxPool2d(2, 2) # output_size = 5
# OUTPUT BLOCK
self.gap = nn.Sequential(
nn.AvgPool2d(kernel_size=5)
) # output_size = 1
self.convblock7 = nn.Sequential(
nn.Conv2d(in_channels=128, out_channels=128,
kernel_size=(1, 1), padding=0, bias=False),
nn.ReLU(),
nn.BatchNorm2d(128),
nn.Dropout(self.dropout_value)
)
self.convblock8 = nn.Sequential(
nn.Conv2d(in_channels=128, out_channels=10,
kernel_size=(1, 1), padding=0, bias=False),
)
self.dropout = nn.Dropout(self.dropout_value)
def forward(self, x):
x = self.convblock1(x)
x = self.convblock2(x)
x = self.convblock3(x)
x = self.pool1(x)
x = self.depthwise1(x)
x = self.convblock4(x)
x = self.pool2(x)
x = self.convblock5(x)
x = self.convblock6(x)
x = self.pool3(x)
x = self.gap(x)
x = self.convblock7(x)
x = self.convblock8(x)
x = x.view(-1, 10)
return F.log_softmax(x, dim=-1)
|
464236
|
import cartography.intel.digitalocean.platform
import tests.data.digitalocean.platform
TEST_UPDATE_TAG = 123456789
def test_transform_and_load_account(neo4j_session):
account_res = tests.data.digitalocean.platform.ACCOUNT_RESPONSE
"""
Test that we can correctly transform and load DOAccount nodes to Neo4j.
"""
account = cartography.intel.digitalocean.platform.transform_account(account_res)
cartography.intel.digitalocean.platform.load_account(neo4j_session, account, TEST_UPDATE_TAG)
query = """
MATCH(a:DOAccount{id:{AccountId}})
RETURN a.id, a.uuid, a.droplet_limit, a.floating_ip_limit, a.status, a.lastupdated
"""
nodes = neo4j_session.run(
query,
AccountId=account_res.uuid,
)
actual_nodes = {
(
n['a.id'],
n['a.uuid'],
n['a.droplet_limit'],
n['a.floating_ip_limit'],
n['a.status'],
n['a.lastupdated'],
) for n in nodes
}
expected_nodes = {
(
account_res.uuid,
account_res.uuid,
account_res.droplet_limit,
account_res.floating_ip_limit,
account_res.status,
TEST_UPDATE_TAG,
),
}
assert actual_nodes == expected_nodes
|
464248
|
from textwrap import dedent
from tests import check_as_expected
ROOT = 'superhelp.helpers.print_help.'
def test_misc():
test_conf = [
(
dedent("""\
pet = 'cat'
"""),
{
ROOT + 'print_overview': 0,
}
),
(
dedent("""\
pet = 'cat'
print(pet)
"""),
{
ROOT + 'print_overview': 1,
}
),
(
dedent("""\
for i in range(2):
print('Hi')
"""),
{
ROOT + 'print_overview': 1,
}
),
(
dedent("""\
for i in range(2):
print(f'Hi {i}')
"""),
{
ROOT + 'print_overview': 1,
}
),
(
dedent("""\
print('Hi')
print('Hi')
print('Hi')
"""),
{
ROOT + 'print_overview': 1,
}
),
(
dedent("""\
p = print
p('Hi')
p('Hi')
"""),
{
ROOT + 'print_overview': 1,
}
),
]
check_as_expected(test_conf, execute_code=True)
check_as_expected(test_conf, execute_code=False)
# test_misc()
|
464259
|
from typing import List, Tuple, Union
import numpy as np
from ...utils.geometry import project_points_onto_plane
def displayed_plane_from_nd_line_segment(
start_point: np.ndarray,
end_point: np.ndarray,
dims_displayed: Union[List[int], np.ndarray],
) -> Tuple[np.ndarray, np.ndarray]:
"""Get the plane defined by start_point and the normal vector that goes
from start_point to end_point.
Note the start_point and end_point are nD and
the returned plane is in the displayed dimensions (i.e., 3D).
Parameters
----------
start_point : np.ndarray
The start point of the line segment in nD coordinates.
end_point : np.ndarray
The end point of the line segment in nD coordinates..
dims_displayed : Union[List[int], np.ndarray]
The dimensions of the data array currently in view.
Returns
-------
plane_point : np.ndarray
The point on the plane that intersects the click ray. This is returned
in data coordinates with only the dimensions that are displayed.
plane_normal : np.ndarray
The normal unit vector for the plane. It points in the direction of the click
in data coordinates.
"""
plane_point = start_point[dims_displayed]
end_position_view = end_point[dims_displayed]
ray_direction = end_position_view - plane_point
plane_normal = ray_direction / np.linalg.norm(ray_direction)
return plane_point, plane_normal
def drag_data_to_projected_distance(
start_position, end_position, view_direction, vector
):
"""Calculate the projected distance between two mouse events.
Project the drag vector between two mouse events onto a 3D vector
specified in data coordinates.
The general strategy is to
1) find mouse drag start and end positions, project them onto a
pseudo-canvas (a plane aligned with the canvas) in data coordinates.
2) project the mouse drag vector onto the (normalised) vector in data
coordinates
Parameters
----------
start_position : np.ndarray
Starting point of the drag vector in data coordinates
end_position : np.ndarray
End point of the drag vector in data coordinates
view_direction : np.ndarray
Vector defining the plane normal of the plane onto which the drag
vector is projected.
vector : np.ndarray
(3,) unit vector or (n, 3) array thereof on which to project the drag
vector from start_event to end_event. This argument is defined in data
coordinates.
Returns
-------
projected_distance : (1, ) or (n, ) np.ndarray of float
"""
# enforce at least 2d input
vector = np.atleast_2d(vector)
# Store the start and end positions in world coordinates
start_position = np.asarray(start_position)
end_position = np.asarray(end_position)
# Project the start and end positions onto a pseudo-canvas, a plane
# parallel to the rendered canvas in data coordinates.
end_position_canvas, _ = project_points_onto_plane(
end_position, start_position, view_direction
)
# Calculate the drag vector on the pseudo-canvas.
drag_vector_canvas = np.squeeze(end_position_canvas - start_position)
# Project the drag vector onto the specified vector(s), return the distance
return np.einsum('j, ij -> i', drag_vector_canvas, vector).squeeze()
|
464283
|
import numpy as np
import neorl.benchmarks.cec17 as functions #import all cec17 functions
import neorl.benchmarks.classic as classics #import all classical functions
from neorl.benchmarks.classic import ackley, levy, bohachevsky #import specific functions
from neorl.benchmarks.cec17 import f3, f10, f21 #import cec17 specific functions
from neorl.benchmarks import bench_2dplot #import the built-in plotter
d1 = 2 #set dimension for classical functions
d2 = 10 #set dimension for cec functions (choose between 2, 10, 20, 30, 50 or 100)
print('------------------------------------------------------')
print('Classical Functions')
print('------------------------------------------------------')
for f in classics.all_functions:
sample = np.random.uniform(low=0, high=10, size=d1)
y = f(sample)
print('Function: {}, x={}, y={}'.format(f.__name__, np.round(sample,2), np.round(y,2)))
print('------------------------------------------------------')
print('CEC2017 Functions')
print('------------------------------------------------------')
for f in functions.all_functions:
sample = np.random.uniform(low=-10, high=10, size=d2)
y = f(sample)
print('Function: {}, x={}, y={}'.format(f.__name__, np.round(sample,2), np.round(y,2)))
print('------------------------------------------------------')
print('Function Plotter')
print('------------------------------------------------------')
bench_2dplot(f3, domain=(-50,50), points=60)
bench_2dplot(f10, savepng='ex4_f10.png')
bench_2dplot(f21, savepng='ex4_f21.png')
bench_2dplot(ackley, savepng='ex4_ackley.png')
bench_2dplot(levy, domain=(-10,10))
bench_2dplot(bohachevsky, points=50)
#------------------------------------------------------------------------------
#NOTE: CEC'17 functions: f11-f20, f29, f30 are not defined for d=2 dimensions,
#so the plotter will FAIL for these functions
#------------------------------------------------------------------------------
|
464326
|
import sublime
from .typing import Optional, Union
class ProgressReporter:
def __init__(self, title: str) -> None:
self.title = title
self._message = None # type: Optional[str]
self._percentage = None # type: Union[None, int, float]
def __del__(self) -> None:
pass
def _render(self) -> str:
result = self.title
if self._message:
result += ': ' + self._message
if self._percentage:
fmt = ' ({:.1f}%)' if isinstance(self._percentage, float) else ' ({}%)'
result += fmt.format(self._percentage)
return result
def __call__(self, message: Optional[str], percentage: Union[None, int, float]) -> None:
if percentage is not None:
self._percentage = percentage
if message is not None:
self._message = message
class ViewProgressReporter(ProgressReporter):
def __init__(self, view: sublime.View, key: str, title: str, message: Optional[str] = None,
percentage: Union[None, int, float] = None) -> None:
super().__init__(title)
self._view = view
self._key = key
self.__call__(message, percentage)
def __del__(self) -> None:
self._view.erase_status(self._key)
super().__del__()
def __call__(self, message: Optional[str] = None, percentage: Union[None, int, float] = None) -> None:
super().__call__(message, percentage)
self._view.set_status(self._key, self._render())
class WindowProgressReporter(ProgressReporter):
def __init__(self, window: sublime.Window, key: str, title: str, message: Optional[str] = None,
percentage: Union[None, int, float] = None) -> None:
super().__init__(title)
self._window = window
self._key = key
self.__call__(message, percentage)
def __del__(self) -> None:
for view in self._window.views():
view.erase_status(self._key)
super().__del__()
def __call__(self, message: Optional[str] = None, percentage: Union[None, int, float] = None) -> None:
super().__call__(message, percentage)
display = self._render()
for view in self._window.views():
view.set_status(self._key, display)
class ApplicationProgressReporter(ProgressReporter):
def __init__(self, key: str, title: str, message: Optional[str] = None,
percentage: Union[None, int, float] = None) -> None:
super().__init__(title)
self._key = key
self.__call__(message, percentage)
def __del__(self) -> None:
for window in sublime.windows():
for view in window.views():
view.erase_status(self._key)
super().__del__()
def __call__(self, message: Optional[str] = None, percentage: Union[None, int, float] = None) -> None:
super().__call__(message, percentage)
display = self._render()
for window in sublime.windows():
for view in window.views():
view.set_status(self._key, display)
|
464336
|
import ctypes
from sys import platform as _platform_name
if _platform_name.startswith('win'):
time_t = ctypes.c_uint32
else:
time_t = ctypes.c_uint64
class DSPROJECT(ctypes.Structure):
_fields_ = [("dsapiVersionNo", ctypes.c_int),
("sessionId", ctypes.c_int),
("valueMark", ctypes.c_ubyte),
("fieldMark", ctypes.c_ubyte)]
class DSJOB(ctypes.Structure):
_fields_ = [("hProject", ctypes.POINTER(DSPROJECT)),
("serverJobHandle", ctypes.c_char_p),
("logData", ctypes.c_char_p),
("logDataLen", ctypes.c_int),
("logDataPsn", ctypes.c_int)]
class _DSJOBINFO(ctypes.Union):
_fields_ = [("jobStatus", ctypes.c_int),
("jobController", ctypes.c_char_p),
("jobStartTime", time_t),
("jobWaveNumber", ctypes.c_int),
("userStatus", ctypes.c_char_p),
("stageList", ctypes.POINTER(ctypes.c_char)),
("paramList", ctypes.POINTER(ctypes.c_char)),
("jobName", ctypes.c_char_p),
("jobControl", ctypes.c_int),
("jobPid", ctypes.c_int),
("jobLastTime", time_t),
("jobInvocations", ctypes.POINTER(ctypes.c_char)),
("jobInterimStatus", ctypes.c_int),
("jobInvocationId", ctypes.c_char_p),
("jobDesc", ctypes.c_char_p),
("stageList2", ctypes.POINTER(ctypes.c_char)),
("jobElapsed", ctypes.c_int),
("jobDMIService", ctypes.c_int),
("jobMultiInvokable", ctypes.c_int),
("jobFullDesc", ctypes.c_char_p),
("jobRestartable", ctypes.c_int)]
class DSJOBINFO(ctypes.Structure):
_fields_ = [("infoType", ctypes.c_int),
("info", _DSJOBINFO)]
class _DSPROJECTINFO(ctypes.Union):
_fields_ = [("jobList", ctypes.POINTER(ctypes.c_char)),
("projectName", ctypes.c_char_p),
("projectPath", ctypes.c_char_p),
("hostName", ctypes.c_char_p),
("installTag", ctypes.c_char_p),
("tcpPort", ctypes.c_char_p)]
class DSPROJECTINFO(ctypes.Structure):
_fields_ = [("infoType", ctypes.c_int),
("info", _DSPROJECTINFO)]
class DSLOGEVENT(ctypes.Structure):
_fields_ = [("eventId", ctypes.c_int),
("timestamp", time_t),
("type", ctypes.c_int),
("message", ctypes.c_char_p)]
class DSLOGDETAILFULL(ctypes.Structure):
_fields_ = [("eventId", ctypes.c_int),
("timestamp", time_t),
("type", ctypes.c_int),
("username", ctypes.c_char_p),
("fullMessage", ctypes.POINTER(ctypes.c_char)),
("messageId", ctypes.c_char_p),
("invocationId", ctypes.c_char_p)]
class DSLOGDETAIL(ctypes.Structure):
_fields_ = [("eventId", ctypes.c_int),
("timestamp", time_t),
("type", ctypes.c_int),
("username", ctypes.c_char_p),
("fullMessage", ctypes.POINTER(ctypes.c_char))]
class _DSPARAM(ctypes.Union):
_fields_ = [("pString", ctypes.c_char_p),
("pEncrypt", ctypes.c_char_p),
("pInt", ctypes.c_int),
("pFloat", ctypes.c_float),
("pPath", ctypes.c_char_p),
("pListValue", ctypes.c_char_p),
("pDate", ctypes.c_char_p),
("pTime", ctypes.c_char_p)]
class DSPARAM(ctypes.Structure):
_fields_ = [("paramType", ctypes.c_int),
("paramValue", _DSPARAM)]
class DSPARAMINFO(ctypes.Structure):
_fields_ = [("defaultValue", DSPARAM),
("helpText", ctypes.c_char_p),
("paramPrompt", ctypes.c_char_p),
("paramType", ctypes.c_int),
("desDefaultValue", DSPARAM),
("listValues", ctypes.c_char_p),
("desListValues", ctypes.c_char_p),
("promptAtRun", ctypes.c_int)]
class _DSREPORTINFO(ctypes.Union):
_fields_ = [("reportText", ctypes.c_char_p)]
class DSREPORTINFO(ctypes.Structure):
_fields_ = [("reportType", ctypes.c_int),
("info", _DSREPORTINFO)]
class DSREPOSUSAGEJOB(ctypes.Structure):
pass
DSREPOSUSAGEJOB._fields_ = [("jobname", ctypes.c_char_p),
("jobtype", ctypes.c_int),
("nextjob", ctypes.POINTER(DSREPOSUSAGEJOB)),
("childjob", ctypes.POINTER(DSREPOSUSAGEJOB))]
class _DSREPOSUSAGE(ctypes.Union):
_fields_ = [("jobs", ctypes.POINTER(DSREPOSUSAGEJOB))]
class DSREPOSUSAGE(ctypes.Structure):
_fields_ = [("infoType", ctypes.c_int),
("info", _DSREPOSUSAGE)]
class DSREPOSJOBINFO(ctypes.Structure):
pass
DSREPOSJOBINFO._fields_ = [("jobname", ctypes.c_char_p),
("jobtype", ctypes.c_int),
("nextjob", ctypes.POINTER(DSREPOSJOBINFO))]
class _DSREPOSINFO(ctypes.Union):
_fields_ = [("jobs", ctypes.POINTER(DSREPOSJOBINFO))]
class DSREPOSINFO(ctypes.Structure):
_fields_ = [("infoType", ctypes.c_int),
("info", _DSREPOSINFO)]
class _DSSTAGEINFO(ctypes.Union):
_fields_ = [("lastError", DSLOGDETAIL),
("typeName", ctypes.c_char_p),
("inRowNum", ctypes.c_int),
("linkList", ctypes.POINTER(ctypes.c_char)),
("stageName", ctypes.c_char_p),
("varList", ctypes.POINTER(ctypes.c_char)),
("stageStartTime", time_t),
("stageEndTime", time_t),
("linkTypes", ctypes.POINTER(ctypes.c_char)),
("stageDesc", ctypes.c_char_p),
("instList", ctypes.POINTER(ctypes.c_char)),
("cpuList", ctypes.POINTER(ctypes.c_char)),
("stageElapsed", ctypes.c_char_p),
("pidList", ctypes.POINTER(ctypes.c_char)),
("stageStatus", ctypes.c_int),
("custInfoList", ctypes.POINTER(ctypes.c_char))]
class DSSTAGEINFO(ctypes.Structure):
_fields_ = [("infoType", ctypes.c_int),
("info", _DSSTAGEINFO)]
class _DSLINKINFO(ctypes.Union):
_fields_ = [("lastError", DSLOGDETAIL),
("rowCount", ctypes.c_int),
("linkName", ctypes.c_char_p),
("linkSQLState", ctypes.c_char_p),
("linkDBMSCode", ctypes.c_char_p),
("linkDesc", ctypes.c_char_p),
("linkedStage", ctypes.c_char_p),
("rowCountList", ctypes.POINTER(ctypes.c_char))]
class DSLINKINFO(ctypes.Structure):
_fields_ = [("infoType", ctypes.c_int),
("info", _DSLINKINFO)]
class _DSVARINFO(ctypes.Union):
_fields_ = [("varValue", ctypes.c_char_p),
("varDesc", ctypes.c_char_p)]
class DSVARINFO(ctypes.Structure):
_fields_ = [("infoType", ctypes.c_int),
("info", _DSVARINFO)]
class _DSCUSTINFO(ctypes.Union):
_fields_ = [("custInfoValue", ctypes.c_char_p),
("custInfoDesc", ctypes.c_char_p)]
class DSCUSTINFO(ctypes.Structure):
_fields_ = [("infoType", ctypes.c_int),
("info", _DSCUSTINFO)]
|
464346
|
import os.path
import unittest
import nbformat
from nbparameterise import code, Parameter
samplenb = os.path.join(os.path.dirname(__file__), 'sample.ipynb')
class BasicTestCase(unittest.TestCase):
def setUp(self):
with open(samplenb) as f:
self.nb = nbformat.read(f, as_version=4)
self.params = code.extract_parameters(self.nb)
def test_extract(self):
assert self.params == [
Parameter('a', str, "Some text"),
Parameter('b', int, 12),
Parameter('b2', int, -7),
Parameter('c', float, 14.0),
Parameter('d', bool, False),
Parameter('e', list, [0, 1.0, True, "text", [0, 1]]),
Parameter('f', dict, {0: 0, "item": True, "dict": {0: "text"}}),
]
assert self.params[4].comment == '# comment:bool'
assert self.params[6].comment == '# comment:dict'
assert self.params[3].metadata == {'display_name': 'Sea'}
def test_rebuild(self):
from_form = [
self.params[0].with_value("New text"),
self.params[1].with_value(21),
self.params[2].with_value(-3),
self.params[3].with_value(0.25),
self.params[4].with_value(True),
]
nb = code.replace_definitions(self.nb, from_form, execute=False)
assert "# comment:bool" in nb.cells[0].source
ns = {}
exec(nb.cells[0].source, ns)
assert ns['a'] == "New text"
assert ns['b'] == 21
assert ns['b2'] == -3
assert ns['c'] == 0.25
assert ns['d'] == True
def test_new_values(self):
params = code.parameter_values(self.params,
a = "New text",
c = 12.0
)
assert [p.name for p in params] == ['a', 'b', 'b2', 'c', 'd', 'e', 'f']
assert params[0].value == 'New text'
assert params[1].value == 12
assert params[3].value == 12.0
assert isinstance(params[3].value, float)
assert params[4].value == False
def test_parameter_repr():
p = Parameter('days', int, 7, metadata={'foo': 'boo'}, comment='# Days to show')
p2 = eval(repr(p)) # The repr should eval to an identical Parameter
assert p2 == p
assert p2.metadata == p.metadata
assert p2.comment == p.comment
|
464347
|
from jiraauth import jclient
import debugmode
"""
This script was used to copy target versions (customfield_10304)
into the fix version field. It's a decent example of how to
iterate over search results and update issues in the result set
"""
i = 0
maxResults=50
num = 50
while i < num:
num, results = jclient.search_issues_with_total('"Target Version/s" is not EMPTY and status not in (Resolved, Closed)', startAt=i)
for issue in results:
print "checking " + issue.key
newFixVersions = None
for target_version in issue.fields.customfield_10304:
if not len([ x for x in issue.fields.fixVersions if x.id == target_version.id ]):
if not newFixVersions:
newFixVersions = [ x for x in issue.fields.fixVersions ]
newFixVersions.append(target_version)
if newFixVersions:
print "Updating " + issue.key + " was " + \
",".join(sorted([x.name for x in issue.fields.fixVersions ])) + \
" now " + ",".join(sorted([x.name for x in newFixVersions ]))
issue.update(fixVersions=[ { 'name': x.name } for x in newFixVersions ])
i += maxResults
print i
|
464400
|
from datasets.base.factory import DatasetFactory
from datasets.base.video.dataset import VideoDataset
from datasets.types.specialized_dataset import SpecializedVideoDatasetType
from datasets.base.video.filter.func import apply_filters_on_video_dataset_
from datasets.MOT.dataset import MultipleObjectTrackingDataset_MemoryMapped
from typing import List
__all__ = ['MultipleObjectTrackingDatasetFactory']
class MultipleObjectTrackingDatasetFactory(DatasetFactory):
def __init__(self, seeds: list):
super(MultipleObjectTrackingDatasetFactory, self).__init__(seeds, VideoDataset,
SpecializedVideoDatasetType.MultipleObjectTracking,
apply_filters_on_video_dataset_,
SpecializedVideoDatasetType.MultipleObjectTracking,
MultipleObjectTrackingDataset_MemoryMapped)
def construct(self, filters: list=None, cache_base_format: bool=True, dump_human_readable: bool=False) -> List[MultipleObjectTrackingDataset_MemoryMapped]:
return super(MultipleObjectTrackingDatasetFactory, self).construct(filters, cache_base_format, dump_human_readable)
def construct_as_base_interface(self, filters=None, make_cache=False, dump_human_readable=False) -> List[VideoDataset]:
return super(MultipleObjectTrackingDatasetFactory, self).construct_as_base_interface(filters, make_cache, dump_human_readable)
|
464412
|
from . import views
from django.conf.urls import url
urlpatterns = [
url(r'^(?P<appname>[^/]+)/$',
'oplog.views.api_oplogs', name='api_oplogs'),
]
|
464465
|
from node import Node
from arrow import Arrow
from polygon import Polygon
class DownArrow(Arrow):
def __init__(self, position = (0, 0)):
Arrow.__init__(self, position, [Node(-0.4, 0.0), Node(0, 0.5), Node(0.4, 0.0)])
def tip(self):
return Node(*(self.position())) + self.nodes()[1]
def direction(self):
return Node(0, 1)
def connector(self):
return Node(self.position()[0], self.position()[1])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.