content
stringlengths 0
894k
| type
stringclasses 2
values |
---|---|
import re
import json
VIEW_KEY_RE = r"a.+?href=\".+?viewkey=(.+?)\""
INFO_RE = r"var flashvars_.+? = ({.+})"
class Extractor(object):
def __init__(self):
self._viewkey_re = re.compile(VIEW_KEY_RE, re.MULTILINE)
self._videoinfo_re = re.compile(INFO_RE, re.MULTILINE)
def get_viewkeys(self, data):
matches = re.findall(self._viewkey_re, data)
# convert to a set to eliminate redundant viewkeys
return set(matches)
def get_video_info(self, data):
info_json = re.search(self._videoinfo_re, data)
if info_json is None:
return None
return json.loads(info_json.group(1))
|
python
|
import logging
import random
import re
from datetime import datetime
from plugins import Processor, handler, match
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("neikea.plugins")
class Strip(Processor):
"""
Turn the 'message' string into a dict that will contain different
versions of the message, including (after this module):
'raw': the message as received
'stripped': the message without leading/trailing whitespace and punctuation
'clean': the same as 'stripped' at first, but will be replaced in the
Addressed Processor if the bot has been addressed
"""
priority = -1600
addressed = False
pattern = re.compile(r"^\s*(.*?)\s*[?!.]*\s*$", re.DOTALL)
@handler
async def handle_strip(self, event):
event.message = {
"raw": event.message,
}
m = self.pattern.search(event.message["raw"])
assert m is not None
event.message["clean"] = event.message["stripped"] = m.group(1)
class Addressed(Processor):
"""
Check to see if this event was addressed to the bot. It looks for messages
of the forms:
@botname: foo
foo, @botname
while still being lenient with whitespace and punctuation. It avoids
responding to messages like "@botname is here".
After this processor, the event has a truthy "addressed" property, and
the message has two new versions:
'clean':
the message stripped of the address and of punctuation (should be
ready to be processed by most other processors)
'deaddressed':
the 'raw' message (with whitespace and punctuation) but without the
address part of the message
"""
priority = -1500
addressed = False
verbs = [
"is",
"has",
"was",
"might",
"may",
"would",
"will",
"isn't",
"hasn't",
"wasn't",
"wouldn't",
"won't",
"can",
"can't",
"did",
"didn't",
"said",
"says",
"should",
"shouldn't",
"does",
"doesn't",
]
async def setup(self, client):
self.mention = f"<@!{client.user.id}>"
self.patterns = [
re.compile(
r"^\s*(?P<username>%s)" % self.mention
+ r"(?:\s*[:;.?>!,-]+\s+|\s+|\s*[,:]\s*)(?P<body>.*)",
re.I | re.DOTALL,
),
# "hello there, bot"-style addressing. But we want to be sure that
# there wasn't normal addressing too.
# (e.g. "@otheruser: we already have a bot, @botname")
re.compile(
r"^(?:\S+:.*|(?P<body>.*),\s*(?P<username>%s))[\s?!.]*$" % self.mention,
re.I | re.DOTALL,
),
]
# Avoid responding to things like "@botname is our bot"
verbs = r"|".join(re.escape(x) for x in self.verbs)
self.verb_pattern = re.compile(
r"^(?:%s)\s+(?:%s)\s+" % (self.mention, verbs), re.I | re.DOTALL
)
@handler
async def handle_addressed(self, event):
if "addressed" not in event:
event.addressed = False
if self.verb_pattern.match(event.message["stripped"]):
return
# Private messages are always addressing the bot, although we will
# still create the 'clean' version of the message below.
if event.private:
event.addressed = True
for pattern in self.patterns:
matches = pattern.search(event.message["stripped"])
if matches and matches.group("username"):
new_message = matches.group("body")
event.addressed = True
event.message["clean"] = new_message
m = pattern.search(event.message["raw"])
assert m is not None
event.message["deaddressed"] = m.group("body")
class Ignore(Processor):
priority = -1500
addressed = False
event_types = ()
ignore_users = []
@handler
async def handle_ignore(self, event):
if event.discord_message.author.id in self.ignore_users:
logger.info("Ignoring %s", event.discord_message.author)
event.processed = True
class Complain(Processor):
priority = 950
processed = True
event_types = ()
complaints = {
"nonsense": (
"Huh?",
"Sorry...",
"Excuse me?",
"*blink*",
"What?",
),
"exception": (
"I'm not feeling too well",
"That didn't go down very well. Burp.",
"That didn't seem to agree with me",
),
"network": (
"The tubes are clogged!",
"I can't reach that site",
"That site seems to be down",
),
}
@handler
async def complain(self, event):
if "complain" in event:
await event.addresponse(random.choice(self.complaints[event.complain]))
elif event.processed:
return
else:
await event.addresponse(random.choice(self.complaints["nonsense"]))
time_replies = ["It's %H:%M!", "It's %-I:%M %p!"]
date_replies = [
"It's %A, %B %-d, %Y!",
"According to my Gary Larson's Far Side desk calendar, it's %A, %B %-d, %Y!",
]
class Time(Processor):
@match("time")
async def time(self, event):
t = datetime.now()
await event.addresponse(t.strftime(random.choice(time_replies)))
@match("date")
async def date(self, event):
t = datetime.now()
await event.addresponse(t.strftime(random.choice(date_replies)))
greetings = (
"afternoon",
"bonjour",
"buon giorno",
"ello",
"evening",
"good day",
"good morning",
"hello",
"hey",
"heya",
"hi there",
"hi",
"hiya",
"hoe gaan dit",
"hoe lyk it",
"hoezit",
"hola",
"howdy",
"howsit",
"howzit",
"lo",
"llo",
"morning",
"salut",
"sup",
"wassup",
"wasup",
"what's up",
"word",
"wotcha",
"wotcher",
"wussup",
"yo",
)
banter_replies = {
"greet": {
"matches": [
r"\b("
+ "|".join(
list(greetings) + [g.replace(" ", "") for g in greetings if " " in g]
)
+ r")\b"
],
"responses": greetings,
},
"reward": {
"matches": [r"\bbot(\s+|\-)?snack\b"],
"responses": ["thanks, $who", "$who thankyou!", ":)"],
"address": False,
},
"praise": {
"matches": [
r"\bgood(\s+fuckin[\'g]?)?\s+(lad|bo(t|y)|g([ui]|r+)rl)\b",
r"\byou\s+(rock|rocks|rewl|rule|are\s+so+\s+co+l)\b",
],
"responses": ["thanks, $who", "$who thankyou!", ":)"],
"address": False,
},
"thanks": {
"matches": [r"\bthank(s|\s*you)\b", r"^\s*ta\s*$", r"^\s*shot\s*$"],
"responses": [
"no problem, $who",
"$who my pleasure",
"sure thing, $who",
"no worries, $who",
"$who np",
"no probs, $who",
"$who no problemo",
"$who not at all",
],
"address": False,
},
"criticism": {
"matches": [
r"\b((kak|bad|st(u|oo)pid|dumb)(\s+fuckin[\'g]?)?\s+(bo(t|y)|g([ui]|r+)rl))|(bot(\s|\-)?s(mack|lap))\b",
],
"responses": ["*whimper*", "sorry, $who :(", ":(", "*cringe*"],
"address": False,
},
"testdates": {
"matches": [
r"\binterpolate dates\b",
],
"responses": [
"year $year month2 $month2 month $month mon $mon day2 $day2 day $day date $date dow $dow weekday $weekday",
],
},
"testtimes": {
"matches": [
r"\binterpolate times\b",
],
"responses": [
"hour $hour minute $minute second $second time $time unixtime $unixtime",
],
},
"testdiscord": {
"matches": [
r"\binterpolate discord\b",
],
"responses": ["who $who channel $channel server $server"],
},
"testexception": {
"matches": [r"\bthrow exception\b"],
"responses": None,
},
}
def _interpolate(message, event):
"Expand factoid variables"
utcnow = datetime.utcnow()
now = datetime.now()
substitutions = [
("who", f"<@!{event.discord_message.author.id}>"),
("channel", f"<#{event.discord_message.channel.id}>"),
("server", event.discord_message.guild.name),
("year", str(now.year)),
("month2", "%02i" % now.month),
("month1", str(now.month)),
("month", now.strftime("%B")),
("mon", now.strftime("%b")),
("day2", "%02i" % now.day),
("day", str(now.day)),
("hour", now.strftime("%-I")),
("hour24", str(now.hour)),
("minute", str(now.minute)),
("second", str(now.second)),
("date", now.strftime("%Y-%m-%d")),
("time", now.strftime("%-I:%M %p")),
("dow", now.strftime("%A")),
("weekday", now.strftime("%A")),
("unixtime", utcnow.strftime("%s")),
]
for var, expansion in substitutions:
message = message.replace("$" + var, expansion)
return message
class Banter(Processor):
@handler
async def static(self, event):
for banter in banter_replies.values():
for match in banter["matches"]:
if re.fullmatch(match, event.message["clean"], re.I):
await event.addresponse(
_interpolate(random.choice(banter["responses"]), event),
address=banter.get("address", True),
)
return
|
python
|
import os
import numpy as np
import sys
import json
def read_text_lines(filepath):
with open(filepath, 'r') as f:
lines = f.readlines()
lines = [l.rstrip() for l in lines]
return lines
def check_path(path):
if not os.path.exists(path):
os.makedirs(path, exist_ok=True) # explicitly set exist_ok when multi-processing
def save_command(save_path, filename='command_train.txt'):
check_path(save_path)
command = sys.argv
save_file = os.path.join(save_path, filename)
# Save all training commands when resuming training
with open(save_file, 'a') as f:
f.write(' '.join(command))
f.write('\n\n')
def save_args(args, filename='args.json'):
args_dict = vars(args)
check_path(args.checkpoint_dir)
save_path = os.path.join(args.checkpoint_dir, filename)
# Save all training args when resuming training
with open(save_path, 'a') as f:
json.dump(args_dict, f, indent=4, sort_keys=False)
f.write('\n\n')
def int_list(s):
"""Convert string to int list"""
return [int(x) for x in s.split(',')]
|
python
|
from twilio.rest import Client
from twilio.twiml.voice_response import Gather, VoiceResponse
import os
class TwilioNotification:
def __init__(self, sid, auth_token):
self.client = Client(sid, auth_token)
def send_call(self, action_url, contacts):
response = VoiceResponse()
gather = Gather(action = action_url, numDigits=6, timeout=10)
gather.say("To book slot ASAP, enter the 6-digit COWIN OTP you just received")
response.say("Book your vaccine slot. Check your messages for the vaccination slotsthat are open.")
response.append(gather)
for contact in contacts:
call = self.client.calls.create(
twiml=response,
from_=os.environ['TWILIO_PHONE_NUMBER'],
to=contact
)
def send_message(self, slots, contacts):
if(slots == []):
return
message = 'Book your vaccination slot at: \n'
for i in range(len(slots)):
message = message + '{number}. {vaccine} vaccine in {hospital} having {dose1_slots} slots for dose 1 and {dose2_slots} slots for dose 2 at {pincode} on {date} \n\n'.format(number = i+1, vaccine=slots[i]['vaccine'], hospital=slots[i]['name'], pincode=slots[i]['pincode'], dose1_slots=slots[i]['available_capacity_dose1'], dose2_slots=slots[i]['available_capacity_dose2'], date=slots[i]['date'])
message = message + "Visit https://selfregistration.cowin.gov.in/ to book your slot ASAP \n"
for contact in contacts:
sms = self.client.messages.create(
body=message,
from_=os.environ['TWILIO_PHONE_NUMBER']
to=contact
)
|
python
|
# -*- coding: utf-8 -*-
# @Time : 2021/5/10 11:13
# @Author : Jiangzhesheng
# @File : test0.py
# @Software: PyCharm
import sys
import os
from flye.repeat_graph.repeat_graph import RepeatGraph
import flye.utils.fasta_parser as fp
from my_change.ond_algo import *
from bioclass import Sequence
def get_edgeseq_info(repeat_graph:RepeatGraph):
unique=[]
repeat=[]
for edge in repeat_graph.edges.values():
seq_num=len(edge.edge_sequences)
try:
cmp=edge.edge_sequences[0].edge_seq_name
for seq in edge.edge_sequences:
assert seq.edge_seq_name[0]==cmp[0],'+-error in %d'%edge.edge_id
if edge.repetitive:
if seq_num==1:
repeat.append(edge.edge_id)
raise AssertionError('repeat %d has %d seq'%(edge.edge_id,seq_num))
else:
if seq_num>1:
unique.append((edge.edge_id,seq_num))
raise AssertionError('unique %d has %d seq'%(edge.edge_id,seq_num))
except AssertionError as e:
print(e)
pass
return repeat,unique
def main(argv):
workdir='/ldfssz1/ST_OCEAN/USER/jiangzhesheng/flye/step_by_step'
edge_file= os.path.join(workdir,'20-repeat-keephaplotype/repeat_graph_edges.fasta')
before_graph=os.path.join(workdir,'20-repeat-keephaplotype/repeat_graph_dump_before_rr')
before_repeat_graph = RepeatGraph(fp.read_sequence_dict(edge_file))
before_repeat_graph.load_from_file(before_graph)
repeat,unique=get_edgeseq_info(repeat_graph=before_repeat_graph)
repeat,unique=len(repeat),len(unique)
sum_repeat=len([i for i in before_repeat_graph.edges.values() if i.repetitive==True])
sum_unique = len([i for i in before_repeat_graph.edges.values() if i.repetitive == False])
print("before rr:")
print("1 seq repeat:",repeat/sum_repeat)
print(">2 seq unique:",unique/sum_unique)
# seqs=repeat_graph.find_edgeid_string(id=326)
# v=ond_algo(A=seqs[0],B=seqs[1])
# print(get_edit_distance(v))
# after_graph = os.path.join(workdir, '20-repeat-copy/repeat_graph_dump_after_rr')
# after_repeat_graph = RepeatGraph(fp.read_sequence_dict(edge_file))
# after_repeat_graph.load_from_file(after_graph)
# repeat,unique = get_edgeseq_info(repeat_graph=after_repeat_graph)
#
# repeat,unique=len(repeat),len(unique)
# sum_repeat=len([i for i in after_repeat_graph.edges.values() if i.repetitive==True])
# sum_unique = len([i for i in after_repeat_graph.edges.values() if i.repetitive == False])
#
# print("after rr:")
# print("1 seq repeat:", repeat / sum_repeat)
# print(">2 seq unique:", unique / sum_unique)
#
# print(len(before_repeat_id),len(after_repeat_id))
#
# for i in before_repeat_id:
# if i not in after_repeat_id:
# print('error with id ',i)
if __name__ == '__main__':
main(sys.argv)
|
python
|
# @Author: Yang Li
# @Date: 2020-05-20 21:17:13
# @Last Modified by: Yang Li
# @Last Modified time: 2021-04-19 22:14:04
from __future__ import division
from __future__ import print_function
import argparse
import time
import numpy as np
import scipy.sparse as sp
import networkx as nx
import torch
from torch import optim
import torch.nn.functional as F
from model import GCNModelVAE, GCNModelAE
from optimizer import loss_function
from utils import load_data, mask_test_edges, preprocess_graph, get_roc_score
from metrics import *
from sklearn.cluster import KMeans
parser = argparse.ArgumentParser()
parser.add_argument('--model', type=str, default='gcn_ae', help="models used")
parser.add_argument('--seed', type=int, default=42, help='Random seed.')
parser.add_argument('--epochs', type=int, default=200, help='Number of epochs to train.')
parser.add_argument('--hidden1', type=int, default=32, help='Number of units in hidden layer 1.')
parser.add_argument('--hidden2', type=int, default=16, help='Number of units in hidden layer 2.')
parser.add_argument('--lr', type=float, default=0.01, help='Initial learning rate.')
parser.add_argument('--dropout', type=float, default=0., help='Dropout rate (1 - keep probability).')
parser.add_argument('--dataset-str', type=str, default='cora', help='type of dataset.')
args = parser.parse_args()
def gae_for(args):
print("Using {} dataset".format(args.dataset_str))
adj, features, g, labels = load_data(args.dataset_str)
n_nodes, feat_dim = features.shape
n_2 = n_nodes * n_nodes
m2 = adj.sum()
# Store original adjacency matrix (without diagonal entries) for later
adj_orig = adj
adj_orig = adj_orig - sp.dia_matrix((adj_orig.diagonal()[np.newaxis, :], [0]), shape=adj_orig.shape)
adj_orig.eliminate_zeros()
# adj_train, train_edges, val_edges, val_edges_false, test_edges, test_edges_false = mask_test_edges(adj)
# adj = adj_train
adj = adj_orig
kk = np.array(adj.sum(axis=1), dtype=np.float32).reshape(-1, 1)
adj_mod = np.array(adj - kk.dot(kk.T) / m2, dtype=np.float32)
def get_modularity(pred_labels):
def encode_onehot(labels):
classes = set(labels)
classes_dict = {
c: np.identity(len(classes))[i, :] for i, c in enumerate(classes)
}
labels_onehot = np.array(
list(map(classes_dict.get, labels)), dtype=np.int32)
return labels_onehot
emb = encode_onehot(pred_labels).astype(np.float32)
Q = np.trace(emb.T.dot(adj_mod).dot(emb)) / m2
return Q
# def get_modularity(predict_label):
# numclass = len(list(set(predict_label)))
# partition = [set() for i in range(numclass)]
# for i in range(len(predict_label)):
# partition[predict_label[i]].add(i)
# mod = nx.algorithms.community.modularity(g, partition)
# return mod
# Some preprocessing
adj_norm = preprocess_graph(adj)
adj_label = adj + sp.eye(adj.shape[0])
# adj_label = sparse_to_tuple(adj_label)
adj_label = torch.FloatTensor(adj_label.toarray())
pos_weight = torch.Tensor([float(adj.shape[0] * adj.shape[0] - adj.sum()) / adj.sum()])
norm = adj.shape[0] * adj.shape[0] / float((adj.shape[0] * adj.shape[0] - adj.sum()) * 2)
model = GCNModelAE(feat_dim, args.hidden1, args.hidden2, args.dropout)
optimizer = optim.Adam(model.parameters(), lr=args.lr)
kmeans = KMeans(n_clusters=7)
hidden_emb = None
for epoch in range(args.epochs):
t = time.time()
model.train()
optimizer.zero_grad()
recovered, mu, logvar = model(features, adj_norm)
# loss = loss_function(preds=recovered, labels=adj_label,
# mu=mu, logvar=logvar, n_nodes=n_nodes,
# norm=norm, pos_weight=pos_weight)
loss = norm * F.binary_cross_entropy_with_logits(recovered, adj_label, pos_weight=pos_weight)
loss.backward()
cur_loss = loss.item()
optimizer.step()
hidden_emb, _ = model.encode(features, adj_norm)
pred_label = kmeans.fit_predict(hidden_emb.data.numpy())
mod = get_modularity(pred_label)
# print("Epoch:", "%04d" % (epoch + 1), "train_loss=", "{:.5f}".format(mod))
cm = clustering_metrics(labels.tolist(), pred_label.tolist())
acc, nmi, ari = cm.Evaluation_Cluster_Model_From_Label()
print(
"loss={:.4f}".format(loss.data),
"mod={:.4f}".format(mod),
"nmi={:.4f}".format(nmi),
"acc={:.4f}".format(acc),
"ari={:.4f}".format(ari)
)
# roc_curr, ap_curr = get_roc_score(hidden_emb.data.numpy(), adj_orig, val_edges, val_edges_false)
# print("Epoch:", '%04d' % (epoch + 1), "train_loss=", "{:.5f}".format(cur_loss),
# "val_ap=", "{:.5f}".format(ap_curr),
# "time=", "{:.5f}".format(time.time() - t)
# )
print("Optimization Finished!")
# roc_score, ap_score = get_roc_score(hidden_emb, adj_orig, test_edges, test_edges_false)
# print('Test ROC score: ' + str(roc_score))
# print('Test AP score: ' + str(ap_score))
if __name__ == '__main__':
gae_for(args)
|
python
|
'''This is sandbox code
'''
|
python
|
i=0
while False:
i+=1
print("Hello:",i)
|
python
|
#! /usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from settings import EMAIL_SMTP_SETTINGS
def send_mail(subject, message, message_type='html'):
message = MIMEText(message, message_type, 'utf-8')
message['From'] = Header(EMAIL_SMTP_SETTINGS.get("display_name"), 'utf-8')
message['To'] = Header(",".join(EMAIL_SMTP_SETTINGS.get("to_addrs")), 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
smtpObj = smtplib.SMTP()
smtpObj.connect(EMAIL_SMTP_SETTINGS.get("host"), EMAIL_SMTP_SETTINGS.get("port"))
smtpObj.login(EMAIL_SMTP_SETTINGS.get("username"), EMAIL_SMTP_SETTINGS.get("password"))
smtpObj.sendmail(EMAIL_SMTP_SETTINGS.get("from_addr"), EMAIL_SMTP_SETTINGS.get("to_addrs"), message.as_string())
if __name__ == "__main__":
send_mail("Test", "<table border='1'><tr><td>100</td></tr></table>")
|
python
|
from zeus import factories
from zeus.constants import Result, Status
from zeus.models import Job
def test_new_job(client, default_source, default_repo, default_hook):
build = factories.BuildFactory(
source=default_source, provider=default_hook.provider, external_id="3"
)
job_xid = "2"
path = "/hooks/{}/{}/builds/{}/jobs/{}".format(
default_hook.id, default_hook.get_signature(), build.external_id, job_xid
)
payload = {"result": "passed", "status": "finished"}
resp = client.post(path, json=payload)
assert resp.status_code == 200, repr(resp.data)
job = Job.query.unrestricted_unsafe().get(resp.json()["id"])
assert job
assert job.build_id == build.id
assert job.repository_id == build.repository_id
assert job.provider == default_hook.provider
assert job.external_id == job_xid
assert job.result == Result.passed
assert job.status == Status.finished
def test_existing_job(client, default_source, default_repo, default_hook):
build = factories.BuildFactory(
source=default_source, provider=default_hook.provider, external_id="3"
)
job = factories.JobFactory(
build=build, provider=default_hook.provider, external_id="2", in_progress=True
)
path = "/hooks/{}/{}/builds/{}/jobs/{}".format(
default_hook.id,
default_hook.get_signature(),
build.external_id,
job.external_id,
)
payload = {"result": "passed", "status": "finished"}
resp = client.post(path, json=payload)
assert resp.status_code == 200, repr(resp.data)
data = resp.json()
assert data["result"] == "passed"
assert data["status"] == "finished"
job = Job.query.unrestricted_unsafe().get(job.id)
assert job.result == Result.passed
assert job.status == Status.finished
|
python
|
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
"""
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='feeder-utilities',
version='1.0.1',
description='Module for feeder utilities, both client and server, handling health and integrity checking',
long_description=long_description,
url='https://github.com/LandRegistry',
author='James Lademann',
author_email='[email protected]',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4'
],
keywords='development',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
install_requires=['kombu==3.0.35', ''],
test_suite='nose.collector',
tests_require=['nose', 'coverage'],
entry_points={
'console_scripts': ['feeder-rpc-client=feeder_utilities.feeder_rpc_client:main']
}
)
|
python
|
from flask import Flask, make_response, render_template, request
app = Flask(__name__, template_folder='template')
@app.route('/')
def index():
return render_template('index02.html')
@app.route('/setcookie', methods = ['POST', 'GET'])
def setcookie():
if request.method == 'POST':
user = request.form['nm']
resp = make_response(render_template('readcookie.html'))
resp.set_cookie('userID', user)
return resp
@app.route('/getcookie')
def getcookie():
name = request.cookies.get('userID')
return '<h1>welcome ' + name + '</h1>'
app.run(host='0.0.0.0', port=81, debug=True)
|
python
|
'''unit test class for churn library'''
import time
import logging
import unittest
from pandas.api.types import is_string_dtype
from functools import wraps
from churn_library import ChurnLibrarySolution
keep_cols = [
'Customer_Age',
'Dependent_count',
'Months_on_book',
'Total_Relationship_Count',
'Months_Inactive_12_mon',
'Contacts_Count_12_mon',
'Credit_Limit',
'Total_Revolving_Bal',
'Avg_Open_To_Buy',
'Total_Amt_Chng_Q4_Q1',
'Total_Trans_Amt',
'Total_Trans_Ct',
'Total_Ct_Chng_Q4_Q1',
'Avg_Utilization_Ratio',
'Gender_Churn',
'Education_Level_Churn',
'Marital_Status_Churn',
'Income_Category_Churn',
'Card_Category_Churn']
logging.basicConfig(
filename='./logs/churn_library.log',
level=logging.INFO,
# filemode='w',
format='%(name)s - %(levelname)s - %(message)s')
def get_time(function):
'''
wrapper to return execution time of a function
'''
@wraps(function)
def wrapper(*args, **kwargs):
t_start = time.time()
run_fun = function(*args, **kwargs)
t_end = time.time() - t_start
logging.info('%s ran in %0.3f sec ', function.__name__, t_end)
logging.info('---------------------------------------------------')
# logging.info(f'{"-"*60}') #does not use lazy formatting
return run_fun
return wrapper
class TestingAndLogging(unittest.TestCase):
'''perform unit tests for all functions in churn library'''
def setUp(self):
'''prepare parameters to be used in the test'''
self.churn_obj = ChurnLibrarySolution()
# needs refactoring so that churn class asserts read file correctness
self.df = self.churn_obj.import_data("./data/bank_data.csv")
self.category_lst = [
col for col in self.df if is_string_dtype(
self.df[col])]
@get_time
def test_import(self):
''' test data import'''
try:
df = self.churn_obj.import_data("./data/bank_data.csv")
logging.info("Testing import_data: SUCCESS")
except FileNotFoundError as err:
logging.error("Testing import_data: file wasn't found")
raise err
try:
assert df.shape[0] > 0
assert df.shape[1] > 0
logging.info(
'churn data has %d rows and %d columns',
df.shape[0],
df.shape[1])
except AssertionError as err:
logging.error(
"Testing import_data: The file doesn't appear to have rows and columns")
raise err
@get_time
def test_eda(self):
'''test perform eda function'''
try:
self.churn_obj.perform_eda(self.df)
logging.info(
"exploratory figures has been generated. check [./images/eda/]")
except Exception as err:
logging.error("someting is wrong with eda()")
raise err
@get_time
def test_encoder_helper(self):
'''test encoder helper'''
try:
df = self.churn_obj.encoder_helper(self.df, self.category_lst)
logging.info("encoder helper ran successfully. ")
except Exception as err:
logging.error("someting is wrong with encoder_helper()")
raise err
@get_time
def test_perform_feature_engineering(self):
'''test perform_feature_engineering'''
df = self.churn_obj.encoder_helper(self.df, self.category_lst)
try:
X_data, X_train, X_test, y_train, y_test = self.churn_obj.perform_feature_engineering(
df, keep_cols)
logging.info(
"Train/Test and feature engineering ran successfully!")
logging.info("X_train is of shape: %d ", X_train.shape)
logging.info("Y_train is of shape: %d ", y_train.shape)
logging.info("X_test is of shape: %d ", X_test.shape)
logging.info("Y_test is of shape: %d ", y_test.shape)
except Exception as err:
logging.error(
"someting is wrong with perform_feature_engineering()")
raise err
@get_time
def test_train_models(self):
'''test train_models'''
df = self.churn_obj.encoder_helper(self.df, self.category_lst)
X_data, X_train, X_test, y_train, y_test = self.churn_obj.perform_feature_engineering(
df, keep_cols)
try:
self.churn_obj.train_models(
X_data, X_train, X_test, y_train, y_test, trained=True)
logging.info("train_models ran successfully!")
except Exception as err:
logging.error("someting is wrong with train_models()")
raise err
if __name__ == '__main__':
unittest.main()
#churn_obj = ChurnLibrarySolution()
#df = churn_obj.import_data("./data/bank_data.csv")
#category_lst = [col for col in df if is_string_dtype(df[col])]
#df = churn_obj.encoder_helper(df, category_lst)
#X_data, X_train, X_test, y_train, y_test = churn_obj.perform_feature_engineering(df,keep_cols)
#churn_obj.train_models(X_data,X_train, X_test, y_train, y_test,trained=True)
|
python
|
from django.db import models
from s3upload.fields import S3UploadField
class Cat(models.Model):
custom_filename = S3UploadField(dest="custom_filename", blank=True)
class Kitten(models.Model):
mother = models.ForeignKey("Cat", on_delete=models.CASCADE)
video = S3UploadField(dest="vids", blank=True)
image = S3UploadField(dest="imgs", blank=True)
pdf = S3UploadField(dest="files", blank=True)
|
python
|
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from .util import number_color
from functools import partial
import glob
import math
from ui.util import number_object
from ui.mouse_event import ReferenceDialog, SnapshotDialog
import copy
Lb_width = 100
Lb_height = 40
Lb_row_shift = 25
Lb_col_shift = 5
Lb_x = 100
Lb_y = 690
Tb_width = 100
Tb_height = 40
Tb_row_shift = 50
Tb_col_shift = 5
Tb_x = 100
Tb_y = 60
_translate = QtCore.QCoreApplication.translate
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(1430, 750)
# Form.resize(1980, 1100)
self.graphicsView = QtWidgets.QGraphicsView(Form)
self.graphicsView.setGeometry(QtCore.QRect(100, 140, 518, 518))
self.graphicsView.setObjectName("graphicsView")
self.graphicsView_GT = QtWidgets.QGraphicsView(Form)
self.graphicsView_GT.setGeometry(QtCore.QRect(800, 140, 570, 570))
self.graphicsView_GT.setObjectName("graphicsView_GT")
# self.graphicsView_2 = QtWidgets.QGraphicsView(Form)
# self.graphicsView_2.setGeometry(QtCore.QRect(652, 140, 518, 518))
# self.graphicsView_2.setObjectName("graphicsView_2")
# Label Buttons to change the semantic meanings of the Brush
# First Row
self.add_brush_widgets(Form)
self.add_top_buttons(Form)
self.add_label_buttons_eg3d(Form)
self.add_tool_buttons(Form)
# self.add_checkbox_widgets(Form)
self.add_update_img_button(Form)
# self.referDialog = ReferenceDialog(self)
# self.referDialog.setObjectName('Reference Dialog')
# # self.referDialog.setWindowTitle('Reference Image:')
# self.referDialog.setWindowTitle('Style Image')
# self.referDialogImage = QtWidgets.QLabel(self.referDialog)
# self.referDialogImage.setFixedSize(512, 512)
# self.referDialog.show()
# self.snapshotDialog = SnapshotDialog(self)
# self.snapshotDialog.setObjectName('Snapshot Dialog')
# self.snapshotDialog.setWindowTitle('Reference Image:')
# self.snapshotDialogImage = QtWidgets.QLabel(self.snapshotDialog)
# self.snapshotDialogImage.setFixedSize(512, 512)
# self.add_intermediate_results_button(Form)
self.add_alpha_bar(Form)
self.add_yaw_bar(Form)
self.add_pitch_bar(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
# Form.setWindowTitle(_translate("Form", "Let's Party Face Manipulation v0.2"))
Form.setWindowTitle(_translate("Form", "Let's Party Face Manipulation"))
self.pushButton.setText(_translate("Form", "Open Image"))
self.pushButton_2.setText(_translate("Form", "StarScreening"))
self.pushButton_3.setText(_translate("Form", "SaveScreening"))
self.pushButton_4.setText(_translate("Form", "Color"))
self.pushButton_5.setText(_translate("Form", "Open Random"))
self.saveImg.setText(_translate("Form", "Save Img"))
def add_alpha_bar(self, Form):
self.alphaLabel = QtWidgets.QLabel(Form)
self.alphaLabel.setObjectName("alphaLabel")
self.alphaLabel.setGeometry(QtCore.QRect(500, 25, 150, 20))
self.alphaLabel.setText('Alpha: 0.5')
font = self.brushsizeLabel.font()
font.setPointSize(10)
font.setBold(True)
self.alphaLabel.setFont(font)
self.alphaSlider = QtWidgets.QSlider(Form)
self.alphaSlider.setOrientation(QtCore.Qt.Horizontal)
self.alphaSlider.setGeometry(QtCore.QRect(500 + 150, 30, 150, 10))
self.alphaSlider.setObjectName("alphaSlider")
self.alphaSlider.setMinimum(0)
self.alphaSlider.setMaximum(20)
self.alphaSlider.setValue(10)
self.alphaSlider.valueChanged.connect(Form.change_alpha_value)
def add_brush_widgets(self, Form):
# self.add_style_imgs_buttons(Form)
self.brushsizeLabel = QtWidgets.QLabel(Form)
self.brushsizeLabel.setObjectName("brushsizeLabel")
self.brushsizeLabel.setGeometry(QtCore.QRect(Tb_x - 1 * Lb_row_shift - 60+10 , 25, 150, 20))
self.brushsizeLabel.setText('Brush size: 6')
font = self.brushsizeLabel.font()
font.setPointSize(10)
font.setBold(True)
self.brushsizeLabel.setFont(font)
self.brushSlider = QtWidgets.QSlider(Form)
self.brushSlider.setOrientation(QtCore.Qt.Horizontal)
self.brushSlider.setGeometry(QtCore.QRect(Tb_x - 1 * Lb_row_shift - 60 + 130+10, 30, 300, 10))
self.brushSlider.setObjectName("brushSlider")
self.brushSlider.setMinimum(1)
self.brushSlider.setMaximum(100)
self.brushSlider.setValue(6)
self.brushSlider.valueChanged.connect(Form.change_brush_size)
def add_yaw_bar(self, Form):
self.yawLabel = QtWidgets.QLabel(Form)
self.yawLabel.setObjectName("yawLabel")
self.yawLabel.setGeometry(QtCore.QRect(500 + 320, 25, 150, 20))
self.yawLabel.setText('Yaw: 0')
font = self.brushsizeLabel.font()
font.setPointSize(10)
font.setBold(True)
self.yawLabel.setFont(font)
self.yawSlider = QtWidgets.QSlider(Form)
self.yawSlider.setOrientation(QtCore.Qt.Horizontal)
self.yawSlider.setGeometry(QtCore.QRect(500 + 470, 30, 150, 10))
self.yawSlider.setObjectName("yawSlider")
self.yawSlider.setMinimum(-50)
self.yawSlider.setMaximum(50)
self.yawSlider.setValue(0)
self.yawSlider.valueChanged.connect(Form.change_yaw_value)
def add_pitch_bar(self, Form):
self.pitchLabel = QtWidgets.QLabel(Form)
self.pitchLabel.setObjectName("pitchLabel")
self.pitchLabel.setGeometry(QtCore.QRect(500 + 630, 25, 150, 20))
self.pitchLabel.setText('Pitch: 0')
font = self.brushsizeLabel.font()
font.setPointSize(10)
font.setBold(True)
self.pitchLabel.setFont(font)
self.pitchSlider = QtWidgets.QSlider(Form)
self.pitchSlider.setOrientation(QtCore.Qt.Horizontal)
self.pitchSlider.setGeometry(QtCore.QRect(500 + 780, 30, 150, 10))
self.pitchSlider.setObjectName("pitchSlider")
self.pitchSlider.setMinimum(-50)
self.pitchSlider.setMaximum(50)
self.pitchSlider.setValue(0)
self.pitchSlider.valueChanged.connect(Form.change_pitch_value)
def add_intermediate_results_button(self, Form):
self.snap_scrollArea = QtWidgets.QScrollArea(Form)
self.snap_scrollArea.setGeometry(QtCore.QRect(100, Lb_y + Lb_height + Lb_col_shift + Lb_height + 30, 1622, 250))
self.snap_scrollArea.setWidgetResizable(True)
self.snap_scrollArea.setObjectName("snap_scrollArea")
self.snap_scrollArea.setAlignment(Qt.AlignCenter)
#self.snap_scrollArea.setStyleSheet("border-color: transparent")
self.snap_scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.snap_scrollAreaWidgetContents = QtWidgets.QWidget()
self.snap_scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 1622, 250))
self.snap_scrollAreaWidgetContents.setObjectName("snap_scrollAreaWidgetContents")
self.snap_gridlLayout = QtWidgets.QGridLayout(self.snap_scrollAreaWidgetContents)
# # snap_horizontalLayout.setContentsMargins(11, 11, 11, 11)
self.snap_gridlLayout.setSpacing(20)
self.snap_gridlLayout.setAlignment(Qt.AlignLeft)
self.snap_style_button_list = []
self.mask_snap_style_button_list = []
for i in range(15):
snap_style_button = QtWidgets.QPushButton()
snap_style_button.setFixedSize(100, 100)
snap_style_button.setStyleSheet("background-color: transparent")
snap_style_button.setIcon(QIcon())
snap_style_button.setIconSize(QSize(100, 100))
snap_style_button.clicked.connect(partial(self.open, i))
# snap_style_button.snap_shot_name = None
self.snap_style_button_list.append(snap_style_button)
# style_button.hide()
self.snap_gridlLayout.addWidget(snap_style_button, 1, i)
mask_snap_style_button = QtWidgets.QPushButton()
mask_snap_style_button.setFixedSize(100, 100)
mask_snap_style_button.setStyleSheet("background-color: transparent")
mask_snap_style_button.setIcon(QIcon())
mask_snap_style_button.setIconSize(QSize(100, 100))
self.mask_snap_style_button_list.append(mask_snap_style_button)
# mask_snap_style_button.hide()
self.snap_gridlLayout.addWidget(mask_snap_style_button, 0, i)
self.snap_scrollArea.setWidget(self.snap_scrollAreaWidgetContents)
def add_update_img_button(self, Form):
self.updateButton = QtWidgets.QPushButton(Form)
self.updateButton.setGeometry(QtCore.QRect(900, 60, 60, 60))
self.updateButton.setText(_translate("Form", "Render"))
self.updateButton.setStyleSheet("background-color: %s;" % number_color[18]+ " color: white")
self.updateButton.setObjectName("updateImg")
self.updateButton.clicked.connect(Form.run_deep_model)
self.updateStyleButton = QtWidgets.QPushButton(Form)
self.updateStyleButton.setGeometry(QtCore.QRect(980, 60, 90, 60))
self.updateStyleButton.setText(_translate("Form", "Change style"))
self.updateStyleButton.setStyleSheet("background-color: %s;" % number_color[17]+ " color: white")
self.updateStyleButton.setObjectName("change style")
self.updateStyleButton.clicked.connect(Form.change_style)
self.updateStyleButton = QtWidgets.QPushButton(Form)
self.updateStyleButton.setGeometry(QtCore.QRect(1300, 60, 90, 60))
self.updateStyleButton.setText(_translate("Form", "Back style"))
self.updateStyleButton.setStyleSheet("background-color: %s;" % number_color[17]+ " color: white")
self.updateStyleButton.setObjectName("back style")
self.updateStyleButton.clicked.connect(Form.back_style)
self.updateStyleButton = QtWidgets.QPushButton(Form)
self.updateStyleButton.setGeometry(QtCore.QRect(1100, 60, 90, 60))
self.updateStyleButton.setText(_translate("Form", "Free View"))
self.updateStyleButton.setStyleSheet("background-color: %s;" % number_color[16]+ " color: white")
self.updateStyleButton.setObjectName("free view")
self.updateStyleButton.clicked.connect(Form.freeview_render)
self.updateStyleButton = QtWidgets.QPushButton(Form)
self.updateStyleButton.setGeometry(QtCore.QRect(1200, 60, 90, 60))
self.updateStyleButton.setText(_translate("Form", "Reset View"))
self.updateStyleButton.setStyleSheet("background-color: %s;" % number_color[15]+ " color: white")
self.updateStyleButton.setObjectName("reset view")
self.updateStyleButton.clicked.connect(Form.reset_view)
def add_checkbox_widgets(self, Form):
self.checkBoxGroupBox = QtWidgets.QGroupBox("Replace Style of Components", Form)
self.checkBoxGroupBox.setGeometry(QtCore.QRect(920, 10, 800, 100))
layout = QtWidgets.QGridLayout()
self.checkBoxGroup = QtWidgets.QButtonGroup(Form)
self.checkBoxGroup.setExclusive(False)
for i, j in enumerate(number_object):
cb = QtWidgets.QCheckBox(number_object[j])
self.checkBoxGroup.addButton(cb, i)
layout.addWidget(cb, i//10, i%10)
cb = QtWidgets.QCheckBox('ALL')
self.checkBoxGroup.addButton(cb, )
layout.addWidget(cb, (i+1)//10, (i+1)%10)
self.checkBoxGroupBox.setLayout(layout)
for i in range(19):
self.checkBoxGroup.button(i).setChecked(True)
checkbox_status = [cb.isChecked() for cb in self.checkBoxGroup.buttons()]
checkbox_status = checkbox_status[:19]
self.checkbox_status = checkbox_status
self.checkBoxGroup.buttonToggled.connect(self.cb_event)
def add_top_buttons(self, Form):
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(Tb_x - 1 * Lb_row_shift - 45, Tb_y, Tb_width, Tb_height))
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(Form.open)
self.pushButton_2 = QtWidgets.QPushButton(Form)
self.pushButton_2.setGeometry(QtCore.QRect(Tb_x - 1 * Lb_row_shift - 45 + 1 * Tb_row_shift + 1 * Tb_width, Tb_y, Tb_width, Tb_height))
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_2.clicked.connect(Form.startScreening)
self.pushButton_3 = QtWidgets.QPushButton(Form)
self.pushButton_3.setGeometry(QtCore.QRect(Tb_x - 1 * Lb_row_shift - 45+ 2 * Tb_row_shift + 2 * Tb_width, Tb_y, Tb_width, Tb_height))
self.pushButton_3.setObjectName("pushButton_3")
self.pushButton_3.clicked.connect(Form.saveScreening)
self.pushButton_4 = QtWidgets.QPushButton(Form)
self.pushButton_4.setGeometry(QtCore.QRect(Tb_x - 1 * Lb_row_shift - 45+ 3 * Tb_row_shift + 3 * Tb_width, Tb_y, Tb_width, Tb_height))
self.pushButton_4.setObjectName("pushButton_4")
self.saveImg = QtWidgets.QPushButton(Form)
self.saveImg.setGeometry(QtCore.QRect(Tb_x - 1 * Lb_row_shift - 45+ 4 * Tb_row_shift + 4 * Tb_width, Tb_y, Tb_width, Tb_height))
self.saveImg.setObjectName("saveImg")
self.saveImg.clicked.connect(Form.save_img)
self.pushButton_5 = QtWidgets.QPushButton(Form)
self.pushButton_5.setGeometry(QtCore.QRect(Tb_x - 1 * Lb_row_shift - 45 + 4 * Tb_row_shift + 5 * Tb_width, Tb_y, Tb_width, Tb_height))
self.pushButton_5.setObjectName("pushButton_5")
self.pushButton_5.clicked.connect(Form.open_random)
self.retranslateUi(Form)
def add_tool_buttons(self, Form):
self.newButton = QtWidgets.QPushButton(Form)
self.newButton.setGeometry(QtCore.QRect(int(Lb_x - 1 * Lb_row_shift - 60), 140, 60, 60))
self.newButton.setObjectName("openButton")
self.newButton.setIcon(QIcon('icons/add_new_document.png'))
self.newButton.setIconSize(QSize(60, 60))
self.newButton.clicked.connect(Form.init_screen)
self.openButton = QtWidgets.QPushButton(Form)
self.openButton.setGeometry(QtCore.QRect(int(Lb_x - 1 * Lb_row_shift - 60), 140 + 60*1 + 10*1, 60, 60))
self.openButton.setObjectName("openButton")
self.openButton.setIcon(QIcon('icons/open.png'))
self.openButton.setIconSize(QSize(60, 60))
self.openButton.clicked.connect(Form.open_reference)
self.fillButton = QtWidgets.QPushButton(Form)
self.fillButton.setGeometry(QtCore.QRect(int(Lb_x - 1*Lb_row_shift - 60), 140 + 60*2 + 10*2, 60, 60))
self.fillButton.setObjectName("fillButton")
self.fillButton.setIcon(QIcon('icons/paint_can.png'))
self.fillButton.setIconSize(QSize(60, 60))
self.fillButton.clicked.connect(partial(Form.mode_select, 2))
self.brushButton = QtWidgets.QPushButton(Form)
self.brushButton.setGeometry(QtCore.QRect(int(Lb_x - 1*Lb_row_shift - 60), 140 + 60*3 + 10*3, 60, 60))
self.brushButton.setObjectName("brushButton")
self.brushButton.setIcon(QIcon('icons/paint_brush.png'))
self.brushButton.setIconSize(QSize(60, 60))
self.brushButton.setStyleSheet("background-color: #85adad")
#self.brushButton.setStyleSheet("background-color:")
self.brushButton.clicked.connect(partial(Form.mode_select, 0))
self.recButton = QtWidgets.QPushButton(Form)
self.recButton.setGeometry(QtCore.QRect(int(Lb_x - 1 * Lb_row_shift - 60), 140 + 60 * 4 + 10 * 4, 60, 60))
self.recButton.setObjectName("undolButton")
self.recButton.setIcon(QIcon('icons/brush_square.png'))
self.recButton.setIconSize(QSize(60, 60))
self.recButton.clicked.connect(partial(Form.mode_select, 1))
self.undoButton = QtWidgets.QPushButton(Form)
self.undoButton.setGeometry(QtCore.QRect(int(Lb_x - 1*Lb_row_shift - 60), 140 + 60*5 + 10*5, 60, 60))
self.undoButton.setObjectName("undolButton")
self.undoButton.setIcon(QIcon('icons/undo.png'))
self.undoButton.setIconSize(QSize(60, 60))
self.undoButton.clicked.connect(Form.undo)
self.saveButton = QtWidgets.QPushButton(Form)
self.saveButton.setGeometry(QtCore.QRect(int(Lb_x - 1 * Lb_row_shift - 60), 140 + 60 * 6 + 10 * 6, 60, 60))
self.saveButton.setObjectName("clean forground")
self.saveButton.setIcon(QIcon('icons/add_new_document.png'))
self.saveButton.setIconSize(QSize(60, 60))
self.saveButton.clicked.connect(Form.cleanForground)
def add_style_imgs_buttons(self, Form):
self.scrollArea = QtWidgets.QScrollArea(Form)
self.scrollArea.setGeometry(QtCore.QRect(1756, 140, 140, 512))
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName("scrollArea")
self.scrollArea.setAlignment(Qt.AlignCenter)
# self.scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 140, 512))
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
verticalLayout = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents)
verticalLayout.setContentsMargins(11, 11, 11, 11)
verticalLayout.setSpacing(6)
img_path_list = glob.glob('imgs/style_imgs_test/*.jpg')
img_path_list.sort()
style_button = QtWidgets.QPushButton(self.scrollAreaWidgetContents)
style_button.setFixedSize(100, 100)
style_button.setIcon(QIcon('icons/random.png'))
style_button.setIconSize(QSize(100, 100))
style_button.clicked.connect(Form.open)
verticalLayout.addWidget(style_button)
for img_path in img_path_list:
style_button = QtWidgets.QPushButton(self.scrollAreaWidgetContents)
style_button.setFixedSize(100, 100)
style_button.setIcon(QIcon(img_path))
style_button.setIconSize(QSize(100, 100))
style_button.clicked.connect(partial(Form.open, img_path))
verticalLayout.addWidget(style_button)
verticalLayout.addWidget(style_button)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
def add_label_buttons(self, Form):
top_x, top_y = 642, 140
row_shift = 10
self.color_Button = QtWidgets.QPushButton(Form)
self.color_Button.setGeometry(QtCore.QRect(int(Lb_x - 1*Lb_row_shift - 60), Lb_y-50, 60, 60))
self.color_Button.setObjectName("labelButton_0")
self.color_Button.setText(_translate("Form", "%s" % number_object[1]))
self.color_Button.setStyleSheet("background-color: %s;" % number_color[1] + " color: black")
self.labelButton_0 = QtWidgets.QPushButton(Form)
self.labelButton_0.setGeometry(QtCore.QRect(top_x, top_y, Lb_width, Lb_height))
self.labelButton_0.setObjectName("labelButton_0")
self.labelButton_0.setText(_translate("Form", "background"))
self.labelButton_0.setStyleSheet("background-color: %s;" % number_color[0]+ " color: white")
self.labelButton_0.clicked.connect(partial(Form.switch_labels, 0))
self.labelButton_1 = QtWidgets.QPushButton(Form)
self.labelButton_1.setGeometry(QtCore.QRect(top_x, top_y + 1*Lb_height + 1*row_shift, Lb_width, Lb_height))
self.labelButton_1.setObjectName("labelButton_1")
self.labelButton_1.setText(_translate("Form", "%s"%number_object[1]))
self.labelButton_1.setStyleSheet("background-color: %s;" % number_color[1] + " color: black")
self.labelButton_1.clicked.connect(partial(Form.switch_labels, 1))
# eye
self.labelButton_3 = QtWidgets.QPushButton(Form)
self.labelButton_3.setGeometry(QtCore.QRect(top_x, top_y + 2*Lb_height + 2*row_shift, int(0.48*Lb_width), Lb_height))
self.labelButton_3.setObjectName("labelButton_3")
self.labelButton_3.setText(_translate("Form", "%s"%number_object[4]))
self.labelButton_3.setStyleSheet("background-color: %s;" % number_color[4] + " color: black")
self.labelButton_3.clicked.connect(partial(Form.switch_labels, 4))
self.labelButton_17 = QtWidgets.QPushButton(Form)
self.labelButton_17.setGeometry(QtCore.QRect(top_x + int(0.54*Lb_width), top_y + 2*Lb_height + 2*row_shift, int(0.48*Lb_width), Lb_height))
self.labelButton_17.setObjectName("labelButton_17")
self.labelButton_17.setText(_translate("Form", "%s"%number_object[5]))
self.labelButton_17.setStyleSheet("background-color: %s;" % number_color[5] + " color: black")
self.labelButton_17.clicked.connect(partial(Form.switch_labels, 5))
# eyebrow
self.labelButton_2 = QtWidgets.QPushButton(Form)
self.labelButton_2.setGeometry(QtCore.QRect(top_x, top_y + 3*Lb_height + 3*row_shift, int(0.48*Lb_width), Lb_height))
self.labelButton_2.setObjectName("labelButton_2")
self.labelButton_2.setText(_translate("Form", "%s"%number_object[2]))
self.labelButton_2.setStyleSheet("background-color: %s;" % number_color[2] + " color: black")
self.labelButton_2.clicked.connect(partial(Form.switch_labels, 2))
self.labelButton_18 = QtWidgets.QPushButton(Form)
self.labelButton_18.setGeometry(QtCore.QRect(top_x + int(0.54*Lb_width), top_y + 3*Lb_height + 3*row_shift, int(0.48*Lb_width), Lb_height))
self.labelButton_18.setObjectName("labelButton_18")
self.labelButton_18.setText(_translate("Form", "%s"%number_object[3]))
self.labelButton_18.setStyleSheet("background-color: %s;" % number_color[3] + " color: black")
self.labelButton_18.clicked.connect(partial(Form.switch_labels, 3))
# nose
self.labelButton_4 = QtWidgets.QPushButton(Form)
self.labelButton_4.setGeometry(QtCore.QRect(top_x, top_y + 4*Lb_height + 4*row_shift, int(0.48*Lb_width), Lb_height))
self.labelButton_4.setObjectName("labelButton_4")
self.labelButton_4.setText(_translate("Form", "%s"%number_object[7]))
self.labelButton_4.setStyleSheet("background-color: %s;" % number_color[7] + " color: black")
self.labelButton_4.clicked.connect(partial(Form.switch_labels, 7))
self.labelButton_5 = QtWidgets.QPushButton(Form)
self.labelButton_5.setGeometry(QtCore.QRect(top_x+ int(0.54*Lb_width), top_y + 4*Lb_height + 4*row_shift, int(0.48*Lb_width), Lb_height))
self.labelButton_5.setObjectName("labelButton_5")
self.labelButton_5.setText(_translate("Form", "%s"%number_object[6]))
self.labelButton_5.setStyleSheet("background-color: %s;" % number_color[6] + " color: black")
self.labelButton_5.clicked.connect(partial(Form.switch_labels, 6))
# mouse
self.labelButton_7 = QtWidgets.QPushButton(Form)
self.labelButton_7.setGeometry(QtCore.QRect(top_x, top_y + 5.5*Lb_height + 5.5*row_shift, Lb_width, int(Lb_height*0.5)))
self.labelButton_7.setObjectName("labelButton_7")
self.labelButton_7.setText(_translate("Form", "%s"%number_object[9]))
self.labelButton_7.setStyleSheet("background-color: %s;" % number_color[9] + " color: black")
self.labelButton_7.clicked.connect(partial(Form.switch_labels, 9))
self.labelButton_6 = QtWidgets.QPushButton(Form)
self.labelButton_6.setGeometry(QtCore.QRect(top_x, int(top_y + 6.0*Lb_height + 6.0*row_shift), Lb_width, int(Lb_height*0.8)))
self.labelButton_6.setObjectName("labelButton_6")
self.labelButton_6.setText(_translate("Form", "%s"%number_object[8]))
self.labelButton_6.setStyleSheet("background-color: %s;" % number_color[8] + " color: black")
self.labelButton_6.clicked.connect(partial(Form.switch_labels, 8))
self.labelButton_8 = QtWidgets.QPushButton(Form)
self.labelButton_8.setGeometry(QtCore.QRect(top_x, int(top_y + 6.8*Lb_height + 6.5*row_shift), Lb_width, int(Lb_height*0.5)))
self.labelButton_8.setObjectName("labelButton_8")
self.labelButton_8.setText(_translate("Form", "%s"%number_object[10]))
self.labelButton_8.setStyleSheet("background-color: %s;" % number_color[10] + " color: black")
self.labelButton_8.clicked.connect(partial(Form.switch_labels, 10))
# ear
self.labelButton_9 = QtWidgets.QPushButton(Form)
self.labelButton_9.setGeometry(QtCore.QRect(top_x, top_y + 8*Lb_height + 8*row_shift, int(0.48*Lb_width), Lb_height))
self.labelButton_9.setObjectName("labelButton_9")
self.labelButton_9.setText(_translate("Form", "%s"%number_object[11]))
self.labelButton_9.setStyleSheet("background-color: %s;" % number_color[11] + " color: black")
self.labelButton_9.clicked.connect(partial(Form.switch_labels, 11))
self.labelButton_19 = QtWidgets.QPushButton(Form)
self.labelButton_19.setGeometry(QtCore.QRect(top_x+int(0.54*Lb_width), top_y + 8*Lb_height + 8*row_shift, int(0.48*Lb_width), Lb_height))
self.labelButton_19.setObjectName("labelButton_19")
self.labelButton_19.setText(_translate("Form", "%s"%number_object[12]))
self.labelButton_19.setStyleSheet("background-color: %s;" % number_color[12] + " color: black")
self.labelButton_19.clicked.connect(partial(Form.switch_labels, 12))
self.labelButton_10 = QtWidgets.QPushButton(Form)
self.labelButton_10.setGeometry(QtCore.QRect(top_x, top_y + 9*Lb_height + 9*row_shift, Lb_width, Lb_height))
self.labelButton_10.setObjectName("labelButton_10")
self.labelButton_10.setText(_translate("Form", "%s"%number_object[13]))
self.labelButton_10.setStyleSheet("background-color: %s;" % number_color[13] + " color: black")
self.labelButton_10.clicked.connect(partial(Form.switch_labels, 13))
########################################
row_shift, col_shift = 20, 8.1
self.labelButton_11 = QtWidgets.QPushButton(Form)
self.labelButton_11.setGeometry(QtCore.QRect(top_x, Lb_y - row_shift, Lb_width, Lb_height))
self.labelButton_11.setObjectName("labelButton_11")
self.labelButton_11.setText(_translate("Form", "%s"%number_object[14]))
self.labelButton_11.setStyleSheet("background-color: %s;" % number_color[14] + " color: black")
self.labelButton_11.clicked.connect(partial(Form.switch_labels, 14))
self.labelButton_12 = QtWidgets.QPushButton(Form)
self.labelButton_12.setGeometry(QtCore.QRect(Lb_x,Lb_y - row_shift , Lb_width, Lb_height))
self.labelButton_12.setObjectName("labelButton_12")
self.labelButton_12.setText(_translate("Form", "%s"%number_object[15]))
self.labelButton_12.setStyleSheet("background-color: %s;" % number_color[15] + " color: black")
self.labelButton_12.clicked.connect(partial(Form.switch_labels, 15))
self.labelButton_13 = QtWidgets.QPushButton(Form)
self.labelButton_13.setGeometry(QtCore.QRect(Lb_x + 1*col_shift + 1*Lb_width,
Lb_y - row_shift, Lb_width, Lb_height))
self.labelButton_13.setObjectName("labelButton_13")
self.labelButton_13.setText(_translate("Form", "%s"%number_object[16]))
self.labelButton_13.setStyleSheet("background-color: %s;" % number_color[16] + " color: black")
self.labelButton_13.clicked.connect(partial(Form.switch_labels, 16))
self.labelButton_14 = QtWidgets.QPushButton(Form)
self.labelButton_14.setGeometry(QtCore.QRect(Lb_x + 2*col_shift + 2*Lb_width,
Lb_y - row_shift, Lb_width, Lb_height))
self.labelButton_14.setObjectName("labelButton_14")
self.labelButton_14.setText(_translate("Form", "%s"%number_object[17]))
self.labelButton_14.setStyleSheet("background-color: %s;" % number_color[17] + " color: black")
self.labelButton_14.clicked.connect(partial(Form.switch_labels, 17))
self.labelButton_15 = QtWidgets.QPushButton(Form)
self.labelButton_15.setGeometry(QtCore.QRect(Lb_x + 3*col_shift + 3*Lb_width,
Lb_y - row_shift, Lb_width, Lb_height))
self.labelButton_15.setObjectName("labelButton_15")
self.labelButton_15.setText(_translate("Form", "%s"%number_object[18]))
self.labelButton_15.setStyleSheet("background-color: %s;" % number_color[18] + " color: black")
self.labelButton_15.clicked.connect(partial(Form.switch_labels, 18))
self.labelButton_16 = QtWidgets.QPushButton(Form)
self.labelButton_16.setGeometry(QtCore.QRect(Lb_x + 4*col_shift + 4*Lb_width,
Lb_y - row_shift, Lb_width, Lb_height))
self.labelButton_16.setObjectName("labelButton_16")
self.labelButton_16.setText(_translate("Form", "%s"%number_object[19]))
self.labelButton_16.setStyleSheet("background-color: %s;" % number_color[19] + " color: black")
self.labelButton_16.clicked.connect(partial(Form.switch_labels, 19))
def add_label_buttons_old(self, Form):
self.color_Button = QtWidgets.QPushButton(Form)
self.color_Button.setGeometry(QtCore.QRect(int(Lb_x - 1*Lb_row_shift - 60), Lb_y, 60, 60))
self.color_Button.setObjectName("labelButton_0")
self.color_Button.setStyleSheet("background-color: %s;" % number_color[1])
self.labelButton_0 = QtWidgets.QPushButton(Form)
self.labelButton_0.setGeometry(QtCore.QRect(Lb_x, Lb_y, Lb_width, Lb_height))
self.labelButton_0.setObjectName("labelButton_0")
self.labelButton_0.setText(_translate("Form", "background"))
self.labelButton_0.setStyleSheet("background-color: %s;" % number_color[0]+ " color: black")
self.labelButton_0.clicked.connect(partial(Form.switch_labels, 0))
self.labelButton_1 = QtWidgets.QPushButton(Form)
self.labelButton_1.setGeometry(QtCore.QRect(Lb_x + 1*Lb_row_shift + 1*Lb_width, Lb_y, Lb_width, Lb_height))
self.labelButton_1.setObjectName("labelButton_1")
self.labelButton_1.setText(_translate("Form", "skin"))
self.labelButton_1.setStyleSheet("background-color: %s;" % number_color[1] + " color: black")
self.labelButton_1.clicked.connect(partial(Form.switch_labels, 1))
self.labelButton_2 = QtWidgets.QPushButton(Form)
self.labelButton_2.setGeometry(QtCore.QRect(Lb_x + 2*Lb_row_shift + 2*Lb_width, Lb_y, Lb_width, Lb_height))
self.labelButton_2.setObjectName("labelButton_2")
self.labelButton_2.setText(_translate("Form", "nose"))
self.labelButton_2.setStyleSheet("background-color: %s;" % number_color[2] + " color: black")
self.labelButton_2.clicked.connect(partial(Form.switch_labels, 2))
self.labelButton_3 = QtWidgets.QPushButton(Form)
self.labelButton_3.setGeometry(QtCore.QRect(Lb_x + 3*Lb_row_shift + 3*Lb_width, Lb_y, Lb_width, Lb_height))
self.labelButton_3.setObjectName("labelButton_3")
self.labelButton_3.setText(_translate("Form", "eye_g"))
self.labelButton_3.setStyleSheet("background-color: %s;" % number_color[3] + " color: black")
self.labelButton_3.clicked.connect(partial(Form.switch_labels, 3))
self.labelButton_4 = QtWidgets.QPushButton(Form)
self.labelButton_4.setGeometry(QtCore.QRect(Lb_x + 4*Lb_row_shift + 4*Lb_width, Lb_y, Lb_width, Lb_height))
self.labelButton_4.setObjectName("labelButton_4")
self.labelButton_4.setText(_translate("Form", "l_eye"))
self.labelButton_4.setStyleSheet("background-color: %s;" % number_color[4] + " color: black")
self.labelButton_4.clicked.connect(partial(Form.switch_labels, 4))
self.labelButton_5 = QtWidgets.QPushButton(Form)
self.labelButton_5.setGeometry(QtCore.QRect(Lb_x + 5*Lb_row_shift + 5*Lb_width, Lb_y, Lb_width, Lb_height))
self.labelButton_5.setObjectName("labelButton_5")
self.labelButton_5.setText(_translate("Form", "r_eye"))
self.labelButton_5.setStyleSheet("background-color: %s;" % number_color[5] + " color: black")
self.labelButton_5.clicked.connect(partial(Form.switch_labels, 5))
self.labelButton_6 = QtWidgets.QPushButton(Form)
self.labelButton_6.setGeometry(QtCore.QRect(Lb_x + 6*Lb_row_shift + 6*Lb_width, Lb_y, Lb_width, Lb_height))
self.labelButton_6.setObjectName("labelButton_6")
self.labelButton_6.setText(_translate("Form", "l_brow"))
self.labelButton_6.setStyleSheet("background-color: %s;" % number_color[6] + " color: black")
self.labelButton_6.clicked.connect(partial(Form.switch_labels, 6))
self.labelButton_7 = QtWidgets.QPushButton(Form)
self.labelButton_7.setGeometry(QtCore.QRect(Lb_x + 7*Lb_row_shift + 7*Lb_width, Lb_y, Lb_width, Lb_height))
self.labelButton_7.setObjectName("labelButton_7")
self.labelButton_7.setText(_translate("Form", "r_brow"))
self.labelButton_7.setStyleSheet("background-color: %s;" % number_color[7] + " color: black")
self.labelButton_7.clicked.connect(partial(Form.switch_labels, 7))
self.labelButton_8 = QtWidgets.QPushButton(Form)
self.labelButton_8.setGeometry(QtCore.QRect(Lb_x + 8*Lb_row_shift + 8*Lb_width, Lb_y, Lb_width, Lb_height))
self.labelButton_8.setObjectName("labelButton_8")
self.labelButton_8.setText(_translate("Form", "l_ear"))
self.labelButton_8.setStyleSheet("background-color: %s;" % number_color[8] + " color: black")
self.labelButton_8.clicked.connect(partial(Form.switch_labels, 8))
self.labelButton_9 = QtWidgets.QPushButton(Form)
self.labelButton_9.setGeometry(QtCore.QRect(Lb_x + 9 * Lb_row_shift + 9 * Lb_width, Lb_y, Lb_width, Lb_height))
self.labelButton_9.setObjectName("labelButton_9")
self.labelButton_9.setText(_translate("Form", "r_ear"))
self.labelButton_9.setStyleSheet("background-color: %s;" % number_color[9] + " color: black")
self.labelButton_9.clicked.connect(partial(Form.switch_labels, 9))
# Second Row
self.labelButton_10 = QtWidgets.QPushButton(Form)
self.labelButton_10.setGeometry(QtCore.QRect(Lb_x,
Lb_y + Lb_height + Lb_col_shift, Lb_width, Lb_height))
self.labelButton_10.setObjectName("labelButton_10")
self.labelButton_10.setText(_translate("Form", "mouth"))
self.labelButton_10.setStyleSheet("background-color: %s;" % number_color[10] + " color: black")
self.labelButton_10.clicked.connect(partial(Form.switch_labels, 10))
self.labelButton_11 = QtWidgets.QPushButton(Form)
self.labelButton_11.setGeometry(QtCore.QRect(Lb_x + 1*Lb_row_shift + 1*Lb_width,
Lb_y + Lb_height + Lb_col_shift, Lb_width, Lb_height))
self.labelButton_11.setObjectName("labelButton_11")
self.labelButton_11.setText(_translate("Form", "u_lip"))
self.labelButton_11.setStyleSheet("background-color: %s;" % number_color[11] + " color: black")
self.labelButton_11.clicked.connect(partial(Form.switch_labels, 11))
self.labelButton_12 = QtWidgets.QPushButton(Form)
self.labelButton_12.setGeometry(QtCore.QRect(Lb_x + 2*Lb_row_shift + 2*Lb_width,
Lb_y + Lb_height + Lb_col_shift, Lb_width, Lb_height))
self.labelButton_12.setObjectName("labelButton_12")
self.labelButton_12.setText(_translate("Form", "l_lip"))
self.labelButton_12.setStyleSheet("background-color: %s;" % number_color[12] + " color: black")
self.labelButton_12.clicked.connect(partial(Form.switch_labels, 12))
self.labelButton_13 = QtWidgets.QPushButton(Form)
self.labelButton_13.setGeometry(QtCore.QRect(Lb_x + 3*Lb_row_shift + 3*Lb_width,
Lb_y + Lb_height + Lb_col_shift, Lb_width, Lb_height))
self.labelButton_13.setObjectName("labelButton_13")
self.labelButton_13.setText(_translate("Form", "hair"))
self.labelButton_13.setStyleSheet("background-color: %s;" % number_color[13] + " color: black")
self.labelButton_13.clicked.connect(partial(Form.switch_labels, 13))
self.labelButton_14 = QtWidgets.QPushButton(Form)
self.labelButton_14.setGeometry(QtCore.QRect(Lb_x + 4*Lb_row_shift + 4*Lb_width,
Lb_y + Lb_height + Lb_col_shift, Lb_width, Lb_height))
self.labelButton_14.setObjectName("labelButton_14")
self.labelButton_14.setText(_translate("Form", "hat"))
self.labelButton_14.setStyleSheet("background-color: %s;" % number_color[14] + " color: black")
self.labelButton_14.clicked.connect(partial(Form.switch_labels, 14))
self.labelButton_15 = QtWidgets.QPushButton(Form)
self.labelButton_15.setGeometry(QtCore.QRect(Lb_x + 5*Lb_row_shift + 5*Lb_width,
Lb_y + Lb_height + Lb_col_shift, Lb_width, Lb_height))
self.labelButton_15.setObjectName("labelButton_15")
self.labelButton_15.setText(_translate("Form", "ear_r"))
self.labelButton_15.setStyleSheet("background-color: %s;" % number_color[15] + " color: black")
self.labelButton_15.clicked.connect(partial(Form.switch_labels, 15))
self.labelButton_16 = QtWidgets.QPushButton(Form)
self.labelButton_16.setGeometry(QtCore.QRect(Lb_x + 6*Lb_row_shift + 6*Lb_width,
Lb_y + Lb_height + Lb_col_shift, Lb_width, Lb_height))
self.labelButton_16.setObjectName("labelButton_16")
self.labelButton_16.setText(_translate("Form", "neck_l"))
self.labelButton_16.setStyleSheet("background-color: %s;" % number_color[16] + " color: black")
self.labelButton_16.clicked.connect(partial(Form.switch_labels, 16))
self.labelButton_17 = QtWidgets.QPushButton(Form)
self.labelButton_17.setGeometry(QtCore.QRect(Lb_x + 7*Lb_row_shift + 7*Lb_width,
Lb_y + Lb_height + Lb_col_shift, Lb_width, Lb_height))
self.labelButton_17.setObjectName("labelButton_17")
self.labelButton_17.setText(_translate("Form", "neck"))
self.labelButton_17.setStyleSheet("background-color: %s;" % number_color[17] + " color: black")
self.labelButton_17.clicked.connect(partial(Form.switch_labels, 17))
self.labelButton_18 = QtWidgets.QPushButton(Form)
self.labelButton_18.setGeometry(QtCore.QRect(Lb_x + 8 * Lb_row_shift + 8 * Lb_width,
Lb_y + Lb_height + Lb_col_shift, Lb_width, Lb_height))
self.labelButton_18.setObjectName("labelButton_18")
self.labelButton_18.setText(_translate("Form", "cloth"))
self.labelButton_18.setStyleSheet("background-color: %s;" % number_color[18] + " color: black")
self.labelButton_18.clicked.connect(partial(Form.switch_labels, 18))
def add_label_buttons_eg3d(self, Form):
top_x, top_y = 642, 140
row_shift = 10
self.color_Button = QtWidgets.QPushButton(Form)
self.color_Button.setGeometry(QtCore.QRect(int(Lb_x - 1*Lb_row_shift - 60), Lb_y-50, 60, 60))
self.color_Button.setObjectName("labelButton_0")
self.color_Button.setText(_translate("Form", "%s" % number_object[1]))
self.color_Button.setStyleSheet("background-color: %s;" % number_color[1] + " color: black")
self.labelButton_0 = QtWidgets.QPushButton(Form)
self.labelButton_0.setGeometry(QtCore.QRect(top_x, top_y, Lb_width, Lb_height))
self.labelButton_0.setObjectName("labelButton_0")
self.labelButton_0.setText(_translate("Form", "background"))
self.labelButton_0.setStyleSheet("background-color: %s;" % number_color[0]+ " color: white")
self.labelButton_0.clicked.connect(partial(Form.switch_labels, 0))
self.labelButton_1 = QtWidgets.QPushButton(Form)
self.labelButton_1.setGeometry(QtCore.QRect(top_x, top_y + 1*Lb_height + 1*row_shift, Lb_width, Lb_height))
self.labelButton_1.setObjectName("labelButton_1")
self.labelButton_1.setText(_translate("Form", "skin"))
self.labelButton_1.setStyleSheet("background-color: %s;" % number_color[1] + " color: black")
self.labelButton_1.clicked.connect(partial(Form.switch_labels, 1))
self.labelButton_2 = QtWidgets.QPushButton(Form)
self.labelButton_2.setGeometry(QtCore.QRect(top_x, top_y + 2*Lb_height + 2*row_shift, Lb_width, Lb_height))
self.labelButton_2.setObjectName("labelButton_2")
self.labelButton_2.setText(_translate("Form", "nose"))
self.labelButton_2.setStyleSheet("background-color: %s;" % number_color[2] + " color: black")
self.labelButton_2.clicked.connect(partial(Form.switch_labels, 2))
self.labelButton_4 = QtWidgets.QPushButton(Form)
self.labelButton_4.setGeometry(QtCore.QRect(top_x, top_y + 3*Lb_height + 3*row_shift, int(0.48*Lb_width), Lb_height))
self.labelButton_4.setObjectName("labelButton_4")
self.labelButton_4.setText(_translate("Form", "l_eye"))
self.labelButton_4.setStyleSheet("background-color: %s;" % number_color[4] + " color: black")
self.labelButton_4.clicked.connect(partial(Form.switch_labels, 4))
self.labelButton_5 = QtWidgets.QPushButton(Form)
self.labelButton_5.setGeometry(QtCore.QRect(top_x + int(0.54*Lb_width), top_y + 3*Lb_height + 3*row_shift, int(0.48*Lb_width), Lb_height))
self.labelButton_5.setObjectName("labelButton_5")
self.labelButton_5.setText(_translate("Form", "r_eye"))
self.labelButton_5.setStyleSheet("background-color: %s;" % number_color[5] + " color: black")
self.labelButton_5.clicked.connect(partial(Form.switch_labels, 5))
self.labelButton_6 = QtWidgets.QPushButton(Form)
self.labelButton_6.setGeometry(QtCore.QRect(top_x, top_y + 4*Lb_height + 4*row_shift, int(0.48*Lb_width), Lb_height))
self.labelButton_6.setObjectName("labelButton_6")
self.labelButton_6.setText(_translate("Form", "l_brow"))
self.labelButton_6.setStyleSheet("background-color: %s;" % number_color[6] + " color: black")
self.labelButton_6.clicked.connect(partial(Form.switch_labels, 6))
self.labelButton_7 = QtWidgets.QPushButton(Form)
self.labelButton_7.setGeometry(QtCore.QRect(top_x + int(0.54*Lb_width), top_y + 4*Lb_height + 4*row_shift, int(0.48*Lb_width), Lb_height))
self.labelButton_7.setObjectName("labelButton_7")
self.labelButton_7.setText(_translate("Form", "r_brow"))
self.labelButton_7.setStyleSheet("background-color: %s;" % number_color[7] + " color: black")
self.labelButton_7.clicked.connect(partial(Form.switch_labels, 7))
self.labelButton_3 = QtWidgets.QPushButton(Form)
self.labelButton_3.setGeometry(QtCore.QRect(top_x, top_y + 5*Lb_height + 5*row_shift, Lb_width, Lb_height))
self.labelButton_3.setObjectName("labelButton_3")
self.labelButton_3.setText(_translate("Form", "eye_g"))
self.labelButton_3.setStyleSheet("background-color: %s;" % number_color[3] + " color: black")
self.labelButton_3.clicked.connect(partial(Form.switch_labels, 3))
self.labelButton_8 = QtWidgets.QPushButton(Form)
self.labelButton_8.setGeometry(QtCore.QRect(top_x, top_y + 6*Lb_height + 6*row_shift, int(0.48*Lb_width), Lb_height))
self.labelButton_8.setObjectName("labelButton_8")
self.labelButton_8.setText(_translate("Form", "l_ear"))
self.labelButton_8.setStyleSheet("background-color: %s;" % number_color[8] + " color: black")
self.labelButton_8.clicked.connect(partial(Form.switch_labels, 8))
self.labelButton_9 = QtWidgets.QPushButton(Form)
self.labelButton_9.setGeometry(QtCore.QRect(top_x + int(0.54*Lb_width), top_y + 6*Lb_height + 6*row_shift, int(0.48*Lb_width), Lb_height))
self.labelButton_9.setObjectName("labelButton_9")
self.labelButton_9.setText(_translate("Form", "r_ear"))
self.labelButton_9.setStyleSheet("background-color: %s;" % number_color[9] + " color: black")
self.labelButton_9.clicked.connect(partial(Form.switch_labels, 9))
self.labelButton_10 = QtWidgets.QPushButton(Form)
self.labelButton_10.setGeometry(QtCore.QRect(top_x, top_y + 7*Lb_height + 7*row_shift, Lb_width, Lb_height))
self.labelButton_10.setObjectName("labelButton_10")
self.labelButton_10.setText(_translate("Form", "mouth"))
self.labelButton_10.setStyleSheet("background-color: %s;" % number_color[10] + " color: black")
self.labelButton_10.clicked.connect(partial(Form.switch_labels, 10))
self.labelButton_11 = QtWidgets.QPushButton(Form)
self.labelButton_11.setGeometry(QtCore.QRect(top_x, top_y + 8*Lb_height + 8*row_shift, Lb_width, Lb_height))
self.labelButton_11.setObjectName("labelButton_11")
self.labelButton_11.setText(_translate("Form", "u_lip"))
self.labelButton_11.setStyleSheet("background-color: %s;" % number_color[11] + " color: black")
self.labelButton_11.clicked.connect(partial(Form.switch_labels, 11))
self.labelButton_12 = QtWidgets.QPushButton(Form)
self.labelButton_12.setGeometry(QtCore.QRect(top_x, top_y + 9*Lb_height + 9*row_shift, Lb_width, Lb_height))
self.labelButton_12.setObjectName("labelButton_12")
self.labelButton_12.setText(_translate("Form", "l_lip"))
self.labelButton_12.setStyleSheet("background-color: %s;" % number_color[12] + " color: black")
self.labelButton_12.clicked.connect(partial(Form.switch_labels, 12))
########################################
row_shift, col_shift = 20, 8.1
self.labelButton_13 = QtWidgets.QPushButton(Form)
self.labelButton_13.setGeometry(QtCore.QRect(top_x, Lb_y - row_shift, Lb_width, Lb_height))
self.labelButton_13.setObjectName("labelButton_13")
self.labelButton_13.setText(_translate("Form", "hair"))
self.labelButton_13.setStyleSheet("background-color: %s;" % number_color[13] + " color: black")
self.labelButton_13.clicked.connect(partial(Form.switch_labels, 13))
self.labelButton_14 = QtWidgets.QPushButton(Form)
self.labelButton_14.setGeometry(QtCore.QRect(Lb_x, Lb_y - row_shift , Lb_width, Lb_height))
self.labelButton_14.setObjectName("labelButton_14")
self.labelButton_14.setText(_translate("Form", "hat"))
self.labelButton_14.setStyleSheet("background-color: %s;" % number_color[14] + " color: black")
self.labelButton_14.clicked.connect(partial(Form.switch_labels, 14))
self.labelButton_15 = QtWidgets.QPushButton(Form)
self.labelButton_15.setGeometry(QtCore.QRect(Lb_x + 1*col_shift + 1*Lb_width,
Lb_y - row_shift, Lb_width, Lb_height))
self.labelButton_15.setObjectName("labelButton_15")
self.labelButton_15.setText(_translate("Form", "ear_r"))
self.labelButton_15.setStyleSheet("background-color: %s;" % number_color[15] + " color: black")
self.labelButton_15.clicked.connect(partial(Form.switch_labels, 15))
self.labelButton_16 = QtWidgets.QPushButton(Form)
self.labelButton_16.setGeometry(QtCore.QRect(Lb_x + 2*col_shift + 2*Lb_width,
Lb_y - row_shift, Lb_width, Lb_height))
self.labelButton_16.setObjectName("labelButton_16")
self.labelButton_16.setText(_translate("Form", "neck_l"))
self.labelButton_16.setStyleSheet("background-color: %s;" % number_color[16] + " color: black")
self.labelButton_16.clicked.connect(partial(Form.switch_labels, 16))
self.labelButton_17 = QtWidgets.QPushButton(Form)
self.labelButton_17.setGeometry(QtCore.QRect(Lb_x + 3*col_shift + 3*Lb_width,
Lb_y - row_shift, Lb_width, Lb_height))
self.labelButton_17.setObjectName("labelButton_17")
self.labelButton_17.setText(_translate("Form", "neck"))
self.labelButton_17.setStyleSheet("background-color: %s;" % number_color[17] + " color: black")
self.labelButton_17.clicked.connect(partial(Form.switch_labels, 17))
self.labelButton_18 = QtWidgets.QPushButton(Form)
self.labelButton_18.setGeometry(QtCore.QRect(Lb_x + 4*col_shift + 4*Lb_width,
Lb_y - row_shift, Lb_width, Lb_height))
self.labelButton_18.setObjectName("labelButton_18")
self.labelButton_18.setText(_translate("Form", "cloth"))
self.labelButton_18.setStyleSheet("background-color: %s;" % number_color[18] + " color: black")
self.labelButton_18.clicked.connect(partial(Form.switch_labels, 18))
def cb_event(self, id, ifchecked):
if id.text() == 'ALL':
if ifchecked:
for cb in self.checkBoxGroup.buttons():
cb.setChecked(True)
else:
for cb in self.checkBoxGroup.buttons():
cb.setChecked(False)
self.change_cb_state()
def change_cb_state(self):
checkbox_status = [cb.isChecked() for cb in self.checkBoxGroup.buttons()]
checkbox_status = checkbox_status[:19]
#self.obj_dic_back = copy.deepcopy(self.obj_dic)
self.checkbox_status = checkbox_status
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
|
python
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Warning: Auto-generated file, don't edit.
pinyin_dict = {
0x3416: 'xié',
0x3469: 'luo',
0x36BB: 'jī',
0x378E: 'bǎ,ba',
0x393D: 'chóu',
0x39D1: 'huī',
0x3D89: 'xī',
0x3E62: 'jiā',
0x3E74: 'gěng',
0x3EA2: 'huò',
0x4056: 'lou',
0x433D: 'cǎi',
0x44D6: 'qióng',
0x45D6: 'dì',
0x45E5: 'zōng',
0x4723: 'xīn',
0x4CA0: 'chūn',
0x4CED: 'jí',
0x4D13: 'shī',
0x4D15: 'liè',
0x4D17: 'jú',
0x4D18: 'tī',
0x4D19: 'pì',
0x4E00: 'yī,yi',
0x4E01: 'dīng,zhēng,ding',
0x4E03: 'qī',
0x4E07: 'wàn,mò',
0x4E08: 'zhàng,zhang',
0x4E09: 'sān,sǎn',
0x4E0A: 'shàng,shang,shǎng',
0x4E0B: 'xià,xia',
0x4E0D: 'bù,bu,bú,bū',
0x4E0E: 'yǔ,yù',
0x4E10: 'gài',
0x4E11: 'chǒu',
0x4E13: 'zhuān',
0x4E14: 'qiě',
0x4E15: 'pī',
0x4E16: 'shì',
0x4E18: 'qiū',
0x4E19: 'bǐng',
0x4E1A: 'yè',
0x4E1B: 'cóng,cōng',
0x4E1C: 'dōng',
0x4E1D: 'sī',
0x4E1E: 'chéng',
0x4E22: 'diū',
0x4E24: 'liǎng',
0x4E25: 'yán,yǎn',
0x4E27: 'sàng,sāng,sang',
0x4E2A: 'gè,ge,gě',
0x4E2B: 'yā',
0x4E2D: 'zhōng,zhòng',
0x4E30: 'fēng',
0x4E32: 'chuàn',
0x4E34: 'lín',
0x4E38: 'wán',
0x4E39: 'dān,dan',
0x4E3A: 'wéi,wèi,wei',
0x4E3B: 'zhǔ',
0x4E3D: 'lì,lí',
0x4E3E: 'jǔ,ju',
0x4E43: 'nǎi',
0x4E45: 'jiǔ',
0x4E48: 'me,má,mó',
0x4E49: 'yì,yi',
0x4E4B: 'zhī',
0x4E4C: 'wū',
0x4E4D: 'zhà',
0x4E4E: 'hū,hu',
0x4E4F: 'fá',
0x4E50: 'lè,yuè,lào',
0x4E52: 'pīng',
0x4E53: 'pāng',
0x4E54: 'qiáo',
0x4E56: 'guāi,guai',
0x4E58: 'chéng,shèng',
0x4E59: 'yǐ',
0x4E5C: 'miē',
0x4E5D: 'jiǔ',
0x4E5E: 'qǐ,qi',
0x4E5F: 'yě',
0x4E60: 'xí',
0x4E61: 'xiāng',
0x4E66: 'shū',
0x4E69: 'jī',
0x4E70: 'mǎi',
0x4E71: 'luàn',
0x4E73: 'rǔ',
0x4E76: 'fǔ',
0x4E7E: 'qián',
0x4E86: 'le,liǎo,liào',
0x4E88: 'yǔ,yú',
0x4E89: 'zhēng',
0x4E8B: 'shì,shi',
0x4E8C: 'èr,ér',
0x4E8D: 'chù',
0x4E8E: 'yú',
0x4E8F: 'kuī',
0x4E91: 'yún',
0x4E92: 'hù,hū',
0x4E94: 'wǔ',
0x4E95: 'jǐng',
0x4E98: 'gèn',
0x4E9A: 'yà',
0x4E9B: 'xiē',
0x4E9F: 'jí',
0x4EA1: 'wáng,wàng',
0x4EA2: 'kàng',
0x4EA4: 'jiāo',
0x4EA5: 'hài',
0x4EA6: 'yì',
0x4EA7: 'chǎn',
0x4EA8: 'hēng',
0x4EA9: 'mǔ',
0x4EAB: 'xiǎng',
0x4EAC: 'jīng',
0x4EAD: 'tíng',
0x4EAE: 'liàng,liang',
0x4EB2: 'qīn,qìng,qín',
0x4EB3: 'bó',
0x4EB5: 'xiè',
0x4EB9: 'wěi',
0x4EBA: 'rén,ren',
0x4EBF: 'yì',
0x4EC0: 'shí,shén,shi',
0x4EC1: 'rén',
0x4EC2: 'lè',
0x4EC3: 'dīng',
0x4EC4: 'zè',
0x4EC5: 'jǐn',
0x4EC6: 'pú,pū',
0x4EC7: 'chóu',
0x4ECA: 'jīn',
0x4ECB: 'jiè',
0x4ECD: 'réng',
0x4ECE: 'cóng',
0x4ED1: 'lún',
0x4ED3: 'cāng',
0x4ED4: 'zǎi,zǐ,zī,zi',
0x4ED5: 'shì',
0x4ED6: 'tā',
0x4ED7: 'zhàng,zhang',
0x4ED8: 'fù,fu',
0x4ED9: 'xiān',
0x4EDF: 'qiān',
0x4EE1: 'gē',
0x4EE3: 'dài',
0x4EE4: 'lìng,líng',
0x4EE5: 'yǐ',
0x4EEA: 'yí',
0x4EEB: 'mù',
0x4EEC: 'men,mén',
0x4EF0: 'yǎng',
0x4EF2: 'zhòng',
0x4EF5: 'wǔ',
0x4EF6: 'jiàn',
0x4EF7: 'jià,ga',
0x4EFB: 'rèn,rén',
0x4EFD: 'fèn,fen',
0x4EFF: 'fǎng',
0x4F01: 'qǐ,qì',
0x4F04: 'diào',
0x4F09: 'kàng',
0x4F0A: 'yī',
0x4F0D: 'wǔ',
0x4F0E: 'jì',
0x4F0F: 'fú,fu',
0x4F10: 'fá',
0x4F11: 'xiū',
0x4F17: 'zhòng',
0x4F18: 'yōu',
0x4F19: 'huǒ,huo',
0x4F1A: 'huì,kuài,hui',
0x4F1E: 'sǎn',
0x4F1F: 'wěi',
0x4F20: 'chuán,zhuàn',
0x4F22: 'yá',
0x4F24: 'shāng',
0x4F25: 'chāng',
0x4F26: 'lún',
0x4F27: 'chen',
0x4F2A: 'wěi',
0x4F2B: 'zhù',
0x4F2F: 'bó,bo,bà,bai,bǎi',
0x4F30: 'gū,gù,gu',
0x4F34: 'bàn',
0x4F36: 'líng,ling',
0x4F38: 'shēn',
0x4F3A: 'sì,cì',
0x4F3C: 'sì,shì',
0x4F3D: 'jiā,gā,qié',
0x4F3E: 'pī',
0x4F43: 'diàn',
0x4F46: 'dàn',
0x4F49: 'qū,qiā',
0x4F4D: 'wèi',
0x4F4E: 'dī',
0x4F4F: 'zhù,zhu',
0x4F50: 'zuǒ',
0x4F51: 'yòu',
0x4F53: 'tǐ,tī',
0x4F55: 'hé',
0x4F57: 'tuó',
0x4F59: 'yú,yu',
0x4F5A: 'yì',
0x4F5B: 'fó,fú',
0x4F5C: 'zuò,zuo,zuō,zuó',
0x4F5D: 'gōu,kòu',
0x4F5E: 'nìng',
0x4F5F: 'tóng',
0x4F60: 'nǐ',
0x4F63: 'yōng,yòng',
0x4F64: 'wǎ',
0x4F67: 'kǎ',
0x4F69: 'pèi',
0x4F6A: 'huái',
0x4F6C: 'lǎo',
0x4F6F: 'yáng',
0x4F70: 'bǎi',
0x4F73: 'jiā',
0x4F7B: 'tiāo',
0x4F7C: 'jiǎo',
0x4F7F: 'shǐ,shi',
0x4F83: 'kǎn',
0x4F84: 'zhí',
0x4F88: 'chǐ',
0x4F89: 'kuǎ',
0x4F8B: 'lì',
0x4F8D: 'shì,shi',
0x4F8F: 'zhū',
0x4F97: 'dòng,tóng',
0x4F9B: 'gōng,gòng',
0x4F9D: 'yī',
0x4FA0: 'xiá',
0x4FA3: 'lǚ',
0x4FA5: 'jiǎo,yáo',
0x4FA6: 'zhēn',
0x4FA7: 'cè',
0x4FA8: 'qiáo',
0x4FA9: 'kuài',
0x4FAA: 'chái',
0x4FAC: 'nóng',
0x4FAE: 'wǔ',
0x4FAF: 'hóu',
0x4FB5: 'qīn',
0x4FBF: 'biàn,pián',
0x4FC3: 'cù',
0x4FC4: 'é',
0x4FC9: 'wú',
0x4FCA: 'jùn',
0x4FCE: 'zǔ',
0x4FCF: 'qiào',
0x4FD0: 'lì,li',
0x4FD1: 'yǒng',
0x4FD7: 'sú',
0x4FD8: 'fú',
0x4FDA: 'lǐ',
0x4FDC: 'pīng',
0x4FDD: 'bǎo',
0x4FDE: 'yú,shù',
0x4FDF: 'sì,qí',
0x4FE1: 'xìn',
0x4FE3: 'yǔ',
0x4FE8: 'yǎn',
0x4FE9: 'liǎ,liǎng',
0x4FEA: 'lì',
0x4FED: 'jiǎn',
0x4FEE: 'xiū',
0x4FEF: 'fǔ',
0x4FF1: 'jù',
0x4FF3: 'pái',
0x4FF8: 'fèng',
0x4FFE: 'bǐ',
0x500C: 'guān',
0x500D: 'bèi',
0x500F: 'shū',
0x5012: 'dǎo,dào',
0x5014: 'jué',
0x5018: 'tǎng,cháng',
0x5019: 'hòu,hou',
0x501A: 'yǐ',
0x501C: 'tì',
0x501F: 'jiè',
0x5021: 'chàng,chāng',
0x5025: 'kǒng,kōng',
0x5026: 'juàn',
0x5028: 'jù',
0x5029: 'qiàn',
0x502A: 'ní',
0x502D: 'wō',
0x503A: 'zhài',
0x503B: 'yē',
0x503C: 'zhí',
0x503E: 'qīng',
0x5041: 'chēng',
0x5043: 'yǎn',
0x5047: 'jiǎ,jià',
0x504C: 'ruò',
0x504E: 'wēi',
0x504F: 'piān',
0x5055: 'xié',
0x505A: 'zuò',
0x505C: 'tíng',
0x5065: 'jiàn',
0x506C: 'zǒng',
0x5076: 'ǒu',
0x5077: 'tōu',
0x507B: 'lóu',
0x507E: 'fèn',
0x507F: 'cháng',
0x5080: 'kuǐ',
0x5085: 'fù,fu',
0x5088: 'lì',
0x508D: 'bàng',
0x50A2: 'jiā',
0x50A3: 'dǎi',
0x50A5: 'tǎng',
0x50A7: 'bīn',
0x50A8: 'chǔ',
0x50A9: 'nuó',
0x50AC: 'cuī',
0x50B2: 'ào',
0x50BB: 'shǎ',
0x50CF: 'xiàng',
0x50D6: 'xī',
0x50DA: 'liáo',
0x50E7: 'sēng',
0x50EC: 'jiāo',
0x50ED: 'jiàn',
0x50EE: 'tóng,zhuàng',
0x50F3: 'sù',
0x50F5: 'jiāng',
0x50FB: 'pì',
0x5105: 'dāng',
0x5106: 'jǐng',
0x5107: 'xuān',
0x510B: 'dān',
0x5112: 'rú',
0x5121: 'lěi',
0x513F: 'er,ér',
0x5140: 'wù',
0x5141: 'yǔn',
0x5143: 'yuán',
0x5144: 'xiōng,xīng,xiong',
0x5145: 'chōng',
0x5146: 'zhào',
0x5148: 'xiān',
0x5149: 'guāng',
0x514B: 'kè',
0x514D: 'miǎn',
0x5151: 'duì',
0x5154: 'tù',
0x5155: 'sì',
0x5156: 'yǎn',
0x515A: 'dǎng',
0x515C: 'dōu,dou',
0x5162: 'jīng',
0x5165: 'rù',
0x5168: 'quán',
0x516B: 'bā',
0x516C: 'gōng,gong',
0x516D: 'liù,lù',
0x516E: 'xī',
0x5170: 'lán',
0x5171: 'gòng',
0x5172: 'tiān',
0x5173: 'guān',
0x5174: 'xīng,xìng',
0x5175: 'bīng',
0x5176: 'qí',
0x5177: 'jù',
0x5178: 'diǎn',
0x5179: 'zī,cí',
0x517B: 'yǎng',
0x517C: 'jiān',
0x517D: 'shòu',
0x5180: 'jì',
0x5185: 'nèi,nei',
0x5188: 'gāng',
0x5189: 'rǎn',
0x518C: 'cè',
0x518D: 'zài',
0x518F: 'jiǒng',
0x5191: 'zhòu',
0x5192: 'mào',
0x5195: 'miǎn',
0x5197: 'rǒng',
0x5198: 'yóu',
0x5199: 'xiě,xiè',
0x519B: 'jūn',
0x519C: 'nóng',
0x51A0: 'guān,guàn',
0x51A2: 'zhǒng',
0x51A4: 'yuān',
0x51A5: 'míng',
0x51AC: 'dōng',
0x51AF: 'féng,píng',
0x51B0: 'bīng',
0x51B2: 'chōng,chòng',
0x51B3: 'jué',
0x51B5: 'kuàng',
0x51B6: 'yě',
0x51B7: 'lěng',
0x51BB: 'dòng',
0x51BC: 'xiǎn',
0x51BD: 'liè',
0x51C0: 'jìng,jing',
0x51C4: 'qī',
0x51C6: 'zhǔn',
0x51C7: 'sōng',
0x51C9: 'liáng',
0x51CB: 'diāo',
0x51CC: 'líng',
0x51CF: 'jiǎn',
0x51D1: 'còu',
0x51DB: 'lǐn',
0x51DD: 'níng',
0x51E0: 'jǐ,jī',
0x51E1: 'fán',
0x51E4: 'fèng',
0x51EB: 'fú',
0x51ED: 'píng',
0x51EF: 'kǎi',
0x51F0: 'huáng',
0x51F3: 'dèng',
0x51F6: 'xiōng',
0x51F8: 'tū',
0x51F9: 'āo,wā',
0x51FA: 'chū,chu',
0x51FB: 'jī,jí',
0x51FC: 'dàng',
0x51FD: 'hán',
0x51FF: 'záo,zuò',
0x5200: 'dāo',
0x5201: 'diāo',
0x5203: 'rèn',
0x5206: 'fēn,fèn,fen',
0x5207: 'qiè,qiē',
0x5208: 'yì,guà',
0x520A: 'kān',
0x520D: 'chú',
0x520E: 'wěn',
0x5211: 'xíng',
0x5212: 'huà,huá,hua',
0x5217: 'liè,lie',
0x5218: 'liú',
0x5219: 'zé',
0x521A: 'gāng,gang',
0x521B: 'chuàng,chuāng',
0x521D: 'chū',
0x5220: 'shān',
0x5224: 'pàn',
0x5225: 'bié',
0x5228: 'bào,páo',
0x5229: 'lì,li',
0x522B: 'bié,biè',
0x522E: 'guā',
0x5230: 'dào,dao',
0x5236: 'zhì',
0x5237: 'shuā',
0x5238: 'quàn',
0x5239: 'shā,chà',
0x523A: 'cì,cī',
0x523B: 'kè',
0x523D: 'guì',
0x5240: 'kǎi',
0x5241: 'duò',
0x5242: 'jì',
0x5243: 'tì',
0x524A: 'xuē,xiāo',
0x524B: 'kēi',
0x524C: 'là,lá,lā',
0x524D: 'qián,qian',
0x5250: 'guǎ',
0x5251: 'jiàn',
0x5254: 'tī,ti',
0x5256: 'pōu',
0x5265: 'bō,bāo',
0x5267: 'jù',
0x5269: 'shèng',
0x526A: 'jiǎn',
0x526F: 'fù',
0x5272: 'gē,guà',
0x527D: 'piāo',
0x527F: 'jiǎo,chāo',
0x5288: 'pī,pǐ',
0x5290: 'huō',
0x529B: 'lì,li',
0x529D: 'quàn',
0x529E: 'bàn',
0x529F: 'gōng',
0x52A0: 'jiā',
0x52A1: 'wù,wu',
0x52A3: 'liè',
0x52A8: 'dòng',
0x52A9: 'zhù',
0x52AA: 'nǔ',
0x52AB: 'jié',
0x52AD: 'shào',
0x52B1: 'lì',
0x52B2: 'jìn,jìng',
0x52B3: 'láo,lao',
0x52BC: 'jié',
0x52BE: 'hé',
0x52BF: 'shì,shi',
0x52C3: 'bó',
0x52C7: 'yǒng',
0x52C9: 'miǎn',
0x52CB: 'xūn',
0x52D0: 'měng',
0x52D2: 'lè,lēi',
0x52D8: 'kān',
0x52DE: 'láo',
0x52DF: 'mù',
0x52E4: 'qín',
0x52F0: 'xié',
0x52FA: 'sháo',
0x52FE: 'gōu,gòu',
0x52FF: 'wù',
0x5300: 'yún',
0x5305: 'bāo,bao',
0x5306: 'cōng',
0x5308: 'xiōng',
0x530D: 'pú',
0x5310: 'fú',
0x5315: 'bǐ',
0x5316: 'huà,huā',
0x5317: 'běi',
0x5319: 'shi,chí',
0x531D: 'zā',
0x5320: 'jiàng,jiang',
0x5321: 'kuāng',
0x5323: 'xiá',
0x5326: 'guǐ',
0x532A: 'fěi',
0x532E: 'kuì,guì',
0x5339: 'pǐ,pí',
0x533A: 'qū,ōu',
0x533B: 'yī',
0x533E: 'biǎn',
0x533F: 'nì',
0x5341: 'shí',
0x5343: 'qiān',
0x5345: 'sà',
0x5347: 'shēng',
0x5348: 'wǔ,wu',
0x5349: 'huì',
0x534A: 'bàn,ban',
0x534E: 'huá,huà,huā',
0x534F: 'xié',
0x5351: 'bēi',
0x5352: 'zú,cù',
0x5353: 'zhuó',
0x5355: 'dān,chán,shàn',
0x5356: 'mài',
0x5357: 'nán,nā',
0x535A: 'bó',
0x535C: 'bǔ,bo',
0x535F: 'bǔ',
0x5360: 'zhàn,zhān',
0x5361: 'kǎ,qiǎ',
0x5362: 'lú',
0x5364: 'lǔ',
0x5366: 'guà',
0x5367: 'wò,wo',
0x536B: 'wèi',
0x536F: 'mǎo',
0x5370: 'yìn',
0x5371: 'wēi',
0x5373: 'jí',
0x5374: 'què',
0x5375: 'luǎn',
0x5377: 'juǎn,juàn',
0x5378: 'xiè',
0x537A: 'jǐn',
0x537F: 'qīng',
0x5382: 'chǎng',
0x5384: 'è',
0x5385: 'tīng',
0x5386: 'lì,li',
0x5389: 'lì',
0x538B: 'yā,yà,ya',
0x538C: 'yàn,yān',
0x5395: 'cè,si',
0x5397: 'tí',
0x5398: 'lí',
0x539A: 'hòu,hou',
0x539D: 'cuò',
0x539F: 'yuán',
0x53A2: 'xiāng',
0x53A5: 'jué',
0x53A6: 'shà,xià',
0x53A8: 'chú',
0x53A9: 'jiù',
0x53AE: 'sī',
0x53BB: 'qù,qu',
0x53BE: 'dū',
0x53BF: 'xiàn',
0x53C2: 'cān,shēn,cēn',
0x53C6: 'ài',
0x53C7: 'dài',
0x53C8: 'yòu',
0x53C9: 'chā,chà',
0x53CA: 'jí',
0x53CB: 'yǒu,you',
0x53CC: 'shuāng,huāng',
0x53CD: 'fǎn',
0x53D1: 'fā,fà,fa',
0x53D2: 'ruò',
0x53D4: 'shū,shu',
0x53D5: 'zhuó',
0x53D6: 'qǔ',
0x53D7: 'shòu,shou',
0x53D8: 'biàn',
0x53D9: 'xù',
0x53DB: 'pàn',
0x53DF: 'sǒu',
0x53E0: 'dié',
0x53E3: 'kǒu,kou,luó',
0x53E4: 'gǔ',
0x53E5: 'jù,jú,gōu',
0x53E6: 'lìng',
0x53E8: 'dāo,dao,tāo',
0x53E9: 'kòu',
0x53EA: 'zhī,zhǐ',
0x53EB: 'jiào',
0x53EC: 'zhào,shào',
0x53ED: 'ba,bā',
0x53EE: 'dīng',
0x53EF: 'kě,kè',
0x53F0: 'tái,tāi',
0x53F1: 'chì',
0x53F2: 'shǐ',
0x53F3: 'yòu',
0x53F5: 'pǒ',
0x53F6: 'yè,xié',
0x53F7: 'hào,háo,hao',
0x53F8: 'sī,si',
0x53F9: 'tàn',
0x53FB: 'lè',
0x53FC: 'diāo',
0x53FD: 'jī,ji',
0x5401: 'xū,yù',
0x5403: 'chī',
0x5404: 'gè,gě',
0x5406: 'yāo',
0x5408: 'hé,gě,he',
0x5409: 'jí',
0x540A: 'diào',
0x540C: 'tóng,tong,tòng',
0x540D: 'míng',
0x540E: 'hòu',
0x540F: 'lì',
0x5410: 'tǔ,tù',
0x5411: 'xiàng',
0x5412: 'zha,zhà',
0x5413: 'xià,hè',
0x5415: 'lǚ',
0x5416: 'ā',
0x5417: 'mǎ,ma,má',
0x541B: 'jūn',
0x541D: 'lìn',
0x541E: 'tūn',
0x541F: 'yín',
0x5420: 'fèi',
0x5421: 'bǐ',
0x5423: 'qìn',
0x5425: 'bù',
0x5426: 'fǒu,pǐ',
0x5427: 'bā,ba',
0x5428: 'dūn',
0x5429: 'fēn',
0x542B: 'hán',
0x542C: 'tīng,ting',
0x542D: 'kēng,háng',
0x542E: 'shǔn',
0x542F: 'qǐ',
0x5431: 'zhī,zī',
0x5432: 'yǐn',
0x5434: 'wú',
0x5435: 'chǎo,chāo,chao',
0x5438: 'xī',
0x5439: 'chuī',
0x543B: 'wěn',
0x543C: 'hǒu',
0x543D: 'ōu,hōng',
0x543E: 'wú,wu',
0x5440: 'yā,ya',
0x5443: 'è',
0x5446: 'dāi',
0x5448: 'chéng',
0x544A: 'gào,gao',
0x544B: 'fū',
0x5450: 'nà',
0x5452: 'ḿ,wǔ,fǔ',
0x5453: 'yì',
0x5454: 'tāi',
0x5455: 'ǒu,òu',
0x5457: 'bài,bei',
0x5458: 'yuán',
0x545B: 'qiāng,qiàng',
0x545C: 'wū',
0x5462: 'ní,ne',
0x5464: 'lìng',
0x5466: 'yōu',
0x5468: 'zhōu',
0x546B: 'tiè,zhān',
0x5471: 'guā,gua',
0x5472: 'zī,cī',
0x5473: 'wèi,wei',
0x5475: 'hē',
0x5476: 'náo',
0x5477: 'gā',
0x547B: 'shēn',
0x547C: 'hū,hu',
0x547D: 'mìng',
0x5480: 'jǔ,zuǐ',
0x5482: 'zā',
0x5484: 'duō',
0x5486: 'páo',
0x548B: 'zǎ,zhā,zhà,za',
0x548C: 'hé,hè,huo,huò,huó,hú',
0x548E: 'jiù',
0x548F: 'yǒng',
0x5490: 'fù',
0x5491: 'dā',
0x5492: 'zhòu',
0x5494: 'kǎ,kā',
0x5495: 'gū,gu',
0x5496: 'kā,gā',
0x5499: 'lóng',
0x549A: 'dōng,dong',
0x549B: 'níng',
0x549D: 'sī',
0x54A3: 'guāng',
0x54A4: 'zhà',
0x54A7: 'liē,liě',
0x54A8: 'zī',
0x54AA: 'mī,mi',
0x54AB: 'zhǐ',
0x54AC: 'yǎo',
0x54AD: 'jī',
0x54AF: 'gē,luò',
0x54B1: 'zán,zan,zá',
0x54B3: 'ké',
0x54B7: 'táo',
0x54B8: 'xián',
0x54BB: 'xiū',
0x54BD: 'yān,yàn,yè',
0x54BE: 'lǎo',
0x54C0: 'āi',
0x54C1: 'pǐn',
0x54C2: 'shěn',
0x54C4: 'hōng,hǒng,hòng',
0x54C6: 'duō',
0x54C7: 'wā',
0x54C8: 'hā,hǎ,ha,hà',
0x54C9: 'zāi',
0x54CC: 'pài',
0x54CD: 'xiǎng',
0x54CE: 'āi',
0x54CF: 'gén',
0x54D0: 'kuāng',
0x54D1: 'yǎ',
0x54D2: 'dā,da',
0x54D4: 'bì,bī',
0x54D5: 'huì,yuě',
0x54D7: 'huá,huā',
0x54DA: 'duǒ',
0x54DD: 'nong,nóng',
0x54DF: 'yō,yo',
0x54E5: 'gē,ge',
0x54E6: 'é',
0x54E7: 'chī,chi',
0x54E8: 'shào,shao',
0x54E9: 'lī,li,lí,lǐ',
0x54EA: 'nǎ,né,na',
0x54ED: 'kū,ku',
0x54EE: 'xiào',
0x54F0: 'láo',
0x54F1: 'bō',
0x54F2: 'zhé',
0x54F3: 'zhā',
0x54FA: 'bǔ,bù',
0x54FC: 'hēng',
0x54FD: 'gěng',
0x5501: 'yàn',
0x5505: 'hān',
0x5506: 'suō,suo',
0x5507: 'chún',
0x5509: 'āi',
0x550F: 'xī',
0x5510: 'táng',
0x5511: 'zuò',
0x5514: 'wú',
0x551B: 'mài',
0x551D: 'gòng',
0x5520: 'lao,láo,lào',
0x5522: 'suǒ',
0x5523: 'zào',
0x5524: 'huàn,huan',
0x5527: 'jī,ji',
0x552C: 'hǔ,hu',
0x552E: 'shòu',
0x552F: 'wéi,wěi',
0x5531: 'chàng',
0x5533: 'lì',
0x5535: 'ǎn',
0x5537: 'yō',
0x553E: 'tuò',
0x553F: 'hū',
0x5541: 'zhōu',
0x5543: 'kěn',
0x5544: 'zhuó',
0x5546: 'shāng',
0x5549: 'lín',
0x554A: 'ā',
0x5555: 'táo',
0x5556: 'dàn',
0x555C: 'chuò',
0x5561: 'fēi',
0x5564: 'pí',
0x5565: 'shá',
0x5566: 'lā,la',
0x5567: 'zé',
0x556A: 'pā',
0x556B: 'zhě',
0x556C: 'sè',
0x556D: 'zhuàn',
0x556E: 'niè',
0x5570: 'luō,luo',
0x5574: 'chǎn,tān',
0x5575: 'bō,bo',
0x5576: 'dìng',
0x5577: 'lāng',
0x5578: 'xiào',
0x557B: 'chì',
0x557C: 'tí',
0x557E: 'jiū',
0x5580: 'kā',
0x5581: 'yóng',
0x5582: 'wèi',
0x5583: 'nán',
0x5584: 'shàn',
0x5586: 'zhé',
0x5587: 'lǎ,là,la,lá,lā',
0x5589: 'hóu',
0x558A: 'hǎn',
0x558B: 'dié',
0x558F: 'nuò,rě',
0x5591: 'yīn',
0x5598: 'chuǎn',
0x5599: 'huì',
0x559C: 'xǐ',
0x559D: 'hē,hè,he',
0x559F: 'kuì',
0x55A7: 'xuān',
0x55A8: 'liàng',
0x55AE: 'dān',
0x55B1: 'lí',
0x55B3: 'zhā,chā,cha',
0x55B5: 'miāo',
0x55B7: 'pēn,pen,pèn',
0x55B9: 'kuí',
0x55BB: 'yù',
0x55BC: 'jié',
0x55BD: 'lóu',
0x55BE: 'kù',
0x55C5: 'xiù',
0x55C9: 'sù',
0x55D1: 'kē,kè',
0x55D2: 'dā,da,tà',
0x55D3: 'sǎng',
0x55D4: 'chēn',
0x55D6: 'sōu',
0x55DC: 'shì',
0x55DD: 'gé',
0x55DF: 'jiē',
0x55E1: 'wēng',
0x55E3: 'sì',
0x55E4: 'chī',
0x55E5: 'háo',
0x55E6: 'suo',
0x55E8: 'hāi',
0x55EA: 'qín',
0x55EB: 'niè',
0x55EF: 'en',
0x55F3: 'ài',
0x55F5: 'tōng',
0x55F7: 'áo',
0x55FD: 'sou',
0x5600: 'dí,dī',
0x5601: 'qī,qi',
0x5608: 'cáo',
0x5609: 'jiā',
0x560C: 'piào',
0x560E: 'gā,gá',
0x5618: 'xū',
0x561A: 'dē',
0x561B: 'ma,má',
0x561F: 'dū',
0x5622: 'yě',
0x5623: 'bēng',
0x5627: 'mì',
0x5631: 'zhǔ',
0x5632: 'cháo,zhāo',
0x5634: 'zuǐ',
0x5636: 'sī',
0x5639: 'liáo',
0x563B: 'xī',
0x563F: 'hēi',
0x564C: 'cēng',
0x564D: 'jiào',
0x564E: 'yē',
0x564F: 'xī',
0x5654: 'dēng',
0x5657: 'pū',
0x5658: 'juē',
0x565C: 'lū,lu',
0x5662: 'ō',
0x5664: 'jìn',
0x5668: 'qì',
0x5669: 'è',
0x566A: 'zào',
0x566C: 'shì',
0x5671: 'xué',
0x5676: 'gá',
0x567B: 'sāi',
0x567C: 'pī',
0x5685: 'rú',
0x568E: 'háo',
0x568F: 'tì',
0x5693: 'chā,cā',
0x56A3: 'xiāo',
0x56B7: 'rǎng,rāng,rang',
0x56BC: 'jiáo,jué',
0x56CA: 'náng,nāng,nang',
0x56D2: 'lán',
0x56D4: 'nang,nāng',
0x56DA: 'qiú',
0x56DB: 'sì',
0x56DD: 'jiǎn',
0x56DE: 'huí,hui',
0x56DF: 'xìn',
0x56E0: 'yīn',
0x56E1: 'nān',
0x56E2: 'tuán',
0x56E4: 'tún',
0x56EB: 'hú',
0x56ED: 'yuán',
0x56F0: 'kùn',
0x56F1: 'cōng',
0x56F4: 'wéi',
0x56F5: 'lún',
0x56F9: 'líng',
0x56FA: 'gù',
0x56FD: 'guó',
0x56FE: 'tú',
0x56FF: 'yòu',
0x5703: 'pǔ',
0x5704: 'yǔ',
0x5706: 'yuán',
0x5708: 'quān,juàn,quan',
0x5709: 'yǔ',
0x5710: 'kū',
0x5719: 'lüè',
0x571C: 'huán',
0x571F: 'tǔ',
0x5723: 'shèng',
0x5728: 'zài,zai',
0x572A: 'gē',
0x572D: 'guī',
0x572E: 'pǐ',
0x5730: 'dì,de,di',
0x5733: 'zhèn',
0x573A: 'chǎng,cháng,chang',
0x573B: 'qí',
0x573E: 'jī',
0x5740: 'zhǐ',
0x5742: 'bǎn',
0x5747: 'jūn',
0x574A: 'fāng,fáng,fang',
0x574B: 'bèn',
0x574D: 'tān',
0x574E: 'kǎn',
0x574F: 'huài',
0x5750: 'zuò',
0x5751: 'kēng,keng',
0x5757: 'kuài',
0x575A: 'jiān',
0x575B: 'tán',
0x575C: 'lì',
0x575D: 'bà',
0x575E: 'wù',
0x575F: 'fén',
0x5760: 'zhuì',
0x5761: 'pō',
0x5764: 'kūn',
0x5766: 'tǎn,tan',
0x5768: 'tuó',
0x5769: 'gān',
0x576A: 'píng',
0x576B: 'diàn',
0x576F: 'pī',
0x5773: 'ào',
0x5777: 'kě,kē',
0x577B: 'dǐ',
0x5782: 'chuí',
0x5783: 'lā',
0x5784: 'lǒng',
0x578B: 'xíng',
0x5792: 'lěi',
0x5793: 'gāi',
0x579B: 'duǒ',
0x579D: 'guǐ',
0x57A0: 'yín',
0x57A2: 'gòu',
0x57A3: 'yuán',
0x57A6: 'kěn',
0x57A9: 'è',
0x57AB: 'diàn',
0x57AD: 'yā',
0x57AE: 'kuǎ',
0x57AF: 'da',
0x57C2: 'gěng',
0x57C3: 'āi',
0x57C7: 'yǒng',
0x57CB: 'mái,mán',
0x57CE: 'chéng',
0x57D4: 'pǔ,bù',
0x57D5: 'chéng',
0x57D7: 'bù',
0x57DA: 'guō',
0x57DF: 'yù',
0x57E0: 'bù',
0x57E4: 'pí',
0x57F2: 'běng',
0x57F5: 'duǒ',
0x57F9: 'péi,bèi',
0x57FA: 'jī',
0x57FC: 'qí',
0x5802: 'táng,tang,tǎng',
0x5803: 'kūn',
0x5806: 'duī,tuī',
0x5807: 'jǐn',
0x5811: 'qiàn',
0x5815: 'duò',
0x5821: 'bǎo,bǔ,pù,pǔ',
0x5824: 'dī,dí,tí',
0x582A: 'kān',
0x5830: 'yàn',
0x5835: 'dǔ',
0x584C: 'tā,ta,tà',
0x584D: 'chéng',
0x5851: 'sù',
0x5854: 'tǎ',
0x5855: 'wěng',
0x5858: 'táng',
0x585E: 'sāi,sè,sài',
0x586B: 'tián',
0x586C: 'yuán',
0x586D: 'wēn',
0x587E: 'shú',
0x5883: 'jìng',
0x5885: 'shù',
0x5889: 'yōng',
0x5892: 'shāng',
0x5893: 'mù',
0x5899: 'qiáng',
0x589E: 'zēng',
0x589F: 'xū',
0x58A8: 'mò',
0x58A9: 'dūn',
0x58C1: 'bì',
0x58C5: 'yōng',
0x58D1: 'hè',
0x58D5: 'háo',
0x58E4: 'rǎng',
0x58EB: 'shì,shi',
0x58EC: 'rén',
0x58EE: 'zhuàng',
0x58F0: 'shēng,sheng',
0x58F3: 'ké,qiào',
0x58F6: 'hú',
0x58F9: 'yī',
0x5904: 'chù,chǔ,chu',
0x5907: 'bèi',
0x590D: 'fù',
0x590F: 'xià',
0x5914: 'kuí',
0x5915: 'xī',
0x5916: 'wài',
0x5919: 'sù',
0x591A: 'duō',
0x591C: 'yè',
0x591F: 'gòu',
0x5924: 'yín',
0x5925: 'huǒ',
0x5927: 'dà,dài,dá,dā',
0x5929: 'tiān',
0x592A: 'tài,tai',
0x592B: 'fū,fu',
0x592D: 'yāo',
0x592E: 'yāng',
0x592F: 'hāng,bèn',
0x5931: 'shī,shi',
0x5934: 'tóu,tou',
0x5937: 'yí',
0x5938: 'kuā',
0x5939: 'jiā,jiá,gā',
0x593A: 'duó',
0x593C: 'kuǎng',
0x593E: 'jiā',
0x5941: 'lián',
0x5942: 'huàn',
0x5944: 'yǎn',
0x5947: 'qí,jī',
0x5948: 'nài',
0x5949: 'fèng',
0x594B: 'fèn',
0x594E: 'kuí',
0x594F: 'zòu',
0x5951: 'qì',
0x5954: 'bēn,bèn',
0x5955: 'yì',
0x5956: 'jiǎng',
0x5957: 'tào,tao',
0x5958: 'zàng',
0x595A: 'xī',
0x5960: 'diàn',
0x5962: 'shē',
0x5965: 'ào',
0x596D: 'shì',
0x5973: 'nǚ',
0x5974: 'nú',
0x5976: 'nǎi,nai',
0x5978: 'jiān',
0x5979: 'tā',
0x597D: 'hǎo,hào,hāo',
0x5981: 'shuò',
0x5982: 'rú,rù',
0x5983: 'fēi',
0x5984: 'wàng',
0x5986: 'zhuāng,zhuang',
0x5987: 'fù,fu',
0x5988: 'mā,ma',
0x598A: 'rèn',
0x598D: 'yán',
0x5992: 'dù,du',
0x5993: 'jì',
0x5996: 'yāo',
0x5997: 'jìn',
0x5999: 'miào',
0x599E: 'niū,niu',
0x59A3: 'bǐ',
0x59A5: 'tuǒ',
0x59A8: 'fáng',
0x59A9: 'wǔ',
0x59AA: 'yù',
0x59AE: 'nī',
0x59AF: 'zhóu',
0x59B2: 'dá',
0x59B9: 'mèi,mei',
0x59BB: 'qī',
0x59BE: 'qiè',
0x59C6: 'mǔ',
0x59CA: 'zǐ',
0x59CB: 'shǐ',
0x59D0: 'jiě,jie',
0x59D1: 'gū,gu',
0x59D2: 'sì',
0x59D3: 'xìng',
0x59D4: 'wěi,wēi',
0x59D7: 'shān',
0x59D8: 'pīn',
0x59DA: 'yáo',
0x59DC: 'jiāng',
0x59E5: 'lǎo,lao,mǔ',
0x59E8: 'yí',
0x59EB: 'jī',
0x59EC: 'jī',
0x59EE: 'héng',
0x59F9: 'chà',
0x59FB: 'yīn',
0x59FF: 'zī',
0x5A01: 'wēi',
0x5A03: 'wá,wa',
0x5A04: 'lóu',
0x5A05: 'yà',
0x5A06: 'ráo',
0x5A07: 'jiāo',
0x5A08: 'luán',
0x5A09: 'pīng',
0x5A0C: 'li',
0x5A11: 'suō',
0x5A13: 'wěi',
0x5A18: 'niáng,niang',
0x5A1C: 'nà,nuó',
0x5A1F: 'juān',
0x5A20: 'shēn',
0x5A23: 'dì',
0x5A25: 'é',
0x5A29: 'miǎn',
0x5A2D: 'āi',
0x5A31: 'yú',
0x5A32: 'wā',
0x5A34: 'xián',
0x5A36: 'qǔ',
0x5A3C: 'chāng',
0x5A40: 'ē',
0x5A46: 'pó,po',
0x5A49: 'wǎn',
0x5A4A: 'biǎo',
0x5A5A: 'hūn',
0x5A62: 'bì',
0x5A6A: 'lán',
0x5A74: 'yīng',
0x5A75: 'chán',
0x5A76: 'shěn,shen',
0x5A77: 'tíng',
0x5A7A: 'wù',
0x5A7F: 'xù,xu',
0x5A92: 'méi',
0x5A95: 'ān',
0x5A9A: 'mèi',
0x5A9B: 'yuán,yuàn',
0x5AB2: 'pì',
0x5AB3: 'xí',
0x5AB5: 'yìng',
0x5ABE: 'gòu',
0x5AC1: 'jià',
0x5AC2: 'sǎo,sao',
0x5AC9: 'jí',
0x5ACC: 'xián',
0x5ACF: 'láng',
0x5AD4: 'pín',
0x5AD6: 'piáo',
0x5AD8: 'léi',
0x5AE0: 'lí',
0x5AE1: 'dí',
0x5AE3: 'yān',
0x5AE6: 'cháng',
0x5AE9: 'nèn,nen',
0x5AEA: 'lào',
0x5B09: 'xī',
0x5B17: 'shàn',
0x5B1B: 'huán,xuān',
0x5B34: 'yíng',
0x5B37: 'mó,mo,mā',
0x5B40: 'shuāng',
0x5B50: 'zi,zǐ',
0x5B51: 'jié',
0x5B53: 'jué',
0x5B54: 'kǒng',
0x5B55: 'yùn',
0x5B57: 'zì,zi',
0x5B58: 'cún',
0x5B59: 'sūn',
0x5B5A: 'fú',
0x5B5B: 'bèi',
0x5B5C: 'zī',
0x5B5D: 'xiào',
0x5B5F: 'mèng',
0x5B62: 'bāo',
0x5B63: 'jì',
0x5B64: 'gū',
0x5B66: 'xué',
0x5B69: 'hái',
0x5B6A: 'luán',
0x5B6C: 'nāo',
0x5B70: 'shú',
0x5B71: 'càn,chán',
0x5B73: 'zī',
0x5B75: 'fū',
0x5B7A: 'rú',
0x5B7D: 'niè',
0x5B81: 'níng,nìng',
0x5B83: 'tā',
0x5B84: 'guǐ',
0x5B85: 'zhái',
0x5B87: 'yǔ',
0x5B88: 'shǒu',
0x5B89: 'ān',
0x5B8B: 'sòng',
0x5B8C: 'wán',
0x5B8F: 'hóng',
0x5B95: 'dàng',
0x5B97: 'zōng',
0x5B98: 'guān',
0x5B99: 'zhòu',
0x5B9A: 'dìng',
0x5B9B: 'wǎn,yuān',
0x5B9C: 'yí,yi',
0x5B9D: 'bǎo',
0x5B9E: 'shí,shi',
0x5BA0: 'chǒng',
0x5BA1: 'shěn',
0x5BA2: 'kè',
0x5BA3: 'xuān',
0x5BA4: 'shì',
0x5BA5: 'yòu',
0x5BA6: 'huàn',
0x5BAA: 'xiàn',
0x5BAB: 'gōng',
0x5BB0: 'zǎi',
0x5BB3: 'hài,hai',
0x5BB4: 'yàn',
0x5BB5: 'xiāo',
0x5BB6: 'jiā,jia,gū',
0x5BB9: 'róng',
0x5BBD: 'kuān',
0x5BBE: 'bīn',
0x5BBF: 'sù,xiù,sū',
0x5BC2: 'jì',
0x5BC4: 'jì',
0x5BC5: 'yín',
0x5BC6: 'mì,mi',
0x5BC7: 'kòu',
0x5BCC: 'fù',
0x5BD0: 'mèi',
0x5BD2: 'hán',
0x5BD3: 'yù',
0x5BDD: 'qǐn',
0x5BDE: 'mò',
0x5BDF: 'chá',
0x5BE1: 'guǎ',
0x5BE4: 'wù',
0x5BE5: 'liáo',
0x5BE8: 'zhài',
0x5BEE: 'liáo',
0x5BF0: 'huán',
0x5BF8: 'cùn,cun',
0x5BF9: 'duì',
0x5BFA: 'sì',
0x5BFB: 'xún',
0x5BFC: 'dǎo',
0x5BFF: 'shòu',
0x5C01: 'fēng',
0x5C04: 'shè',
0x5C06: 'jiàng,jiāng,qiāng',
0x5C09: 'wèi,yù',
0x5C0A: 'zūn',
0x5C0F: 'xiǎo',
0x5C11: 'shǎo,shào,shao',
0x5C14: 'ěr',
0x5C15: 'gǎ',
0x5C16: 'jiān',
0x5C18: 'chén',
0x5C1A: 'shàng,shang',
0x5C1C: 'gá,ga',
0x5C1D: 'cháng',
0x5C24: 'yóu',
0x5C25: 'liào',
0x5C27: 'yáo',
0x5C2C: 'gà',
0x5C31: 'jiù,jiu',
0x5C34: 'gān',
0x5C38: 'shī,shǐ',
0x5C39: 'yǐn',
0x5C3A: 'chǐ,chě',
0x5C3B: 'kāo',
0x5C3C: 'ní',
0x5C3D: 'jìn,jǐn',
0x5C3E: 'wěi,yǐ',
0x5C3F: 'niào,suī',
0x5C40: 'jú',
0x5C41: 'pì,pi',
0x5C42: 'céng',
0x5C43: 'xì',
0x5C44: 'bī,bi',
0x5C45: 'jū',
0x5C48: 'qū,qu',
0x5C49: 'tì,tí,ti',
0x5C4A: 'jiè',
0x5C4B: 'wū',
0x5C4C: 'diǎo',
0x5C4E: 'shǐ',
0x5C4F: 'píng,bǐng,bīng',
0x5C50: 'jī',
0x5C51: 'xiè',
0x5C55: 'zhǎn',
0x5C59: 'ē',
0x5C5E: 'shǔ,zhǔ',
0x5C60: 'tú',
0x5C61: 'lǚ',
0x5C63: 'xǐ',
0x5C65: 'lǚ',
0x5C6F: 'tún,zhūn',
0x5C71: 'shān',
0x5C79: 'yì',
0x5C7F: 'yǔ',
0x5C81: 'suì',
0x5C82: 'qǐ',
0x5C88: 'yá',
0x5C8C: 'jí',
0x5C90: 'qí',
0x5C91: 'cén',
0x5C94: 'chà',
0x5C96: 'qū',
0x5C97: 'gǎng,gāng',
0x5C98: 'xiàn',
0x5C9A: 'lán',
0x5C9B: 'dǎo',
0x5CA2: 'kě',
0x5CA9: 'yán',
0x5CAB: 'xiù',
0x5CAC: 'jiǎ',
0x5CAD: 'lǐng,líng',
0x5CB1: 'dài',
0x5CB3: 'yuè',
0x5CB7: 'mín',
0x5CB8: 'àn',
0x5CC4: 'yì',
0x5CC7: 'bā',
0x5CCB: 'xún',
0x5CD2: 'dòng,tóng',
0x5CD9: 'zhì,shì',
0x5CDA: 'mì',
0x5CE1: 'xiá',
0x5CE5: 'zhēng',
0x5CE6: 'luán',
0x5CE8: 'é',
0x5CEA: 'yù',
0x5CED: 'qiào',
0x5CF0: 'fēng',
0x5CFB: 'jùn',
0x5D01: 'kǎn',
0x5D02: 'láo',
0x5D03: 'lái',
0x5D06: 'kōng',
0x5D07: 'chóng',
0x5D0E: 'qí',
0x5D14: 'cuī',
0x5D16: 'yá',
0x5D1B: 'jué',
0x5D26: 'yān',
0x5D29: 'bēng',
0x5D2D: 'zhǎn',
0x5D2E: 'gù',
0x5D34: 'wǎi',
0x5D3D: 'zǎi',
0x5D4A: 'shèng',
0x5D4B: 'méi',
0x5D4C: 'qiàn,kǎn',
0x5D4E: 'yú',
0x5D56: 'chá',
0x5D58: 'róng',
0x5D5B: 'yú',
0x5D5E: 'tú',
0x5D69: 'sōng',
0x5D6B: 'zī',
0x5D6C: 'wéi',
0x5D74: 'jǐ',
0x5D82: 'zhàng',
0x5D8C: 'dǎo',
0x5D99: 'lín',
0x5DAA: 'yè',
0x5DB7: 'yí',
0x5DC5: 'diān',
0x5DCD: 'wēi',
0x5DDD: 'chuān',
0x5DDE: 'zhōu',
0x5DE1: 'xún',
0x5DE2: 'cháo',
0x5DE5: 'gōng,ēi',
0x5DE6: 'zuǒ',
0x5DE7: 'qiǎo',
0x5DE8: 'jù',
0x5DE9: 'gǒng',
0x5DEB: 'wū',
0x5DEE: 'chā,chāi,chà,cī',
0x5DF1: 'jǐ,ji',
0x5DF2: 'yǐ',
0x5DF3: 'sì',
0x5DF4: 'bā,ba',
0x5DF7: 'xiàng',
0x5DFD: 'xùn',
0x5DFE: 'jīn',
0x5E01: 'bì',
0x5E02: 'shì',
0x5E03: 'bù,bǔ',
0x5E05: 'shuài',
0x5E06: 'fān',
0x5E08: 'shī',
0x5E0C: 'xī',
0x5E0F: 'wéi',
0x5E10: 'zhàng',
0x5E11: 'tǎng',
0x5E15: 'pà',
0x5E16: 'tiě,tiē,tiè',
0x5E18: 'lián',
0x5E19: 'zhì',
0x5E1A: 'zhou,zhǒu',
0x5E1B: 'bó',
0x5E1C: 'zhì',
0x5E1D: 'dì',
0x5E21: 'píng',
0x5E26: 'dài',
0x5E27: 'zhēn',
0x5E2D: 'xí',
0x5E2E: 'bāng,bang',
0x5E37: 'wéi',
0x5E38: 'cháng',
0x5E39: 'shà',
0x5E3C: 'guó',
0x5E3D: 'mào',
0x5E42: 'mì',
0x5E44: 'wò',
0x5E45: 'fú,fu',
0x5E4C: 'huǎng',
0x5E54: 'màn',
0x5E55: 'mù',
0x5E5B: 'zhàng',
0x5E61: 'fān',
0x5E62: 'chuáng',
0x5E6A: 'méng',
0x5E72: 'gān,gàn',
0x5E73: 'píng',
0x5E74: 'nián',
0x5E76: 'bìng',
0x5E78: 'xìng',
0x5E7A: 'yāo',
0x5E7B: 'huàn',
0x5E7C: 'yòu',
0x5E7D: 'yōu',
0x5E7F: 'guǎng',
0x5E84: 'zhuāng',
0x5E86: 'qìng',
0x5E87: 'bì',
0x5E8A: 'chuáng',
0x5E8F: 'xù',
0x5E90: 'lú',
0x5E91: 'wǔ,wú',
0x5E93: 'kù',
0x5E94: 'yìng,yīng,ying',
0x5E95: 'dǐ',
0x5E96: 'páo',
0x5E97: 'diàn',
0x5E99: 'miào',
0x5E9A: 'gēng',
0x5E9C: 'fǔ',
0x5E9E: 'páng',
0x5E9F: 'fèi',
0x5EA6: 'dù,duó,du',
0x5EA7: 'zuò',
0x5EAD: 'tíng',
0x5EB5: 'ān',
0x5EB6: 'shù',
0x5EB7: 'kāng',
0x5EB8: 'yōng',
0x5EBE: 'yǔ',
0x5EC9: 'lián',
0x5ECA: 'láng',
0x5ECC: 'zhì',
0x5ED1: 'qín',
0x5ED3: 'kuò',
0x5ED6: 'liào',
0x5EE5: 'kuài',
0x5EEA: 'lǐn',
0x5EF6: 'yán',
0x5EF7: 'tíng',
0x5EFA: 'jiàn',
0x5EFF: 'niàn',
0x5F00: 'kāi,kai',
0x5F02: 'yì',
0x5F03: 'qì',
0x5F04: 'nòng,nong,lòng,leng',
0x5F08: 'yì',
0x5F0A: 'bì',
0x5F0B: 'yì',
0x5F0F: 'shì,shi',
0x5F11: 'shì',
0x5F13: 'gōng',
0x5F15: 'yǐn',
0x5F17: 'fú',
0x5F18: 'hóng',
0x5F1B: 'chí',
0x5F1F: 'dì,di,tì',
0x5F20: 'zhāng',
0x5F25: 'mí',
0x5F26: 'xián',
0x5F27: 'hú',
0x5F29: 'nǔ',
0x5F2A: 'jìng',
0x5F2D: 'mǐ',
0x5F2F: 'wān',
0x5F31: 'ruò',
0x5F39: 'dàn,tán,tan',
0x5F3A: 'qiáng,qiǎng,jiàng',
0x5F3C: 'bì',
0x5F40: 'gòu',
0x5F52: 'guī',
0x5F53: 'dāng,dàng,dang',
0x5F55: 'lù',
0x5F56: 'tuàn',
0x5F57: 'huì',
0x5F58: 'zhì',
0x5F5D: 'yí',
0x5F5F: 'huò',
0x5F62: 'xíng,xing',
0x5F64: 'tōng,tóng',
0x5F66: 'yàn',
0x5F67: 'yù',
0x5F69: 'cǎi,cai',
0x5F6A: 'biāo',
0x5F6C: 'bīn',
0x5F6D: 'péng',
0x5F70: 'zhāng',
0x5F71: 'yǐng',
0x5F73: 'chì',
0x5F77: 'páng,fǎng',
0x5F78: 'zhōng',
0x5F79: 'yì',
0x5F7B: 'chè',
0x5F7C: 'bǐ',
0x5F80: 'wǎng',
0x5F81: 'zhēng,zhèng',
0x5F84: 'jìng',
0x5F85: 'dài,dāi',
0x5F87: 'xùn',
0x5F88: 'hěn',
0x5F89: 'yáng',
0x5F8A: 'huái',
0x5F8B: 'lǜ',
0x5F90: 'xú',
0x5F92: 'tú',
0x5F95: 'lái',
0x5F97: 'dé,de,děi',
0x5F98: 'pái',
0x5F99: 'xǐ',
0x5F9C: 'cháng',
0x5FA1: 'yù',
0x5FA8: 'huáng',
0x5FAA: 'xún',
0x5FAD: 'yáo',
0x5FAE: 'wēi',
0x5FAF: 'xī',
0x5FB5: 'zhǐ',
0x5FB7: 'dé',
0x5FBC: 'jiǎo',
0x5FBD: 'huī',
0x5FC3: 'xīn,xin',
0x5FC5: 'bì',
0x5FC6: 'yì',
0x5FCC: 'jì',
0x5FCD: 'rěn',
0x5FCF: 'chàn',
0x5FD0: 'tǎn',
0x5FD1: 'tè',
0x5FD2: 'tè',
0x5FD6: 'cǔn',
0x5FD7: 'zhì',
0x5FD8: 'wàng',
0x5FD9: 'máng,mang',
0x5FDE: 'mín',
0x5FE0: 'zhōng',
0x5FE1: 'chōng',
0x5FE4: 'wǔ',
0x5FE7: 'yōu',
0x5FEA: 'zhōng,sōng',
0x5FEB: 'kuài,kuai',
0x5FEE: 'zhì',
0x5FF1: 'chén',
0x5FF5: 'niàn',
0x5FF8: 'niǔ',
0x5FFB: 'xīn',
0x5FFD: 'hū,hu',
0x5FFE: 'kài',
0x5FFF: 'fèn',
0x6000: 'huái',
0x6001: 'tài,tai',
0x6002: 'sǒng',
0x6004: 'òu',
0x6005: 'chàng',
0x6006: 'chuàng',
0x600D: 'zuò',
0x600E: 'zěn',
0x6012: 'nù',
0x6014: 'zhēng,zhèng',
0x6015: 'pà',
0x6016: 'bù',
0x6019: 'hù',
0x601B: 'dá',
0x601C: 'lián',
0x601D: 'sī,si',
0x6020: 'dài',
0x6021: 'yí',
0x6025: 'jí',
0x6026: 'pēng',
0x6027: 'xìng,xing',
0x6028: 'yuàn',
0x6029: 'ní',
0x602A: 'guài',
0x602B: 'fú',
0x602F: 'qiè',
0x6035: 'chù',
0x603B: 'zǒng',
0x603C: 'duǐ,duì',
0x6041: 'rèn',
0x6043: 'shì',
0x604B: 'liàn',
0x604D: 'huǎng',
0x6050: 'kǒng',
0x6052: 'héng',
0x6053: 'xī',
0x6055: 'shù',
0x6059: 'yàng',
0x6062: 'huī',
0x6063: 'zì',
0x6064: 'xù',
0x6068: 'hèn',
0x6069: 'ēn',
0x606A: 'kè',
0x606B: 'dòng',
0x606C: 'tián',
0x606D: 'gōng',
0x606F: 'xī,xi',
0x6070: 'qià',
0x6073: 'kěn',
0x6076: 'è,wù,ě',
0x6078: 'tòng',
0x6079: 'yān',
0x607A: 'kǎi',
0x607B: 'cè',
0x607C: 'nǎo',
0x607F: 'yǒng',
0x6084: 'qiāo,qiǎo,qiao',
0x6089: 'xī',
0x608C: 'tì',
0x608D: 'hàn',
0x6092: 'yì',
0x6094: 'huǐ',
0x6096: 'bèi',
0x609A: 'sǒng',
0x609B: 'quān',
0x609D: 'kuī',
0x609F: 'wù',
0x60A0: 'yōu,you',
0x60A3: 'huàn',
0x60A6: 'yuè',
0x60A7: 'lì',
0x60A8: 'nín',
0x60AC: 'xuán',
0x60AD: 'qiān',
0x60AF: 'mǐn',
0x60B1: 'fěi',
0x60B2: 'bēi',
0x60B4: 'cuì',
0x60B8: 'jì',
0x60BB: 'xìng',
0x60BC: 'dào',
0x60C5: 'qíng,qing',
0x60C6: 'chóu',
0x60CA: 'jīng',
0x60CB: 'wǎn',
0x60D1: 'huò,huo',
0x60D3: 'quán',
0x60D5: 'tì',
0x60D8: 'wǎng',
0x60D9: 'chuò',
0x60DA: 'hū',
0x60DB: 'hūn',
0x60DC: 'xī',
0x60DD: 'chǎng',
0x60DF: 'wéi,wei',
0x60E0: 'huì',
0x60E6: 'diàn',
0x60E7: 'jù',
0x60E8: 'cǎn',
0x60E9: 'chéng',
0x60EB: 'bèi',
0x60EC: 'qiè',
0x60ED: 'cán',
0x60EE: 'dàn',
0x60EF: 'guàn',
0x60F0: 'duò',
0x60F3: 'xiǎng,xiǎn',
0x60F4: 'zhuì',
0x60F6: 'huáng',
0x60F9: 'rě',
0x60FA: 'xīng',
0x6101: 'chóu',
0x6106: 'qiān',
0x6108: 'yù',
0x6109: 'yú',
0x610E: 'bì',
0x610F: 'yì,yi',
0x6115: 'è',
0x611A: 'yú',
0x611F: 'gǎn',
0x6120: 'yùn',
0x6123: 'lèng,leng',
0x6124: 'fèn',
0x6127: 'kuì',
0x612B: 'sù',
0x613F: 'yuàn',
0x6148: 'cí',
0x614C: 'huāng',
0x614E: 'shèn',
0x6151: 'shè',
0x6155: 'mù',
0x6162: 'màn,man',
0x6167: 'huì',
0x6168: 'kǎi',
0x6170: 'wèi',
0x6175: 'yōng',
0x6177: 'kāng',
0x618B: 'biē',
0x618E: 'zēng',
0x6194: 'qiáo',
0x619D: 'duì',
0x61A7: 'chōng',
0x61A8: 'hān',
0x61A9: 'qì',
0x61AC: 'jǐng',
0x61B7: 'chù',
0x61BE: 'hàn',
0x61C2: 'dǒng',
0x61C8: 'xiè',
0x61CA: 'ào',
0x61CB: 'mào',
0x61D1: 'mèn',
0x61D2: 'lǎn',
0x61E6: 'nuò',
0x61EE: 'yōu',
0x61F5: 'měng',
0x61FF: 'yì',
0x6206: 'gàng',
0x6208: 'gē',
0x620A: 'wù',
0x620B: 'jiān',
0x620C: 'xū,qu',
0x620D: 'shù',
0x620E: 'róng',
0x620F: 'xì',
0x6210: 'chéng,cheng',
0x6211: 'wǒ',
0x6212: 'jiè',
0x6215: 'qiāng',
0x6216: 'huò',
0x6217: 'qiàng,qiāng',
0x6218: 'zhàn,zhan',
0x621A: 'qī,qi',
0x621B: 'jiá',
0x621F: 'jǐ',
0x622A: 'jié',
0x622E: 'lù',
0x6233: 'chuō',
0x6234: 'dài',
0x6237: 'hù,hu',
0x623D: 'hù',
0x623E: 'lì',
0x623F: 'fáng,fang',
0x6240: 'suǒ',
0x6241: 'biǎn,piān',
0x6242: 'diàn',
0x6247: 'shàn,shān,shan',
0x6248: 'hù',
0x6249: 'fēi',
0x624B: 'shǒu,shou',
0x624D: 'cái,cai',
0x624E: 'zhā,zā,zhá,zha',
0x6251: 'pū',
0x6252: 'bā,pá',
0x6253: 'dǎ,dá,da',
0x6254: 'rēng',
0x6258: 'tuō',
0x625B: 'káng',
0x6263: 'kòu',
0x6266: 'qiān',
0x6267: 'zhí',
0x6269: 'kuò',
0x626A: 'mén',
0x626B: 'sǎo,sào',
0x626C: 'yáng',
0x626D: 'niǔ,niu',
0x626E: 'bàn,ban',
0x626F: 'chě,che',
0x6270: 'rǎo',
0x6273: 'bān',
0x6276: 'fú',
0x6279: 'pī',
0x627C: 'è',
0x627E: 'zhǎo',
0x627F: 'chéng,cheng',
0x6280: 'jì',
0x6283: 'biàn',
0x6284: 'chāo',
0x6289: 'jué',
0x628A: 'bǎ,bà',
0x628F: 'wán',
0x6291: 'yì',
0x6292: 'shū',
0x6293: 'zhuā',
0x6295: 'tóu',
0x6296: 'dǒu',
0x6297: 'kàng',
0x6298: 'zhé,zhē,shé',
0x629A: 'fǔ',
0x629B: 'pāo',
0x629F: 'tuán',
0x62A0: 'kōu',
0x62A1: 'lún,lūn',
0x62A2: 'qiǎng,qiāng',
0x62A4: 'hù',
0x62A5: 'bào',
0x62A8: 'pēng',
0x62AB: 'pī',
0x62AC: 'tái',
0x62B1: 'bào',
0x62B5: 'dǐ',
0x62B9: 'mǒ,mò,mā',
0x62BB: 'chēn',
0x62BC: 'yā',
0x62BD: 'chōu,chou',
0x62BF: 'mǐn',
0x62C2: 'fú,bì',
0x62C5: 'dān,dàn,dan',
0x62C6: 'chāi',
0x62C7: 'mǔ,mu',
0x62C8: 'niān',
0x62C9: 'lā,la,lǎ,là',
0x62CA: 'fǔ',
0x62CC: 'bàn',
0x62CD: 'pāi',
0x62CE: 'līn',
0x62D0: 'guǎi,guai',
0x62D2: 'jù',
0x62D3: 'tuò,tà',
0x62D4: 'bá',
0x62D6: 'tuō',
0x62D7: 'ào,niù,ǎo',
0x62D8: 'jū',
0x62D9: 'zhuō,zhuó',
0x62DA: 'pàn,pīn',
0x62DB: 'zhāo',
0x62DC: 'bài,bái,bai',
0x62DF: 'nǐ',
0x62E2: 'lǒng',
0x62E3: 'jiǎn',
0x62E5: 'yōng',
0x62E6: 'lán',
0x62E7: 'nǐng,níng',
0x62E8: 'bō',
0x62E9: 'zé,zhái',
0x62EC: 'kuò',
0x62ED: 'shì',
0x62EE: 'jié',
0x62EF: 'zhěng',
0x62F1: 'gǒng,gōng',
0x62F3: 'quán',
0x62F4: 'shuān',
0x62F6: 'zǎn',
0x62F7: 'kǎo',
0x62FC: 'pīn',
0x62FD: 'zhuài,zhuǎi,yè',
0x62FE: 'shí,shi,shè,shī',
0x62FF: 'ná',
0x6301: 'chí,chi',
0x6302: 'guà',
0x6307: 'zhǐ,zhi',
0x6308: 'qiè',
0x6309: 'àn',
0x630E: 'kuà',
0x6311: 'tiāo,tiǎo',
0x6316: 'wā',
0x631A: 'zhì',
0x631B: 'luán',
0x631D: 'wō',
0x631E: 'tà',
0x631F: 'xié',
0x6320: 'náo,nao',
0x6321: 'dǎng,dàng',
0x6323: 'zhēng,zhèng',
0x6324: 'jǐ',
0x6325: 'huī',
0x6328: 'ái,āi',
0x632A: 'nuó',
0x632B: 'cuò',
0x632F: 'zhèn',
0x6332: 'sa,suō',
0x6339: 'yì',
0x633A: 'tǐng',
0x633D: 'wǎn',
0x6342: 'wǔ',
0x6345: 'tǒng',
0x6346: 'kǔn',
0x6349: 'zhuō',
0x634B: 'luō',
0x634D: 'hàn',
0x634E: 'shāo',
0x634F: 'niē,nie',
0x6350: 'juān',
0x6355: 'bǔ',
0x635E: 'lāo',
0x635F: 'sǔn',
0x6361: 'jiǎn',
0x6362: 'huàn',
0x6363: 'dǎo,dao',
0x6367: 'pěng',
0x6369: 'liè',
0x636E: 'jù,jū',
0x636F: 'dáo',
0x6371: 'ái',
0x6376: 'chuí',
0x6377: 'jié',
0x637A: 'nà',
0x637B: 'niǎn',
0x6380: 'xiān',
0x6382: 'diān',
0x6387: 'duō,duo',
0x6388: 'shòu',
0x6389: 'diào',
0x638C: 'zhǎng,zhang',
0x638F: 'tāo',
0x6390: 'qiā',
0x6392: 'pái,pǎi',
0x6396: 'yè,yē',
0x6398: 'jué',
0x63A0: 'lüè',
0x63A2: 'tàn',
0x63A3: 'chè',
0x63A5: 'jiē',
0x63A7: 'kòng',
0x63A8: 'tuī',
0x63A9: 'yǎn',
0x63AA: 'cuò',
0x63AC: 'jū',
0x63AE: 'qián',
0x63B0: 'bāi',
0x63B3: 'lǔ',
0x63B4: 'guāi',
0x63B7: 'zhì',
0x63B8: 'shàn,dǎn',
0x63BA: 'chān',
0x63C4: 'yú',
0x63C6: 'kuí',
0x63C9: 'róu',
0x63CD: 'zòu',
0x63CE: 'xuān',
0x63CF: 'miáo',
0x63D0: 'tí,dī',
0x63D2: 'chā',
0x63D6: 'yī',
0x63D8: 'yóng',
0x63E0: 'yà',
0x63E1: 'wò',
0x63E3: 'chuǎi,chuāi,chuài',
0x63E6: 'lá',
0x63E9: 'kāi',
0x63EA: 'jiū',
0x63ED: 'jiē',
0x63F4: 'yuán',
0x63F6: 'yé',
0x63FD: 'lǎn',
0x63FE: 'wèn',
0x6400: 'chān',
0x6401: 'gē,ge',
0x6402: 'lōu,lǒu,lou',
0x6405: 'jiǎo',
0x640B: 'chuāi',
0x640F: 'bó',
0x6410: 'chù',
0x6413: 'cuō,cuo',
0x6414: 'sāo',
0x641C: 'sōu',
0x641E: 'gǎo',
0x6421: 'sǎng',
0x6426: 'nuò',
0x642A: 'táng',
0x642C: 'bān',
0x642D: 'dā,da',
0x6433: 'huá',
0x6434: 'qiān',
0x643A: 'xié',
0x6441: 'èn',
0x6444: 'shè',
0x6446: 'bǎi,bai',
0x6447: 'yáo',
0x6448: 'bìn',
0x644A: 'tān,tan',
0x6452: 'bìng',
0x6454: 'shuāi,shuǎi',
0x6458: 'zhāi',
0x645E: 'luò',
0x6467: 'cuī',
0x6469: 'mó,mā',
0x6478: 'mō,mo',
0x6479: 'mó',
0x647A: 'zhé',
0x6482: 'liào',
0x6485: 'juē',
0x6487: 'piě,piē',
0x6491: 'chēng',
0x6492: 'sā,sǎ,sa',
0x6495: 'sī',
0x649E: 'zhuàng',
0x64A4: 'chè',
0x64A9: 'liáo,liāo',
0x64AC: 'qiào',
0x64AD: 'bō',
0x64AE: 'cuō',
0x64B0: 'zhuàn',
0x64B5: 'niǎn',
0x64B7: 'xié',
0x64B8: 'lū',
0x64BA: 'cuān',
0x64BC: 'hàn',
0x64C0: 'gǎn',
0x64C2: 'léi,lèi',
0x64C5: 'shàn',
0x64CD: 'cāo,cào',
0x64CE: 'qíng',
0x64D2: 'qín',
0x64D8: 'bò',
0x64DE: 'sǒu',
0x64E2: 'zhuó',
0x64E4: 'xǐng',
0x64E6: 'cā',
0x6500: 'pān',
0x6509: 'huō',
0x6512: 'cuán,zǎn',
0x6518: 'rǎng,rang',
0x6525: 'zuàn',
0x652B: 'jué',
0x652F: 'zhī',
0x6536: 'shōu',
0x6538: 'yōu',
0x6539: 'gǎi',
0x653B: 'gōng',
0x653E: 'fàng',
0x653F: 'zhèng',
0x6545: 'gù,gu',
0x6548: 'xiào',
0x654C: 'dí',
0x654F: 'mǐn',
0x6551: 'jiù',
0x6555: 'chì',
0x6556: 'áo',
0x6559: 'jiào,jiāo',
0x655B: 'liǎn',
0x655D: 'bì',
0x655E: 'chǎng,chang,cháng',
0x6562: 'gǎn',
0x6563: 'sàn,sǎn,san',
0x6566: 'dūn',
0x656A: 'duō',
0x656C: 'jìng',
0x6570: 'shù,shǔ,shu,shuò',
0x6572: 'qiāo',
0x6574: 'zhěng',
0x6577: 'fū',
0x6587: 'wén',
0x658B: 'zhāi',
0x658C: 'bīn',
0x6590: 'fěi',
0x6591: 'bān',
0x6593: 'lán',
0x6597: 'dòu,dǒu',
0x6599: 'liào,liao',
0x659B: 'hú',
0x659C: 'xié,xie',
0x659D: 'jiǎ',
0x659F: 'zhēn',
0x65A1: 'wò',
0x65A4: 'jīn',
0x65A5: 'chì',
0x65A7: 'fǔ',
0x65A9: 'zhǎn',
0x65AB: 'zhuó',
0x65AD: 'duàn',
0x65AF: 'sī',
0x65B0: 'xīn',
0x65B9: 'fāng,fang',
0x65BD: 'shī',
0x65C1: 'páng',
0x65C3: 'zhān',
0x65C4: 'mào,máo',
0x65C5: 'lǚ',
0x65C6: 'pèi',
0x65CB: 'xuán,xuàn',
0x65CC: 'jīng',
0x65CE: 'nǐ',
0x65CF: 'zú',
0x65D6: 'yǐ',
0x65D7: 'qí',
0x65DB: 'fān',
0x65E0: 'wú,mó,wū',
0x65E2: 'jì',
0x65E5: 'rì',
0x65E6: 'dàn',
0x65E7: 'jiù',
0x65E8: 'zhǐ',
0x65E9: 'zǎo',
0x65EC: 'xún',
0x65ED: 'xù',
0x65EE: 'gā',
0x65EF: 'lá',
0x65F0: 'gàn',
0x65F1: 'hàn',
0x65F6: 'shí',
0x65F7: 'kuàng',
0x65FA: 'wàng',
0x6600: 'yún',
0x6602: 'áng',
0x6606: 'kūn',
0x6609: 'fǎng',
0x660A: 'hào',
0x660C: 'chāng',
0x660E: 'míng,ming',
0x660F: 'hūn',
0x6613: 'yì',
0x6614: 'xī',
0x6619: 'tán',
0x661D: 'zan',
0x661F: 'xīng,xing',
0x6620: 'yìng',
0x6625: 'chūn',
0x6627: 'mèi',
0x6628: 'zuó',
0x662B: 'xù',
0x662D: 'zhāo',
0x662F: 'shì,shi',
0x6631: 'yù',
0x6634: 'mǎo',
0x6635: 'nì',
0x663C: 'zhòu',
0x663E: 'xiǎn',
0x6643: 'huǎng,huàng,huang',
0x664B: 'jìn',
0x664C: 'shǎng',
0x664F: 'yàn',
0x6652: 'shài',
0x6653: 'xiǎo',
0x6654: 'yè',
0x6655: 'yùn,yūn',
0x6656: 'huī',
0x6657: 'hán',
0x665A: 'wǎn',
0x6664: 'wù',
0x6666: 'huì',
0x6668: 'chén',
0x666C: 'zuì',
0x666E: 'pǔ',
0x666F: 'jǐng',
0x6670: 'xī',
0x6674: 'qíng',
0x6676: 'jīng',
0x6677: 'guǐ',
0x667A: 'zhì',
0x667E: 'liàng',
0x6682: 'zàn',
0x6684: 'xuān',
0x6686: 'yí',
0x6687: 'xiá',
0x6691: 'shǔ',
0x6696: 'nuǎn',
0x6697: 'àn',
0x66A1: 'wěng',
0x66A7: 'ài',
0x66A8: 'jì',
0x66AE: 'mù',
0x66B4: 'bào,pù',
0x66B9: 'xiān',
0x66BE: 'tūn',
0x66D9: 'shǔ',
0x66DA: 'méng',
0x66DC: 'yào',
0x66DD: 'pù,bào',
0x66E6: 'xī',
0x66F0: 'yuē',
0x66F1: 'yuē',
0x66F2: 'qū,qǔ',
0x66F3: 'yè',
0x66F4: 'gēng,gèng',
0x66F9: 'cáo',
0x66FC: 'màn',
0x66FE: 'zēng,céng',
0x66FF: 'tì',
0x6700: 'zuì',
0x6708: 'yuè',
0x6709: 'yǒu',
0x670A: 'ruǎn',
0x670B: 'péng',
0x670D: 'fú,fu,fù',
0x6710: 'qú',
0x6714: 'shuò',
0x6715: 'zhèn',
0x6717: 'lǎng',
0x671B: 'wàng',
0x671D: 'cháo,zhāo',
0x671F: 'qī',
0x6726: 'méng',
0x6728: 'mù',
0x672A: 'wèi',
0x672B: 'mò,mo,me',
0x672C: 'běn',
0x672D: 'zhá',
0x672F: 'shù,zhú',
0x6731: 'zhū',
0x6734: 'pǔ,pò,piáo,pú',
0x6735: 'duǒ,duo,duō',
0x673A: 'jī',
0x673D: 'xiǔ',
0x6740: 'shā',
0x6742: 'zá,za',
0x6743: 'quán',
0x6746: 'gǎn,gān',
0x6748: 'chà',
0x6749: 'shān',
0x674C: 'wù',
0x674E: 'lǐ,li',
0x674F: 'xìng',
0x6750: 'cái,cai',
0x6751: 'cūn',
0x6753: 'sháo',
0x6756: 'zhàng',
0x675C: 'dù',
0x675E: 'qǐ',
0x675F: 'shù',
0x6760: 'gàng',
0x6761: 'tiáo,tiao',
0x6765: 'lái,lai',
0x6768: 'yáng',
0x676A: 'miǎo',
0x676D: 'háng',
0x676F: 'bēi',
0x6770: 'jié',
0x6773: 'yǎo',
0x6775: 'chǔ',
0x6777: 'pa,pá',
0x677C: 'zhù',
0x677E: 'sōng',
0x677F: 'bǎn',
0x6781: 'jí',
0x6784: 'gòu',
0x6787: 'pí',
0x6789: 'wǎng,wang',
0x678B: 'fāng',
0x6790: 'xī,xi',
0x6792: 'yā',
0x6793: 'dǒu',
0x6795: 'zhěn',
0x6797: 'lín',
0x6798: 'ruì',
0x679A: 'méi',
0x679C: 'guǒ',
0x679D: 'zhī',
0x679E: 'cōng,zōng',
0x67A2: 'shū',
0x67A3: 'zǎo',
0x67A5: 'lì',
0x67AA: 'qiāng',
0x67AB: 'fēng',
0x67AD: 'xiāo',
0x67AF: 'kū',
0x67B3: 'zhǐ',
0x67B6: 'jià',
0x67B7: 'jiā',
0x67B8: 'gǒu,gōu,jǔ',
0x67C4: 'bǐng',
0x67CA: 'zhōng',
0x67CF: 'bǎi,bó,bò',
0x67D0: 'mǒu',
0x67D1: 'gān',
0x67D3: 'rǎn',
0x67D4: 'róu',
0x67D8: 'zhè',
0x67DA: 'yòu',
0x67DC: 'guì',
0x67DD: 'tuò',
0x67DE: 'zhà,zuò',
0x67E0: 'níng',
0x67E2: 'dǐ',
0x67E5: 'chá,zhā',
0x67E9: 'jiù',
0x67EC: 'jiǎn',
0x67EF: 'kē',
0x67F0: 'nài',
0x67F1: 'zhù',
0x67F3: 'liǔ',
0x67F4: 'chái',
0x67FF: 'shì',
0x6800: 'zhī',
0x6805: 'zhà,shān',
0x6807: 'biāo',
0x6808: 'zhàn',
0x6809: 'zhì,jié',
0x680B: 'dòng',
0x680E: 'lì',
0x680F: 'lán',
0x6811: 'shù',
0x6813: 'shuān',
0x6816: 'qī,xī',
0x6817: 'lì',
0x681D: 'kuò',
0x6821: 'xiào,jiào',
0x6829: 'xǔ',
0x682A: 'zhū',
0x6831: 'gǒng',
0x6832: 'kǎo',
0x6833: 'lǎo',
0x6834: 'zhān',
0x6837: 'yàng',
0x6838: 'hé,hú,hē',
0x6839: 'gēn',
0x683C: 'gé,ge',
0x683D: 'zāi',
0x683E: 'luán',
0x6840: 'jié',
0x6841: 'héng,háng',
0x6842: 'guì',
0x6843: 'táo,tao',
0x6844: 'guāng',
0x6845: 'wéi',
0x6846: 'kuàng',
0x6848: 'àn',
0x6849: 'ān',
0x684C: 'zhuō',
0x684E: 'zhì',
0x6850: 'tóng',
0x6851: 'sāng,sǎng',
0x6853: 'huán',
0x6854: 'jú,jié',
0x6855: 'jiù',
0x6860: 'yā',
0x6861: 'ráo',
0x6862: 'zhēn',
0x6863: 'dàng,dǎng',
0x6864: 'qī',
0x6865: 'qiáo',
0x6866: 'huà',
0x6867: 'guì,huì',
0x6868: 'jiǎng',
0x6869: 'zhuāng',
0x686B: 'suō',
0x6872: 'po',
0x6874: 'fú',
0x6876: 'tǒng',
0x6877: 'jué',
0x6881: 'liáng,liang',
0x6885: 'méi',
0x6886: 'bāng',
0x688F: 'gù',
0x6893: 'zǐ',
0x6897: 'gěng',
0x689C: 'jiā',
0x68A2: 'shāo',
0x68A3: 'chén',
0x68A6: 'mèng',
0x68A7: 'wú',
0x68A8: 'lí',
0x68AD: 'suō',
0x68AF: 'tī',
0x68B0: 'xiè',
0x68B3: 'shū',
0x68B5: 'fàn,fán',
0x68BC: 'táo',
0x68BE: 'lái',
0x68BF: 'lián',
0x68C0: 'jiǎn',
0x68C2: 'líng',
0x68C9: 'mián',
0x68CB: 'qí',
0x68CD: 'gùn',
0x68D2: 'bàng',
0x68D5: 'zōng,zòng',
0x68D8: 'jí',
0x68DA: 'péng,peng',
0x68E0: 'táng',
0x68E3: 'dì',
0x68EE: 'sēn',
0x68F0: 'chuí',
0x68F1: 'léng,leng,líng,lēng',
0x68F5: 'kē',
0x68FA: 'guān',
0x68FB: 'fēn',
0x68FC: 'fén',
0x6901: 'guǒ',
0x6905: 'yǐ',
0x6906: 'zhòu,chóu,diào',
0x690B: 'liáng',
0x690D: 'zhí',
0x690E: 'zhuī,zhù',
0x6912: 'jiāo',
0x691F: 'dú',
0x6924: 'luó',
0x6925: 'zhī',
0x692A: 'pèng',
0x692D: 'tuǒ',
0x6930: 'yē,yé',
0x6934: 'duàn',
0x693D: 'chuán',
0x693F: 'chūn',
0x6942: 'zhā',
0x6954: 'xiē',
0x695A: 'chǔ,chu',
0x695D: 'liàn',
0x695E: 'léng,lèng,leng',
0x6960: 'nán',
0x6963: 'méi',
0x6966: 'xuàn',
0x696E: 'chǔ',
0x6977: 'kǎi',
0x6978: 'qiū',
0x6979: 'yíng',
0x697C: 'lóu,lòu,lou',
0x6982: 'gài',
0x6984: 'lǎn',
0x6985: 'wēn',
0x6986: 'yú',
0x6988: 'lǘ',
0x6989: 'jǔ',
0x6994: 'láng,lang',
0x6995: 'róng',
0x6998: 'jǔ',
0x699B: 'zhēn',
0x699C: 'bǎng,bàng',
0x69A7: 'fěi',
0x69A8: 'zhà',
0x69AB: 'sǔn',
0x69AD: 'xiè',
0x69B4: 'liú,liu',
0x69B7: 'què',
0x69BB: 'tà',
0x69C1: 'gǎo',
0x69C3: 'pán',
0x69CC: 'chuí',
0x69D0: 'huái',
0x69D1: 'dāi',
0x69D4: 'gāo',
0x69DB: 'kǎn,jiàn',
0x69DC: 'zuì',
0x69DF: 'bīng,bīn',
0x69ED: 'qì',
0x69F2: 'hú',
0x69F5: 'huàn',
0x69FA: 'kāng',
0x69FD: 'cáo',
0x69FF: 'jǐn',
0x6A0A: 'fán',
0x6A1F: 'zhāng',
0x6A21: 'mó,mú',
0x6A2A: 'héng,hèng',
0x6A31: 'yīng',
0x6A35: 'qiáo',
0x6A3D: 'zūn',
0x6A44: 'gǎn',
0x6A47: 'qiāo',
0x6A50: 'tuó',
0x6A58: 'jú',
0x6A59: 'chéng',
0x6A5B: 'jué',
0x6A61: 'xiàng',
0x6A65: 'zhū',
0x6A71: 'chú',
0x6A79: 'lǔ',
0x6A7C: 'yuán',
0x6A80: 'tán',
0x6A83: 'yǐn',
0x6A84: 'xí',
0x6A8E: 'qín',
0x6A90: 'yán',
0x6A97: 'bò',
0x6AAC: 'méng',
0x6AB5: 'jì',
0x6AC6: 'kuí',
0x6B20: 'qiàn,qian',
0x6B21: 'cì',
0x6B22: 'huān,huan',
0x6B23: 'xīn',
0x6B27: 'ōu',
0x6B32: 'yù',
0x6B37: 'xī',
0x6B3A: 'qī',
0x6B3E: 'kuǎn',
0x6B3F: 'kǎn',
0x6B43: 'shà',
0x6B47: 'xiē',
0x6B49: 'qiàn',
0x6B4C: 'gē,ge',
0x6B54: 'xū',
0x6B59: 'shè',
0x6B62: 'zhǐ',
0x6B63: 'zhèng,zhēng',
0x6B64: 'cǐ',
0x6B65: 'bù',
0x6B66: 'wǔ',
0x6B67: 'qí',
0x6B6A: 'wāi,wai',
0x6B79: 'dǎi',
0x6B7B: 'sǐ',
0x6B7C: 'jiān',
0x6B82: 'cú',
0x6B83: 'yāng',
0x6B84: 'tiǎn',
0x6B86: 'dài',
0x6B87: 'shāng',
0x6B89: 'xùn',
0x6B8A: 'shū',
0x6B8B: 'cán',
0x6B8D: 'piǎo',
0x6B92: 'yǔn',
0x6B93: 'liàn',
0x6B96: 'zhí,shi',
0x6B97: 'yè',
0x6B9A: 'dān',
0x6B9C: 'dié',
0x6BA1: 'bìn',
0x6BB4: 'ōu',
0x6BB5: 'duàn',
0x6BB7: 'yīn,yān',
0x6BBF: 'diàn',
0x6BC1: 'huǐ',
0x6BC2: 'gǔ,gū',
0x6BC5: 'yì',
0x6BCB: 'wú',
0x6BCD: 'mǔ',
0x6BCF: 'měi',
0x6BD0: 'ǎi',
0x6BD2: 'dú',
0x6BD3: 'yù',
0x6BD4: 'bǐ,bì,bí,bī',
0x6BD5: 'bì',
0x6BD6: 'bì',
0x6BD7: 'pí',
0x6BD9: 'bì',
0x6BDB: 'máo,mao',
0x6BE1: 'zhān',
0x6BEB: 'háo',
0x6BEF: 'tǎn',
0x6BFD: 'jiàn',
0x6C05: 'chǎng',
0x6C0F: 'shì,zhī',
0x6C11: 'mín',
0x6C13: 'máng,méng',
0x6C14: 'qì,qi',
0x6C18: 'dāo',
0x6C1B: 'fēn',
0x6C1F: 'fú',
0x6C22: 'qīng',
0x6C24: 'yīn',
0x6C27: 'yǎng',
0x6C28: 'ān',
0x6C2A: 'kè',
0x6C2E: 'dàn',
0x6C2F: 'lǜ',
0x6C30: 'qíng',
0x6C32: 'yūn',
0x6C34: 'shuǐ,shui',
0x6C38: 'yǒng',
0x6C39: 'dàng',
0x6C3D: 'tǔn',
0x6C40: 'tīng',
0x6C41: 'zhī',
0x6C42: 'qiú',
0x6C47: 'huì',
0x6C49: 'hàn',
0x6C50: 'xī',
0x6C55: 'shàn',
0x6C57: 'hàn,hán',
0x6C59: 'wū',
0x6C5B: 'xùn',
0x6C5D: 'rǔ',
0x6C5E: 'gǒng',
0x6C5F: 'jiāng',
0x6C60: 'chí',
0x6C61: 'wū',
0x6C64: 'tāng,táng',
0x6C68: 'mì',
0x6C69: 'gǔ',
0x6C6A: 'wāng',
0x6C6B: 'jǐng',
0x6C70: 'tài,tai',
0x6C72: 'jí',
0x6C74: 'biàn',
0x6C76: 'wèn',
0x6C79: 'xiōng',
0x6C7D: 'qì',
0x6C7E: 'fén',
0x6C81: 'qìn',
0x6C82: 'yí',
0x6C83: 'wò',
0x6C85: 'yuán',
0x6C86: 'hàng',
0x6C88: 'shěn,chén',
0x6C89: 'chén,chēn',
0x6C8C: 'dùn',
0x6C90: 'mù',
0x6C93: 'tà,ta',
0x6C99: 'shā',
0x6C9B: 'pèi',
0x6C9F: 'gōu,gòu',
0x6CA1: 'méi,mò',
0x6CA3: 'fēng',
0x6CA4: 'òu',
0x6CA5: 'lì',
0x6CA6: 'lún',
0x6CA7: 'cāng',
0x6CAA: 'hù',
0x6CAB: 'mò,mo',
0x6CAD: 'shù',
0x6CAE: 'jǔ',
0x6CB1: 'tuó',
0x6CB3: 'hé',
0x6CB8: 'fèi',
0x6CB9: 'yóu',
0x6CBB: 'zhì',
0x6CBC: 'zhǎo',
0x6CBD: 'gū',
0x6CBE: 'zhān',
0x6CBF: 'yán',
0x6CC3: 'jū',
0x6CC4: 'xiè',
0x6CC5: 'qiú',
0x6CC6: 'yì',
0x6CC9: 'quán',
0x6CCA: 'bó,pō',
0x6CCC: 'mì,bì',
0x6CD3: 'hóng',
0x6CD4: 'gān',
0x6CD5: 'fǎ,fá,fa',
0x6CD7: 'sì',
0x6CDB: 'fàn,fan',
0x6CDD: 'sù',
0x6CDE: 'nìng',
0x6CE1: 'pào,pāo,pao',
0x6CE2: 'bō',
0x6CE3: 'qì',
0x6CE5: 'ní,nì',
0x6CE8: 'zhù',
0x6CEA: 'lèi',
0x6CEE: 'pàn',
0x6CEF: 'mǐn',
0x6CF0: 'tài',
0x6CF1: 'yāng',
0x6CF3: 'yǒng',
0x6CF5: 'bèng',
0x6CF7: 'lóng,shuāng',
0x6CF8: 'lú',
0x6CFB: 'xiè',
0x6CFC: 'pō,po',
0x6CFD: 'zé',
0x6CFE: 'jīng',
0x6D01: 'jié',
0x6D04: 'huí',
0x6D07: 'yīn',
0x6D0B: 'yáng,yāng',
0x6D12: 'sǎ',
0x6D17: 'xǐ,xiǎn',
0x6D19: 'zhū',
0x6D1B: 'luò',
0x6D1E: 'dòng,tóng',
0x6D23: 'mǐ',
0x6D25: 'jīn',
0x6D27: 'wěi',
0x6D28: 'xiáo',
0x6D2A: 'hóng',
0x6D2E: 'táo',
0x6D31: 'ěr',
0x6D32: 'zhōu',
0x6D35: 'xún',
0x6D3B: 'huó,huo',
0x6D3C: 'wā',
0x6D3D: 'qià',
0x6D3E: 'pài',
0x6D41: 'liú',
0x6D43: 'jiā',
0x6D45: 'qiǎn',
0x6D46: 'jiāng,jiàng',
0x6D47: 'jiāo',
0x6D48: 'zhēn',
0x6D49: 'shī',
0x6D4A: 'zhuó',
0x6D4B: 'cè',
0x6D4E: 'jì,jǐ',
0x6D4F: 'liú',
0x6D50: 'chǎn',
0x6D51: 'hún',
0x6D52: 'hǔ',
0x6D53: 'nóng',
0x6D54: 'xún',
0x6D59: 'zhè',
0x6D5A: 'jùn,xùn',
0x6D5C: 'bāng',
0x6D60: 'xī',
0x6D63: 'huàn',
0x6D66: 'pǔ',
0x6D69: 'hào',
0x6D6A: 'làng',
0x6D6E: 'fú',
0x6D74: 'yù',
0x6D77: 'hǎi',
0x6D78: 'jìn',
0x6D7D: 'suī',
0x6D82: 'tú,tu',
0x6D85: 'niè',
0x6D88: 'xiāo',
0x6D89: 'shè',
0x6D8C: 'yǒng,chōng',
0x6D8E: 'xián,xian',
0x6D93: 'juān',
0x6D95: 'tì',
0x6D9B: 'tāo',
0x6D9D: 'lào',
0x6D9E: 'lái',
0x6D9F: 'lián',
0x6DA1: 'wō,guō',
0x6DA3: 'huàn',
0x6DA4: 'dí',
0x6DA6: 'rùn',
0x6DA7: 'jiàn',
0x6DA8: 'zhǎng,zhàng',
0x6DA9: 'sè',
0x6DAA: 'fú',
0x6DAE: 'shuàn',
0x6DAF: 'yá',
0x6DB2: 'yè',
0x6DB5: 'hán',
0x6DB8: 'hé',
0x6DBF: 'zhuō',
0x6DC0: 'diàn',
0x6DC4: 'zī',
0x6DC5: 'xī',
0x6DC6: 'xiáo',
0x6DC7: 'qí',
0x6DCB: 'lín,lìn',
0x6DCC: 'tǎng',
0x6DD1: 'shū',
0x6DD6: 'nào',
0x6DD8: 'táo',
0x6DDE: 'sōng',
0x6DE1: 'dàn',
0x6DE4: 'yū',
0x6DEB: 'yín',
0x6DEC: 'cuì',
0x6DEE: 'huái',
0x6DEF: 'yù',
0x6DF1: 'shēn',
0x6DF3: 'chún',
0x6DF7: 'hùn,hún,hun',
0x6DF9: 'yān',
0x6DFB: 'tiān',
0x6DFC: 'miǎo',
0x6E05: 'qīng',
0x6E0A: 'yuān',
0x6E0C: 'lù',
0x6E0D: 'zì',
0x6E0E: 'dú',
0x6E10: 'jiàn,jiān',
0x6E11: 'miǎn',
0x6E14: 'yú',
0x6E17: 'shèn',
0x6E1A: 'zhǔ',
0x6E1D: 'yú',
0x6E20: 'qú',
0x6E21: 'dù',
0x6E23: 'zhā,zhà',
0x6E24: 'bó',
0x6E25: 'wò',
0x6E29: 'wēn',
0x6E2B: 'xiè',
0x6E2D: 'wèi',
0x6E2F: 'gǎng',
0x6E32: 'xuàn',
0x6E34: 'kě',
0x6E38: 'yóu,you',
0x6E3A: 'miǎo',
0x6E43: 'pài',
0x6E44: 'méi',
0x6E49: 'tián',
0x6E4D: 'tuān',
0x6E4E: 'miǎn',
0x6E54: 'jiān',
0x6E56: 'hú',
0x6E58: 'xiāng',
0x6E5B: 'zhàn',
0x6E5F: 'huáng',
0x6E63: 'mǐn',
0x6E6E: 'yān,yīn',
0x6E7E: 'wān',
0x6E7F: 'shī',
0x6E83: 'kuì,huì',
0x6E85: 'jiàn',
0x6E86: 'xù',
0x6E87: 'lóu',
0x6E89: 'gài',
0x6E8F: 'táng',
0x6E90: 'yuán',
0x6E98: 'kè',
0x6E9C: 'liū,liu,liù',
0x6E9F: 'míng',
0x6EA2: 'yì',
0x6EA5: 'pǔ',
0x6EA6: 'wēi',
0x6EA7: 'lì',
0x6EAA: 'xī',
0x6EAF: 'sù',
0x6EB2: 'sōu',
0x6EB4: 'xiù',
0x6EB6: 'róng',
0x6EB7: 'hùn',
0x6EBA: 'nì,niào',
0x6EC1: 'chú',
0x6EC2: 'pāng',
0x6EC7: 'diān',
0x6ECB: 'zī',
0x6ED1: 'huá',
0x6ED3: 'zǐ',
0x6ED4: 'tāo',
0x6ED5: 'téng',
0x6EDA: 'gǔn',
0x6EDE: 'zhì',
0x6EE1: 'mǎn',
0x6EE4: 'lǜ',
0x6EE5: 'làn',
0x6EE6: 'luán',
0x6EE8: 'bīn',
0x6EE9: 'tān',
0x6EF4: 'dī',
0x6F02: 'piāo,piǎo,piào',
0x6F06: 'qī',
0x6F09: 'lù',
0x6F0F: 'lòu',
0x6F13: 'lí',
0x6F14: 'yǎn',
0x6F15: 'cáo',
0x6F20: 'mò',
0x6F29: 'xuán',
0x6F2A: 'yī',
0x6F2B: 'màn',
0x6F2D: 'mǎng',
0x6F2F: 'luò',
0x6F31: 'shù',
0x6F33: 'zhāng',
0x6F36: 'huàn',
0x6F3C: 'cuǐ',
0x6F3E: 'yàng',
0x6F47: 'xiāo',
0x6F4D: 'wéi',
0x6F58: 'pān',
0x6F5C: 'qián',
0x6F5E: 'lù',
0x6F5F: 'xì',
0x6F62: 'huáng',
0x6F66: 'liáo',
0x6F6D: 'tán',
0x6F6E: 'cháo',
0x6F74: 'zhū',
0x6F78: 'shān',
0x6F7A: 'chán',
0x6F7C: 'tóng',
0x6F7D: 'pǔ',
0x6F84: 'chéng,dèng',
0x6F88: 'chè',
0x6F8E: 'péng',
0x6F9C: 'lán',
0x6FA1: 'zǎo',
0x6FA5: 'xiè',
0x6FA7: 'lǐ',
0x6FB3: 'ào',
0x6FB9: 'dàn',
0x6FC0: 'jī',
0x6FC2: 'lián',
0x6FC9: 'suī',
0x6FCA: 'huì',
0x6FD2: 'bīn',
0x6FD9: 'yíng',
0x6FDE: 'bì',
0x6FE0: 'háo',
0x6FE1: 'rú',
0x6FEE: 'pú',
0x6FEF: 'zhuó',
0x700D: 'chán',
0x7011: 'pù',
0x701A: 'hàn',
0x701B: 'yíng',
0x7023: 'xiè',
0x704C: 'guàn',
0x705E: 'bà',
0x7062: 'nǎng',
0x706B: 'huǒ,huo',
0x706D: 'miè',
0x706F: 'dēng',
0x7070: 'huī',
0x7075: 'líng,ling',
0x7076: 'zào',
0x7078: 'jiǔ',
0x707C: 'zhuó',
0x707E: 'zāi',
0x707F: 'càn',
0x7080: 'yáng',
0x7086: 'wén',
0x7089: 'lú',
0x708A: 'chuī',
0x708E: 'yán',
0x7092: 'chǎo',
0x7094: 'quē',
0x7095: 'kàng',
0x7096: 'dùn',
0x7099: 'zhì',
0x70AB: 'xuàn',
0x70AC: 'jù',
0x70AD: 'tàn',
0x70AE: 'pào,páo',
0x70AF: 'jiǒng',
0x70B3: 'bǐng',
0x70B7: 'zhù',
0x70B8: 'zhà,zhá,dàn',
0x70B9: 'diǎn,dian',
0x70BB: 'shí',
0x70BC: 'liàn',
0x70BD: 'chì',
0x70C1: 'shuò',
0x70C2: 'làn',
0x70C3: 'tīng',
0x70C8: 'liè',
0x70CA: 'yàng,yáng',
0x70D8: 'hōng',
0x70D9: 'lào',
0x70DB: 'zhú',
0x70DC: 'xuǎn',
0x70DD: 'zhēng',
0x70DF: 'yān',
0x70E4: 'kǎo',
0x70E6: 'fán,fan',
0x70E7: 'shāo',
0x70E8: 'yè',
0x70E9: 'huì',
0x70EB: 'tàng',
0x70EC: 'jìn',
0x70ED: 'rè',
0x70EF: 'xī',
0x70F7: 'wán',
0x70F9: 'pēng',
0x70FD: 'fēng',
0x7109: 'yān',
0x710A: 'hàn',
0x710C: 'qū,jùn',
0x7113: 'hán',
0x7115: 'huàn',
0x7116: 'mèn',
0x7117: 'jú',
0x7118: 'tāo,dào',
0x7119: 'bèi',
0x711A: 'fén',
0x7122: 'kòng',
0x7126: 'jiāo',
0x7130: 'yàn',
0x7131: 'yàn',
0x7136: 'rán',
0x7145: 'duàn',
0x714A: 'xuān',
0x714C: 'huáng',
0x714E: 'jiān',
0x715C: 'yù',
0x715E: 'shā,shà',
0x7164: 'méi',
0x7166: 'xù',
0x7167: 'zhào',
0x716E: 'zhǔ',
0x7172: 'bāo',
0x7178: 'biān',
0x717D: 'shān',
0x7184: 'xī',
0x718A: 'xióng',
0x718F: 'xūn',
0x7194: 'róng',
0x7199: 'xī',
0x719F: 'shú,shóu',
0x71A0: 'yì',
0x71A8: 'yùn',
0x71AC: 'áo,āo',
0x71B3: 'màn',
0x71B5: 'shāng',
0x71B9: 'xī',
0x71C3: 'rán',
0x71CE: 'liáo,liǎo',
0x71D0: 'lín',
0x71D5: 'yàn,yān',
0x71DA: 'yì',
0x71E5: 'zào',
0x71E7: 'suì',
0x71EE: 'xiè',
0x7206: 'bào,zhà',
0x720C: 'kòng',
0x7228: 'cuàn',
0x722A: 'zhǎo,zhuǎ',
0x722C: 'pá',
0x7231: 'ài,ai',
0x7235: 'jué',
0x7236: 'fù,fu',
0x7237: 'yé,ye',
0x7238: 'bà,bǎ,ba',
0x7239: 'diē,die',
0x723D: 'shuǎng',
0x7247: 'piàn,piān',
0x7248: 'bǎn',
0x724C: 'pái,pai',
0x724D: 'dú',
0x7252: 'dié',
0x7256: 'yǒu',
0x7259: 'yá',
0x725B: 'niú',
0x725D: 'pìn',
0x725F: 'móu,mù',
0x7261: 'mǔ,mù',
0x7262: 'láo',
0x7264: 'māng',
0x7266: 'máo',
0x7267: 'mù',
0x7269: 'wù,wu',
0x7272: 'shēng',
0x7274: 'dǐ',
0x7275: 'qiān',
0x7278: 'zì',
0x7279: 'tè',
0x727A: 'xī',
0x727B: 'máng',
0x727E: 'wǔ',
0x7280: 'xī,xi',
0x7281: 'lí',
0x7282: 'lí',
0x7284: 'jī',
0x728A: 'dú',
0x728D: 'qián,jiān',
0x728E: 'fēng',
0x728F: 'piān',
0x7292: 'kào',
0x729F: 'jiàng',
0x72AA: 'kuí',
0x72AC: 'quǎn',
0x72AF: 'fàn',
0x72B0: 'qiú',
0x72B6: 'zhuàng',
0x72B7: 'guǎng',
0x72B8: 'mǎ',
0x72B9: 'yóu',
0x72C1: 'yǔn',
0x72C2: 'kuáng',
0x72C4: 'dí',
0x72C8: 'bèi',
0x72C9: 'pī',
0x72CD: 'páo',
0x72CE: 'xiá',
0x72D0: 'hú',
0x72D2: 'fèi',
0x72D3: 'pī',
0x72D7: 'gǒu,gōu',
0x72D9: 'jū',
0x72DD: 'xiǎn',
0x72DE: 'níng',
0x72E0: 'hěn',
0x72E1: 'jiǎo',
0x72E9: 'shòu',
0x72EC: 'dú',
0x72ED: 'xiá',
0x72EE: 'shī',
0x72EF: 'kuài',
0x72F0: 'zhēng',
0x72F1: 'yù',
0x72F2: 'sūn',
0x72F3: 'yú',
0x72F8: 'lí,li',
0x72FC: 'láng',
0x7301: 'lì',
0x7303: 'xiǎn',
0x7307: 'xiāo',
0x730E: 'liè',
0x7315: 'mí',
0x7316: 'chāng',
0x7317: 'yī',
0x731B: 'měng',
0x731C: 'cāi',
0x731D: 'cù',
0x731E: 'shē',
0x7322: 'hú',
0x7325: 'wěi',
0x7329: 'xīng,xing',
0x732A: 'zhū',
0x732B: 'māo,máo',
0x732C: 'wei',
0x732E: 'xiàn',
0x7333: 'jiā',
0x7334: 'hóu',
0x7335: 'piàn',
0x7338: 'méi',
0x733E: 'huá',
0x733F: 'yuán',
0x7350: 'zhāng',
0x7352: 'áo',
0x7355: 'cuī',
0x7357: 'jué',
0x7359: 'bì',
0x7360: 'liáo',
0x736C: 'xiè',
0x736D: 'tǎ',
0x736F: 'xūn',
0x7374: 'měng',
0x737E: 'huān',
0x7383: 'jué',
0x7384: 'xuán',
0x7387: 'lǜ,shuài',
0x7389: 'yù',
0x738B: 'wáng,wang',
0x738E: 'dīng',
0x7391: 'jī',
0x7393: 'dì',
0x7397: 'yú',
0x739B: 'mǎ',
0x739F: 'wén',
0x73A1: 'yá',
0x73A2: 'fēn',
0x73A6: 'jué',
0x73A9: 'wán',
0x73AB: 'méi',
0x73AE: 'wěi',
0x73AF: 'huán,huan',
0x73B0: 'xiàn',
0x73B2: 'líng',
0x73B3: 'dài',
0x73B7: 'diàn',
0x73BA: 'xǐ',
0x73BB: 'bō',
0x73C0: 'pò',
0x73C2: 'kē',
0x73C5: 'shēn',
0x73C8: 'jiā',
0x73C9: 'mín',
0x73CA: 'shān',
0x73CD: 'zhēn',
0x73D0: 'fà',
0x73D1: 'lóng',
0x73D3: 'jiào',
0x73D9: 'gǒng',
0x73DE: 'luò',
0x73E0: 'zhū',
0x73E3: 'xún',
0x73E5: 'ěr',
0x73E7: 'yáo',
0x73ED: 'bān',
0x73F2: 'hún',
0x7403: 'qiú',
0x7405: 'láng',
0x7406: 'lǐ,li',
0x7409: 'liú',
0x740A: 'yá',
0x7410: 'suǒ',
0x741B: 'chēn',
0x7422: 'zhuó,zuó',
0x7425: 'hǔ',
0x7426: 'qí',
0x742A: 'qí',
0x742E: 'cóng',
0x7433: 'lín',
0x7434: 'qín,qin',
0x7435: 'pí',
0x7436: 'pa,pá',
0x743C: 'qióng',
0x7441: 'mào',
0x7444: 'xuān',
0x7455: 'xiá',
0x7459: 'nǎo',
0x745A: 'hú',
0x745B: 'yīng',
0x745C: 'yú',
0x745E: 'ruì',
0x745F: 'sè',
0x7470: 'guī,gui',
0x7476: 'yáo',
0x7477: 'ài',
0x747E: 'jǐn',
0x7480: 'cuǐ',
0x7483: 'li,lí',
0x7487: 'xuán',
0x748B: 'zhāng',
0x748E: 'yīng',
0x7490: 'lù',
0x749C: 'huáng',
0x749E: 'pú',
0x74A7: 'bì',
0x74A8: 'càn',
0x74BA: 'wèn',
0x74DC: 'guā',
0x74E0: 'hù',
0x74E2: 'piáo',
0x74E3: 'bàn',
0x74E4: 'ráng',
0x74E6: 'wǎ,wà',
0x74EE: 'wèng',
0x74EF: 'ōu',
0x74F4: 'líng',
0x74F6: 'píng',
0x74F7: 'cí',
0x74FF: 'bù',
0x7504: 'zhēn',
0x750D: 'méng',
0x7518: 'gān',
0x751A: 'shèn',
0x751C: 'tián',
0x751F: 'shēng,sheng',
0x7525: 'sheng,shēng',
0x7528: 'yòng,yong',
0x7529: 'shuǎi',
0x752A: 'lù',
0x752B: 'fǔ,fu',
0x752C: 'yǒng',
0x7530: 'tián',
0x7531: 'yóu',
0x7532: 'jiǎ,jia',
0x7533: 'shēn',
0x7534: 'zhá',
0x7535: 'diàn',
0x7537: 'nán',
0x7538: 'diàn',
0x753A: 'tǐng,dīng',
0x753B: 'huà,hua',
0x753E: 'zāi',
0x7545: 'chàng',
0x754B: 'tián',
0x754C: 'jiè,gà',
0x754F: 'wèi',
0x7551: 'tián',
0x7554: 'pàn',
0x7559: 'liú',
0x755A: 'běn',
0x755B: 'zhěn',
0x755C: 'chù,xù',
0x7565: 'lüè',
0x7566: 'qí',
0x756A: 'fān,pān',
0x7572: 'yú,shē',
0x7574: 'chóu',
0x7578: 'jī',
0x7579: 'wǎn',
0x757F: 'jī',
0x7586: 'jiāng',
0x758F: 'shū',
0x7591: 'yí',
0x7594: 'dīng',
0x7596: 'jiē',
0x7597: 'liáo,liǎo',
0x7599: 'gē',
0x759A: 'jiù',
0x759D: 'shàn',
0x759F: 'nüè,yào',
0x75A0: 'lì',
0x75A1: 'yáng',
0x75A3: 'yóu',
0x75A4: 'bā',
0x75A5: 'jiè',
0x75AB: 'yì',
0x75AC: 'lì',
0x75AD: 'zòng',
0x75AE: 'chuāng',
0x75AF: 'fēng,feng',
0x75B1: 'pào',
0x75B2: 'pí',
0x75B4: 'kē',
0x75B5: 'cī',
0x75B8: 'dǎn,da',
0x75B9: 'zhěn',
0x75BC: 'téng',
0x75BD: 'jū',
0x75BE: 'jí,ji',
0x75C2: 'jiā',
0x75C5: 'bìng,bing',
0x75C7: 'zhèng,zhēng',
0x75C8: 'yōng',
0x75C9: 'jìng',
0x75CA: 'quán',
0x75CD: 'yí',
0x75D2: 'yǎng,yang',
0x75D4: 'zhì',
0x75D5: 'hén',
0x75D8: 'dòu',
0x75DB: 'tòng,tong',
0x75DE: 'pǐ',
0x75E2: 'lì',
0x75E3: 'zhì',
0x75E4: 'cuó',
0x75E6: 'wù',
0x75E7: 'shā',
0x75E8: 'láo',
0x75EA: 'huàn',
0x75EB: 'xián',
0x75F0: 'tán',
0x75F1: 'fèi',
0x75F2: 'má',
0x75F4: 'chī',
0x75F9: 'bì',
0x75FC: 'gù',
0x75FF: 'wěi',
0x7600: 'yū',
0x7601: 'cuì',
0x7605: 'dàn',
0x7606: 'shèn',
0x760A: 'hóu',
0x7610: 'yǔ',
0x7618: 'lòu',
0x7619: 'sào',
0x761B: 'chì',
0x761C: 'xī',
0x761F: 'wēn',
0x7620: 'jí',
0x7622: 'bān',
0x7624: 'liú',
0x7626: 'shòu',
0x7629: 'da',
0x762A: 'biě,biē',
0x762B: 'tān',
0x7630: 'luǒ',
0x7634: 'zhàng',
0x7638: 'qué',
0x763E: 'yǐn',
0x7640: 'huáng',
0x7643: 'lóng',
0x764C: 'ái',
0x7654: 'yì',
0x7656: 'pǐ',
0x765C: 'diàn',
0x765E: 'lài',
0x7663: 'xuǎn',
0x766B: 'diān',
0x766F: 'qú',
0x7678: 'guǐ',
0x767B: 'dēng',
0x767D: 'bái,bai',
0x767E: 'bǎi,bò',
0x7680: 'bī',
0x7682: 'zào',
0x7684: 'de,dì,dī,dí',
0x7686: 'jiē',
0x7687: 'huáng',
0x7688: 'guī',
0x768B: 'gāo',
0x768C: 'mò',
0x768E: 'jiǎo',
0x7691: 'ái',
0x7692: 'é',
0x7693: 'hào',
0x7696: 'wǎn',
0x7699: 'xī',
0x76AE: 'pí,pi',
0x76B1: 'zhòu',
0x76B4: 'cūn',
0x76BF: 'mǐn',
0x76C2: 'yú',
0x76C5: 'zhōng',
0x76C6: 'pén',
0x76C8: 'yíng',
0x76CA: 'yì',
0x76CE: 'àng',
0x76CF: 'zhǎn',
0x76D0: 'yán',
0x76D1: 'jiān,jiàn',
0x76D2: 'hé',
0x76D4: 'kuī',
0x76D6: 'gài,gě,gai',
0x76D7: 'dào',
0x76D8: 'pán',
0x76DB: 'shèng,chéng',
0x76DF: 'méng',
0x76E5: 'guàn',
0x76EE: 'mù,mu',
0x76EF: 'dīng',
0x76F1: 'xū',
0x76F2: 'máng,mang',
0x76F4: 'zhí',
0x76F8: 'xiāng,xiàng',
0x76F9: 'dǔn',
0x76FC: 'pàn',
0x76FE: 'dùn',
0x7701: 'shěng,xǐng,sheng',
0x7704: 'miàn,miǎn',
0x7707: 'miǎo',
0x7708: 'dān',
0x7709: 'méi',
0x770B: 'kàn,kān,kan',
0x770D: 'kōu',
0x7719: 'yí',
0x771F: 'zhēn',
0x7720: 'mián',
0x7726: 'zì',
0x7728: 'zhǎ',
0x7729: 'xuàn',
0x772C: 'lóng',
0x772F: 'mī,mi',
0x7733: 'míng',
0x7735: 'chī',
0x7736: 'kuàng',
0x7737: 'juàn',
0x7738: 'móu',
0x773A: 'tiào',
0x773C: 'yǎn,yan',
0x773D: 'mò',
0x7740: 'zhe,zhuó,zháo,zhāo',
0x7741: 'zhēng',
0x7743: 'suō',
0x7747: 'dì',
0x7750: 'lài',
0x7751: 'jiǎn',
0x7752: 'shǎn',
0x775A: 'yá',
0x775B: 'jīng,jing',
0x7761: 'shuì',
0x7762: 'suī',
0x7763: 'dū',
0x7765: 'bì',
0x7766: 'mù',
0x7768: 'nì',
0x776A: 'gāo',
0x776B: 'jié',
0x776C: 'cǎi',
0x7779: 'dǔ',
0x777A: 'hóu',
0x777D: 'kuí',
0x777E: 'gāo',
0x777F: 'ruì',
0x7780: 'mào',
0x7784: 'miáo,miào',
0x7785: 'chǒu',
0x7788: 'wěng',
0x778B: 'chēn',
0x778C: 'kē',
0x778E: 'xiā',
0x7791: 'míng',
0x7792: 'mán',
0x7793: 'fèn',
0x77A0: 'chēng',
0x77A5: 'piē',
0x77A7: 'qiáo',
0x77A9: 'zhǔ',
0x77AA: 'dèng',
0x77AC: 'shùn',
0x77AD: 'liào',
0x77B0: 'kàn',
0x77B3: 'tóng',
0x77BB: 'zhān',
0x77BD: 'gǔ',
0x77BF: 'qú',
0x77CD: 'jué',
0x77D7: 'chù',
0x77DB: 'máo',
0x77DC: 'jīn',
0x77E2: 'shǐ',
0x77E3: 'yǐ',
0x77E5: 'zhī',
0x77E9: 'jǔ,ju',
0x77EB: 'jiǎo,jiáo',
0x77EC: 'cuó',
0x77ED: 'duǎn',
0x77EE: 'ǎi',
0x77F3: 'shí,dàn,shī',
0x77F6: 'jī',
0x77F8: 'gān',
0x77FB: 'kū',
0x77FD: 'xī',
0x77FE: 'fán',
0x77FF: 'kuàng',
0x7800: 'dàng',
0x7801: 'mǎ',
0x7802: 'shā',
0x780C: 'qì,qiè',
0x780D: 'kǎn',
0x7812: 'pī',
0x7814: 'yán',
0x7816: 'zhuān',
0x7817: 'chē',
0x781A: 'yàn',
0x781D: 'fǎ',
0x7822: 'kē',
0x7823: 'tuó',
0x7825: 'dǐ',
0x7827: 'zhēn',
0x782C: 'lá',
0x782D: 'biān',
0x7830: 'pēng',
0x7834: 'pò',
0x7837: 'shēn',
0x7838: 'zá',
0x783A: 'lì',
0x783B: 'lóng',
0x783E: 'lì',
0x7840: 'chǔ',
0x7845: 'guī',
0x7847: 'náo',
0x7850: 'dòng',
0x7855: 'shuò',
0x7859: 'ái,wéi',
0x785A: 'qiáo',
0x785D: 'xiāo',
0x786A: 'wò',
0x786B: 'liú',
0x786C: 'yìng',
0x786E: 'què',
0x7877: 'jiǎn',
0x787C: 'péng',
0x7881: 'jī',
0x7887: 'dìng',
0x7889: 'diāo',
0x788C: 'lù,lu,liù',
0x788D: 'ài',
0x788E: 'suì',
0x7891: 'bēi',
0x7897: 'wǎn',
0x7898: 'diǎn',
0x789A: 'bèi',
0x789B: 'qì',
0x789C: 'chen',
0x789F: 'dié',
0x78A1: 'zhou',
0x78A3: 'jié',
0x78A7: 'bì',
0x78B0: 'pèng',
0x78B1: 'jiǎn',
0x78B3: 'tàn',
0x78B4: 'chá,chā',
0x78BE: 'niǎn',
0x78C1: 'cí',
0x78C5: 'bàng,páng',
0x78CA: 'lěi',
0x78CB: 'cuō',
0x78D0: 'pán',
0x78D5: 'kē,kè,ke',
0x78D9: 'gǔn',
0x78E1: 'kàn',
0x78E8: 'mó,mò,mo',
0x78EC: 'qìng',
0x78F2: 'qú',
0x78F4: 'dèng',
0x78F7: 'lín',
0x78FA: 'huáng',
0x7901: 'jiāo',
0x790C: 'lèi',
0x7913: 'jiāng',
0x791C: 'yù',
0x7924: 'cǎ',
0x7934: 'bó',
0x793A: 'shì,shi',
0x793C: 'lǐ',
0x793E: 'shè',
0x7940: 'sì',
0x7941: 'qí',
0x7946: 'xiān',
0x7947: 'qí',
0x7948: 'qí',
0x7949: 'zhǐ',
0x7950: 'yòu',
0x7953: 'fú',
0x7956: 'zǔ',
0x795A: 'zuò',
0x795B: 'qū',
0x795C: 'hù',
0x795D: 'zhù',
0x795E: 'shén,shen',
0x795F: 'suì',
0x7960: 'cí',
0x7965: 'xiáng',
0x7968: 'piào',
0x796D: 'jì',
0x796F: 'zhēn',
0x7977: 'dǎo',
0x7978: 'huò',
0x797A: 'qí',
0x7980: 'bǐng',
0x7981: 'jìn,jīn',
0x7984: 'lù',
0x7985: 'chán,shàn',
0x798A: 'xì',
0x798F: 'fú',
0x799B: 'zhēn',
0x79A7: 'xǐ',
0x79B3: 'ráng',
0x79B9: 'yǔ',
0x79BA: 'yú',
0x79BB: 'lí',
0x79BD: 'qín',
0x79BE: 'hé',
0x79C0: 'xiù',
0x79C1: 'sī',
0x79C3: 'tū',
0x79C6: 'gǎn',
0x79C9: 'bǐng',
0x79CB: 'qiū',
0x79CD: 'zhǒng,zhòng',
0x79D1: 'kē',
0x79D2: 'miǎo',
0x79D5: 'bǐ',
0x79D8: 'mì,bì',
0x79DF: 'zū',
0x79E3: 'mò',
0x79E4: 'chèng',
0x79E6: 'qín',
0x79E7: 'yāng',
0x79E9: 'zhì',
0x79EB: 'shú',
0x79ED: 'zǐ',
0x79EF: 'jī,ji',
0x79F0: 'chēng,chèn,chèng',
0x79F8: 'jiē',
0x79FB: 'yí',
0x79FD: 'huì',
0x7A00: 'xī',
0x7A02: 'láng',
0x7A03: 'fū',
0x7A0B: 'chéng',
0x7A0D: 'shāo,shào',
0x7A0E: 'shuì',
0x7A14: 'rěn',
0x7A17: 'bài',
0x7A19: 'zhí',
0x7A1A: 'zhì',
0x7A1E: 'kē',
0x7A20: 'chóu',
0x7A23: 'sū',
0x7A28: 'biǎn',
0x7A33: 'wěn',
0x7A37: 'jì',
0x7A3B: 'dào',
0x7A3C: 'jia,jià',
0x7A3D: 'jī,qǐ',
0x7A3F: 'gǎo',
0x7A46: 'mù',
0x7A51: 'sè',
0x7A57: 'suì',
0x7A70: 'ráng',
0x7A74: 'xué',
0x7A76: 'jiū,jiu',
0x7A77: 'qióng',
0x7A78: 'xī',
0x7A79: 'qióng',
0x7A7A: 'kōng,kòng',
0x7A7F: 'chuān',
0x7A80: 'zhūn',
0x7A81: 'tū',
0x7A83: 'qiè',
0x7A84: 'zhǎi',
0x7A85: 'yǎo',
0x7A88: 'yǎo',
0x7A8D: 'qiào',
0x7A91: 'yáo',
0x7A92: 'zhì',
0x7A95: 'tiǎo',
0x7A96: 'jiào',
0x7A97: 'chuāng',
0x7A98: 'jiǒng',
0x7A9C: 'cuàn',
0x7A9D: 'wō,wo',
0x7A9F: 'kū',
0x7AA0: 'kē',
0x7AA3: 'sù',
0x7AA5: 'kuī',
0x7AA6: 'dòu',
0x7AA8: 'yìn',
0x7AB3: 'yǔ',
0x7AB8: 'xī',
0x7ABE: 'kuǎn',
0x7ABF: 'lóng,long',
0x7ACB: 'lì',
0x7AD6: 'shù,shu',
0x7AD9: 'zhàn',
0x7ADE: 'jìng',
0x7ADF: 'jìng',
0x7AE0: 'zhāng',
0x7AE3: 'jùn',
0x7AE5: 'tóng',
0x7AE6: 'sǒng',
0x7AED: 'jié',
0x7AEF: 'duān',
0x7AF9: 'zhú',
0x7AFA: 'zhú',
0x7AFD: 'yú',
0x7AFF: 'gān',
0x7B03: 'dǔ',
0x7B04: 'jī',
0x7B06: 'bā,ba',
0x7B08: 'jí',
0x7B0A: 'zhào',
0x7B0B: 'sǔn',
0x7B11: 'xiào',
0x7B14: 'bǐ',
0x7B19: 'shēng',
0x7B1B: 'dí',
0x7B1E: 'chī',
0x7B20: 'lì',
0x7B24: 'tiáo',
0x7B25: 'sì',
0x7B26: 'fú',
0x7B28: 'bèn',
0x7B2B: 'zǐ',
0x7B2C: 'dì',
0x7B3A: 'jiān',
0x7B3C: 'lóng,lǒng',
0x7B40: 'guì',
0x7B45: 'xiǎn',
0x7B49: 'děng',
0x7B4A: 'jiǎo',
0x7B4B: 'jīn',
0x7B4C: 'quán',
0x7B4F: 'fá',
0x7B50: 'kuāng',
0x7B51: 'zhù',
0x7B52: 'tǒng,tong',
0x7B54: 'dá,dā,da',
0x7B55: 'háng',
0x7B56: 'cè',
0x7B5A: 'bì',
0x7B5B: 'shāi',
0x7B5C: 'dāng',
0x7B5D: 'zhēng',
0x7B60: 'yún',
0x7B62: 'pá',
0x7B6E: 'shì',
0x7B72: 'shāo',
0x7B75: 'yán',
0x7B77: 'kuài',
0x7B79: 'chóu',
0x7B7C: 'yún',
0x7B7E: 'qiān',
0x7B80: 'jiǎn',
0x7B8D: 'gū',
0x7B90: 'qìng',
0x7B93: 'lù',
0x7B94: 'bó',
0x7B95: 'jī',
0x7B97: 'suàn',
0x7B9C: 'kōng',
0x7BA1: 'guǎn',
0x7BA7: 'qiè',
0x7BA9: 'luó',
0x7BAA: 'dān',
0x7BAB: 'xiāo',
0x7BAD: 'jiàn',
0x7BB1: 'xiāng',
0x7BB4: 'zhēn',
0x7BB8: 'zhù',
0x7BC6: 'zhuàn',
0x7BC7: 'piān',
0x7BCC: 'hóu',
0x7BD1: 'kuì',
0x7BD3: 'lǒu',
0x7BD6: 'táng',
0x7BD9: 'gāo',
0x7BDD: 'gōu',
0x7BE1: 'cuàn',
0x7BE5: 'lì',
0x7BE6: 'bì',
0x7BEA: 'chí',
0x7BEE: 'lán',
0x7BF1: 'lí,li',
0x7BF7: 'péng,peng',
0x7BFE: 'miè',
0x7C07: 'cù',
0x7C09: 'zào',
0x7C0C: 'sù',
0x7C15: 'lè',
0x7C27: 'huáng',
0x7C2A: 'zān',
0x7C38: 'bǒ,bò',
0x7C3F: 'bù',
0x7C40: 'zhòu',
0x7C41: 'lài',
0x7C4D: 'jí',
0x7C73: 'mǐ,mi',
0x7C7B: 'lèi',
0x7C7C: 'xiān',
0x7C7D: 'zǐ',
0x7C89: 'fěn',
0x7C91: 'bā',
0x7C92: 'lì',
0x7C95: 'pò',
0x7C97: 'cū',
0x7C98: 'nián,zhān',
0x7C9D: 'lì',
0x7C9F: 'sù',
0x7CA4: 'yuè',
0x7CA5: 'zhōu,yù',
0x7CAA: 'fèn',
0x7CAE: 'liáng',
0x7CB1: 'liáng',
0x7CB2: 'càn',
0x7CB3: 'jīng',
0x7CB9: 'cuì',
0x7CBC: 'lín',
0x7CBD: 'zòng',
0x7CBE: 'jīng,jing',
0x7CBF: 'guǒ',
0x7CC1: 'sǎn',
0x7CC5: 'róu',
0x7CCA: 'hú,hu,hū,hù',
0x7CCC: 'zān',
0x7CCD: 'cí',
0x7CD5: 'gāo',
0x7CD6: 'táng',
0x7CD7: 'qiǔ',
0x7CD9: 'cāo',
0x7CDC: 'mí',
0x7CDF: 'zāo',
0x7CE0: 'kāng',
0x7CE2: 'mó',
0x7CE8: 'jiàng',
0x7CEC: 'shǔ',
0x7CEF: 'nuò',
0x7CFB: 'xì,xi,jì',
0x7D0A: 'wěn',
0x7D20: 'sù',
0x7D22: 'suǒ,suo',
0x7D27: 'jǐn',
0x7D2B: 'zǐ',
0x7D2F: 'lěi,lèi,léi',
0x7D4D: 'rèn',
0x7D58: 'cì',
0x7D5C: 'xié',
0x7D6E: 'xù,xu',
0x7DA6: 'qí',
0x7DB7: 'cuì',
0x7E29: 'cài',
0x7E41: 'fán',
0x7E47: 'yóu,yáo',
0x7E82: 'zuǎn',
0x7EA0: 'jiū',
0x7EA2: 'hóng,gōng',
0x7EA3: 'zhòu',
0x7EA4: 'xiān,qiàn',
0x7EA5: 'hé',
0x7EA6: 'yuē,yāo,yuè',
0x7EA7: 'jí',
0x7EA8: 'wán',
0x7EAA: 'jì',
0x7EAB: 'rèn',
0x7EAC: 'wěi',
0x7EAD: 'yún',
0x7EAF: 'chún',
0x7EB0: 'pī',
0x7EB1: 'shā',
0x7EB2: 'gāng',
0x7EB3: 'nà',
0x7EB4: 'rèn',
0x7EB5: 'zòng',
0x7EB6: 'lún',
0x7EB7: 'fēn',
0x7EB8: 'zhǐ',
0x7EB9: 'wén',
0x7EBA: 'fǎng',
0x7EBD: 'niǔ',
0x7EBE: 'shū',
0x7EBF: 'xiàn',
0x7EC0: 'gàn',
0x7EC2: 'fú',
0x7EC3: 'liàn',
0x7EC4: 'zǔ',
0x7EC5: 'shēn',
0x7EC6: 'xì,xi',
0x7EC7: 'zhī',
0x7EC8: 'zhōng',
0x7EC9: 'zhōu,zhòu',
0x7ECA: 'bàn',
0x7ECB: 'fú',
0x7ECC: 'chù',
0x7ECD: 'shào',
0x7ECE: 'yì',
0x7ECF: 'jīng',
0x7ED1: 'bǎng',
0x7ED2: 'róng',
0x7ED3: 'jié,jiē,jie',
0x7ED4: 'kù',
0x7ED5: 'rào',
0x7ED7: 'háng',
0x7ED8: 'huì',
0x7ED9: 'gěi,jǐ',
0x7EDA: 'xuàn',
0x7EDB: 'jiàng',
0x7EDC: 'luò',
0x7EDD: 'jué',
0x7EDE: 'jiǎo',
0x7EDF: 'tǒng',
0x7EE2: 'juàn',
0x7EE3: 'xiù',
0x7EE5: 'suí',
0x7EE6: 'tāo,dí',
0x7EE7: 'jì',
0x7EE9: 'jì',
0x7EEA: 'xù',
0x7EED: 'xù',
0x7EEE: 'qǐ',
0x7EEF: 'fēi',
0x7EF0: 'chuò',
0x7EF2: 'gǔn',
0x7EF3: 'shéng',
0x7EF4: 'wéi,wei',
0x7EF5: 'mián',
0x7EF6: 'shòu',
0x7EF7: 'bēng,bèng,běng',
0x7EF8: 'chóu',
0x7EFA: 'liǔ',
0x7EFB: 'quǎn',
0x7EFC: 'zōng',
0x7EFD: 'zhàn',
0x7EFF: 'lǜ,lù',
0x7F00: 'zhuì,chuò',
0x7F02: 'kè',
0x7F04: 'jiān',
0x7F05: 'miǎn',
0x7F06: 'lǎn',
0x7F08: 'miǎo',
0x7F09: 'jī',
0x7F0E: 'duàn',
0x7F13: 'huǎn',
0x7F14: 'dì',
0x7F15: 'lǚ',
0x7F16: 'biān',
0x7F18: 'yuán',
0x7F19: 'jìn',
0x7F1A: 'fù',
0x7F1B: 'rù',
0x7F1C: 'zhěn',
0x7F1D: 'fèng,féng,feng',
0x7F1F: 'gǎo',
0x7F20: 'chán,chan',
0x7F21: 'lí',
0x7F22: 'yì',
0x7F24: 'bīn',
0x7F25: 'piǎo',
0x7F26: 'màn',
0x7F28: 'yīng',
0x7F29: 'suō',
0x7F2A: 'miù,móu',
0x7F2C: 'xié',
0x7F2D: 'liáo',
0x7F2E: 'shàn',
0x7F30: 'jiāng',
0x7F31: 'qiǎn',
0x7F33: 'huán',
0x7F34: 'jiǎo',
0x7F36: 'fǒu',
0x7F38: 'gāng,gang',
0x7F3A: 'quē',
0x7F42: 'yīng',
0x7F44: 'qìng',
0x7F45: 'xià',
0x7F4D: 'léi',
0x7F50: 'guàn',
0x7F51: 'wǎng',
0x7F54: 'wǎng',
0x7F55: 'hǎn,han',
0x7F57: 'luó,luō,luo',
0x7F58: 'fú',
0x7F5A: 'fá',
0x7F5F: 'gǔ',
0x7F61: 'gāng',
0x7F62: 'bà',
0x7F69: 'zhào',
0x7F6A: 'zuì,zui',
0x7F6E: 'zhì,zhi',
0x7F72: 'shǔ',
0x7F74: 'pí',
0x7F79: 'lí',
0x7F7E: 'zēng',
0x7F81: 'jī',
0x7F8A: 'yáng',
0x7F8C: 'qiāng',
0x7F8E: 'měi,mǎi',
0x7F94: 'gāo',
0x7F9A: 'líng',
0x7F9D: 'dī',
0x7F9E: 'xiū',
0x7F9F: 'qiǎng',
0x7FA1: 'xiàn',
0x7FA4: 'qún',
0x7FA7: 'suō',
0x7FA8: 'xiàn',
0x7FAF: 'jié',
0x7FB1: 'yuán',
0x7FB2: 'xī',
0x7FB8: 'léi',
0x7FB9: 'gēng',
0x7FBC: 'chàn',
0x7FBD: 'yǔ',
0x7FBF: 'yì',
0x7FC1: 'wēng',
0x7FC5: 'chì',
0x7FCC: 'yì',
0x7FCE: 'líng',
0x7FD4: 'xiáng',
0x7FD5: 'xī',
0x7FD8: 'qiào,qiáo',
0x7FDF: 'zhái,dí',
0x7FE0: 'cuì',
0x7FE1: 'fěi',
0x7FE5: 'zhù',
0x7FE6: 'jiǎn',
0x7FE9: 'piān',
0x7FEE: 'hé',
0x7FF0: 'hàn',
0x7FF1: 'áo',
0x7FF3: 'yì',
0x7FFB: 'fān',
0x7FFC: 'yì',
0x8000: 'yào',
0x8001: 'lǎo,lao',
0x8003: 'kǎo',
0x8004: 'mào',
0x8005: 'zhě',
0x8006: 'qí',
0x800B: 'dié',
0x800C: 'ér',
0x800D: 'shuǎ',
0x8010: 'nài',
0x8012: 'lěi',
0x8015: 'gēng,gèng',
0x8017: 'hào',
0x8018: 'yún',
0x8019: 'pá,bà,pā',
0x801C: 'sì',
0x8026: 'ǒu',
0x8032: 'huái',
0x8033: 'ěr',
0x8035: 'dīng',
0x8036: 'yē,yé',
0x8037: 'dā',
0x8038: 'sǒng',
0x803B: 'chǐ',
0x803D: 'dān',
0x803F: 'gěng',
0x8042: 'niè',
0x8043: 'dān',
0x8046: 'líng',
0x804A: 'liáo',
0x804B: 'lóng',
0x804C: 'zhí',
0x804D: 'níng',
0x8052: 'guō',
0x8054: 'lián',
0x8058: 'pìn',
0x805A: 'jù',
0x8069: 'kuì',
0x806A: 'cōng',
0x806F: 'lián',
0x807F: 'yù',
0x8083: 'sù',
0x8084: 'yì',
0x8086: 'sì',
0x8087: 'zhào',
0x8089: 'ròu',
0x808B: 'lèi',
0x808C: 'jī',
0x808F: 'cào',
0x8093: 'huāng',
0x8096: 'xiào,xiāo',
0x8098: 'zhǒu',
0x809A: 'dù,dǔ,du',
0x809B: 'gāng',
0x809D: 'gān',
0x80A0: 'cháng,chang',
0x80A1: 'gǔ,gu',
0x80A2: 'zhī,zhi',
0x80A4: 'fū',
0x80A5: 'féi',
0x80A9: 'jiān',
0x80AA: 'fáng',
0x80AD: 'nà',
0x80AE: 'āng',
0x80AF: 'kěn',
0x80B1: 'gōng',
0x80B2: 'yù',
0x80B4: 'yáo',
0x80BA: 'fèi,fēi',
0x80BD: 'tài',
0x80BE: 'shèn',
0x80BF: 'zhǒng,zhōng',
0x80C0: 'zhàng',
0x80C1: 'xié',
0x80C2: 'shèn',
0x80C3: 'wèi',
0x80C4: 'zhòu',
0x80C6: 'dǎn',
0x80CC: 'bèi,bēi',
0x80CE: 'tāi',
0x80D6: 'pàng,pán',
0x80DA: 'pēi',
0x80DB: 'jiǎ',
0x80DC: 'shèng',
0x80DD: 'zhī',
0x80DE: 'bāo',
0x80E0: 'qū',
0x80E1: 'hú,hu',
0x80E4: 'yìn',
0x80E5: 'xū',
0x80E7: 'lóng,lōng',
0x80E8: 'dòng',
0x80EA: 'lú',
0x80EB: 'jìng',
0x80EC: 'nǔ',
0x80ED: 'yān',
0x80EF: 'kuà',
0x80F0: 'yí',
0x80F1: 'guāng',
0x80F3: 'gē,gé,gā',
0x80F4: 'dòng',
0x80F6: 'jiāo',
0x80F8: 'xiōng',
0x80FA: 'àn',
0x80FC: 'pián',
0x80FD: 'néng',
0x8102: 'zhī,zhǐ',
0x8106: 'cuì',
0x8109: 'mài,mò',
0x810A: 'jǐ,jí,ji',
0x810D: 'kuài',
0x810F: 'zāng,zàng',
0x8110: 'qí',
0x8111: 'nǎo',
0x8113: 'nóng',
0x8114: 'luán',
0x8116: 'bó',
0x811A: 'jiǎo,jiao',
0x8129: 'xiū',
0x812C: 'pāo',
0x812F: 'pú,fǔ',
0x8131: 'tuō',
0x8132: 'niào',
0x8137: 'lì',
0x8138: 'liǎn',
0x813E: 'pí',
0x8146: 'tiǎn',
0x8148: 'jīng',
0x814A: 'là',
0x814B: 'yè',
0x814C: 'yān,ā',
0x8150: 'fǔ,fu',
0x8151: 'fǔ',
0x8153: 'féi',
0x8154: 'qiāng',
0x8155: 'wàn',
0x8158: 'guó',
0x815A: 'dìng',
0x8165: 'xīng',
0x8167: 'shù',
0x8169: 'nǎn',
0x816D: 'è',
0x816E: 'sāi',
0x8170: 'yāo',
0x8171: 'jiàn',
0x8174: 'yú',
0x8179: 'fù',
0x817A: 'xiàn',
0x817B: 'nì',
0x817C: 'tiǎn,miǎn',
0x817D: 'wà',
0x817E: 'téng,teng',
0x817F: 'tuǐ',
0x8180: 'bǎng,páng,bàng',
0x8182: 'lǚ',
0x8188: 'gé,gè',
0x818A: 'bó,bo',
0x818F: 'gāo,gào',
0x8191: 'bìn',
0x8198: 'biāo',
0x819B: 'táng',
0x819C: 'mó',
0x819D: 'xī',
0x81A8: 'péng',
0x81AA: 'chuài',
0x81B2: 'jiāo',
0x81B3: 'shàn',
0x81BA: 'yīng',
0x81BB: 'shān',
0x81C0: 'tún',
0x81C2: 'bì,bei',
0x81C3: 'yōng',
0x81C6: 'yì',
0x81CA: 'sào,sāo',
0x81CC: 'gǔ',
0x81DC: 'zā',
0x81E3: 'chén',
0x81E7: 'zāng',
0x81EA: 'zì,zi,zī',
0x81EC: 'niè',
0x81ED: 'chòu,xiù',
0x81F2: 'niè',
0x81F3: 'zhì',
0x81F4: 'zhì,zhi',
0x81FB: 'zhēn',
0x81FC: 'jiù',
0x81FE: 'yú',
0x8200: 'yǎo',
0x8202: 'chōng',
0x8204: 'xì',
0x8205: 'jiù,jiu',
0x8206: 'yú',
0x820C: 'shé,jī',
0x820D: 'shè,shě',
0x8210: 'shì',
0x8212: 'shū,shu',
0x8214: 'tiǎn',
0x821B: 'chuǎn',
0x821C: 'shùn',
0x821E: 'wǔ',
0x821F: 'zhōu',
0x8222: 'shān',
0x8228: 'bǎn',
0x822A: 'háng',
0x822B: 'fǎng',
0x822C: 'bān,pán,bō',
0x8230: 'jiàn',
0x8231: 'cāng',
0x8232: 'líng',
0x8235: 'duò',
0x8236: 'bó',
0x8237: 'xián',
0x8239: 'chuán',
0x823A: 'jiǎ',
0x8244: 'shāo',
0x8245: 'yú',
0x8247: 'tǐng',
0x824B: 'měng',
0x824E: 'huáng',
0x824F: 'shǒu',
0x825F: 'chōng',
0x8268: 'méng',
0x826E: 'gèn,gěn',
0x826F: 'liáng',
0x8270: 'jiān',
0x8272: 'sè,shǎi',
0x8273: 'yàn',
0x827A: 'yì',
0x827B: 'lè',
0x827D: 'jiāo',
0x827E: 'ài,yì',
0x827F: 'nǎi',
0x8282: 'jié,jiē,jie',
0x828A: 'qiān',
0x828B: 'yù',
0x828D: 'sháo,què',
0x828E: 'xiōng,qiōng',
0x828F: 'dù',
0x8291: 'qǐ',
0x8292: 'máng',
0x8297: 'xiāng',
0x8299: 'fú',
0x829C: 'wú',
0x829D: 'zhī',
0x82A1: 'qiàn',
0x82A5: 'jiè,gài',
0x82A6: 'lú,lu',
0x82AA: 'qí',
0x82AB: 'yuán,yán',
0x82AC: 'fēn',
0x82AD: 'bā',
0x82AE: 'ruì',
0x82AF: 'xīn',
0x82B1: 'huā,hua',
0x82B3: 'fāng',
0x82B7: 'zhǐ',
0x82B8: 'yún',
0x82B9: 'qín',
0x82BD: 'yá',
0x82BE: 'fú,fèi',
0x82C4: 'biàn',
0x82C7: 'wěi',
0x82CB: 'xiàn',
0x82CC: 'cháng',
0x82CD: 'cāng',
0x82CE: 'zhù',
0x82CF: 'sū',
0x82D1: 'yuàn',
0x82D2: 'rǎn',
0x82D3: 'líng',
0x82D4: 'tái',
0x82D5: 'tiáo,sháo',
0x82D7: 'miáo',
0x82D8: 'qǐng',
0x82DB: 'kē',
0x82DC: 'mù',
0x82DE: 'bāo',
0x82DF: 'gǒu',
0x82E1: 'yǐ',
0x82E3: 'jù,qǔ',
0x82E4: 'piě',
0x82E5: 'ruò,rě',
0x82E6: 'kǔ',
0x82E7: 'níng',
0x82EB: 'shān',
0x82EF: 'běn',
0x82F1: 'yīng',
0x82F2: 'zhǎ',
0x82F4: 'jū',
0x82F7: 'gān',
0x82F9: 'píng',
0x82FB: 'fú',
0x8300: 'fú',
0x8301: 'zhuó',
0x8302: 'mào',
0x8303: 'fàn',
0x8304: 'qié,jiā',
0x8305: 'máo',
0x8308: 'cí',
0x8309: 'mò,mo',
0x830C: 'chí',
0x830E: 'jīng',
0x830F: 'lóng',
0x8314: 'yíng',
0x8315: 'qióng',
0x8317: 'míng',
0x831A: 'yìn',
0x831B: 'gèn',
0x831C: 'qiàn,xī',
0x8327: 'jiǎn',
0x8328: 'cí',
0x832B: 'máng',
0x832C: 'chá',
0x832D: 'jiāo',
0x832F: 'fú',
0x8331: 'zhū',
0x8332: 'zī',
0x8333: 'jiāng',
0x8334: 'huí',
0x8335: 'yīn',
0x8336: 'chá',
0x8338: 'róng,rōng',
0x8339: 'rú',
0x833C: 'tóng',
0x8340: 'xún',
0x8343: 'quán',
0x8346: 'jīng',
0x8347: 'xìng',
0x8349: 'cǎo',
0x834F: 'rěn',
0x8350: 'jiàn',
0x8351: 'tí',
0x8352: 'huāng',
0x8354: 'lì',
0x835A: 'jiá',
0x835B: 'ráo',
0x835C: 'bì',
0x835E: 'qiáo',
0x835F: 'huì',
0x8360: 'jì,qí',
0x8361: 'dàng,dang',
0x8363: 'róng',
0x8364: 'hūn,xūn',
0x8365: 'xíng,yíng',
0x8367: 'yíng',
0x8368: 'qián,xún',
0x836B: 'yìn',
0x836C: 'mǎi',
0x836D: 'hóng',
0x836F: 'yào,yao',
0x8377: 'hé,hè,he',
0x8378: 'bí',
0x837B: 'dí',
0x837C: 'tú',
0x837D: 'sui,suī',
0x8385: 'lì',
0x8386: 'pú',
0x8389: 'lì,li',
0x838E: 'shā,suō',
0x8392: 'jǔ',
0x8393: 'méi',
0x8398: 'shēn,xīn',
0x839C: 'yóu',
0x839E: 'guǎn,wǎn',
0x83A0: 'yǒu',
0x83A8: 'làng',
0x83A9: 'piǎo',
0x83AA: 'é',
0x83AB: 'mò,mo',
0x83B0: 'kǎn',
0x83B1: 'lái',
0x83B2: 'lián',
0x83B3: 'shí',
0x83B4: 'wō',
0x83B7: 'huò',
0x83B8: 'yóu',
0x83B9: 'yíng,yīng',
0x83BA: 'yīng',
0x83BC: 'chún',
0x83BD: 'mǎng',
0x83BF: 'cì',
0x83C0: 'wǎn',
0x83C1: 'jīng,jing',
0x83C5: 'jiān',
0x83C7: 'gū,gu',
0x83CA: 'jú',
0x83CC: 'jūn,jùn',
0x83CF: 'hé',
0x83D4: 'fú',
0x83D6: 'chāng',
0x83D8: 'sōng',
0x83DC: 'cài',
0x83DF: 'tù',
0x83E0: 'bō',
0x83E5: 'xī',
0x83E9: 'pú',
0x83EA: 'dàng',
0x83F0: 'gū,gu',
0x83F1: 'líng',
0x83F2: 'fēi,fěi',
0x83F4: 'ān',
0x83F8: 'yān',
0x83F9: 'zū',
0x83FD: 'shū',
0x83FE: 'tián',
0x8401: 'qí',
0x8403: 'cuì',
0x8404: 'tao,táo',
0x840B: 'qī',
0x840C: 'méng',
0x840D: 'píng',
0x840E: 'wěi,wēi',
0x8418: 'nài',
0x841C: 'tiē',
0x841D: 'luó',
0x8423: 'dìng',
0x8424: 'yíng',
0x8425: 'yíng',
0x8426: 'yíng',
0x8427: 'xiāo',
0x8428: 'sà',
0x842E: 'yú',
0x8430: 'liàn',
0x8431: 'xuān',
0x8438: 'yú',
0x8439: 'biān,biǎn',
0x843C: 'è',
0x843D: 'luò,lào,luo,là',
0x8444: 'zuò',
0x8446: 'bǎo',
0x8447: 'róu',
0x844E: 'lǜ',
0x8457: 'zhù,zhuó',
0x8459: 'xiāng',
0x845A: 'shèn',
0x845B: 'gě,gé',
0x8461: 'pú',
0x8463: 'dǒng',
0x8469: 'pā',
0x846B: 'hú',
0x846C: 'zàng',
0x8471: 'cōng',
0x8473: 'wēi',
0x8475: 'kuí',
0x847A: 'qì',
0x8482: 'dì',
0x848B: 'jiǎng',
0x8490: 'sōu',
0x8497: 'làng',
0x8499: 'méng,měng,mēng',
0x849C: 'suàn',
0x849F: 'jǔ',
0x84A1: 'bàng',
0x84AD: 'chú',
0x84B2: 'pú',
0x84B4: 'shuò',
0x84B8: 'zhēng',
0x84BB: 'ruò',
0x84BD: 'ēn',
0x84BF: 'hāo',
0x84C2: 'mì',
0x84C4: 'xù',
0x84C9: 'róng',
0x84CA: 'wěng',
0x84D0: 'rù',
0x84D1: 'suō',
0x84D3: 'bèi',
0x84D6: 'bì',
0x84DD: 'lán,lan',
0x84DF: 'jì',
0x84E0: 'lí',
0x84E3: 'yù',
0x84E5: 'yíng',
0x84E6: 'mò',
0x84EC: 'péng,pēng,peng',
0x84FC: 'liǎo',
0x84FF: 'xu',
0x8511: 'miè',
0x8513: 'màn,mán',
0x8517: 'zhè,zhe',
0x851A: 'wèi,yù',
0x851F: 'cù',
0x8521: 'cài',
0x852B: 'niān',
0x852C: 'shū',
0x8537: 'qiáng',
0x8539: 'liǎn',
0x853A: 'lìn',
0x853B: 'kòu',
0x853C: 'ǎi',
0x853D: 'bì',
0x8543: 'bō,fán,fān',
0x8548: 'xùn',
0x8549: 'jiāo,qiáo',
0x854A: 'ruǐ',
0x8559: 'huì',
0x8560: 'rú',
0x8564: 'ruí',
0x8568: 'jué',
0x8572: 'qí',
0x8574: 'yùn',
0x8579: 'wèng',
0x857A: 'jí',
0x857B: 'hóng',
0x857E: 'lěi',
0x8584: 'bó,báo,bò',
0x8587: 'wēi',
0x858F: 'yì',
0x859B: 'xuē',
0x85AA: 'xīn',
0x85AE: 'sǒu',
0x85AF: 'shǔ',
0x85B0: 'xūn',
0x85B9: 'tái',
0x85C1: 'gǎo',
0x85C9: 'jiè,jí',
0x85CA: 'biǎn',
0x85CF: 'zàng,cáng',
0x85D0: 'miǎo',
0x85D2: 'qiè',
0x85D3: 'xiǎn',
0x85D5: 'ǒu',
0x85D8: 'lǘ',
0x85DC: 'lí',
0x85E0: 'jiào',
0x85E4: 'téng',
0x85E8: 'biāo',
0x85E9: 'fān',
0x85FB: 'zǎo',
0x85FF: 'huò',
0x8605: 'héng',
0x8611: 'mó',
0x8616: 'niè',
0x8618: 'ráng',
0x8627: 'qú',
0x8635: 'zhí',
0x8638: 'zhàn',
0x863C: 'mí',
0x864E: 'hǔ,hu,hū,hù',
0x864F: 'lǔ',
0x8650: 'nüè',
0x8651: 'lǜ',
0x8654: 'qián',
0x865A: 'xū',
0x865E: 'yú',
0x8662: 'guó',
0x866B: 'chóng,chong',
0x866E: 'jǐ',
0x8670: 'dīng',
0x8671: 'shī',
0x8679: 'hóng',
0x867A: 'huǐ',
0x867B: 'méng',
0x867C: 'gè',
0x867D: 'suī',
0x867E: 'xiā,há',
0x8680: 'shí',
0x8681: 'yǐ',
0x8682: 'mǎ,mà,mā',
0x868A: 'wén',
0x868C: 'bàng,bèng',
0x868D: 'pí',
0x8693: 'yǐn',
0x8695: 'cán',
0x8696: 'yuán',
0x869C: 'yá',
0x869D: 'háo',
0x86A3: 'gōng',
0x86A4: 'zǎo,zao',
0x86A7: 'jiè',
0x86A9: 'chī',
0x86AA: 'dǒu',
0x86AF: 'qiū',
0x86B0: 'yóu',
0x86B1: 'zha,zhà',
0x86B4: 'yòu',
0x86B5: 'é,kē',
0x86B6: 'hān',
0x86BA: 'rán',
0x86C0: 'zhù',
0x86C4: 'gū,gǔ',
0x86C6: 'qū',
0x86C7: 'shé,yí',
0x86C9: 'líng',
0x86CA: 'gǔ',
0x86CB: 'dàn',
0x86CE: 'lì',
0x86D0: 'qū,qu',
0x86D4: 'huí',
0x86D9: 'wā',
0x86DB: 'zhū,zhu',
0x86DC: 'yī',
0x86DE: 'kuò',
0x86DF: 'jiāo',
0x86E4: 'gé,há',
0x86ED: 'zhì',
0x86EE: 'mán',
0x86F0: 'zhé',
0x86F1: 'jiá',
0x86F2: 'náo',
0x86F3: 'sī',
0x86F4: 'qí',
0x86F5: 'xíng',
0x86F8: 'shāo,xiāo',
0x86F9: 'yǒng',
0x86FE: 'é',
0x8700: 'shǔ',
0x8702: 'fēng',
0x8703: 'shèn',
0x8707: 'zhé',
0x8708: 'wú',
0x8709: 'fú',
0x870A: 'lí',
0x870D: 'chú',
0x8710: 'jié',
0x8711: 'dàn',
0x8712: 'yán,yan',
0x8713: 'tíng',
0x8715: 'tuì',
0x8717: 'wō',
0x8718: 'zhī',
0x8719: 'sōng',
0x871A: 'fēi,fěi',
0x871C: 'mì',
0x8721: 'là',
0x8722: 'měng',
0x8723: 'qiāng',
0x8725: 'xī',
0x872E: 'yù',
0x8731: 'pí',
0x8734: 'yì',
0x8737: 'quán',
0x873B: 'qīng',
0x873D: 'liǎng',
0x873F: 'wān',
0x8743: 'zhuō',
0x8744: 'wǎng',
0x8747: 'yíng,ying',
0x8748: 'guō,guo',
0x8749: 'chán',
0x874C: 'kē',
0x874E: 'xiē',
0x8750: 'mào',
0x8751: 'xū',
0x8753: 'yú',
0x8757: 'huáng',
0x8759: 'biān',
0x875B: 'wēi',
0x8760: 'fú',
0x8763: 'yóu',
0x8765: 'máo',
0x876E: 'fù',
0x8770: 'kuí',
0x8772: 'là',
0x8773: 'dài',
0x8774: 'hú',
0x8776: 'dié',
0x877C: 'lóu',
0x877D: 'chūn',
0x877E: 'róng',
0x8782: 'láng,lang',
0x8783: 'páng',
0x8785: 'xī',
0x8788: 'yuán',
0x8789: 'wēng',
0x878B: 'sōu',
0x878D: 'róng',
0x879F: 'míng',
0x87A8: 'mǎn',
0x87AB: 'zhē',
0x87AC: 'cáo',
0x87AD: 'chī',
0x87AF: 'áo',
0x87B3: 'táng',
0x87B5: 'piāo',
0x87BA: 'luó',
0x87BD: 'zhōng',
0x87C0: 'shuài',
0x87C6: 'ma,má',
0x87CA: 'máo',
0x87CB: 'xī',
0x87CF: 'xiāo',
0x87D1: 'zhāng',
0x87D2: 'mǎng',
0x87DF: 'liáo',
0x87E0: 'pán',
0x87E2: 'xǐ',
0x87E5: 'huáng',
0x87EA: 'huì',
0x87ED: 'jiāo',
0x87EE: 'shan,shàn',
0x87F9: 'xiè',
0x87FE: 'chán',
0x880A: 'lián',
0x8813: 'měng',
0x8815: 'rú',
0x8816: 'huò',
0x881B: 'miè',
0x8821: 'lǐ',
0x8822: 'chǔn',
0x882E: 'yē',
0x8832: 'juān',
0x8835: 'xī',
0x8839: 'dù',
0x883C: 'qú',
0x8840: 'xuè,xiě,xuě',
0x8845: 'xìn',
0x884C: 'xíng,háng,xing,héng',
0x884D: 'yǎn',
0x8854: 'xián',
0x8857: 'jiē',
0x8859: 'yá',
0x8861: 'héng',
0x8862: 'qú',
0x8863: 'yī,yì',
0x8865: 'bǔ,bu',
0x8868: 'biǎo',
0x8869: 'chǎ,chà',
0x886B: 'shān',
0x886C: 'chèn,chen',
0x886E: 'gǔn',
0x8870: 'shuāi',
0x8877: 'zhōng',
0x887D: 'rèn',
0x887E: 'qīn',
0x8881: 'yuán',
0x8882: 'mèi',
0x8884: 'ǎo',
0x8885: 'niǎo',
0x8888: 'jiā',
0x888B: 'dài,dai',
0x888D: 'páo',
0x8892: 'tǎn',
0x8896: 'xiù',
0x889C: 'wà',
0x88A4: 'mào',
0x88AB: 'bèi',
0x88AD: 'xí',
0x88AF: 'bó',
0x88B1: 'fu,fú',
0x88B4: 'kù',
0x88B7: 'jiá',
0x88BC: 'gē',
0x88C1: 'cái',
0x88C2: 'liè',
0x88C5: 'zhuāng,zhuang',
0x88C6: 'dāng',
0x88CE: 'chéng',
0x88D2: 'póu',
0x88D4: 'yì',
0x88D5: 'yù',
0x88D8: 'qiú',
0x88D9: 'qún',
0x88DF: 'shā',
0x88E2: 'lian',
0x88E3: 'liǎn',
0x88E4: 'kù',
0x88E8: 'bì',
0x88F0: 'duō',
0x88F1: 'biǎo',
0x88F3: 'shang,cháng',
0x88F4: 'péi',
0x88F8: 'luǒ',
0x88F9: 'guǒ,guo',
0x88FC: 'xī',
0x8902: 'guà',
0x890A: 'biǎn',
0x8910: 'hè',
0x8912: 'bāo',
0x8913: 'bǎo',
0x8919: 'bèi',
0x891A: 'chǔ',
0x891B: 'lǚ',
0x891F: 'tā',
0x8921: 'dā',
0x8925: 'rù',
0x892A: 'tuì,tùn',
0x892B: 'chǐ',
0x8934: 'lán',
0x8935: 'lí',
0x8936: 'zhě',
0x8941: 'qiǎng',
0x8944: 'xiāng',
0x895F: 'jīn',
0x896B: 'shì',
0x897B: 'pàn',
0x897F: 'xī,xi',
0x8981: 'yào,yāo',
0x8983: 'tán',
0x8986: 'fù',
0x89C1: 'jiàn,xiàn,jian,jiān',
0x89C2: 'guān,guàn',
0x89C3: 'yàn',
0x89C4: 'guī',
0x89C5: 'mì',
0x89C6: 'shì',
0x89C7: 'chān',
0x89C8: 'lǎn',
0x89C9: 'jué,jiào',
0x89CA: 'jì',
0x89CB: 'xí',
0x89CE: 'yú',
0x89D0: 'jìn',
0x89D1: 'qù',
0x89D2: 'jiǎo,jué',
0x89DA: 'gū',
0x89DC: 'zī,zuǐ',
0x89DE: 'shāng',
0x89E3: 'jiě,xiè,jiè',
0x89E5: 'gōng',
0x89E6: 'chù',
0x89F1: 'bì',
0x89FD: 'xī',
0x8A00: 'yán',
0x8A07: 'hōng',
0x8A3E: 'zǐ',
0x8A48: 'lì',
0x8A5D: 'zhǔ',
0x8A79: 'zhān',
0x8A89: 'yù',
0x8A8A: 'téng',
0x8A93: 'shì',
0x8B66: 'jǐng',
0x8B6C: 'pì',
0x8BA1: 'jì,ji',
0x8BA2: 'dìng',
0x8BA3: 'fù',
0x8BA4: 'rèn',
0x8BA5: 'jī',
0x8BA6: 'jié',
0x8BA7: 'hòng',
0x8BA8: 'tǎo',
0x8BA9: 'ràng',
0x8BAA: 'shàn',
0x8BAB: 'qì',
0x8BAD: 'xùn,xun',
0x8BAE: 'yì',
0x8BAF: 'xùn',
0x8BB0: 'jì,ji',
0x8BB2: 'jiǎng',
0x8BB3: 'huì,hui',
0x8BB4: 'ōu',
0x8BB6: 'yà',
0x8BB7: 'nè',
0x8BB8: 'xǔ',
0x8BB9: 'é',
0x8BBA: 'lùn,lún',
0x8BBC: 'sòng',
0x8BBD: 'fěng',
0x8BBE: 'shè,she',
0x8BBF: 'fǎng',
0x8BC0: 'jué',
0x8BC1: 'zhèng',
0x8BC2: 'gǔ',
0x8BC3: 'hē',
0x8BC4: 'píng',
0x8BC5: 'zǔ',
0x8BC6: 'shí,shi,zhì,shì',
0x8BC8: 'zhà',
0x8BC9: 'sù,su',
0x8BCA: 'zhěn',
0x8BCB: 'dǐ',
0x8BCC: 'zhōu',
0x8BCD: 'cí',
0x8BCF: 'zhào',
0x8BD1: 'yì',
0x8BD2: 'yí',
0x8BD3: 'kuāng',
0x8BD5: 'shì',
0x8BD7: 'shī',
0x8BD8: 'jié',
0x8BD9: 'huī',
0x8BDA: 'chéng',
0x8BDB: 'zhū',
0x8BDD: 'huà,hua',
0x8BDE: 'dàn',
0x8BDF: 'gòu',
0x8BE0: 'quán',
0x8BE1: 'guǐ',
0x8BE2: 'xún',
0x8BE3: 'yì',
0x8BE4: 'zhèng',
0x8BE5: 'gāi',
0x8BE6: 'xiáng,xiang',
0x8BE7: 'chà',
0x8BE8: 'hùn',
0x8BE9: 'xǔ',
0x8BEB: 'jiè',
0x8BEC: 'wū',
0x8BED: 'yǔ,yu',
0x8BEE: 'qiào',
0x8BEF: 'wù,wu',
0x8BF1: 'yòu',
0x8BF2: 'huì',
0x8BF3: 'kuáng',
0x8BF4: 'shuō,shuì,shuo',
0x8BF5: 'sòng',
0x8BF6: 'ēi',
0x8BF7: 'qǐng',
0x8BF8: 'zhū',
0x8BFA: 'nuò',
0x8BFB: 'dú,dòu',
0x8BFD: 'fěi',
0x8BFE: 'kè',
0x8BFF: 'wěi',
0x8C00: 'yú',
0x8C01: 'shéi,shuí',
0x8C03: 'diào,tiáo',
0x8C04: 'chǎn',
0x8C05: 'liàng',
0x8C06: 'zhūn',
0x8C08: 'tán',
0x8C0A: 'yì',
0x8C0B: 'móu,mòu',
0x8C0D: 'dié',
0x8C0E: 'huǎng',
0x8C0F: 'jiàn',
0x8C10: 'xié',
0x8C11: 'xuè',
0x8C12: 'yè',
0x8C13: 'wèi',
0x8C14: 'è',
0x8C15: 'yù',
0x8C17: 'chán',
0x8C18: 'zī',
0x8C19: 'ān',
0x8C1A: 'yàn',
0x8C1B: 'dì',
0x8C1C: 'mí,mèi',
0x8C1F: 'mó',
0x8C22: 'xiè,xie',
0x8C23: 'yáo',
0x8C24: 'bàng',
0x8C25: 'shì',
0x8C26: 'qiān',
0x8C27: 'mì',
0x8C28: 'jǐn',
0x8C29: 'màn',
0x8C2A: 'zhé',
0x8C2C: 'miù',
0x8C2D: 'tán',
0x8C2E: 'zèn',
0x8C2F: 'qiáo',
0x8C30: 'lán',
0x8C31: 'pǔ',
0x8C32: 'jué',
0x8C33: 'yàn',
0x8C34: 'qiǎn',
0x8C35: 'zhān',
0x8C36: 'chèn',
0x8C37: 'gǔ,yù',
0x8C41: 'huò,huō,huá',
0x8C46: 'dòu',
0x8C47: 'jiāng',
0x8C49: 'chǐ',
0x8C4C: 'wān',
0x8C55: 'shǐ',
0x8C5A: 'tún',
0x8C5E: 'hòu',
0x8C61: 'xiàng',
0x8C62: 'huàn',
0x8C6A: 'háo',
0x8C6B: 'yù',
0x8C71: 'wēn',
0x8C78: 'zhì',
0x8C79: 'bào',
0x8C7A: 'chái',
0x8C82: 'diāo',
0x8C85: 'xiū',
0x8C89: 'háo,hé',
0x8C8A: 'mò',
0x8C8C: 'mào',
0x8C94: 'pí',
0x8D1D: 'bèi',
0x8D1E: 'zhēn',
0x8D1F: 'fù,fu',
0x8D21: 'gòng',
0x8D22: 'cái',
0x8D23: 'zé',
0x8D24: 'xián',
0x8D25: 'bài',
0x8D26: 'zhàng',
0x8D27: 'huò',
0x8D28: 'zhì',
0x8D29: 'fàn',
0x8D2A: 'tān',
0x8D2B: 'pín',
0x8D2C: 'biǎn',
0x8D2D: 'gòu',
0x8D2E: 'zhù',
0x8D2F: 'guàn',
0x8D30: 'èr',
0x8D31: 'jiàn',
0x8D32: 'bì,bēn',
0x8D34: 'tiē',
0x8D35: 'guì',
0x8D37: 'dài',
0x8D38: 'mào',
0x8D39: 'fèi',
0x8D3A: 'hè',
0x8D3B: 'yí',
0x8D3C: 'zéi',
0x8D3D: 'zhì',
0x8D3E: 'jiǎ,gǔ',
0x8D3F: 'huì,huī',
0x8D40: 'zī',
0x8D41: 'lìn',
0x8D42: 'lù',
0x8D43: 'zāng',
0x8D44: 'zī',
0x8D45: 'gāi',
0x8D48: 'zhèn',
0x8D49: 'lài',
0x8D4A: 'shē',
0x8D4B: 'fù',
0x8D4C: 'dǔ',
0x8D4D: 'jī',
0x8D4E: 'shú',
0x8D4F: 'shǎng',
0x8D50: 'cì',
0x8D51: 'bì',
0x8D52: 'zhōu',
0x8D53: 'gēng',
0x8D54: 'péi',
0x8D55: 'dǎn',
0x8D56: 'lài',
0x8D58: 'zhuì',
0x8D5A: 'zhuàn',
0x8D5B: 'sài',
0x8D5D: 'yàn',
0x8D5E: 'zàn',
0x8D60: 'zèng',
0x8D61: 'shàn',
0x8D62: 'yíng',
0x8D63: 'gàn',
0x8D64: 'chì',
0x8D66: 'shè',
0x8D67: 'nǎn',
0x8D6B: 'hè',
0x8D6D: 'zhě',
0x8D70: 'zǒu',
0x8D73: 'jiū',
0x8D74: 'fù',
0x8D75: 'zhào',
0x8D76: 'gǎn',
0x8D77: 'qǐ,qi',
0x8D78: 'shàn',
0x8D81: 'chèn',
0x8D84: 'jū,qie',
0x8D85: 'chāo',
0x8D8A: 'yuè',
0x8D8B: 'qū',
0x8D91: 'zī',
0x8D94: 'liè',
0x8D9F: 'tàng,tāng',
0x8DA3: 'qù',
0x8DA6: 'zī',
0x8DB3: 'zú',
0x8DB4: 'pā',
0x8DB8: 'dǔn',
0x8DBA: 'fū',
0x8DBC: 'jiǎn',
0x8DBE: 'zhǐ',
0x8DBF: 'tā',
0x8DC2: 'qǐ,qì,qí,zhī',
0x8DC3: 'yuè',
0x8DC4: 'qiàng',
0x8DC6: 'tái',
0x8DCB: 'bá',
0x8DCC: 'diē,die',
0x8DCE: 'tuó',
0x8DCF: 'jiā',
0x8DD1: 'pǎo',
0x8DD7: 'fū',
0x8DDA: 'shān',
0x8DDB: 'bǒ',
0x8DDD: 'jù',
0x8DDF: 'gēn',
0x8DE3: 'xiǎn',
0x8DE4: 'jiāo',
0x8DE8: 'kuà',
0x8DE9: 'zhuǎi',
0x8DEA: 'guì',
0x8DEF: 'lù,lu',
0x8DF3: 'tiào',
0x8DF5: 'jiàn,jian',
0x8DF6: 'da',
0x8DF7: 'qiāo,qiào',
0x8DF9: 'xiān',
0x8DFB: 'jī',
0x8E05: 'xué',
0x8E09: 'liàng',
0x8E0A: 'yǒng',
0x8E0C: 'chóu',
0x8E0F: 'tà,tā',
0x8E14: 'chuō',
0x8E18: 'jū',
0x8E1D: 'huái',
0x8E1E: 'jù',
0x8E1F: 'chí',
0x8E22: 'tī,ti',
0x8E23: 'bó',
0x8E25: 'qiè',
0x8E29: 'cǎi',
0x8E2A: 'zōng',
0x8E2C: 'zhì',
0x8E2E: 'diǎn',
0x8E2F: 'zhí',
0x8E31: 'duó',
0x8E35: 'zhǒng',
0x8E36: 'dì',
0x8E3A: 'jiàn',
0x8E3D: 'jǔ',
0x8E40: 'dié,die',
0x8E42: 'róu',
0x8E44: 'tí',
0x8E47: 'jiǎn',
0x8E48: 'dǎo',
0x8E49: 'cuō',
0x8E4A: 'xī,qī',
0x8E4B: 'tà',
0x8E51: 'niè',
0x8E52: 'pán',
0x8E59: 'cù',
0x8E5A: 'tāng',
0x8E61: 'qiàng',
0x8E66: 'bèng',
0x8E67: 'zāo',
0x8E69: 'bié',
0x8E6C: 'dēng,dèng',
0x8E6D: 'cèng,ceng',
0x8E70: 'chú',
0x8E72: 'dūn,dùn',
0x8E74: 'cù',
0x8E76: 'jué,juě',
0x8E7C: 'pǔ',
0x8E7F: 'cuān',
0x8E81: 'zào',
0x8E85: 'zhú',
0x8E87: 'chú',
0x8E8F: 'lìn',
0x8E94: 'chán',
0x8E9E: 'xiè',
0x8EAB: 'shēn,shēng',
0x8EAC: 'gōng',
0x8EAF: 'qū',
0x8EB2: 'duǒ',
0x8EBA: 'tǎng',
0x8EC3: 'duǒ',
0x8F02: 'jú',
0x8F57: 'kǎn',
0x8F58: 'huàn',
0x8F66: 'chē,jū',
0x8F67: 'yà,zhá',
0x8F68: 'guǐ',
0x8F69: 'xuān',
0x8F6B: 'rèn',
0x8F6C: 'zhuǎn,zhuàn,zhuǎi,zhuan',
0x8F6D: 'è',
0x8F6E: 'lún',
0x8F6F: 'ruǎn',
0x8F70: 'hōng',
0x8F71: 'gū',
0x8F72: 'kē,kě',
0x8F73: 'lu',
0x8F74: 'zhóu,zhòu',
0x8F76: 'yì',
0x8F78: 'zhěn',
0x8F7B: 'qīng',
0x8F7C: 'shì',
0x8F7D: 'zài,zǎi',
0x8F7E: 'zhì',
0x8F7F: 'jiào',
0x8F83: 'jiào',
0x8F84: 'zhé',
0x8F85: 'fǔ',
0x8F86: 'liàng',
0x8F87: 'niǎn',
0x8F88: 'bèi',
0x8F89: 'huī',
0x8F8A: 'gǔn',
0x8F8C: 'liáng',
0x8F8D: 'chuò',
0x8F90: 'fú',
0x8F91: 'jí,ji',
0x8F92: 'wēn',
0x8F93: 'shū',
0x8F94: 'pèi',
0x8F95: 'yuán',
0x8F96: 'xiá',
0x8F97: 'zhǎn',
0x8F98: 'lù',
0x8F99: 'zhé',
0x8F9B: 'xīn',
0x8F9C: 'gū',
0x8F9E: 'cí',
0x8F9F: 'pì,bì',
0x8FA3: 'là,la,lā',
0x8FA8: 'biàn',
0x8FA9: 'biàn',
0x8FAB: 'biàn',
0x8FB0: 'chén,chen',
0x8FB1: 'rǔ',
0x8FB9: 'biān,bian',
0x8FBD: 'liáo',
0x8FBE: 'dá,da',
0x8FC1: 'qiān',
0x8FC2: 'yū',
0x8FC4: 'qì',
0x8FC5: 'xùn',
0x8FC7: 'guò,guo',
0x8FC8: 'mài',
0x8FCE: 'yíng',
0x8FD0: 'yùn',
0x8FD1: 'jìn',
0x8FD4: 'fǎn',
0x8FD5: 'wǔ',
0x8FD8: 'huán,hái',
0x8FD9: 'zhè',
0x8FDB: 'jìn',
0x8FDC: 'yuǎn,yuàn',
0x8FDD: 'wéi',
0x8FDE: 'lián,lian',
0x8FDF: 'chí',
0x8FE2: 'tiáo',
0x8FE4: 'yǐ,yí',
0x8FE5: 'jiǒng',
0x8FE6: 'jiā',
0x8FE9: 'ěr',
0x8FEA: 'dí',
0x8FEB: 'pò,pǎi',
0x8FED: 'dié',
0x8FEE: 'zé',
0x8FF0: 'shù',
0x8FF3: 'jìng',
0x8FF7: 'mí',
0x8FF8: 'bèng',
0x8FF9: 'jì',
0x8FFA: 'nǎi',
0x8FFD: 'zhuī',
0x9000: 'tuì',
0x9001: 'sòng,song',
0x9002: 'shì,kuò',
0x9003: 'táo',
0x9005: 'hòu',
0x9006: 'nì',
0x9009: 'xuǎn',
0x900A: 'xùn',
0x900B: 'bū',
0x900D: 'xiāo',
0x900F: 'tòu',
0x9010: 'zhú',
0x9012: 'dì',
0x9014: 'tú',
0x9017: 'dòu',
0x901A: 'tōng,tong',
0x901B: 'guàng,guang',
0x901D: 'shì',
0x901E: 'chěng',
0x901F: 'sù',
0x9020: 'zào',
0x9021: 'qūn',
0x9022: 'féng',
0x9026: 'lǐ',
0x902E: 'dài,dǎi',
0x9035: 'kuí',
0x9036: 'wēi',
0x9038: 'yì',
0x903B: 'luó',
0x903C: 'bī,bi',
0x903E: 'yú',
0x9041: 'dùn',
0x9042: 'suì',
0x9044: 'chuán',
0x9047: 'yù',
0x904D: 'biàn',
0x904F: 'è',
0x9050: 'xiá',
0x9051: 'huáng',
0x9052: 'qiú',
0x9053: 'dào,dao',
0x9057: 'yí',
0x905B: 'liù,liú',
0x905D: 'tà',
0x9062: 'ta',
0x9063: 'qiǎn',
0x9065: 'yáo',
0x9068: 'áo',
0x906D: 'zāo',
0x906E: 'zhē',
0x9074: 'lín',
0x9075: 'zūn',
0x907D: 'jù',
0x907F: 'bì',
0x9080: 'yāo',
0x9082: 'xiè',
0x9083: 'suì',
0x9088: 'miǎo',
0x908B: 'lā',
0x9091: 'yì',
0x9093: 'dèng',
0x9095: 'yōng',
0x9097: 'hán',
0x9099: 'máng',
0x909B: 'qióng',
0x90A1: 'fāng',
0x90A2: 'xíng',
0x90A3: 'nà,nǎ,na',
0x90A6: 'bāng',
0x90A8: 'cūn',
0x90AA: 'xié',
0x90AE: 'yóu',
0x90AF: 'hán',
0x90B1: 'qiū',
0x90B3: 'pī',
0x90B5: 'shào',
0x90B7: 'wǎ',
0x90B8: 'dǐ',
0x90B9: 'zōu',
0x90BA: 'yè',
0x90BB: 'lín',
0x90C1: 'yù',
0x90C5: 'zhì',
0x90C7: 'xún',
0x90CA: 'jiāo',
0x90CE: 'láng,lang,làng',
0x90CF: 'jiá',
0x90D1: 'zhèng',
0x90D3: 'yùn',
0x90DB: 'fú',
0x90DD: 'hǎo',
0x90E1: 'jùn',
0x90E2: 'yǐng',
0x90E4: 'xì',
0x90E7: 'yún',
0x90E8: 'bù',
0x90EB: 'pí',
0x90ED: 'guō',
0x90EF: 'tán',
0x90F4: 'chēn',
0x90F8: 'dān',
0x90FD: 'dū,dōu',
0x90FE: 'yǎn',
0x9102: 'è',
0x9104: 'juàn',
0x910B: 'sōu',
0x9119: 'bǐ',
0x911E: 'yín',
0x9122: 'yān',
0x912F: 'shàn',
0x9131: 'pó',
0x9143: 'líng',
0x9146: 'fēng',
0x9149: 'yǒu',
0x914A: 'dǐng,dīng',
0x914B: 'qiú',
0x914C: 'zhuó',
0x914D: 'pèi',
0x9152: 'jiǔ',
0x9155: 'máo',
0x9157: 'xù',
0x915A: 'fēn',
0x915D: 'yùn',
0x915E: 'tài',
0x9162: 'cù,zuò',
0x9163: 'hān',
0x9165: 'sū',
0x9166: 'fā',
0x9169: 'mǐng',
0x916A: 'lào,luò',
0x916C: 'chóu,chou',
0x916E: 'tóng',
0x916F: 'zhǐ',
0x9170: 'xiān',
0x9171: 'jiàng',
0x9172: 'chéng',
0x9175: 'jiào',
0x9176: 'méi',
0x9177: 'kù',
0x9178: 'suān',
0x917F: 'niàng,niáng',
0x9184: 'táo',
0x9187: 'chún',
0x9189: 'zuì',
0x918B: 'cù',
0x918C: 'kūn',
0x918D: 'tí',
0x9190: 'hú',
0x9192: 'xǐng',
0x919A: 'mí',
0x919B: 'quán',
0x91A2: 'hǎi',
0x91A3: 'táng',
0x91AA: 'láo',
0x91AE: 'jiào',
0x91B4: 'lǐ',
0x91BA: 'xūn',
0x91C7: 'cǎi',
0x91C9: 'yòu',
0x91CA: 'shì',
0x91CC: 'lǐ,li',
0x91CD: 'zhòng,chóng',
0x91CE: 'yě',
0x91CF: 'liàng,liáng,liang',
0x91D1: 'jīn',
0x91DC: 'fǔ',
0x9274: 'jiàn',
0x927E: 'móu',
0x92AE: 'luán',
0x933E: 'zàn',
0x936A: 'móu',
0x938F: 'liú',
0x93CA: 'ào',
0x93D6: 'áo',
0x946B: 'xīn',
0x9488: 'zhēn',
0x9489: 'dīng,dìng,ding',
0x948A: 'zhāo',
0x948C: 'liào',
0x948E: 'qiān',
0x9492: 'fán',
0x9493: 'diào',
0x9497: 'chāi',
0x9499: 'gài',
0x949B: 'tài',
0x949C: 'jù',
0x949D: 'dùn',
0x949E: 'chāo',
0x949F: 'zhōng,zhong',
0x94A0: 'nà',
0x94A1: 'bèi',
0x94A2: 'gāng',
0x94A3: 'bǎn',
0x94A5: 'yào,yuè',
0x94A6: 'qīn',
0x94A7: 'jūn',
0x94A8: 'wū',
0x94A9: 'gōu,gòu',
0x94AE: 'niǔ',
0x94AF: 'bǎ',
0x94B0: 'yù',
0x94B1: 'qián,qian',
0x94B3: 'qián',
0x94B4: 'gǔ',
0x94B5: 'bō',
0x94B9: 'bó',
0x94BA: 'yuè',
0x94BB: 'zuān,zuàn',
0x94BE: 'jiǎ',
0x94C0: 'yóu',
0x94C1: 'tiě,tie',
0x94C3: 'líng',
0x94C4: 'shuò',
0x94C5: 'qiān,yán',
0x94C6: 'mǎo',
0x94C9: 'xuàn',
0x94CE: 'duó',
0x94D0: 'kào',
0x94D3: 'máng',
0x94D7: 'jiá',
0x94DB: 'dāng,chēng,dang',
0x94DC: 'tóng',
0x94DD: 'lǚ',
0x94DE: 'diào',
0x94E0: 'kǎi',
0x94E1: 'zhá',
0x94E2: 'zhū',
0x94E3: 'xǐ,xiǎn',
0x94E4: 'tǐng',
0x94E7: 'huá',
0x94E8: 'quán',
0x94E9: 'shā',
0x94EC: 'gè',
0x94ED: 'míng',
0x94EE: 'zhēng',
0x94F0: 'jiǎo',
0x94F2: 'chǎn',
0x94F3: 'chòng',
0x94F5: 'ǎn',
0x94F6: 'yín',
0x94F8: 'zhù',
0x94FA: 'pū,pù',
0x94FE: 'liàn',
0x94FF: 'kēng',
0x9500: 'xiāo',
0x9501: 'suǒ',
0x9502: 'lǐ',
0x9503: 'zèng',
0x9504: 'chú',
0x9505: 'guō',
0x9506: 'gào',
0x9508: 'xiù',
0x9509: 'cuò',
0x950B: 'fēng',
0x950C: 'xīn',
0x950F: 'jiǎn',
0x9510: 'ruì',
0x9512: 'láng',
0x9514: 'jū',
0x9515: 'ā',
0x9519: 'cuò',
0x951A: 'máo',
0x951F: 'kūn',
0x9521: 'xī',
0x9522: 'gù',
0x9523: 'luó',
0x9524: 'chuí',
0x9525: 'zhuī',
0x9526: 'jǐn',
0x9528: 'xiān',
0x952A: 'huō',
0x952D: 'dìng',
0x952E: 'jiàn',
0x952F: 'jù,ju',
0x9530: 'měng',
0x9531: 'zī',
0x9532: 'qiè',
0x9535: 'qiāng',
0x9537: 'è',
0x9539: 'qiāo',
0x953B: 'duàn',
0x953E: 'huán',
0x9540: 'dù',
0x9541: 'měi',
0x9542: 'lòu',
0x9547: 'zhèn',
0x9548: 'bó',
0x954A: 'niè',
0x954C: 'juān',
0x954D: 'niè',
0x954F: 'liù,liú',
0x9550: 'gǎo,hào',
0x9551: 'bàng',
0x9553: 'jiā',
0x9555: 'róng',
0x9556: 'biāo',
0x955A: 'bèng',
0x955C: 'jìng',
0x955E: 'zú',
0x9563: 'liào',
0x9567: 'lán',
0x9569: 'cuān',
0x956A: 'qiāng',
0x956B: 'dèng',
0x956C: 'huò',
0x956D: 'léi',
0x956F: 'zhuó',
0x9570: 'lián',
0x9572: 'chǎ',
0x9573: 'biāo',
0x9574: 'là',
0x9576: 'xiāng',
0x957F: 'cháng,zhǎng',
0x95A6: 'chù',
0x95E8: 'mén,men',
0x95E9: 'shuān',
0x95EA: 'shǎn',
0x95ED: 'bì',
0x95EE: 'wèn',
0x95EF: 'chuǎng',
0x95F0: 'rùn',
0x95F1: 'wéi',
0x95F2: 'xián',
0x95F3: 'hóng',
0x95F4: 'jiān,jiàn,gān',
0x95F5: 'mǐn',
0x95F7: 'mèn,mēn,men',
0x95F8: 'zhá',
0x95F9: 'nào,nao',
0x95FA: 'guī',
0x95FB: 'wén',
0x95FD: 'mǐn',
0x95FE: 'lǘ',
0x9600: 'fá',
0x9601: 'gé',
0x9602: 'hé',
0x9603: 'kǔn',
0x9604: 'jiū',
0x9605: 'yuè',
0x9606: 'láng,làng',
0x9607: 'shé',
0x9608: 'yù',
0x9609: 'yān',
0x960A: 'chāng',
0x960B: 'xì',
0x960E: 'yán',
0x960F: 'yān,è',
0x9610: 'chǎn',
0x9611: 'lán',
0x9612: 'qù',
0x9614: 'kuò',
0x9616: 'hé',
0x9617: 'tián',
0x9619: 'què,quē',
0x961C: 'fù',
0x961F: 'duì',
0x9621: 'qiān',
0x9622: 'wù',
0x962A: 'bǎn',
0x962E: 'ruǎn',
0x9631: 'jǐng',
0x9632: 'fáng,fang',
0x9633: 'yáng,yang',
0x9634: 'yīn',
0x9635: 'zhèn',
0x9636: 'jiē',
0x963B: 'zǔ',
0x963F: 'ā,ē',
0x9640: 'tuó',
0x9642: 'pí,bēi,pō',
0x9644: 'fù',
0x9645: 'jì',
0x9646: 'lù',
0x9647: 'lǒng',
0x9648: 'chén',
0x9649: 'xíng',
0x964B: 'lòu',
0x964C: 'mò',
0x964D: 'jiàng,xiáng',
0x9650: 'xiàn',
0x9655: 'shǎn',
0x965B: 'bì',
0x965C: 'xiá',
0x965F: 'zhì',
0x9661: 'dǒu',
0x9662: 'yuàn',
0x9664: 'chú',
0x9667: 'niè',
0x9668: 'yǔn',
0x9669: 'xiǎn',
0x966A: 'péi',
0x9672: 'chuí',
0x9674: 'pí',
0x9675: 'líng',
0x9676: 'táo',
0x9677: 'xiàn',
0x9685: 'yú,yù',
0x9686: 'lóng,lōng',
0x968B: 'suí',
0x968D: 'huáng',
0x968F: 'suí',
0x9690: 'yǐn',
0x9694: 'gé',
0x9698: 'ài',
0x9699: 'xì',
0x969C: 'zhàng',
0x96A7: 'suì',
0x96B0: 'xí',
0x96B6: 'lì',
0x96BC: 'sǔn',
0x96BD: 'juàn,jùn',
0x96BE: 'nán,nàn,nan',
0x96C0: 'què,qiǎo,qiāo',
0x96C1: 'yàn',
0x96C4: 'xióng',
0x96C5: 'yǎ,yā',
0x96C6: 'jí',
0x96C7: 'gù',
0x96C9: 'zhì',
0x96CC: 'cí',
0x96CD: 'yōng',
0x96CF: 'chú',
0x96D5: 'diāo',
0x96DA: 'huán',
0x96E0: 'chóu',
0x96E8: 'yǔ,yù',
0x96EA: 'xuě',
0x96EF: 'wén',
0x96F0: 'fēn',
0x96F3: 'lì',
0x96F6: 'líng,ling',
0x96F7: 'léi',
0x96F9: 'báo',
0x96FE: 'wù',
0x9700: 'xū',
0x9701: 'jì',
0x9702: 'mù',
0x9704: 'xiāo',
0x9706: 'tíng',
0x9707: 'zhèn',
0x9709: 'méi',
0x970D: 'huò',
0x970E: 'shà',
0x970F: 'fēi',
0x9713: 'ní',
0x9716: 'lín',
0x971C: 'shuāng',
0x971E: 'xiá',
0x9722: 'mài',
0x972A: 'yín',
0x972D: 'ǎi',
0x9730: 'xiàn',
0x9732: 'lù,lòu',
0x9738: 'bà',
0x9739: 'pī',
0x973E: 'mái',
0x9752: 'qīng',
0x9753: 'liàng,jìng',
0x9756: 'jìng',
0x9759: 'jìng',
0x975B: 'diàn',
0x975E: 'fēi',
0x9760: 'kào',
0x9761: 'mǐ,mí',
0x9762: 'miàn,mian',
0x9765: 'yè',
0x9769: 'gé',
0x976A: 'ding',
0x976C: 'jiān',
0x9774: 'xuē',
0x9776: 'bǎ',
0x977C: 'dá',
0x9785: 'yāng,yǎng',
0x978B: 'xié',
0x978D: 'ān',
0x9791: 'dá',
0x9798: 'qiào',
0x979D: 'shàng',
0x97A0: 'jū',
0x97A3: 'róu',
0x97AD: 'biān',
0x97B2: 'gōu',
0x97B4: 'bèi',
0x97E6: 'wéi',
0x97E7: 'rèn',
0x97E9: 'hán',
0x97EA: 'wěi',
0x97EC: 'tāo',
0x97ED: 'jiǔ',
0x97F3: 'yīn,yin',
0x97F5: 'yùn',
0x97F6: 'sháo',
0x9875: 'yè',
0x9876: 'dǐng',
0x9877: 'qǐng',
0x9879: 'xiàng,xiang',
0x987A: 'shùn',
0x987B: 'xū',
0x987C: 'xū',
0x987D: 'wán',
0x987E: 'gù,gu',
0x987F: 'dùn',
0x9881: 'bān',
0x9882: 'sòng',
0x9884: 'yù',
0x9885: 'lú',
0x9886: 'lǐng',
0x9887: 'pō',
0x9888: 'jǐng,gěng',
0x9889: 'jié',
0x988A: 'jiá',
0x988C: 'hé',
0x988D: 'yǐng',
0x988F: 'kē',
0x9890: 'yí',
0x9891: 'pín',
0x9893: 'tuí',
0x9894: 'hàn',
0x9896: 'yǐng',
0x9897: 'kē',
0x9898: 'tí',
0x989A: 'è',
0x989B: 'zhuān',
0x989C: 'yán',
0x989D: 'é,è',
0x989E: 'niè',
0x98A0: 'diān',
0x98A1: 'sǎng',
0x98A2: 'hào',
0x98A4: 'chàn,zhàn,zhan',
0x98A5: 'rú',
0x98A6: 'pín',
0x98A7: 'quán',
0x98CE: 'fēng',
0x98D0: 'zhǎn',
0x98D2: 'sà',
0x98D3: 'jù',
0x98D5: 'sōu',
0x98D6: 'yáo',
0x98D8: 'piāo',
0x98D9: 'biāo',
0x98DE: 'fēi',
0x98DF: 'shí,shi',
0x98E7: 'sūn',
0x98E8: 'xiǎng',
0x990D: 'yàn',
0x9910: 'cān',
0x992E: 'tiè',
0x9954: 'yōng',
0x9955: 'tāo',
0x9965: 'jī',
0x9967: 'xíng',
0x9968: 'tun',
0x9969: 'xì',
0x996A: 'rèn',
0x996B: 'yù',
0x996C: 'chì,chi',
0x996D: 'fàn',
0x996E: 'yǐn',
0x996F: 'jiàn',
0x9970: 'shì',
0x9971: 'bǎo',
0x9972: 'sì',
0x9974: 'yí',
0x9975: 'ěr',
0x9976: 'ráo',
0x9977: 'xiǎng',
0x9978: 'hé',
0x9979: 'le',
0x997A: 'jiǎo',
0x997C: 'bǐng,bing',
0x997D: 'bō,bo',
0x997F: 'è',
0x9980: 'yú',
0x9981: 'něi',
0x9982: 'jùn',
0x9984: 'hún',
0x9985: 'xiàn',
0x9986: 'guǎn',
0x9988: 'kuì',
0x998A: 'sōu',
0x998B: 'chán',
0x998D: 'mó,mo',
0x998F: 'liú',
0x9990: 'xiū',
0x9991: 'jǐn',
0x9992: 'mán',
0x9993: 'sǎn',
0x9994: 'zhuàn',
0x9995: 'nǎng',
0x9996: 'shǒu,shou',
0x9997: 'kuí',
0x9999: 'xiāng',
0x99A5: 'fù',
0x99A8: 'xīn',
0x9A03: 'ái',
0x9A6C: 'mǎ,ma',
0x9A6D: 'yù',
0x9A6E: 'tuó,duò',
0x9A6F: 'xùn',
0x9A70: 'chí',
0x9A71: 'qū',
0x9A73: 'bó',
0x9A74: 'lǘ',
0x9A76: 'shǐ',
0x9A78: 'fù',
0x9A79: 'jū',
0x9A7A: 'zōu',
0x9A7B: 'zhù',
0x9A7C: 'tuó,tuo',
0x9A7D: 'nú',
0x9A7E: 'jià',
0x9A7F: 'yì',
0x9A81: 'xiāo',
0x9A82: 'mà,ma',
0x9A84: 'jiāo',
0x9A85: 'huá',
0x9A86: 'luò',
0x9A87: 'hài',
0x9A88: 'pián',
0x9A8A: 'lí',
0x9A8B: 'chěng',
0x9A8C: 'yàn',
0x9A8F: 'jùn',
0x9A90: 'qí',
0x9A91: 'qí',
0x9A92: 'kè',
0x9A95: 'sù',
0x9A97: 'piàn',
0x9A98: 'zhì',
0x9A9A: 'sāo',
0x9A9B: 'wù',
0x9A9C: 'ào',
0x9A9D: 'liú',
0x9A9E: 'qiān',
0x9AA1: 'luó',
0x9AA4: 'zhòu',
0x9AA5: 'jì',
0x9AA6: 'shuāng',
0x9AA7: 'xiāng',
0x9AA8: 'gǔ,gū,gu',
0x9AB0: 'tóu',
0x9AB6: 'dǐ',
0x9AB7: 'kū',
0x9AB8: 'hái',
0x9ABA: 'hóu',
0x9ABC: 'gé',
0x9AC0: 'bì',
0x9AC2: 'qià',
0x9AC5: 'lóu',
0x9ACB: 'kuān',
0x9ACC: 'bìn',
0x9AD3: 'suǐ',
0x9AD8: 'gāo',
0x9ADD: 'láo',
0x9ADE: 'sào',
0x9AE6: 'máo',
0x9AEB: 'tiáo',
0x9AED: 'zī',
0x9AEF: 'rán',
0x9AFB: 'jì',
0x9B03: 'zōng',
0x9B12: 'zhěn',
0x9B13: 'bìn',
0x9B1F: 'huan,huán',
0x9B23: 'liè',
0x9B3B: 'yù',
0x9B3C: 'guǐ',
0x9B41: 'kuí',
0x9B42: 'hún',
0x9B43: 'bá',
0x9B44: 'pò',
0x9B45: 'mèi',
0x9B46: 'xù,xū',
0x9B47: 'yǎn',
0x9B49: 'liǎng',
0x9B4D: 'wǎng',
0x9B4F: 'wèi',
0x9B51: 'chī',
0x9B54: 'mó',
0x9B56: 'xū',
0x9B60: 'tuō',
0x9B63: 'yú',
0x9BA8: 'qí',
0x9C46: 'zhāng',
0x9C65: 'guì',
0x9C7C: 'yú',
0x9C7F: 'yóu',
0x9C81: 'lǔ',
0x9C83: 'bā',
0x9C85: 'bà',
0x9C86: 'píng',
0x9C88: 'lú',
0x9C8B: 'fù',
0x9C8D: 'bào',
0x9C8E: 'hòu',
0x9C8F: 'pí',
0x9C90: 'tái',
0x9C91: 'guī',
0x9C94: 'wěi',
0x9C97: 'zéi',
0x9C99: 'kuài',
0x9C9B: 'jiāo',
0x9C9C: 'xiān,xiǎn',
0x9C9E: 'xiǎng',
0x9C9F: 'xún',
0x9CA0: 'gěng',
0x9CA1: 'lí',
0x9CA2: 'lián',
0x9CA3: 'jiān',
0x9CA4: 'lǐ',
0x9CA5: 'shí',
0x9CA8: 'shā',
0x9CA9: 'huàn',
0x9CAB: 'jì',
0x9CAD: 'qīng',
0x9CAE: 'líng',
0x9CAF: 'qí',
0x9CB1: 'fēi',
0x9CB2: 'kūn',
0x9CB3: 'chāng',
0x9CB4: 'gù',
0x9CB5: 'ní',
0x9CB6: 'nián',
0x9CB7: 'diāo',
0x9CB8: 'jīng',
0x9CBB: 'zī',
0x9CBC: 'fèn',
0x9CBD: 'dié',
0x9CC0: 'tí',
0x9CC3: 'sāi',
0x9CC4: 'è',
0x9CC5: 'qiu,qiū',
0x9CCC: 'áo',
0x9CCD: 'qí',
0x9CCF: 'guān',
0x9CD1: 'páng',
0x9CD4: 'biào',
0x9CD5: 'xuě',
0x9CD6: 'biē',
0x9CD7: 'mán',
0x9CD9: 'yōng',
0x9CDC: 'guì',
0x9CDD: 'shàn',
0x9CDE: 'lín',
0x9CDF: 'zūn',
0x9CE2: 'lǐ',
0x9CEF: 'fèng',
0x9CFD: 'yán,jiān',
0x9D02: 'jué',
0x9D03: 'jué',
0x9D14: 'fú',
0x9D56: 'bī',
0x9D5F: 'kuáng',
0x9D92: 'chì',
0x9D97: 'tí',
0x9E1F: 'niǎo,diǎo',
0x9E20: 'jiū',
0x9E21: 'jī',
0x9E22: 'yuān',
0x9E23: 'míng',
0x9E25: 'ōu',
0x9E26: 'yā',
0x9E27: 'cāng',
0x9E28: 'bǎo',
0x9E29: 'zhèn',
0x9E2A: 'gū',
0x9E2B: 'dōng',
0x9E2C: 'lú',
0x9E2D: 'yā',
0x9E2E: 'xiāo',
0x9E2F: 'yāng,yang',
0x9E30: 'líng',
0x9E31: 'chī',
0x9E32: 'qú',
0x9E33: 'yuān',
0x9E35: 'tuó',
0x9E36: 'sī',
0x9E37: 'zhì',
0x9E38: 'ér',
0x9E39: 'guā',
0x9E3A: 'xiū',
0x9E3B: 'héng',
0x9E3D: 'gē',
0x9E3E: 'luán',
0x9E3F: 'hóng',
0x9E40: 'wú',
0x9E41: 'bó',
0x9E42: 'lí',
0x9E43: 'juān',
0x9E44: 'hú,gǔ',
0x9E45: 'é',
0x9E46: 'yù',
0x9E47: 'xián',
0x9E48: 'tí',
0x9E49: 'wǔ',
0x9E4A: 'què',
0x9E4B: 'miáo',
0x9E4C: 'ān',
0x9E4D: 'kūn',
0x9E4E: 'bēi',
0x9E4F: 'péng',
0x9E51: 'chún',
0x9E52: 'gēng',
0x9E54: 'sù',
0x9E55: 'hú',
0x9E57: 'è',
0x9E58: 'hú',
0x9E59: 'qiū',
0x9E5A: 'cí',
0x9E5B: 'méi',
0x9E5C: 'wù',
0x9E5E: 'yào',
0x9E5F: 'wēng',
0x9E60: 'liú',
0x9E61: 'jí',
0x9E63: 'jiān',
0x9E64: 'hè',
0x9E66: 'yīng',
0x9E67: 'zhè',
0x9E68: 'liù',
0x9E69: 'liáo',
0x9E6A: 'jiāo',
0x9E6B: 'jiù',
0x9E6C: 'yù',
0x9E6D: 'lù',
0x9E6E: 'huán',
0x9E70: 'yīng',
0x9E71: 'hù',
0x9E72: 'méng',
0x9E73: 'guàn',
0x9E74: 'shuāng',
0x9E7F: 'lù',
0x9E82: 'jǐ',
0x9E87: 'qún',
0x9E88: 'zhǔ',
0x9E8B: 'mí',
0x9E92: 'qí',
0x9E93: 'lù',
0x9E9D: 'shè',
0x9E9F: 'lín',
0x9EA6: 'mài',
0x9EB4: 'qū',
0x9EB8: 'fū',
0x9EBB: 'má,ma,mā',
0x9EBD: 'me,mó',
0x9EBE: 'huī',
0x9EBF: 'mǒ',
0x9EC4: 'huáng',
0x9EC7: 'tiān',
0x9ECD: 'shǔ',
0x9ECE: 'lí',
0x9ECF: 'nián',
0x9ED0: 'chī',
0x9ED1: 'hēi',
0x9ED4: 'qián',
0x9ED8: 'mò',
0x9EDB: 'dài',
0x9EDC: 'chù',
0x9EDD: 'yǒu',
0x9EDF: 'yī',
0x9EE0: 'xiá',
0x9EE2: 'qū',
0x9EE5: 'qíng',
0x9EE7: 'lí',
0x9EE9: 'dú',
0x9EEF: 'àn',
0x9F0B: 'yuán',
0x9F0D: 'tuó',
0x9F0E: 'dǐng',
0x9F13: 'gǔ,gu',
0x9F20: 'shǔ',
0x9F22: 'fén',
0x9F29: 'qú',
0x9F2C: 'yòu',
0x9F2F: 'wú',
0x9F31: 'jīng',
0x9F37: 'xī',
0x9F39: 'yǎn',
0x9F3B: 'bí',
0x9F3E: 'hān',
0x9F4C: 'jì',
0x9F50: 'qí',
0x9F51: 'jī',
0x9F67: 'niè',
0x9F71: 'zōu',
0x9F75: 'yú',
0x9F7F: 'chǐ',
0x9F83: 'jǔ',
0x9F84: 'líng',
0x9F85: 'bāo',
0x9F87: 'zī',
0x9F88: 'yín',
0x9F89: 'yǔ',
0x9F8A: 'chuò',
0x9F8B: 'qǔ',
0x9F8C: 'wò',
0x9F99: 'lóng',
0x9F9A: 'gōng',
0x9F9B: 'kān',
0x9F9F: 'guī,qiū,jūn',
0x9FA0: 'yuè',
0x2020C: 'yú',
0x21484: 'lǎn',
0x22650: 'náo',
0x251A7: 'rún,shùn',
0x25ED7: 'chá',
0x28C3F: 'xì',
0x29F7E: 'ān',
0x29F8C: 'kāng',
0x2B5AE: 'yǐ',
0x2B689: 'hóng',
0x2B6ED: 'kuáng',
0x2BAC7: 'è',
0x2BD95: 'yíng',
0x2C35B: 'lì',
0x2C7C1: 'yì',
0x2C7FD: 'dōng',
0x2CB41: 'mǔ',
0x2CDA8: 'jì',
0x30EDD: 'biáng',
}
from pypinyin import load_single_dict
def load():
load_single_dict(pinyin_dict)
|
python
|
class DefaultableEntityEndpointsMixin(object):
"""
Defaultable entity endpoints.
"""
def set_default(self, id_):
"""
Sets a entity with given ID as default.
Args:
id_ (str): entity ID.
Returns:
dict: new entity.
"""
self.request('POST', '/'.join((self.name, id_, "set-default")), headers=self.headers)
|
python
|
sexo = str(input('Informe seu sexo [M / F]: ')).strip().upper()[0] # pega somente a primeira letra
while sexo != 'M' and sexo != 'F':
sexo = str(input('DADOS INVALIDOS. Informe seu sexo [M / F]: ')).strip().upper()
|
python
|
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, DateField
from wtforms.validators import DataRequired
class EntryForm(FlaskForm):
entry = StringField('Entry',validators=[DataRequired()])
project = StringField('Project')
notes = StringField('Notes')
save = SubmitField('Save')
|
python
|
'''
# DC Racer Testing and Reporting System (DC RTRS)
This script runs a standard test across all the different
student code bases. The tests will be based on 100 frame
scenarios.
'''
import cv2
import numpy as np
import platform
#import matplotlib.pyplot as plt
import time
import sys
from os import listdir
from os.path import isfile, join
##
## VARIABLES
##
# Turn on OpenCV Output
DEBUG = True
DEMO_MODE = True
# Video frame rate. 33 = ~30 fps, 50 = ~20fps
WAIT_TIME = 50
# Directory when capturing data for analysis
OUTPUT_DIR = "capture"
## TESTING WINDOWS AND DEBUGGING
# set up the windows for testing
if DEBUG:
cv2.namedWindow("live")
# set some variables for testing output
font = cv2.FONT_HERSHEY_SIMPLEX
### B E G I N P R O G R A M ###
roi_num = 0
im_num = 1
frame_num = 0
count = 0
## setup
dir_path = os.path.dirname(os.path.realpath(__file__))
dir_data = os.path.join(dir_path, 'data')
## result variables
results = {}
## import library / code for testing.
#from scripts.detect import detect
# load test cases
testfile = open('tests.csv', 'r')
header = True
for testcase in testfile:
if header:
header = False
continue
# for each test, run the detect function and store the result(s)
folder = os.path.join(dir_data, testcase[1])
onlyfiles = [f for f in listdir(folder) if isfile(join(folder, f))]
results[testcase] = {'correct' : 0, 'incorrect' : 0,
'true_pos' : 0, 'false_pos' : 0,
'true_neg' : 0, 'false_neg' : 0,
'percentage' : 0, 'total_img' : len(onlyfiles)}
for f in onlyfiles:
name = f
img = os.path.join(folder, f)
frame = cv2.imread(img)
# process frame
res = detect(frame)
# process results
# TODO - strip file name and get the detection value from the file name
# TODO - compare with result from res
# save results
while True:
# grab a frame from file
frame = cv2.imread("{1}/{0}_cam-image_array_.jpg".format(im_num, VIDEO_FILE))
im_num += 1
# convert to HSV image
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# trackbars
if TRACKBARS:
l_h = cv2.getTrackbarPos("L-H", "trackbars")
l_s = cv2.getTrackbarPos("L-S", "trackbars")
l_v = cv2.getTrackbarPos("L-V", "trackbars")
u_h = cv2.getTrackbarPos("U-H", "trackbars")
u_s = cv2.getTrackbarPos("U-S", "trackbars")
u_v = cv2.getTrackbarPos("U-V", "trackbars")
lower_trackbars = np.array([l_h, l_s, l_v])
upper_trackbars = np.array([u_s, u_h, u_v])
mask_tbars = cv2.inRange(hsv, lower_trackbars, upper_trackbars)
cv2.imshow("trackbarview", mask_tbars)
#mask = cv2.blur(mask, (5,5))
mask_red = cv2.inRange(hsv, lower_red_stop, upper_red_stop)
mask_red2 = cv2.inRange(hsv, lower_red2_stop, upper_red2_stop)
mask_white = cv2.inRange(hsv, lower_white_stop, upper_stop)
maskfilter = mask_red + mask_red2
#mask = mask + mask_white
##mask = cv2.GaussianBlur(mask, (3,3), 0)
#mask = cv2.erode(mask, kernel)
#mask = cv2.dilate(, kernel, iterations=1)
mask = cv2.morphologyEx(maskfilter, cv2.MORPH_OPEN, kernel, iterations=1)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=1)
mask = cv2.dilate(mask, kernel, iterations=2)
##mask = cv2.erode(mask, kernel, iterations=1)
#mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
#mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
#mask = cv2.erode(mask, kernel)
img = cv2.bitwise_and(frame,frame,mask = mask)
# find shapes
# contours detection
height, width = mask.shape[:2]
contours, _ = cv2.findContours(mask[0:int(height/2), 0:width], cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# find the largest contour first that fits all our conditions.
largest_area = -1
rect = None
for cnt in contours:
area = cv2.contourArea(cnt)
#approx = cv2.approxPolyDP(cnt, 0.01 * cv2.arcLength(cnt, True), True)
x,y,w,h = cv2.boundingRect(cnt)
vr = valid_range(x,y,w,h,frame)
if not vr:
continue
if area > largest_area and area > AREA_SIZE:
largest_area = area
rect = cv2.boundingRect(cnt)
# we found a rect that fits the conditions
if largest_area > 0:
# capture a ROI image and store for later
x,y,w,h = rect
roi = frame[y:y+h, x:x+w]
# check if valid range
vr = valid_range(x,y,w,h,frame)
if not vr:
continue
#cv2.imwrite("{2}/{1}_roi-{0}.jpg".format(roi_num, frame_num, OUTPUT_DIR), roi)
count += 1
#cv2.drawContours(frame, [approx], 0, (0,0,0), 2)
#print(len(cnt), " - ", count)
if len(cnt) == 8:
print("octagon!!", count)
#x = approx.ravel()[0]
#y = approx.ravel()[1]
cv2.rectangle(frame, (x,y), (x+w, y+h), (0,0,0), 2)
cv2.putText(frame, "STOP", (x,y), font, 1, (0,0,0))
if DEBUG:
cv2.imshow("processed", img)
cv2.imshow("mask", mask)
cv2.imshow("color filter", maskfilter)
if DEMO_MODE or DEBUG:
cv2.imshow("live", frame)
key = cv2.waitKey(WAIT_TIME)
if key == ord('q'):
break
continue
cap.release()
cv2.destroyAllWindows()
sys.exit(0)
|
python
|
from io import *
|
python
|
with open('/usr/local/airflow//dags/1','a+') as f:
f.write("1")
|
python
|
x = input("x : ")
print(type(x))
y = int(x) + 1
print(y)
print(f"x : {x}, y : {y}")
#there are some falsy values in python3 whenever we use them in boolean sense it will output false
# "" --> this a empty string which is falsy according to python3
# 0 --> no. zero is also falsy
# None --> which represent absense of a value falsy
#
|
python
|
#
# PySNMP MIB module XEDIA-L2DIAL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/XEDIA-L2DIAL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:36:26 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint")
ModuleCompliance, ObjectGroup, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup")
Counter32, ObjectIdentity, TimeTicks, IpAddress, Counter64, Integer32, Gauge32, iso, Unsigned32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Bits, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "ObjectIdentity", "TimeTicks", "IpAddress", "Counter64", "Integer32", "Gauge32", "iso", "Unsigned32", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Bits", "ModuleIdentity")
TextualConvention, DisplayString, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "RowStatus")
xediaMibs, = mibBuilder.importSymbols("XEDIA-REG", "xediaMibs")
xediaL2DialMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 838, 3, 30))
if mibBuilder.loadTexts: xediaL2DialMIB.setLastUpdated('9902272155Z')
if mibBuilder.loadTexts: xediaL2DialMIB.setOrganization('Xedia Corp.')
l2DialObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 838, 3, 30, 1))
l2DialConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 838, 3, 30, 2))
l2DialStatusTable = MibTable((1, 3, 6, 1, 4, 1, 838, 3, 30, 1, 1), )
if mibBuilder.loadTexts: l2DialStatusTable.setStatus('current')
l2DialStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 838, 3, 30, 1, 1, 1), ).setIndexNames((0, "XEDIA-L2DIAL-MIB", "l2DialStatusIpAddress"))
if mibBuilder.loadTexts: l2DialStatusEntry.setStatus('current')
l2DialStatusIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 838, 3, 30, 1, 1, 1, 1), IpAddress())
if mibBuilder.loadTexts: l2DialStatusIpAddress.setStatus('current')
l2DialStatusSublayer = MibTableColumn((1, 3, 6, 1, 4, 1, 838, 3, 30, 1, 1, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: l2DialStatusSublayer.setStatus('current')
l2DialCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 838, 3, 30, 2, 1))
l2DialGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 838, 3, 30, 2, 2))
l2DialCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 838, 3, 30, 2, 1, 1)).setObjects(("XEDIA-L2DIAL-MIB", "l2DialStatusGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
l2DialCompliance = l2DialCompliance.setStatus('current')
l2DialStatusGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 838, 3, 30, 2, 2, 1)).setObjects(("XEDIA-L2DIAL-MIB", "l2DialStatusSublayer"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
l2DialStatusGroup = l2DialStatusGroup.setStatus('current')
mibBuilder.exportSymbols("XEDIA-L2DIAL-MIB", l2DialGroups=l2DialGroups, l2DialStatusIpAddress=l2DialStatusIpAddress, l2DialObjects=l2DialObjects, PYSNMP_MODULE_ID=xediaL2DialMIB, xediaL2DialMIB=xediaL2DialMIB, l2DialConformance=l2DialConformance, l2DialStatusEntry=l2DialStatusEntry, l2DialStatusSublayer=l2DialStatusSublayer, l2DialStatusTable=l2DialStatusTable, l2DialCompliance=l2DialCompliance, l2DialCompliances=l2DialCompliances, l2DialStatusGroup=l2DialStatusGroup)
|
python
|
'''
Stacking the cubes with sizes in descending order from bottom to top.
**NOTE**
Every time only the left-most or the right-most cube can be stacked from the array/list.
'''
#Input Format:
'''
The first line contains a single integer T, the number of test cases.
For each test case, there are 2 lines.
The first line of each test case contains N, the number of cubes.
The second line contains N space separated integers, denoting the sideLengths of each cube in that order.
'''
#Sample Input:
'''
2
6
4 3 2 1 3 4
3
1 3 2
'''
#OUTPUT:
'''
Yes
No
'''
#Code
for t in range(int(input())):
n=int(input())
c=list(map(int,input().split()))
s=[]
i=0
for i in range(n):
if c==[]:
break
if (c[0]>=c[-1] and s==[]) or (c[0]>=c[-1] and s[-1]>=c[0]):
s.append(c[0])
c.remove(c[0])
elif (c[0]<c[-1] and s==[]) or (c[0]<c[-1] and s[-1]>=c[-1]):
s.append(c[-1])
c.pop(-1)
if c==[]:
print("Yes")
else:
print("No")
|
python
|
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
from taysistunto.feeds import SpeakerFeed, DocumentFeed, ActionFeed, ActionsByWordFeed
urlpatterns = patterns('',
# Examples:
url(r'^$', 'taysistunto.views.index'),
url(r'^(?P<page>\d+)$', 'taysistunto.views.index'),
url(r'^stopify/(?P<word>.*)$', 'taysistunto.views.stopify'),
url(r'^document$', 'taysistunto.views.document'),
url(r'^puhujat/(?P<id>\d+)(-[\-\w]*)?$', 'taysistunto.views.speaker'),
# url(r'^puhujat/(?P<id>\d+)(-[\-\w]*)?/puheenvuorot$', 'taysistunto.views.latest_speaker_actions'),
# url(r'^puhujat/(?P<id>\d+)(-[\-\w]*)?/puheenvuorot/(?P<page>\d+)$', 'taysistunto.views.latest_speaker_actions'),
# url(r'^puhujat/(?P<id>\d+)(-[\-\w]*)?/puheenvuorot/vuosi-(?P<year>\d{4})$', 'taysistunto.views.latest_speaker_actions'),
# url(r'^puhujat/(?P<id>\d+)(-[\-\w]*)?/puheenvuorot/vuosi-(?P<year>\d{4})/(?P<page>\d+)$', 'taysistunto.views.latest_speaker_actions'),
url(r'^puhujat/(?P<id>\d+)(-[\-\w]*)?/syote$', SpeakerFeed.SpeakerFeed()),
url(r'^puhujat$', 'taysistunto.views.all_speakers'),
url(r'^puheenvuorot$', 'taysistunto.views.action_search'),
url(r'^istunnot/(?P<id>[\d\-]+)$', 'taysistunto.views.document'),
url(r'^istunnot/(?P<doc_id>[\d\-]+)/(?P<subject_id>\d+)(-[\-\w]*)?$', 'taysistunto.views.subject'),
url(r'^istunnot/(?P<doc_id>[\d\-]+)/(?P<subject_id>\d+)(-[\-\w]*)?/(?P<action_id>\d+)$', 'taysistunto.views.action'),
url(r'^sanat/?$', 'taysistunto.views.words'),
url(r'^sanat/(?P<word>[^/]+)$', 'taysistunto.views.word'),
url(r'^sanat/(?P<word>[^/]+)/vuosi-(?P<year>\d{4})$', 'taysistunto.views.word'),
url(r'^sanat/(?P<word>[^/]+)/syote$', ActionsByWordFeed.ActionsByWordFeed()),
url(r'^puheenvuorot/syote$', ActionFeed.ActionFeed()),
url(r'^arkisto$', 'taysistunto.views.archive'),
url(r'^arkisto/(?P<chosen_year>\d+)$', 'taysistunto.views.archive'),
url(r'^(?P<tpl>(info))$', 'taysistunto.views.static_content'),
url(r'^istunnot/syote$', DocumentFeed.DocumentFeed()),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^puh-admin/', include(admin.site.urls)),
url(r'^tilaukset/(?P<email>.{5,100})-(?P<checksum>\w{16})$', 'taysistunto.views.manage_subscriptions'),
url(r'^tilaukset/(?P<email>.{5,100})-(?P<checksum>\w{16})/istunnot/lopeta$', 'taysistunto.views.end_subscription'),
url(r'^tilaukset/(?P<email>.{5,100})-(?P<checksum>\w{16})/puheenvuorot/(?P<id>\d+)/lopeta$', 'taysistunto.views.end_subscription'),
url(r'^test-action-mail/(?P<action_id>\d+)$', 'taysistunto.views.test_action_mail'),
url(r'^test-document-mail$', 'taysistunto.views.test_document_mail'),
url(r'^tilaa$', 'taysistunto.views.subscribe'),
)
|
python
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Christian Heider Nielsen"
__doc__ = r"""
Created on 02/03/2020
"""
from enum import Enum
__all__ = ["UpscaleMode", "MergeMode"]
class MergeMode(Enum):
Concat = 0
Add = 1
class UpscaleMode(Enum):
FractionalTranspose = 0
Upsample = 1
if __name__ == "__main__":
assert MergeMode.Concat in MergeMode
assert not (UpscaleMode.Upsample in MergeMode)
assert UpscaleMode.Upsample in UpscaleMode
assert not (MergeMode.Add in UpscaleMode)
# assert not (0 in UpscaleMode)
# assert not (3 in UpscaleMode)
|
python
|
"""Refiner is the refinement module public interface. RefinerFactory is
what should usually be used to construct a Refiner."""
import copy
import logging
import math
import psutil
import libtbx
from dxtbx.model.experiment_list import ExperimentList
from libtbx.phil import parse
import dials.util
from dials.algorithms.refinement import DialsRefineConfigError
from dials.algorithms.refinement.constraints import ConstraintManagerFactory
from dials.algorithms.refinement.engine import AdaptLstbx, refinery_phil_str
from dials.algorithms.refinement.parameterisation import (
build_prediction_parameterisation,
)
from dials.algorithms.refinement.parameterisation import (
phil_str as parameterisation_phil_str,
)
from dials.algorithms.refinement.parameterisation.autoreduce import AutoReduce
from dials.algorithms.refinement.parameterisation.parameter_report import (
ParameterReporter,
)
from dials.algorithms.refinement.prediction.managed_predictors import (
ExperimentsPredictorFactory,
)
from dials.algorithms.refinement.refinement_helpers import ordinal_number, string_sel
from dials.algorithms.refinement.reflection_manager import ReflectionManagerFactory
from dials.algorithms.refinement.reflection_manager import (
phil_str as reflections_phil_str,
)
from dials.algorithms.refinement.restraints import RestraintsParameterisation
from dials.algorithms.refinement.target import TargetFactory
from dials.algorithms.refinement.target import phil_str as target_phil_str
from dials.array_family import flex
logger = logging.getLogger(__name__)
# The include scope directive does not work here. For example:
#
# include scope dials.algorithms.refinement.outlier_detection.phil_scope
#
# results in:
#
# AttributeError: 'module' object has no attribute 'refinement'
#
# to work around this, just include external phil scopes as strings
format_data = {
"reflections_phil": reflections_phil_str,
"target_phil": target_phil_str,
"parameterisation_phil": parameterisation_phil_str,
"refinery_phil": refinery_phil_str,
}
phil_scope = parse(
"""
refinement
.help = "Parameters to configure the refinement"
{
mp
.expert_level = 2
{
nproc = 1
.type = int(value_min=1)
.help = "The number of processes to use. Not all choices of refinement"
"engine support nproc > 1. Where multiprocessing is possible,"
"it is helpful only in certain circumstances, so this is not"
"recommended for typical use."
}
parameterisation
.help = "Parameters to control the parameterisation of experimental models"
{
%(parameterisation_phil)s
}
%(refinery_phil)s
target
.help = "Parameters to configure the target function"
.expert_level = 1
{
%(target_phil)s
}
reflections
.help = "Parameters used by the reflection manager"
{
%(reflections_phil)s
}
}
"""
% format_data,
process_includes=True,
)
RAD2DEG = 180 / math.pi
def _copy_experiments_for_refining(experiments):
"""
Make a partial copy of experiments, copying properties used in refinement.
Any experiment property that can be altered by refinement e.g. Beam,
Detector and Goniometer will be deep-copied, whereas anything that the
refiner doesn't touch (e.g. Scan, ImageSet) will be left as original
references.
This makes it safe to pass an object into the refiner or get an object
out of the refiner without having to worry about your copy being
unexpectedly altered, but saves time by avoiding the copying of potentially
expensive experiment properties (e.g. ImageSet and its attributes).
Args
experiments (Experiment or ExperimentList or Iterable[Experiment]):
Returns:
ExperimentList: The copied experiments in new ExperimentList
"""
# Look for a non-list e.g. a single experiment and convert to a list
if not hasattr(experiments, "__iter__"):
experiments = [experiments]
out_list = ExperimentList()
# Save a map of object id to copies so shared objects remain shared
id_memo = {}
# Copy each experiment individually
for experiment in experiments:
# Be inclusive about the initial copy
new_exp = copy.copy(experiment)
# Ensure every 'refined' attribute is uniquely copied
for model in ["beam", "goniometer", "detector", "crystal"]:
original = getattr(experiment, model)
if id(original) not in id_memo:
id_memo[id(original)] = copy.deepcopy(original)
# assign the new copy to the experiment
setattr(new_exp, model, id_memo[id(original)])
# Collect this together
out_list.append(new_exp)
return out_list
def _trim_scans_to_observations(experiments, reflections):
"""Check the range of each scan matches the range of observed data and
trim the scan to match if it is too wide"""
# Get observed image number (or at least observed phi)
obs_phi = reflections["xyzobs.mm.value"].parts()[2]
try:
obs_z = reflections["xyzobs.px.value"].parts()[2]
except KeyError:
obs_z = None
# Get z_min and z_max from shoeboxes if present
try:
shoebox = reflections["shoebox"]
bb = shoebox.bounding_boxes()
z_min, z_max = bb.parts()[4:]
if z_min.all_eq(0):
shoebox = None
except KeyError:
shoebox = None
for iexp, exp in enumerate(experiments):
sel = reflections["id"] == iexp
isel = sel.iselection()
if obs_z is not None:
exp_z = obs_z.select(isel)
else:
exp_phi = obs_phi.select(isel)
exp_z = exp.scan.get_array_index_from_angle(exp_phi, deg=False)
start, stop = exp.scan.get_array_range()
min_exp_z = flex.min(exp_z)
max_exp_z = flex.max(exp_z)
# If observed array range is correct, skip to next experiment
if int(min_exp_z) == start and int(math.ceil(max_exp_z)) == stop:
continue
# Extend array range either by shoebox size, or 0.5 deg if shoebox not available
if shoebox is not None:
obs_start = flex.min(z_min.select(isel))
obs_stop = flex.max(z_max.select(isel))
else:
obs_start = int(min_exp_z)
obs_stop = int(math.ceil(max_exp_z))
half_deg_in_images = int(math.ceil(0.5 / exp.scan.get_oscillation()[1]))
obs_start -= half_deg_in_images
obs_stop += half_deg_in_images
# Convert obs_start, obs_stop from position in array range to integer image number
if obs_start > start or obs_stop < stop:
im_start = max(start, obs_start) + 1
im_stop = min(obs_stop, stop)
logger.warning(
"The reflections for experiment {0} do not fill the scan range. The scan will be trimmed "
"to images {{{1},{2}}} to match the range of observed data".format(
iexp, im_start, im_stop
)
)
# Ensure the scan is unique to this experiment and set trimmed limits
exp.scan = copy.deepcopy(exp.scan)
new_oscillation = (
exp.scan.get_angle_from_image_index(im_start),
exp.scan.get_oscillation()[1],
)
exp.scan.set_image_range((im_start, im_stop))
exp.scan.set_oscillation(new_oscillation)
return experiments
class RefinerFactory:
"""Factory class to create refiners"""
@staticmethod
def _filter_reflections(reflections):
"""Return a copy of the input reflections filtered to keep only
those columns that are required by refinement"""
cols = [
"id",
"miller_index",
"panel",
"s1",
"xyzobs.mm.value",
"xyzobs.px.value",
"xyzcal.px",
"xyzobs.mm.variance",
"flags",
"shoebox",
"delpsical.weights",
]
# NB xyzobs.px.value & xyzcal.px required by SauterPoon outlier rejector
# NB delpsical.weights is used by ExternalDelPsiWeightingStrategy
rt = flex.reflection_table()
# copy columns to the new table. Could use the select method
# for this except that 's1' is optional in the input so would want
# to copy that in like this if present anyway
for k in cols:
if k in reflections:
rt[k] = reflections[k]
return rt
@classmethod
def from_parameters_data_experiments(cls, params, reflections, experiments):
# TODO Checks on the input
# E.g. does every experiment contain at least one overlapping model with at
# least one other experiment? Are all the experiments either rotation series
# or stills (the combination of both not yet supported)?
# copy the experiments
experiments = _copy_experiments_for_refining(experiments)
# copy and filter the reflections
reflections = cls._filter_reflections(reflections)
return cls._build_components(params, reflections, experiments)
@classmethod
def _build_components(cls, params, reflections, experiments):
"""low level build"""
# Currently a refinement job can only have one parameterisation of the
# prediction equation. This can either be of the XYDelPsi (stills) type, the
# XYPhi (scans) type or the scan-varying XYPhi type with a varying crystal
# model
single_as_still = params.refinement.parameterisation.treat_single_image_as_still
exps_are_stills = []
for exp in experiments:
if exp.scan is None:
exps_are_stills.append(True)
elif exp.scan.get_num_images() == 1:
if single_as_still:
exps_are_stills.append(True)
elif exp.scan.is_still():
exps_are_stills.append(True)
else:
exps_are_stills.append(False)
else:
if exp.scan.get_oscillation()[1] <= 0.0:
raise DialsRefineConfigError("Cannot refine a zero-width scan")
exps_are_stills.append(False)
# check experiment types are consistent
if not all(exps_are_stills[0] == e for e in exps_are_stills):
raise DialsRefineConfigError("Cannot refine a mixture of stills and scans")
do_stills = exps_are_stills[0]
# If experiments are stills, ensure scan-varying refinement won't be attempted
if do_stills:
params.refinement.parameterisation.scan_varying = False
# Refiner does not accept scan_varying=Auto. This is a special case for
# doing macrocycles of refinement in dials.refine.
if params.refinement.parameterisation.scan_varying is libtbx.Auto:
params.refinement.parameterisation.scan_varying = False
# Trim scans and calculate reflection block_width if required for scan-varying refinement
if (
params.refinement.parameterisation.scan_varying
and params.refinement.parameterisation.trim_scan_to_observations
):
experiments = _trim_scans_to_observations(experiments, reflections)
from dials.algorithms.refinement.reflection_manager import BlockCalculator
block_calculator = BlockCalculator(experiments, reflections)
if params.refinement.parameterisation.compose_model_per == "block":
reflections = block_calculator.per_width(
params.refinement.parameterisation.block_width, deg=True
)
elif params.refinement.parameterisation.compose_model_per == "image":
reflections = block_calculator.per_image()
logger.debug("\nBuilding reflection manager")
logger.debug("Input reflection list size = %d observations", len(reflections))
# create reflection manager
refman = ReflectionManagerFactory.from_parameters_reflections_experiments(
params.refinement.reflections, reflections, experiments, do_stills
)
logger.debug(
"Number of observations that pass initial inclusion criteria = %d",
refman.get_accepted_refs_size(),
)
sample_size = refman.get_sample_size()
if sample_size > 0:
logger.debug("Working set size = %d observations", sample_size)
logger.debug("Reflection manager built\n")
# configure use of sparse data types
params = cls.config_sparse(params, experiments)
do_sparse = params.refinement.parameterisation.sparse
# create managed reflection predictor
ref_predictor = ExperimentsPredictorFactory.from_experiments(
experiments,
force_stills=do_stills,
spherical_relp=params.refinement.parameterisation.spherical_relp_model,
)
# Predict for the managed observations, set columns for residuals and set
# the used_in_refinement flag to the predictions
obs = refman.get_obs()
ref_predictor(obs)
x_obs, y_obs, phi_obs = obs["xyzobs.mm.value"].parts()
x_calc, y_calc, phi_calc = obs["xyzcal.mm"].parts()
obs["x_resid"] = x_calc - x_obs
obs["y_resid"] = y_calc - y_obs
obs["phi_resid"] = phi_calc - phi_obs
# determine whether to do basic centroid analysis to automatically
# determine outlier rejection block
if params.refinement.reflections.outlier.block_width is libtbx.Auto:
ca = refman.get_centroid_analyser()
analysis = ca(calc_average_residuals=False, calc_periodograms=False)
else:
analysis = None
# Now predictions and centroid analysis are available, so we can finalise
# the reflection manager
refman.finalise(analysis)
# Create model parameterisations
logger.debug("Building prediction equation parameterisation")
pred_param = build_prediction_parameterisation(
params.refinement.parameterisation, experiments, refman, do_stills
)
# Build a constraints manager, if requested
cmf = ConstraintManagerFactory(params, pred_param)
constraints_manager = cmf()
# Test for parameters that have too little data to refine and act accordingly
autoreduce = AutoReduce(
params.refinement.parameterisation.auto_reduction,
pred_param,
refman,
constraints_manager,
cmf,
)
autoreduce()
# if reduction was done, constraints_manager will have changed
constraints_manager = autoreduce.constraints_manager
# Build a restraints parameterisation (if requested).
# Only unit cell restraints are supported at the moment.
restraints_parameterisation = cls.config_restraints(
params.refinement.parameterisation, pred_param
)
# Parameter reporting
logger.debug("Prediction equation parameterisation built")
logger.debug("Parameter order : name mapping")
for i, e in enumerate(pred_param.get_param_names()):
logger.debug("Parameter %03d : %s", i + 1, e)
param_reporter = ParameterReporter(
pred_param.get_detector_parameterisations(),
pred_param.get_beam_parameterisations(),
pred_param.get_crystal_orientation_parameterisations(),
pred_param.get_crystal_unit_cell_parameterisations(),
pred_param.get_goniometer_parameterisations(),
)
# Create target function
logger.debug("Building target function")
target = cls.config_target(
params.refinement.target,
experiments,
refman,
ref_predictor,
pred_param,
restraints_parameterisation,
do_stills,
do_sparse,
)
logger.debug("Target function built")
# create refinery
logger.debug("Building refinement engine")
refinery = cls.config_refinery(params, target, pred_param, constraints_manager)
logger.debug("Refinement engine built")
nparam = len(pred_param)
ndim = target.dim
nref = len(refman.get_matches())
logger.info(
"There are %s parameters to refine against %s reflections in %s dimensions",
nparam,
nref,
ndim,
)
if not params.refinement.parameterisation.sparse and isinstance(
refinery, AdaptLstbx
):
dense_jacobian_gigabytes = (
nparam * nref * ndim * flex.double.element_size()
) / 1e9
avail_memory_gigabytes = psutil.virtual_memory().available / 1e9
# Report if the Jacobian requires a large amount of storage
if (
dense_jacobian_gigabytes > 0.2 * avail_memory_gigabytes
or dense_jacobian_gigabytes > 0.5
):
logger.info(
"Storage of the Jacobian matrix requires %.1f GB",
dense_jacobian_gigabytes,
)
# build refiner interface and return
if params.refinement.parameterisation.scan_varying:
refiner = ScanVaryingRefiner
else:
refiner = Refiner
return refiner(
experiments, pred_param, param_reporter, refman, target, refinery
)
@staticmethod
def config_sparse(params, experiments):
"""Configure whether to use sparse datatypes"""
# Automatic selection for sparse parameter
if params.refinement.parameterisation.sparse == libtbx.Auto:
if len(experiments) > 1:
params.refinement.parameterisation.sparse = True
else:
params.refinement.parameterisation.sparse = False
if params.refinement.refinery.engine == "SparseLevMar":
params.refinement.parameterisation.sparse = True
if params.refinement.mp.nproc > 1:
if params.refinement.refinery.engine != "SparseLevMar":
# sparse vectors cannot be pickled, so can't use easy_mp here
params.refinement.parameterisation.sparse = False
else:
pass # but SparseLevMar requires sparse jacobian; does not implement mp
# Check incompatible selection
elif (
params.refinement.parameterisation.sparse and params.refinement.mp.nproc > 1
):
logger.warning(
"Could not set sparse=True and nproc=%s", params.refinement.mp.nproc
)
logger.warning("Resetting sparse=False")
params.refinement.parameterisation.sparse = False
return params
@staticmethod
def config_restraints(params, pred_param):
"""Given a set of user parameters plus a model parameterisation, create
restraints plus a parameterisation of these restraints
Params:
params: The input PHIL parameters
pred_param: A PredictionParameters object
Returns:
A restraints parameterisation or None
"""
if not any(
(
params.crystal.unit_cell.restraints.tie_to_target,
params.crystal.unit_cell.restraints.tie_to_group,
)
):
return None
if params.scan_varying and not params.crystal.unit_cell.force_static:
logger.warning("Restraints will be ignored for scan_varying=True")
return None
det_params = pred_param.get_detector_parameterisations()
beam_params = pred_param.get_beam_parameterisations()
xl_ori_params = pred_param.get_crystal_orientation_parameterisations()
xl_uc_params = pred_param.get_crystal_unit_cell_parameterisations()
gon_params = pred_param.get_goniometer_parameterisations()
rp = RestraintsParameterisation(
detector_parameterisations=det_params,
beam_parameterisations=beam_params,
xl_orientation_parameterisations=xl_ori_params,
xl_unit_cell_parameterisations=xl_uc_params,
goniometer_parameterisations=gon_params,
)
# Shorten params path
cell_r = params.crystal.unit_cell.restraints
for tie in cell_r.tie_to_target:
if len(tie.values) != 6:
raise DialsRefineConfigError(
"6 cell parameters must be provided as the tie_to_target.values."
)
if len(tie.sigmas) != 6:
raise DialsRefineConfigError(
"6 sigmas must be provided as the tie_to_target.sigmas. "
"Note that individual sigmas of 0.0 will remove "
"the restraint for the corresponding cell parameter."
)
if tie.id is None:
# get one experiment id for each parameterisation to apply to all
tie.id = [e.get_experiment_ids()[0] for e in xl_uc_params]
for exp_id in tie.id:
rp.add_restraints_to_target_xl_unit_cell(exp_id, tie.values, tie.sigmas)
for tie in cell_r.tie_to_group:
if len(tie.sigmas) != 6:
raise DialsRefineConfigError(
"6 sigmas must be provided as the tie_to_group.sigmas. "
"Note that individual sigmas of 0.0 will remove "
"the restraint for the corresponding cell parameter."
)
if tie.id is None:
rp.add_restraints_to_group_xl_unit_cell(tie.target, "all", tie.sigmas)
else:
rp.add_restraints_to_group_xl_unit_cell(tie.target, tie.id, tie.sigmas)
return rp
@staticmethod
def config_refinery(params, target, pred_param, constraints_manager):
"""Given a set of parameters, a target class, a prediction
parameterisation class and a constraints_manager (which could be None),
build a refinery
Params:
params The input parameters
Returns:
The refinery instance
"""
# Shorten parameter path
options = params.refinement.refinery
if options.engine == "SimpleLBFGS":
from dials.algorithms.refinement.engine import SimpleLBFGS as refinery
elif options.engine == "LBFGScurvs":
from dials.algorithms.refinement.engine import LBFGScurvs as refinery
elif options.engine == "GaussNewton":
from dials.algorithms.refinement.engine import (
GaussNewtonIterations as refinery,
)
elif options.engine == "LevMar":
from dials.algorithms.refinement.engine import (
LevenbergMarquardtIterations as refinery,
)
elif options.engine == "SparseLevMar":
from dials.algorithms.refinement.sparse_engine import (
SparseLevenbergMarquardtIterations as refinery,
)
else:
raise RuntimeError(
"Refinement engine " + options.engine + " not recognised"
)
logger.debug("Selected refinement engine type: %s", options.engine)
engine = refinery(
target=target,
prediction_parameterisation=pred_param,
constraints_manager=constraints_manager,
log=options.log,
tracking=options.journal,
max_iterations=options.max_iterations,
)
if params.refinement.mp.nproc > 1:
nproc = params.refinement.mp.nproc
try:
engine.set_nproc(nproc)
except NotImplementedError:
logger.warning(
"Could not set nproc=%s for refinement engine of type %s",
nproc,
options.engine,
)
return engine
# Overload to allow subclasses of RefinerFactory to use a different
# TargetFactory
@staticmethod
def config_target(
params,
experiments,
reflection_manager,
predictor,
pred_param,
restraints_param,
do_stills,
do_sparse,
):
target = TargetFactory.from_parameters_and_experiments(
params,
experiments,
reflection_manager,
predictor,
pred_param,
restraints_param,
do_stills,
do_sparse,
)
return target
class Refiner:
"""Public interface for performing DIALS refinement.
Public methods:
run
rmsds
get_experiments
get_matches
get_param_reporter
parameter_correlation_plot
selection_used_for_refinement
predict_for_reflection_table
predict_for_indexed
Notes:
* The return value of run is a recorded history of the refinement
* The experiments accessor provides a copy of the experiments used by
refinement
* get_matches exposes the function of the same name from the privately
stored reflection manager
* The return value of selection_used_for_refinement is a flex.bool
"""
def __init__(
self, experiments, pred_param, param_reporter, refman, target, refinery
):
"""
Mandatory arguments:
experiments - a dxtbx ExperimentList object
pred_param - An object derived from the PredictionParameterisation class
param_reporter -A ParameterReporter object
refman - A ReflectionManager object
target - An object derived from the Target class
refinery - An object derived from the Refinery class
"""
# the experimental models
self._experiments = experiments
# refinement module main objects
self._pred_param = pred_param
self._refman = refman
self._target = target
self._refinery = refinery
# parameter reporter
self._param_report = param_reporter
# Keep track of whether this is stills or scans type refinement
self.experiment_type = refman.experiment_type
return
def get_experiments(self):
"""Return a copy of the current refiner experiments"""
return _copy_experiments_for_refining(self._experiments)
def rmsds(self):
"""Return rmsds of the current model"""
# ensure predictions for the matches are up to date
self._refinery.prepare_for_step()
return self._target.rmsds()
def rmsds_for_reflection_table(self, reflections):
"""Calculate unweighted RMSDs for the specified reflections"""
# ensure predictions for these reflections are up to date
preds = self.predict_for_reflection_table(reflections)
return self._target.rmsds_for_reflection_table(preds)
def get_matches(self):
"""Delegated to the reflection manager"""
return self._refman.get_matches()
def get_free_reflections(self):
"""Delegated to the reflection manager"""
return self._refman.get_free_reflections()
def get_param_reporter(self):
"""Get the ParameterReport object linked to this Refiner"""
return self._param_report
def get_parameter_correlation_matrix(self, step, col_select=None):
"""Return the correlation matrix between columns of the Jacobian at
the specified refinement step. The parameter col_select can be used
to select subsets of the full number of columns. The column labels
are also returned as a list of strings"""
corrmats = self._refinery.get_correlation_matrix_for_step(step)
if corrmats is None:
return None, None
all_labels = self._pred_param.get_param_names()
if col_select is None:
col_select = list(range(len(all_labels)))
sel = string_sel(col_select, all_labels)
labels = [e for e, s in zip(all_labels, sel) if s]
num_cols = len(labels)
if num_cols == 0:
return None, None
for k, corrmat in corrmats.items():
assert corrmat.is_square_matrix()
idx = flex.bool(sel).iselection()
sub_corrmat = flex.double(flex.grid(num_cols, num_cols))
for (i, x) in enumerate(idx):
for (j, y) in enumerate(idx):
sub_corrmat[i, j] = corrmat[x, y]
corrmats[k] = sub_corrmat
return (corrmats, labels)
@property
def history(self):
"""Get the refinement engine's step history"""
return self._refinery.history
def print_step_table(self):
"""print useful output about refinement steps in the form of a simple table"""
logger.info("\nRefinement steps:")
rmsd_multipliers = []
header = ["Step", "Nref"]
for (name, units) in zip(self._target.rmsd_names, self._target.rmsd_units):
if units == "mm":
header.append(name + "\n(mm)")
rmsd_multipliers.append(1.0)
elif units == "rad": # convert radians to degrees for reporting
header.append(name + "\n(deg)")
rmsd_multipliers.append(RAD2DEG)
else: # leave unknown units alone
header.append(name + "\n(" + units + ")")
rows = []
for i in range(self._refinery.history.get_nrows()):
rmsds = [
r * m
for (r, m) in zip(self._refinery.history["rmsd"][i], rmsd_multipliers)
]
rows.append(
[str(i), str(self._refinery.history["num_reflections"][i])]
+ [f"{r:.5g}" for r in rmsds]
)
logger.info(dials.util.tabulate(rows, header))
logger.info(self._refinery.history.reason_for_termination)
return
def print_out_of_sample_rmsd_table(self):
"""print out-of-sample RSMDs per step, if these were tracked"""
# check if it makes sense to proceed
if "out_of_sample_rmsd" not in self._refinery.history:
return
nref = len(self.get_free_reflections())
if nref < 10:
return # don't do anything if very few refs
logger.info("\nRMSDs for out-of-sample (free) reflections:")
rmsd_multipliers = []
header = ["Step", "Nref"]
for (name, units) in zip(self._target.rmsd_names, self._target.rmsd_units):
if units == "mm":
header.append(name + "\n(mm)")
rmsd_multipliers.append(1.0)
elif units == "rad": # convert radians to degrees for reporting
header.append(name + "\n(deg)")
rmsd_multipliers.append(RAD2DEG)
else: # leave unknown units alone
header.append(name + "\n(" + units + ")")
rows = []
for i in range(self._refinery.history.get_nrows()):
rmsds = [
r * m
for r, m in zip(
self._refinery.history["out_of_sample_rmsd"][i], rmsd_multipliers
)
]
rows.append([str(i), str(nref)] + [f"{e:.5g}" for e in rmsds])
logger.info(dials.util.tabulate(rows, header))
return
def print_exp_rmsd_table(self):
"""print useful output about refinement steps in the form of a simple table"""
logger.info("\nRMSDs by experiment:")
header = ["Exp\nid", "Nref"]
for (name, units) in zip(self._target.rmsd_names, self._target.rmsd_units):
if name == "RMSD_X" or name == "RMSD_Y" and units == "mm":
header.append(name + "\n(px)")
elif name == "RMSD_Phi" and units == "rad":
# will convert radians to images for reporting of scans
header.append("RMSD_Z" + "\n(images)")
elif units == "rad":
# will convert other angles in radians to degrees (e.g. for
# RMSD_DeltaPsi and RMSD_2theta)
header.append(name + "\n(deg)")
else: # skip other/unknown RMSDs
pass
rows = []
for iexp, exp in enumerate(self._experiments):
detector = exp.detector
px_sizes = [p.get_pixel_size() for p in detector]
it = iter(px_sizes)
px_size = next(it)
if not all(tst == px_size for tst in it):
logger.info(
"The detector in experiment %d does not have the same pixel "
+ "sizes on each panel. Skipping...",
iexp,
)
continue
px_per_mm = [1.0 / e for e in px_size]
scan = exp.scan
try:
images_per_rad = 1.0 / abs(scan.get_oscillation(deg=False)[1])
except (AttributeError, ZeroDivisionError):
images_per_rad = None
raw_rmsds = self._target.rmsds_for_experiment(iexp)
if raw_rmsds is None:
continue # skip experiments where rmsd cannot be calculated
num = self._target.get_num_matches_for_experiment(iexp)
rmsds = []
for (name, units, rmsd) in zip(
self._target.rmsd_names, self._target.rmsd_units, raw_rmsds
):
if name == "RMSD_X" and units == "mm":
rmsds.append(rmsd * px_per_mm[0])
elif name == "RMSD_Y" and units == "mm":
rmsds.append(rmsd * px_per_mm[1])
elif name == "RMSD_Phi" and units == "rad":
rmsds.append(rmsd * images_per_rad)
elif units == "rad":
rmsds.append(rmsd * RAD2DEG)
rows.append([str(iexp), str(num)] + [f"{r:.5g}" for r in rmsds])
if len(rows) > 0:
logger.info(dials.util.tabulate(rows, header))
return
def print_panel_rmsd_table(self):
"""print useful output about refinement steps in the form of a simple table"""
if len(self._experiments.scans()) > 1:
logger.warning(
"Multiple scans present. Only the first scan will be used "
"to determine the image width for reporting RMSDs"
)
scan = self._experiments.scans()[0]
try:
images_per_rad = 1.0 / abs(scan.get_oscillation(deg=False)[1])
except AttributeError:
images_per_rad = None
for idetector, detector in enumerate(self._experiments.detectors()):
if len(detector) == 1:
continue
logger.info("\nDetector %s RMSDs by panel:", idetector + 1)
header = ["Panel\nid", "Nref"]
for (name, units) in zip(self._target.rmsd_names, self._target.rmsd_units):
if name == "RMSD_X" or name == "RMSD_Y" and units == "mm":
header.append(name + "\n(px)")
elif (
name == "RMSD_Phi" and units == "rad"
): # convert radians to images for reporting of scans
header.append("RMSD_Z" + "\n(images)")
elif (
name == "RMSD_DeltaPsi" and units == "rad"
): # convert radians to degrees for reporting of stills
header.append(name + "\n(deg)")
else: # skip RMSDs that cannot be expressed in image/scan space
pass
rows = []
for ipanel, panel in enumerate(detector):
px_size = panel.get_pixel_size()
px_per_mm = [1.0 / e for e in px_size]
num = self._target.get_num_matches_for_panel(ipanel)
if num <= 0:
continue
raw_rmsds = self._target.rmsds_for_panel(ipanel)
if raw_rmsds is None:
continue # skip panels where rmsd cannot be calculated
rmsds = []
for (name, units, rmsd) in zip(
self._target.rmsd_names, self._target.rmsd_units, raw_rmsds
):
if name == "RMSD_X" and units == "mm":
rmsds.append(rmsd * px_per_mm[0])
elif name == "RMSD_Y" and units == "mm":
rmsds.append(rmsd * px_per_mm[1])
elif name == "RMSD_Phi" and units == "rad":
rmsds.append(rmsd * images_per_rad)
elif name == "RMSD_DeltaPsi" and units == "rad":
rmsds.append(rmsd * RAD2DEG)
rows.append([str(ipanel), str(num)] + [f"{r:.5g}" for r in rmsds])
if len(rows) > 0:
logger.info(dials.util.tabulate(rows, header))
return
def run(self):
"""Run refinement"""
####################################
# Do refinement and return history #
####################################
logger.debug("\nExperimental models before refinement:")
for i, beam in enumerate(self._experiments.beams()):
logger.debug(ordinal_number(i) + " " + str(beam))
for i, detector in enumerate(self._experiments.detectors()):
logger.debug(ordinal_number(i) + " " + str(detector))
for i, goniometer in enumerate(self._experiments.goniometers()):
if goniometer is None:
continue
logger.debug(ordinal_number(i) + " " + str(goniometer))
for i, scan in enumerate(self._experiments.scans()):
if scan is None:
continue
logger.debug(ordinal_number(i) + " " + str(scan))
for i, crystal in enumerate(self._experiments.crystals()):
logger.debug(ordinal_number(i) + " " + str(crystal))
self._refinery.run()
# These involve calculation, so skip them when output is quiet
if logger.getEffectiveLevel() < logging.ERROR:
self.print_step_table()
self.print_out_of_sample_rmsd_table()
self.print_exp_rmsd_table()
det_npanels = [len(d) for d in self._experiments.detectors()]
if any(n > 1 for n in det_npanels):
self.print_panel_rmsd_table()
# Perform post-run tasks to write the refined states back to the models
self._update_models()
logger.debug("\nExperimental models after refinement:")
for i, beam in enumerate(self._experiments.beams()):
logger.debug(ordinal_number(i) + " " + str(beam))
for i, detector in enumerate(self._experiments.detectors()):
logger.debug(ordinal_number(i) + " " + str(detector))
for i, goniometer in enumerate(self._experiments.goniometers()):
if goniometer is None:
continue
logger.debug(ordinal_number(i) + " " + str(goniometer))
for i, scan in enumerate(self._experiments.scans()):
if scan is None:
continue
logger.debug(ordinal_number(i) + " " + str(scan))
for i, crystal in enumerate(self._experiments.crystals()):
logger.debug(ordinal_number(i) + " " + str(crystal))
# Report on the refined parameters
logger.debug(str(self._param_report))
# Return the refinement history
return self._refinery.history
def _update_models(self):
"""Perform any extra tasks required to update the models after refinement.
Does nothing here, but used by subclasses"""
pass
def selection_used_for_refinement(self):
"""Return a selection as a flex.bool in terms of the input reflection
data of those reflections that were used in the final step of
refinement."""
matches = self._refman.get_matches()
selection = flex.bool(len(self._refman.get_indexed()), False)
try: # new reflection table format for matches
isel = matches["iobs"]
selection.set_selected(isel, True)
except TypeError: # old ObsPredMatch format for matches
for m in matches:
selection[m.iobs] = True
return selection
def predict_for_indexed(self):
"""perform prediction for all the indexed reflections passed into
refinement and additionally set the used_in_refinement flag. Do not
compose the derivatives of states of the model as this is expensive and
they are not needed outside of a refinement run"""
reflections = self.predict_for_reflection_table(
self._refman.get_indexed(), skip_derivatives=True
)
reflections.sort("iobs")
mask = self.selection_used_for_refinement()
reflections.set_flags(mask, reflections.flags.used_in_refinement)
return reflections
def predict_for_reflection_table(self, reflections, skip_derivatives=False):
"""perform prediction for all reflections in the supplied table"""
# delegate to the target object, which has access to the predictor
return self._target.predict_for_reflection_table(reflections, skip_derivatives)
class ScanVaryingRefiner(Refiner):
"""Includes functionality to update the models with their states at
scan-points after scan-varying refinement"""
def _update_models(self):
for iexp, exp in enumerate(self._experiments):
ar_range = exp.scan.get_array_range()
obs_image_numbers = list(range(ar_range[0], ar_range[1] + 1))
# write scan-varying s0 vectors back to beam models
s0_list = self._pred_param.get_varying_s0(obs_image_numbers, iexp)
if s0_list is not None:
exp.beam.set_s0_at_scan_points(s0_list)
# write scan-varying setting rotation matrices back to goniometer models
S_list = self._pred_param.get_varying_setting_rotation(
obs_image_numbers, iexp
)
if S_list is not None:
exp.goniometer.set_setting_rotation_at_scan_points(S_list)
# write scan-varying crystal setting matrices back to crystal models
A_list = self._pred_param.get_varying_UB(obs_image_numbers, iexp)
if A_list is not None:
exp.crystal.set_A_at_scan_points(A_list)
# Calculate scan-varying errors if requested
if self._pred_param.set_scan_varying_errors:
# get state covariance matrices the whole range of images. We select
# the first element of this at each image because crystal scan-varying
# parameterisations are not multi-state
state_cov_list = [
self._pred_param.calculate_model_state_uncertainties(
obs_image_number=t, experiment_id=iexp
)
for t in range(ar_range[0], ar_range[1] + 1)
]
if "U_cov" in state_cov_list[0]:
u_cov_list = [e["U_cov"] for e in state_cov_list]
else:
u_cov_list = None
if "B_cov" in state_cov_list[0]:
b_cov_list = [e["B_cov"] for e in state_cov_list]
else:
b_cov_list = None
# return these to the model parameterisations to be set in the models
self._pred_param.set_model_state_uncertainties(
u_cov_list, b_cov_list, iexp
)
|
python
|
#
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible_collections.community.general.tests.unit.compat.mock import patch
from ansible_collections.community.general.plugins.modules.network.onyx import onyx_bgp
from ansible_collections.community.general.tests.unit.modules.utils import set_module_args
from ..onyx_module import TestOnyxModule, load_fixture
class TestOnyxBgpModule(TestOnyxModule):
module = onyx_bgp
def setUp(self):
super(TestOnyxBgpModule, self).setUp()
self.mock_get_config = patch.object(
onyx_bgp.OnyxBgpModule, "_get_bgp_summary")
self.get_config = self.mock_get_config.start()
self.mock_load_config = patch(
'ansible_collections.community.general.plugins.module_utils.network.onyx.onyx.load_config')
self.load_config = self.mock_load_config.start()
def tearDown(self):
super(TestOnyxBgpModule, self).tearDown()
self.mock_get_config.stop()
self.mock_load_config.stop()
def load_fixtures(self, commands=None, transport='cli'):
config_file = 'onyx_bgp_show.cfg'
self.get_config.return_value = load_fixture(config_file)
self.load_config.return_value = None
def test_bgp_no_change(self):
neighbor = dict(remote_as=322, neighbor='10.2.3.5', multihop=255)
set_module_args(dict(as_number=172, router_id='1.2.3.4',
neighbors=[neighbor],
networks=['172.16.1.0/24'],
evpn=True, fast_external_fallover=True,
max_paths=31, ecmp_bestpath=True,
))
self.execute_module(changed=False)
def test_bgp_remove(self):
set_module_args(dict(as_number=172, state='absent'))
commands = ['no router bgp 172']
self.execute_module(changed=True, commands=commands)
def test_bgp_with_vrf_changed(self):
set_module_args(dict(as_number=173, vrf='new_vrf'))
commands = ['no router bgp 172 vrf default', 'router bgp 173 vrf new_vrf', 'exit']
self.execute_module(changed=True, commands=commands)
def test_bgp_change(self):
neighbor = dict(remote_as=173, neighbor='10.2.3.4')
set_module_args(dict(as_number=174, router_id='1.2.3.4',
neighbors=[neighbor],
evpn=False, fast_external_fallover=False,
max_paths=32, ecmp_bestpath=False,
))
commands = ['no router bgp 172 vrf default', 'router bgp 174 vrf default', 'exit',
'router bgp 174 vrf default router-id 1.2.3.4 force',
'router bgp 174 vrf default neighbor 10.2.3.4 remote-as 173',
'no router bgp 174 vrf default neighbor evpn peer-group',
'no router bgp 174 vrf default address-family l2vpn-evpn auto-create',
'router bgp 174 vrf default no bgp fast-external-fallover',
'router bgp 174 vrf default maximum-paths 32',
'router bgp 174 vrf default no bestpath as-path multipath-relax force']
self.execute_module(changed=True, commands=commands)
def test_bgp_add_neighbor(self):
neighbors = [dict(remote_as=173, neighbor='10.2.3.4'),
dict(remote_as=175, neighbor='10.2.3.5'),
dict(remote_as=175, neighbor='10.2.3.6', multihop=250)]
set_module_args(dict(as_number=172, router_id='1.2.3.4',
neighbors=neighbors,
networks=['172.16.1.0/24'],
evpn=True))
commands = ['router bgp 172 vrf default neighbor 10.2.3.5 remote-as 175',
'router bgp 172 vrf default neighbor 10.2.3.6 remote-as 175',
'router bgp 172 vrf default neighbor 10.2.3.6 ebgp-multihop 250',
'router bgp 172 vrf default neighbor 10.2.3.6 peer-group evpn',
'router bgp 172 vrf default neighbor 10.2.3.4 peer-group evpn']
self.execute_module(changed=True, commands=commands)
def test_bgp_del_neighbor(self):
set_module_args(dict(as_number=172,
networks=['172.16.1.0/24'],
purge=True))
commands = ['router bgp 172 vrf default no neighbor 10.2.3.4 remote-as 173',
'router bgp 172 vrf default no neighbor 10.2.3.5 remote-as 322']
self.execute_module(changed=True, commands=commands)
def test_bgp_add_network(self):
neighbors = [dict(remote_as=173, neighbor='10.2.3.4')]
set_module_args(dict(as_number=172, router_id='1.2.3.4',
neighbors=neighbors,
networks=['172.16.1.0/24', '172.16.2.0/24']))
commands = ['router bgp 172 vrf default network 172.16.2.0 /24']
self.execute_module(changed=True, commands=commands)
def test_bgp_del_network(self):
neighbors = [dict(remote_as=173, neighbor='10.2.3.4')]
set_module_args(dict(as_number=172, neighbors=neighbors))
commands = ['router bgp 172 no network 172.16.1.0 /24']
self.execute_module(changed=True, commands=commands)
|
python
|
import torch
from enum import Enum
from experiments import constants
class OptimizerType(Enum):
SGD = 0
Adam = 1
class SchedulerType(Enum):
MultiStep = 0
class SingleNetworkOptimization(object):
def __init__(self, network: torch.nn.Module, n_epochs: int,
lr=1e-4, weight_decay=1e-3, optimizer_type: OptimizerType = OptimizerType.SGD, grad_norm_clipping=10,
betas=(0.9, 0.999), enable_lr_scheduler=False, gamma: float = 0.1, scheduler_steps: list = []):
self.n_epochs = n_epochs
self.network = network
self.optimizer_type = optimizer_type
if self.optimizer_type == OptimizerType.SGD:
self.opt = torch.optim.SGD(network.parameters(), lr=lr, momentum=0.0, nesterov=False,
weight_decay=weight_decay)
elif self.optimizer_type == OptimizerType.Adam:
self.opt = torch.optim.Adam(network.parameters(), lr=lr, weight_decay=weight_decay, betas=betas)
else:
raise NotImplemented
self.grad_norm_clipping = grad_norm_clipping
self.enable_lr_scheduler = enable_lr_scheduler
self.scheduler_list = []
if self.enable_lr_scheduler:
self.scheduler_list.append(
torch.optim.lr_scheduler.MultiStepLR(self.opt, milestones=scheduler_steps, gamma=gamma))
self.norm_type = 2
def end_epoch(self):
[s.step() for s in self.scheduler_list]
def zero_grad(self):
self.opt.zero_grad()
def step(self):
if self.grad_norm_clipping > 0:
grad_norm = torch.nn.utils.clip_grad.clip_grad_norm_(self.network.parameters(),
max_norm=self.grad_norm_clipping).item()
else:
grad_norm = torch.norm(
torch.stack(
[torch.norm(p.grad.detach(), self.norm_type).to(constants.DEVICE) for p in
self.network.parameters() if p.grad is not None]),
self.norm_type)
self.opt.step()
return grad_norm
|
python
|
import sys
import random
import time
from cnn import utils
import logging
import warnings
warnings.filterwarnings("ignore")
import argparse
import torch.utils
import torch.backends.cudnn as cudnn
from utils.scheduler import Scheduler
from torchvision.transforms import transforms
import torchvision.datasets as datasets
from tensorboardX import SummaryWriter
from cnn.supernet import *
from distributed import *
from utils.auto_augment import auto_augment_transform
from utils.Mixup import Mixup
from utils.loss import *
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
parser = argparse.ArgumentParser("RepNAS")
parser.add_argument('--data', type=str, default='.', help='location of the data')
parser.add_argument('--workers', type=int, default=50, help='number of data loading workers')
parser.add_argument('--model', type=str, default='RepVGGA0', help='type of model which can be selected in [RepVGG_A0, RepVGG_A1, RepVGG_B2g4, RepVGG_B3]')
parser.add_argument('--batch_size', type=int, default=256, help='batch size')
parser.add_argument('--base_lr', type=float, default=0.1, help='init learning rate')
parser.add_argument('--momentum', type=float, default=0.9, help='momentum')
parser.add_argument('--weight_decay', type=float, default=1e-4, help='weight decay')
parser.add_argument('--lr_mode', type=str, default='cosine', help='[step, poly, cosine]')
parser.add_argument('--wd_mode', type=str, default='cosine', help='[step, poly, cosine]')
parser.add_argument('--warmup_lr', type=float, default=0.1, help='init warmup learning rate')
parser.add_argument('--warmup_epochs', type=int, default=0, help='number of warmup epochs')
parser.add_argument('--warmup_mode', type=str, default='constant', help='mode of warmup [constant, linear]')
parser.add_argument('--mixup', action='store_true', help='using mixup')
parser.add_argument('--autoaugment', action='store_true', help='using autoaugment')
parser.add_argument('--smooth', action='store_true', help='using smooth CE')
parser.add_argument('--report_freq', type=float, default=500, help='report frequency')
parser.add_argument('--epochs', type=int, default=150, help='number of training epochs')
parser.add_argument('--resume', action='store_true', help='resume from checkpoint')
parser.add_argument('--seed', type=int, default=2, help='random seed')
parser.add_argument('--save', type=str, default='logs', help='experiment name')
parser.add_argument('--random_epochs', type=int, default=15, help='number of random sample epochs')
parser.add_argument('--fixed_epochs', type=int, default=100, help='number of fixed epochs.')
parser.add_argument('--arch_lr', type=float, default=1e-4, help='learning rate for arch encoding')
parser.add_argument('--arch_weight_decay', type=float, default=5e-4, help='weight decay for arch encoding')
parser.add_argument('--kept_ratio', type=float, default=0.34, help='learning rate for arch encoding')
parser.add_argument('--local_rank', type=int, default=0, help='number for current rank')
args = parser.parse_args()
CLASSES = 1000
def set_random_seed(seed=None):
"""set random seed"""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
def main():
if not torch.cuda.is_available():
logging.info('no gpu device available')
sys.exit(1)
current_time = time.strftime("%Y-%m-%dT%H:%M", time.localtime())
args.distributed = False
if 'WORLD_SIZE' in os.environ:
args.distributed = int(os.environ['WORLD_SIZE']) > 1
args.batch_size = args.batch_size // int(os.environ['WORLD_SIZE'])
if args.distributed:
gpu_id = init_dist()
set_random_seed(args.seed)
if is_master():
Writer = SummaryWriter(log_dir=current_time)
print(args)
else:
Writer = None
cudnn.benchmark = True
cudnn.enabled = True
if not args.mixup and args.smooth:
criterion_smooth = LabelSmoothingCrossEntropy().cuda()
elif args.mixup and args.smooth:
criterion_smooth = SoftTargetCrossEntropy().cuda()
else:
criterion_smooth = nn.CrossEntropyLoss().cuda()
criterion = nn.CrossEntropyLoss().cuda()
model = model_map[args.model]()
model = model.cuda()
param = []
arch_param = []
for key, value in model.named_parameters():
if not value.requires_grad:
continue
if 'alphas' in key:
arch_param += [{'params': [value], 'lr': args.arch_lr, 'weight_decay': args.arch_weight_decay}]
else:
if 'bias' in key or 'bn' in key:
weight_decay = 0
else:
weight_decay = args.weight_decay
param += [{'params': [value], 'lr': args.base_lr, 'weight_decay': weight_decay}]
optimizer = torch.optim.SGD(
param,
momentum=args.momentum,
)
arch_optimizer = torch.optim.Adam(
arch_param,
betas=(0.5, 0.999),
weight_decay=args.arch_weight_decay
)
current_epoch = 0
if args.resume and os.path.exists(os.path.join(args.save, 'ckpt.pt')):
print('loading checkpoint')
checkpoint = torch.load(os.path.join(args.save, 'ckpt.pt'), map_location='cpu')
current_epoch = checkpoint['epoch']
state_dict = OrderedDict()
for name, param in checkpoint['model'].items():
state_dict[name] = param
model.load_state_dict(state_dict)
optimizer.load_state_dict(checkpoint['optimizer'])
arch_optimizer.load_state_dict(checkpoint['arch_optimizer'])
model.fixed_path = checkpoint['fixed_path']
if is_master():
print("total path = {}".format(model.original_ops))
model.constraint = args.kept_ratio
if args.distributed:
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[gpu_id], find_unused_parameters=True)
model_without_ddp = model.module
else:
model_without_ddp = model
traindir = os.path.join(args.data, 'train')
validdir = os.path.join(args.data, 'val')
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
if args.autoaugment:
transformer = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
auto_augment_transform('original', dict(translate_const=int(224*0.45), img_mean=tuple([min(255, round(255 * x)) for x in [0.485, 0.456, 0.406]]))),
transforms.ToTensor(),
normalize,
])
else:
transformer = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
train_dataset = datasets.ImageFolder(
traindir,
transformer)
if args.distributed:
train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)
else:
train_sampler = None
train_queue = torch.utils.data.DataLoader(
train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None),
num_workers=args.workers, pin_memory=True, sampler=train_sampler)
val_dataset = datasets.ImageFolder(validdir, transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
]))
valid_queue = torch.utils.data.DataLoader(
val_dataset,
batch_size=args.batch_size, shuffle=False,
num_workers=args.workers, pin_memory=True)
mixup_fn = Mixup() if args.mixup else None
if is_master():
print("step num for each epoch:", len(train_queue))
lr_scheduler = Scheduler(optimizer, len(train_queue), 'lr', args.epochs, base_value=args.base_lr)
lr_scheduler.update(0, current_epoch)
wd_scheduler = Scheduler(arch_optimizer, len(train_queue),
'weight_decay', args.epochs - args.random_epochs - args.fixed_epochs,
base_value=args.arch_weight_decay)
wd_scheduler.update(0, max(0, current_epoch - args.random_epochs))
best_top1 = 0
for i in range(current_epoch, args.epochs):
if args.distributed:
train_queue.sampler.set_epoch(i)
if is_master():
print('epoch {}'.format(i))
if i < args.random_epochs:
model_without_ddp.random_sample = True
elif i == args.random_epochs and is_master():
torch.save({'model': model_without_ddp.state_dict(),
'epoch': i,
'optimizer': optimizer.state_dict(),
'arch_optimizer': arch_optimizer.state_dict(),
'fixed_path': model_without_ddp.fixed_path
}, os.path.join(args.save, 'pretrained.pt'))
else:
model_without_ddp.random_sample = False
if i >= args.epochs - args.fixed_epochs and model_without_ddp.fixed_path is None:
model_without_ddp.fixed_mask()
if is_master():
print("fixed path:", model_without_ddp.fixed_path)
train(args, train_queue, model, model_without_ddp, optimizer, arch_optimizer, lr_scheduler, wd_scheduler, i, mixup_fn, criterion_smooth, Writer)
top1 = infer(valid_queue, model, criterion, i, Writer)
if is_master():
print(model_without_ddp.alphas.sigmoid())
print("epoch:{} top1:{:3f}".format(i, top1))
torch.save({'model': model_without_ddp.state_dict(),
'epoch': i+1,
'optimizer': optimizer.state_dict(),
'arch_optimizer': arch_optimizer.state_dict(),
'fixed_path': model_without_ddp.fixed_path
}, os.path.join(args.save, 'ckpt.pt'))
if top1 > best_top1:
torch.save({'model': model_without_ddp.state_dict(),
'epoch': i + 1,
'top1': top1,
'fixed_path': model_without_ddp.fixed_path}, os.path.join(args.save, 'best.pt'))
best_top1 = top1
if is_master():
Writer.close()
def train(args, train_queue, model, model_without_ddp, optimizer, arch_optimizer, lr_scheduler, wd_scheduler, epoch, mixup_fn, criterion, Writer):
obj = utils.AvgrageMeter()
top1 = utils.AvgrageMeter()
top5 = utils.AvgrageMeter()
model.train()
if mixup_fn is not None:
mixup_fn.mixup_enabled = False
for step, (inputs, targets) in enumerate(train_queue):
optimizer.zero_grad()
arch_optimizer.zero_grad()
inputs = inputs.cuda()
targets = targets.cuda()
if mixup_fn is not None:
inputs, smooth_targets = mixup_fn(inputs, targets)
else:
inputs, smooth_targets = inputs, targets
logits, rank = model(inputs)
loss = criterion(logits, smooth_targets)
#loss += 2 * (rank.sum() / rank.numel() - args.kept_ratio) ** 2
loss.backward()
nn.utils.clip_grad_norm(model_without_ddp.parameters(), 5)
prec1, prec5 = utils.accuracy(logits, targets, topk=(1, 5))
n = inputs.size(0)
if args.distributed:
dist_all_reduce_tensor(loss)
dist_all_reduce_tensor(prec1)
dist_all_reduce_tensor(prec5)
obj.update(loss.item(), n)
top1.update(prec1.item(), n)
top5.update(prec5.item(), n)
optimizer.step()
if not model_without_ddp.random_sample and model_without_ddp.fixed_path is None:
arch_optimizer.step()
wd_scheduler.update(step, epoch - args.random_epochs)
lr_scheduler.update(step, epoch)
if any(torch.isnan(model_without_ddp.alphas.view(-1))):
sys.exit(1)
if step % args.report_freq == 0 and is_master():
# print(model.alphas.sigmoid())
print('train step:{}\
lr:{:.3f} wd:{:.3f}\
loss:{:.3f} top1:{:.3f}\
top5:{:.3f}'.format(step,
lr_scheduler.value,
wd_scheduler.value,
obj.avg, top1.avg, top5.avg))
Writer.add_scalar('train loss', obj.avg, epoch*len(train_queue)+step)
Writer.add_scalar('train top1 acc', top1.avg, epoch*len(train_queue)+step)
def infer(valid_queue, model, criterion, epoch, Writer):
objs = utils.AvgrageMeter()
top1 = utils.AvgrageMeter()
top5 = utils.AvgrageMeter()
model.eval()
with torch.no_grad():
for step, (input, target) in enumerate(valid_queue):
input = input.cuda()
target = target.cuda()
logits, _ = model(input)
loss = criterion(logits, target)
prec1, prec5 = utils.accuracy(logits, target, topk=(1, 5))
n = input.size(0)
dist_all_reduce_tensor(loss)
dist_all_reduce_tensor(prec1)
dist_all_reduce_tensor(prec5)
objs.update(loss.item(), n)
top1.update(prec1.item(), n)
top5.update(prec5.item(), n)
if is_master():
Writer.add_scalar('valid loss', objs.avg, epoch)
Writer.add_scalar('valid top1 acc', top1.avg, epoch)
return top1.avg
if __name__ == '__main__':
main()
|
python
|
#!/usr/bin/env python3
import base64
import os
import subprocess
import sys
import yaml
EDITOR = os.environ.get('EDITOR', 'vi')
class NoDatesSafeLoader(yaml.SafeLoader):
@classmethod
def remove_implicit_resolver(cls, tag_to_remove):
"""
Remove implicit resolvers for a particular tag
Takes care not to modify resolvers in super classes.
We want to load datetimes as strings, not dates, because we
go on to serialise as json which doesn't have the advanced types
of yaml, and leads to incompatibilities down the track.
"""
if 'yaml_implicit_resolvers' not in cls.__dict__:
cls.yaml_implicit_resolvers = cls.yaml_implicit_resolvers.copy()
for first_letter, mappings in cls.yaml_implicit_resolvers.items():
cls.yaml_implicit_resolvers[first_letter] = [
(tag, regexp)
for tag, regexp in mappings
if tag != tag_to_remove
]
def repr_str(dumper, data):
if '\n' in data:
return dumper.represent_scalar(
u'tag:yaml.org,2002:str', data, style='|')
return dumper.orig_represent_str(data)
def decode(secret):
if 'data' in secret:
secret['data'] = {
k: base64.b64decode(v).decode('utf8')
for k, v in secret['data'].items()
}
return secret
def encode(secret):
if 'data' in secret:
secret['data'] = {
k: base64.b64encode(v.encode())
for k, v in secret['data'].items()
}
return secret
def edit(fname):
with open(fname, 'r') as fid:
secret = yaml.load(fid, Loader=NoDatesSafeLoader)
decoded = decode(secret)
with open(fname, 'w') as fid:
fid.write(yaml.safe_dump(decoded, default_flow_style=False))
subprocess.check_call(EDITOR.split() + [fname])
with open(fname, 'r') as fid:
edited = yaml.load(fid, Loader=NoDatesSafeLoader)
encoded = encode(edited)
with open(fname, 'w') as fid:
fid.write(yaml.safe_dump(encoded, default_flow_style=False))
def main():
NoDatesSafeLoader.remove_implicit_resolver('tag:yaml.org,2002:timestamp')
yaml.SafeDumper.orig_represent_str = yaml.SafeDumper.represent_str
yaml.add_representer(str, repr_str, Dumper=yaml.SafeDumper)
fname = sys.argv[1]
edit(fname)
if __name__ == '__main__':
main()
|
python
|
#!/usr/bin/python
"""
Basic class for communication to Parrot Bebop
usage:
./bebop.py <task> [<metalog> [<F>]]
"""
import sys
import socket
import datetime
import struct
import time
import numpy as np
import math
from navdata import *
from commands import *
from video import VideoFrames
# this will be in new separate repository as common library fo droneika Python-powered drones
from apyros.metalog import MetaLog, disableAsserts
from apyros.manual import myKbhit, ManualControlException
HOST = "192.168.42.1"
DISCOVERY_PORT = 44444
NAVDATA_PORT = 43210 # d2c_port
COMMAND_PORT = 54321 # c2d_port
class Bebop:
def __init__( self, metalog=None, onlyIFrames=True ):
if metalog is None:
self._discovery()
metalog = MetaLog()
self.navdata = metalog.createLoggedSocket( "navdata", headerFormat="<BBBI" )
self.navdata.bind( ('',NAVDATA_PORT) )
if metalog.replay:
self.commandSender = CommandSenderReplay(metalog.createLoggedSocket( "cmd", headerFormat="<BBBI" ),
hostPortPair=(HOST, COMMAND_PORT), checkAsserts=metalog.areAssertsEnabled())
else:
self.commandSender = CommandSender(metalog.createLoggedSocket( "cmd", headerFormat="<BBBI" ),
hostPortPair=(HOST, COMMAND_PORT))
self.console = metalog.createLoggedInput( "console", myKbhit ).get
self.metalog = metalog
self.buf = ""
self.videoFrameProcessor = VideoFrames( onlyIFrames=onlyIFrames, verbose=False )
self.videoCbk = None
self.videoCbkResults = None
self.battery = None
self.flyingState = None
self.flatTrimCompleted = False
self.manualControl = False
self.time = None
self.moveByEnd = None
self.altitude = None
self.angle = (0,0,0)
self.position = (0,0,0)
self.speed = (0,0,0)
self.positionGPS = None
self.cameraTilt = -90
self.cameraPan = 0
self.lastImageResult = None
self.navigateHomeState = None
self.config()
self.commandSender.start()
def _discovery( self ):
"start communication with the drone"
filename = "tmp.bin" # TODO combination outDir + date/time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP
s.connect( (HOST, DISCOVERY_PORT) )
s.send( '{"controller_type":"computer", "controller_name":"katarina", "d2c_port":"43210"}' )
f = open( filename, "wb" )
while True:
data = s.recv(10240)
if len(data) > 0:
f.write(data)
f.flush()
break
f.close()
s.close()
def _update( self, cmd ):
"internal send command and return navdata"
if not self.manualControl:
self.manualControl = self.console()
if self.manualControl:
# raise exception only once
raise ManualControlException()
# send even None, to sync in/out queues
self.commandSender.send( cmd )
while len(self.buf) == 0:
data = self.navdata.recv(40960)
self.buf += data
data, self.buf = cutPacket( self.buf )
return data
def _parseData( self, data ):
try:
parseData( data, drone=self, verbose=False )
except AssertionError, e:
print "AssertionError", e
def update( self, cmd=None, ackRequest=False ):
"send command and return navdata"
if cmd is None:
data = self._update( None )
else:
data = self._update( packData(cmd, ackRequest=ackRequest) )
while True:
if ackRequired(data):
self._parseData( data )
data = self._update( createAckPacket(data) )
elif pongRequired(data):
self._parseData( data ) # update self.time
data = self._update( createPongPacket(data) )
elif videoAckRequired(data):
if self.videoCbk:
self.videoFrameProcessor.append( data )
frame = self.videoFrameProcessor.getFrameEx()
if frame:
self.videoCbk( frame, debug=self.metalog.replay )
if self.videoCbkResults:
ret = self.videoCbkResults()
if ret is not None:
print ret
self.lastImageResult = ret
data = self._update( createVideoAckPacket(data) )
else:
break
self._parseData( data )
return data
def setVideoCallback( self, cbk, cbkResult=None ):
"set cbk for collected H.264 encoded video frames & access to results queue"
self.videoCbk = cbk
if cbkResult is None:
self.videoCbkResults = None
else:
self.videoCbkResults = self.metalog.createLoggedInput( "cv2", cbkResult ).get
def config( self ):
# initial cfg
dt = self.metalog.now()
if dt: # for compatibility with older log files
self.update( cmd=setDateCmd( date=dt.date() ) )
self.update( cmd=setTimeCmd( time=dt.time() ) )
for cmd in setSpeedSettingsCmdList( maxVerticalSpeed=1.0, maxRotationSpeed=90.0,
hullProtection=True, outdoor=True ):
self.update( cmd=cmd )
self.update( cmd=requestAllStatesCmd() )
self.update( cmd=requestAllSettingsCmd() )
self.moveCamera( tilt=self.cameraTilt, pan=self.cameraPan )
self.update( videoAutorecordingCmd( enabled=False ) )
def takeoff( self ):
print "Taking off ...",
self.update( videoRecordingCmd( on=True ) )
self.update( cmd=takeoffCmd() )
prevState = None
for i in xrange(100):
self.update( cmd=None )
if self.flyingState != 1 and prevState == 1:
break
prevState = self.flyingState
print "FLYING"
def land2( self ):
print "Landing ..."
landing_speed = 75
self.update( videoRecordingCmd( on=False ) )
while self.altitude > 0.1 :
self.update( movePCMDCmd( True, 0, 0, 0, -landing_speed ) )
self.update( cmd=emergencyCmd() )
if(self.flyingState == 0):
print "LANDED"
def land( self ):
print "Landing ..."
landing_speed = 75
self.update( videoRecordingCmd( on=False ) )
while self.altitude > 0.1 :
self.update( movePCMDCmd( True, 0, 0, 0, -landing_speed ) )
while(self.flyingState != 0):
self.update( cmd=landCmd() )
print "LANDED"
def hover( self, timeout ):
startTime = self.time
count = 0
while(self.time-startTime<timeout):
self.update( cmd=movePCMDCmd( active=True, roll=0, pitch=0, yaw=0, gaz=0 ) )
count += 1
print count
def emergency( self ):
self.update( cmd=emergencyCmd() )
def trim( self ):
print "Trim:",
self.flatTrimCompleted = False
for i in xrange(10):
print i,
self.update( cmd=None )
print
self.update( cmd=trimCmd() )
for i in xrange(10):
print i,
self.update( cmd=None )
if self.flatTrimCompleted:
break
def takePicture( self ):
self.update( cmd=takePictureCmd() )
print 'picture taken at time ', self.time
def videoEnable( self ):
"enable video stream"
self.update( cmd=videoStreamingCmd( enable=True ), ackRequest=True )
def videoDisable( self ):
"enable video stream"
self.update( cmd=videoStreamingCmd( enable=False ), ackRequest=True )
def moveCamera( self, tilt, pan ):
"Tilt/Pan camera consign for the drone (in degrees)"
self.update( cmd=moveCameraCmd( tilt=tilt, pan=pan) )
self.cameraTilt, self.cameraPan = tilt, pan # maybe move this to parse data, drone should confirm that
def resetHome( self ):
self.update( cmd=resetHomeCmd() )
def stop( self, timeout=3.0 ):
print 'stopping the drone'
startTime = self.time
droneSpeed = self.speed[0]**2+self.speed[1]**2+self.speed[2]**2
while(self.time-startTime<timeout and droneSpeed>0.3):
self.update( movePCMDCmd( True, self.speed[1]*50, self.speed[0]*50, 0, -self.speed[2]*50 ) )
droneSpeed = self.speed[0]**2+self.speed[1]**2+self.speed[2]**2
print 'stopping position ', -self.position[1], -self.position[0], -self.position[2]
print 'droneSpeed ',droneSpeed
self.update( movePCMDCmd( True, 0, 0, 0, 0 ) )
def moveX( self, dX, speed, timeout=3.0 ):
print 'moveX', dX
if(dX < 0):
speed = -speed
assert self.time is not None
startTime = self.time
startPos = -self.position[0]
while abs(self.position[0]+startPos) < abs(dX) and self.time-startTime < timeout:
self.update( movePCMDCmd( True, speed, 0, 0, 0 ) )
print 'position ', self.position[0], self.position[1], self.position[2]
print 'current speed x',-self.speed[0]
self.update( movePCMDCmd( True, 0, 0, 0, 0 ) )
def moveY( self, dY, speed, timeout=3.0 ):
print 'moveY', dY
if(dY < 0):
speed = -speed
assert self.time is not None
startTime = self.time
startY = self.position[1]
while abs(self.position[1]-startY) < abs(dY) and self.time-startTime < timeout:
self.update( movePCMDCmd( True, 0, speed, 0, 0 ) )
currentY = self.position[1]
print 'current position y axis',currentY
print 'current speed y',self.speed[1]
print 'end position ', -self.position[0], self.position[1], -self.position[2]
self.update( movePCMDCmd( True, 0, 0, 0, 0 ) )
def moveZ( self, altitude, timeout=5.0 ):
speed = 50 #in percentage
assert self.time is not None
assert self.altitude is not None
startTime = self.time
if self.altitude < altitude:#going up
while self.altitude < altitude and self.time-startTime < timeout and altitude>0:
self.update( movePCMDCmd( True, 0, 0, 0, speed ) )
# print 'going up ', self.altitude, self.time-startTime
self.update( movePCMDCmd( True, 0, 0, 0, 0 ) )
return
else:
while self.altitude > altitude and self.time-startTime < timeout and altitude>0:
self.update( movePCMDCmd( True, 0, 0, 0, -speed ) )
#print 'going down ', self.altitude, self.time-startTime
self.update( movePCMDCmd( True, 0, 0, 0, 0 ) )
return
self.update( movePCMDCmd( True, 0, 0, 0, 0 ) )
def moveBy( self, dX, dY, timeout=5.0):
# outdated function.
# TODO: modify targetSpeed so it doesn't use updated values.
print 'move by ', dX, dY
startTime = self.time
startPosition = [0]*2
startPosition[0] = -self.position[1]
startPosition[1] = -self.position[0]
print 'starting position ',startPosition
targetPosition = [0]*2
currentSpeed = [0]*2
targetSpeed = [0]*2
inputSpeed = [0]*2
targetPosition[0] = startPosition[0]+dX
targetPosition[1] = startPosition[1]+dY
top_speed = 40
initial_distance = np.sqrt(abs(targetPosition[1]-startPosition[0])**2+abs(targetPosition[0]-startPosition[1])**2)
print 'tartgetPos x ', targetPosition[0], ' y ', targetPosition[1]
while(self.time-startTime<timeout):
distance = np.sqrt(abs(targetPosition[1]+self.position[0])**2+abs(targetPosition[0]+self.position[1])**2)
# print 'distance ',distance
if(distance<0.2):
print 'arrived', distance
break
if(distance>initial_distance+2):
print 'drone out of path', distance
break
targetSpeed[0] = targetPosition[0]+self.position[1]
targetSpeed[1] = targetPosition[1]+self.position[0]
targetSpeed[0] = targetSpeed[0]/np.sqrt(targetSpeed[0]**2+targetSpeed[1]**2)
targetSpeed[1] = targetSpeed[1]/np.sqrt(targetSpeed[0]**2+targetSpeed[1]**2)
#print 'targetSpeed x ',targetSpeed[0],' y ',targetSpeed[1]
currentSpeed[0] = -self.speed[1]/np.sqrt(self.speed[0]**2+self.speed[1]**2)
currentSpeed[1] = -self.speed[0]/np.sqrt(self.speed[0]**2+self.speed[1]**2)
#print 'currentSpeed x ',currentSpeed[0], ' y ',currentSpeed[1]
inputSpeed[0] = targetSpeed[0]-currentSpeed[0]
inputSpeed[1] = targetSpeed[1]-currentSpeed[1]
#print 'inputSpeed x ',inputSpeed[0],' y ',inputSpeed[1]
self.update( movePCMDCmd( True, inputSpeed[0]*top_speed, inputSpeed[1]*top_speed, 0, 0 ) )
self.update( cmd=movePCMDCmd( True, 0, 0, 0, 0 ) )
endPosition = self.position
print 'end position x ',-endPosition[1],' y ',-endPosition[0]
def calibrate( self, dX, dY, timeout=3.0 ):
startTime = self.time
rotation_speed = 75
print 'start angle= ',self.angle[2]
rotation = np.arctan2(dX,dY)
print 'rotation= ',rotation
if(rotation+self.angle[2]>math.pi):
rotateAngle = -2*math.pi+rotation+self.angle[2]
elif(rotation+self.angle[2]<-math.pi):
rotateAngle = 2*math.pi+rotation+self.angle[2]
else:
rotateAngle = self.angle[2]+rotation
if(rotation < 0):
print 'counterclockwise', rotateAngle
while abs(self.angle[2]-rotateAngle) > 0.1 and self.time-startTime < timeout:
self.update( movePCMDCmd( True, 0, 0, -rotation_speed, 0 ) )
self.update( movePCMDCmd( True, 0, 0, 0, 0 ) )
print 'end angle= ',self.angle[2]
return
else:
print 'clockwise',rotateAngle
while abs(self.angle[2]-rotateAngle) > 0.1 and self.time-startTime < timeout:
self.update( movePCMDCmd( True, 0, 0, rotation_speed, 0 ) )
self.update( movePCMDCmd( True, 0, 0, 0, 0 ) )
print 'end angle= ',self.angle[2]
return
def resetPosition( self, startAngle, timeout=3.0 ):
print 'reset angle...'
# self.moveZ(altitude)
rotation_speed = 75
assert self.time is not None
startTime = self.time
if abs(startAngle-self.angle[2])<0.1:
print 'already calibrated'
self.update( movePCMDCmd( True, 0, 0, 0, 0 ) )
else:
if self.angle[2] < 0:
print 'calibrate clockwise'
while abs(self.angle[2]-startAngle) > 0.1 and self.time-startTime < timeout:
self.update( movePCMDCmd( True, 0, 0, rotation_speed, 0 ) )
self.update( movePCMDCmd( True, 0, 0, 0, 0 ) )
print 'end angle= ',self.angle[2]
return
else:
print 'calibrate counterclockwise'
while abs(self.angle[2]-startAngle) > 0.1 and self.time-startTime < timeout:
self.update( movePCMDCmd( True, 0, 0, -rotation_speed, 0 ) )
self.update( movePCMDCmd( True, 0, 0, 0, 0 ) )
print 'end angle= ',self.angle[2]
return
def moveTo( self, X, Y, Z, timeout=8.0 ):
print 'move to ', X, Y, Z
update_count = 0
startTime = self.time
startPosition = [0]*3
currentSpeed_norm = 0
targetSpeed_norm = 0
startPosition[0] = -self.position[0]
startPosition[1] = self.position[1]
startPosition[2] = -self.position[2]
print 'starting position x ', startPosition[0], ' y ', startPosition[1], ' z ', startPosition[2]
targetPosition = [0]*3
currentSpeed = [0]*3
targetSpeed = [0]*3
inputSpeed = [0]*3
tempSpeed = [0]*3
targetPosition[0] = X
targetPosition[1] = Y
targetPosition[2] = Z
top_speed = 40
initial_distance = np.sqrt(abs(targetPosition[0]+startPosition[0])**2+ \
abs(targetPosition[1]-startPosition[1])**2+ \
abs(targetPosition[2]+startPosition[2])**2)
print 'initial distance', initial_distance
print 'tartgetPos x ', targetPosition[0], ' y ', targetPosition[1], ' z ', targetPosition[2]
while(self.time-startTime<timeout):
print 'current position x ',-self.position[0],' y ',self.position[1],' z ',-self.position[2]
# update_count = update_count+1
distance = np.sqrt(abs(targetPosition[0]+self.position[0])**2+ \
abs(targetPosition[1]-self.position[1])**2+ \
abs(targetPosition[2]+self.position[2])**2)
# print 'flight distance ',distance
# print 'time ',self.time
if(distance<0.1):
# self.moveCamera( tilt=-90, pan=0 )
# self.takePicture();
print 'arrived', distance
break
if(distance>initial_distance+1):
print 'drone out of path', distance
break
targetSpeed_X = targetPosition[0]+self.position[0]
targetSpeed_Y = targetPosition[1]-self.position[1]
targetSpeed_Z = targetPosition[2]+self.position[2]
targetSpeed_norm = np.sqrt(targetSpeed_X**2+targetSpeed_Y**2+targetSpeed_Z**2)
targetSpeed[0] = targetSpeed_X/targetSpeed_norm
targetSpeed[1] = targetSpeed_Y/targetSpeed_norm
targetSpeed[2] = targetSpeed_Z/targetSpeed_norm
print 'targetSpeed x ',targetSpeed[0],' y ',targetSpeed[1], ' z ', targetSpeed[2]
currentSpeed_norm = np.sqrt(self.speed[0]**2+self.speed[1]**2+self.speed[2]**2)
# if currentSpeed_norm == 0:
# currentSpeed_norm = 1
# print 'currentspeednorm', currentSpeed_norm
currentSpeed[0] = -self.speed[1]/currentSpeed_norm
currentSpeed[1] = self.speed[0]/currentSpeed_norm
currentSpeed[2] = -self.speed[2]/currentSpeed_norm
# print 'currentSpeed x ',currentSpeed[0], ' y ',currentSpeed[1], ' z ', currentSpeed[2]
tempSpeed[0] = (targetSpeed[0]-currentSpeed[0])
tempSpeed[1] = (targetSpeed[1]-currentSpeed[1])
tempSpeed[2] = (targetSpeed[2]-currentSpeed[2])
# print 'tempSpeed x ',tempSpeed[0],' y ',tempSpeed[1], ' z ', tempSpeed[2]
inputSpeed_norm = np.sqrt(tempSpeed[0]**2+tempSpeed[1]**2+tempSpeed[2]**2)
inputSpeed[0] = tempSpeed[0]/inputSpeed_norm
inputSpeed[1] = tempSpeed[1]/inputSpeed_norm
inputSpeed[2] = tempSpeed[2]/inputSpeed_norm
# print 'inputSpeed x ',inputSpeed[0]*top_speed,' y ',inputSpeed[1]*top_speed, ' z ', inputSpeed[2]*top_speed
self.update( movePCMDCmd( True, inputSpeed[0]*top_speed, inputSpeed[1]*top_speed, 0, inputSpeed[2]*top_speed ) )
self.update( cmd=movePCMDCmd( True, 0, 0, 0, 0 ) )
endPosition = self.position
# print 'update count ', update_count
print 'end position x ',-endPosition[0],' y ',endPosition[1],' z ',-endPosition[2]
def moveTo2( self, X, Y, Z, timeout=5.0 ):
print 'move to2 ', X, Y, Z
startTime = self.time
startPosition = [0]*3
currentSpeed_norm = 0
targetSpeed_norm = 0
startPosition[0] = -self.position[1]
startPosition[1] = -self.position[0]
startPosition[2] = -self.position[2]
print 'starting position x ', startPosition[0], ' y ', startPosition[1], ' z ', startPosition[2]
targetPosition = [0]*3
targetSpeed = [0]*3
inputSpeed = [0]*3
tempSpeed = [0]*3
targetPosition[0] = X
targetPosition[1] = Y
targetPosition[2] = Z
top_speed = 50
initial_distance = np.sqrt(abs(targetPosition[1]-startPosition[0])**2+ \
abs(targetPosition[0]-startPosition[1])**2+ \
abs(targetPosition[2]-startPosition[2])**2)
print 'tartgetPos x ', targetPosition[0], ' y ', targetPosition[1], ' z ', targetPosition[2]
while(self.time-startTime<timeout):
distance = np.sqrt(abs(targetPosition[1]+self.position[0])**2+ \
abs(targetPosition[0]+self.position[1])**2+ \
abs(targetPosition[2]+self.position[2])**2)
print 'flight distance ',distance
# print 'time ',self.time
if(distance<0.2):
# self.moveCamera( tilt=-90, pan=0 )
# self.takePicture();
print 'arrived', distance
break
if(distance>initial_distance+2):
print 'drone out of path', distance
break
targetSpeed_X = targetPosition[0]+self.position[1]
targetSpeed_Y = targetPosition[1]+self.position[0]
targetSpeed_Z = targetPosition[2]+self.position[2]
targetSpeed_norm = np.sqrt(targetSpeed_X**2+targetSpeed_Y**2+targetSpeed_Z**2)
targetSpeed[0] = targetSpeed_X/targetSpeed_norm
targetSpeed[1] = targetSpeed_Y/targetSpeed_norm
targetSpeed[2] = targetSpeed_Z/targetSpeed_norm
# print 'targetSpeed x ',targetSpeed[0],' y ',targetSpeed[1], ' z ', targetSpeed[2]
self.update( movePCMDCmd( True, targetSpeed[0]*top_speed, targetSpeed[1]*top_speed, 0, targetSpeed[2]*top_speed ) )
self.update( cmd=movePCMDCmd( True, 0, 0, 0, 0 ) )
endPosition = self.position
print 'end position x ',-endPosition[1],' y ',-endPosition[0],' z ',-endPosition[2]
def moveToCancel( self ):
self.update( cmd=cancelMoveToCmd() )
def wait( self, duration ):
print "Wait", duration
assert self.time is not None
startTime = self.time
while self.time-startTime < duration:
self.update()
if __name__ == "__main__":
if len(sys.argv) < 2:
print __doc__
sys.exit(2)
metalog=None
if len(sys.argv) > 2:
metalog = MetaLog( filename=sys.argv[2] )
if len(sys.argv) > 3 and sys.argv[3] == 'F':
disableAsserts()
drone = Bebop( metalog=metalog )
print "Battery:", drone.battery
|
python
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A template task with a ball that should touch left or right wall."""
import numpy as np
import phyre.creator as creator_lib
@creator_lib.define_task_template(
ball_x=np.linspace(0.1, 0.9, 32),
ball_y=np.linspace(0, 40, 8),
ball_r=np.linspace(0.05, 0.12, 5),
left=[True, False],
version='6',
)
def build_task(C, ball_x, ball_y, ball_r, left):
target_wall = C.add('static bar', 1.0, left=0, angle=90, bottom=0)
if not left:
target_wall.set_right(C.scene.width)
shelf_size = 0.99 - ball_r * 2
shelf = C.add('static bar', shelf_size, center_x=C.scene.width / 2, top=20)
C.add('static bar', 0.2, angle=65, right=shelf.left + 5, top=shelf.top)
C.add('static bar', 0.2, angle=-65, left=shelf.right - 5, top=shelf.top)
ball = C.add(
'dynamic ball',
ball_r,
left=ball_x * C.scene.width,
bottom=ball_y + shelf.top)
if ball.center_x <= shelf.left or ball.center_x >= shelf.right:
raise creator_lib.SkipTemplateParams
if abs(ball.center_x - target_wall.center_x) > C.scene.width * .7:
raise creator_lib.SkipTemplateParams
C.update_task(
body1=ball,
body2=target_wall,
relationships=[C.SpatialRelationship.TOUCHING])
C.set_meta(C.SolutionTier.BALL)
|
python
|
import numpy as np
import csv
import json
import argparse
import pickle
ap = argparse.ArgumentParser()
ap.add_argument("-m", "--method", help="vote Method to learn from")
ap.add_argument("-r", "--row", help="data row joined by comma")
ap.add_argument("-f", "--filename", help="filename of dataset")
args = vars(ap.parse_args())
models = pickle.loads(open(args["method"]+".pkl").read())
def read_csv(filename):
dataset = []
with open(filename, 'rb') as f:
reader = csv.reader(f)
for row in reader:
dataset.append([float(el) for el in row])
return dataset
if args["row"] is not None:
predictions = []
for m in models:
prediction = float(m.predict([float(el) for el in args["row"].split(',')]))
if prediction > 0.5:
prediction = 1
else:
prediction = 0
predictions.append(prediction)
print (sum(predictions)/float(len(predictions)))
elif args["filename"] is not None:
dataset = read_csv(args["filename"])
all_predictions = []
for m in models:
all_predictions.append(m.predict(dataset))
final_predictions = []
for prediction_row in np.array(all_predictions).transpose():
predicted = []
for el in prediction_row:
if el > 0.5:
predicted.append(1)
else:
predicted.append(0)
final_predictions.append(sum(predicted)/float(len(predicted)))
print(json.dumps(final_predictions))
|
python
|
# Copyright (C) Izumi Kawashima
#
# json2oscimv4 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# json2oscimv4 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with json2oscimv4. If not, see <http://www.gnu.org/licenses/>.
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import json
import TileData_v4_pb2
from pyproj import Transformer,Proj
EPSG3857 = Proj('+init=EPSG:3857')
EPSG4326 = Proj('+init=EPSG:4326')
transformer3857to4326 = Transformer.from_proj(EPSG3857,EPSG4326)
transformer4326to3857 = Transformer.from_proj(EPSG4326,EPSG3857)
SIZE = 256
SCALE_FACTOR = 20037508.342789244
HEIGHT_PER_METER = 100.0
YES_VALUES = frozenset(['yes','1','true'])
NAME_KEYS = frozenset(['name','name:ja','name:en'])
TAG_PREDEFINED_KEYS = [
"access",
"addr:housename",
"addr:housenumber",
"addr:interpolation",
"admin_level",
"aerialway",
"aeroway",
"amenity",
"area",
"barrier",
"bicycle",
"brand",
"bridge",
"boundary",
"building",
"construction",
"covered",
"culvert",
"cutting",
"denomination",
"disused",
"embankment",
"foot",
"generator:source",
"harbour",
"highway",
"historic",
"horse",
"intermittent",
"junction",
"landuse",
"layer",
"leisure",
"lock",
"man_made",
"military",
"motorcar",
"name",
"natural",
"oneway",
"operator",
"population",
"power",
"power_source",
"place",
"railway",
"ref",
"religion",
"route",
"service",
"shop",
"sport",
"surface",
"toll",
"tourism",
"tower:type",
"tracktype",
"tunnel",
"water",
"waterway",
"wetland",
"width",
"wood",
"height",
"min_height",
"roof:shape",
"roof:height",
"rank"
]
TAG_PREDEFINED_VALUES = [
"yes",
"residential",
"service",
"unclassified",
"stream",
"track",
"water",
"footway",
"tertiary",
"private",
"tree",
"path",
"forest",
"secondary",
"house",
"no",
"asphalt",
"wood",
"grass",
"paved",
"primary",
"unpaved",
"bus_stop",
"parking",
"parking_aisle",
"rail",
"driveway",
"8",
"administrative",
"locality",
"turning_circle",
"crossing",
"village",
"fence",
"grade2",
"coastline",
"grade3",
"farmland",
"hamlet",
"hut",
"meadow",
"wetland",
"cycleway",
"river",
"school",
"trunk",
"gravel",
"place_of_worship",
"farm",
"grade1",
"traffic_signals",
"wall",
"garage",
"gate",
"motorway",
"living_street",
"pitch",
"grade4",
"industrial",
"road",
"ground",
"scrub",
"motorway_link",
"steps",
"ditch",
"swimming_pool",
"grade5",
"park",
"apartments",
"restaurant",
"designated",
"bench",
"survey_point",
"pedestrian",
"hedge",
"reservoir",
"riverbank",
"alley",
"farmyard",
"peak",
"level_crossing",
"roof",
"dirt",
"drain",
"garages",
"entrance",
"street_lamp",
"deciduous",
"fuel",
"trunk_link",
"information",
"playground",
"supermarket",
"primary_link",
"concrete",
"mixed",
"permissive",
"orchard",
"grave_yard",
"canal",
"garden",
"spur",
"paving_stones",
"rock",
"bollard",
"convenience",
"cemetery",
"post_box",
"commercial",
"pier",
"bank",
"hotel",
"cliff",
"retail",
"construction",
"-1",
"fast_food",
"coniferous",
"cafe",
"6",
"kindergarten",
"tower",
"hospital",
"yard",
"sand",
"public_building",
"cobblestone",
"destination",
"island",
"abandoned",
"vineyard",
"recycling",
"agricultural",
"isolated_dwelling",
"pharmacy",
"post_office",
"motorway_junction",
"pub",
"allotments",
"dam",
"secondary_link",
"lift_gate",
"siding",
"stop",
"main",
"farm_auxiliary",
"quarry",
"10",
"station",
"platform",
"taxiway",
"limited",
"sports_centre",
"cutline",
"detached",
"storage_tank",
"basin",
"bicycle_parking",
"telephone",
"terrace",
"town",
"suburb",
"bus",
"compacted",
"toilets",
"heath",
"works",
"tram",
"beach",
"culvert",
"fire_station",
"recreation_ground",
"bakery",
"police",
"atm",
"clothes",
"tertiary_link",
"waste_basket",
"attraction",
"viewpoint",
"bicycle",
"church",
"shelter",
"drinking_water",
"marsh",
"picnic_site",
"hairdresser",
"bridleway",
"retaining_wall",
"buffer_stop",
"nature_reserve",
"village_green",
"university",
"1",
"bar",
"townhall",
"mini_roundabout",
"camp_site",
"aerodrome",
"stile",
"9",
"car_repair",
"parking_space",
"library",
"pipeline",
"true",
"cycle_barrier",
"4",
"museum",
"spring",
"hunting_stand",
"disused",
"car",
"tram_stop",
"land",
"fountain",
"hiking",
"manufacture",
"vending_machine",
"kiosk",
"swamp",
"unknown",
"7",
"islet",
"shed",
"switch",
"rapids",
"office",
"bay",
"proposed",
"common",
"weir",
"grassland",
"customers",
"social_facility",
"hangar",
"doctors",
"stadium",
"give_way",
"greenhouse",
"guest_house",
"viaduct",
"doityourself",
"runway",
"bus_station",
"water_tower",
"golf_course",
"conservation",
"block",
"college",
"wastewater_plant",
"subway",
"halt",
"forestry",
"florist",
"butcher"
]
def heightstr2float(_height):
if type(_height) is str:
if _height[-1] == 'm':
_height = _height[:-1]
_height = _height.strip()
return _height
predefined_key_idx = {}
predefined_value_idx = {}
for i in range(len(TAG_PREDEFINED_KEYS)):
predefined_key = TAG_PREDEFINED_KEYS[i]
predefined_key_idx[predefined_key] = i
for i in range(len(TAG_PREDEFINED_VALUES)):
predefined_value = TAG_PREDEFINED_VALUES[i]
predefined_value_idx[predefined_value] = i
def convert(tile_z,tile_x,tile_y,buffer_pixels,fr):
paz = 20037508.342789244 / 256 / (2 ** tile_z)
tile_x = tile_x*SIZE
tile_y = tile_y*SIZE
center = (SIZE << tile_z) >> 1
min_lat3857 = ((center - (tile_y+SIZE+paz))/center)*SCALE_FACTOR
max_lat3857 = ((center - (tile_y-paz))/center)*SCALE_FACTOR
min_lon3857 = (((tile_x-paz)-center)/center)*SCALE_FACTOR
max_lon3857 = (((tile_x+SIZE+paz)-center)/center)*SCALE_FACTOR
min_lon4326,min_lat4326 = transformer3857to4326.transform(min_lon3857,min_lat3857)
max_lon4326,max_lat4326 = transformer3857to4326.transform(max_lon3857,max_lat3857)
oscim_tile = TileData_v4_pb2.Data()
oscim_tile.version = 4
found_points = []
found_polygons = []
found_lines = []
appending_target = None
tag2idx = {}
serialized_tags = []
oscim_keys = []
key2oscim_idx = {}
oscim_values = []
value2oscim_idx = {}
def ll2xy(lon,lat):
lon3857,lat3857 = transformer4326to3857.transform(lon,lat)
rx = float(lon3857-min_lon3857)/float(max_lon3857-min_lon3857)
ry = float(lat3857-min_lat3857)/float(max_lat3857-min_lat3857)
rx = rx-0.5
rx = rx*float(SIZE+buffer_pixels)/float(SIZE)
rx = rx+0.5
x = int(rx*4096.0)
ry = ry-0.5
ry = -ry*float(SIZE+buffer_pixels)/float(SIZE) # NEGATE!
ry = ry+0.5
y = int(ry*4096.0)
return x,y
def lls2xy(lls):
abs_xys = []
for ll in lls:
lon = ll[0]
lat = ll[1]
x,y = ll2xy(lon,lat)
abs_xys.append([x,y])
last_x = 0
last_y = 0
delta_xys = []
for x,y in abs_xys:
dx = x-last_x
dy = y-last_y
if dx != 0 or dy != 0:
delta_xys.append([dx,dy])
last_x = x
last_y = y
return delta_xys
def llss2xy(llss):
abs_xyss = []
for lls in llss:
abs_xys = []
for ll in lls:
lon = ll[0]
lat = ll[1]
x,y = ll2xy(lon,lat)
abs_xys.append([x,y])
abs_xys = abs_xys[:-1]
abs_xyss.append(abs_xys)
last_x = 0
last_y = 0
delta_xyss = []
for abs_xys in abs_xyss:
delta_xys = []
for x,y in abs_xys:
dx = x-last_x
dy = y-last_y
if dx != 0 or dy != 0:
delta_xys.append([dx,dy])
last_x = x
last_y = y
delta_xyss.append(delta_xys)
return delta_xyss
j = json.loads(fr)
layers = j['features']
for layer in layers:
if layer['properties']['layer'] in frozenset(['admin_lines']): continue
features = layer['features']
for feature in features:
fixed_kv = {}
names_kv = {}
tag_idxs_in_feature = []
properties = feature['properties']
if 'min_zoom' in properties:
min_zoom = int(properties['min_zoom'])
if tile_z > min_zoom: continue
kv = {}
if layer['properties']['layer'] == 'land':
fixed_kv['land'] = 'land'
else:
for key in properties:
if key in frozenset(['id','sort_rank','source','surface']): continue
value = properties[key]
kv[key] = value
for key in kv.keys():
value = kv[key]
if key in NAME_KEYS:
names_kv[key] = value
if 'oneway' in kv and str(kv['oneway']).lower() in YES_VALUES:
fixed_kv['oneway'] = 'yes'
if 'area' in kv and str(kv['area']).lower() in YES_VALUES:
fixed_kv['area'] = 'yes'
elif 'tunnel' in kv and str(kv['tunnel']).lower() in YES_VALUES:
fixed_kv['tunnel'] = 'yes'
elif 'bridge' in kv and str(kv['bridge']).lower() in YES_VALUES:
fixed_kv['bridge'] = 'yes'
if 'leisure' in kv:
leisure = kv['leisure']
fixed_kv['leisure'] = leisure
if 'natural' in kv:
natural = kv['natural']
if natural in frozenset(['village_green','meadow','wood']):
fixed_kv['landuse'] = natural
elif natural == 'mountain_range': pass
else:
fixed_kv['natural'] = natural
if 'landuse' in kv:
landuse = kv['landuse']
if landuse in frozenset(['park','natural_reserve']):
fixed_kv['leisure'] = landuse
elif landuse == 'field':
fixed_kv['landuse'] = 'farmland'
elif landuse in frozenset(['grassland','scrub']):
fixed_kv['natural'] = landuse
else:
fixed_kv['landuse'] = landuse
for explicit_kind in frozenset(['waterway']):
if explicit_kind in kv: fixed_kv[explicit_kind] = kv[explicit_kind]
if 'type' in kv:
type_ = kv['type']
property_layer = layer['properties']['layer']
if property_layer in frozenset(['buildings','building:part']):
fixed_kv['building'] = 'yes'
fixed_kv['type'] = 'yes'
if 'id' in kv:
fixed_kv['id'] = kv['id']
if tile_z > 16:
if 'height' in kv:
_height = float(heightstr2float(kv['height']))*HEIGHT_PER_METER
fixed_kv['height'] = str(_height)
elif 'building:levels' in kv:
fixed_kv['building:levels'] = str(kv['building:levels'])
if 'min_height' in kv:
_min_height = heightstr2float(kv['min_height'])*HEIGHT_PER_METER
fixed_kv['min_height'] = str(_min_height)
if 'colour' in kv: fixed_kv['colour'] = kv['colour']
elif type_ in frozenset([
'atm',
'bank',
'bar',
'bench',
'bicycle',
'bicycle_rental',
'books',
'bus_station',
'cafe',
'cinema',
'clothes',
'convenience',
'dry_cleaning',
'fast_food',
'fountain',
'grave_yard',
'hospital',
'library',
'parking',
'pharmacy',
'place_of_worship',
'police',
'post_box',
'post_office',
'pub',
'recycling',
'restaurant',
'school',
'shelter',
'supermarket',
'university',
'telephone',
'theatre',
'toilets'
]):
fixed_kv['amenity'] = type_
elif type_ == 'administrative':
fixed_kv['boundary'] = 'administrative'
admin_level = int(kv['admin_level'])
if admin_level == 2:
fixed_kv['place'] = 'country'
elif admin_level == 4:
fixed_kv['place'] = 'city'
elif admin_level == 7:
fixed_kv['place'] = 'village'
elif admin_level == 8:
fixed_kv['place'] = 'town'
elif type_ == 'place_of_worship':
fixed_kv['amenity'] = type_
elif type_ =='riverbank':
fixed_kv['natural'] = 'water'
if 'class' in kv:
class_value = kv['class']
if class_value in frozenset(['earth']):
fixed_kv['landuse'] = 'urban'
# WATER
elif class_value == 'natural':
if type_ == 'lake;pond':
fixed_kv['water'] = 'pond'
if type_ == 'beach':
fixed_kv['natural'] = 'beach'
elif type_ == 'river':
fixed_kv['waterway'] = 'river'
elif type_ in frozenset(['water','riverbank','ocean']):
fixed_kv['natural'] = 'water'
elif type_ == 'wood':
fixed_kv['landuse'] = 'wood'
# LEISURE
elif class_value == 'leisure':
if type_ in frozenset(['pitch','park','playground','common','garden']):
fixed_kv['leisure'] = type_
# LANDUSE
elif class_value == 'landuse':
if type_ in frozenset(['park','natural_reserve']):
fixed_kv['leisure'] = type_
elif type_ == 'field':
fixed_kv['landuse'] = 'farmland'
elif type_ in frozenset(['grassland','scrub','tree']):
fixed_kv['natural'] = type_
else:
fixed_kv['landuse'] = type_
# ROADS
elif class_value == 'highway':
if type_ == 'minor_road':
fixed_kv['highway'] = 'residential'
elif type_ == 'highway':
fixed_kv['highway'] = 'motorway'
elif type_ == 'residential':
fixed_kv['highway'] = 'service'
elif type_ == 'pedestrian':
fixed_kv['highway'] = 'footway'
else:
fixed_kv['highway'] = type_
# RAILS
elif class_value == 'railway':
if type_ in frozenset(['rail','subway','station','platform']):
fixed_kv['railway'] = type_
# AIR
elif class_value == 'aeroway':
if type_ in frozenset(['aerodrome','apron','helipad']):
fixed_kv['aeroway'] = type_
elif class_value in frozenset(['pitch','park','playground','common','garden']):
fixed_kv['leisure'] = class_value
elif class_value == 'tourism':
fixed_kv['tourism'] = type_
elif class_value in frozenset(['viewpoint','museum','information','park','theme_park','attraction']):
fixed_kv['tourism'] = class_value
elif class_value == 'office':
fixed_kv['office'] = type_
if len(fixed_kv) == 0: continue
merged_kv = {}
for key in names_kv: merged_kv[key] = names_kv[key]
for key in fixed_kv: merged_kv[key] = fixed_kv[key]
# print(layer['properties']['layer'],merged_kv)
for key in merged_kv.keys():
value = merged_kv[key]
if key in predefined_key_idx:
key_idx = predefined_key_idx[key]
else:
if key in key2oscim_idx:
key_idx = key2oscim_idx[key]
else:
key_idx = len(oscim_keys)
key2oscim_idx[key] = key_idx
oscim_keys.append(key)
key_idx = key_idx+256
if value in predefined_value_idx:
value_idx = predefined_value_idx[value]
else:
if value in value2oscim_idx:
value_idx = value2oscim_idx[value]
else:
value_idx = len(oscim_values)
value2oscim_idx[value] = value_idx
oscim_values.append(value)
value_idx = value_idx+256
tag = (key_idx,value_idx)
if tag in tag2idx:
tag_idx = tag2idx[tag]
else:
tag_idx = int(len(serialized_tags)/2)
tag2idx[tag] = tag_idx
serialized_tags.append(int(key_idx))
serialized_tags.append(int(value_idx))
tag_idxs_in_feature.append(int(tag_idx))
if len(tag_idxs_in_feature) == 0: continue
geometry = feature['geometry']
geometry_type = geometry['type']
c = geometry['coordinates']
if geometry_type == 'Point':
oscim_element = TileData_v4_pb2.Data.Element()
oscim_element.num_tags = len(tag_idxs_in_feature)
oscim_element.tags.extend(tag_idxs_in_feature)
x,y = ll2xy(c[0],c[1])
oscim_element.coordinates.extend([x,y])
oscim_element.indices.extend([1])
oscim_element.num_indices = 1
found_points.append(oscim_element)
elif geometry_type == 'MultiPoint':
for cp in c:
oscim_element = TileData_v4_pb2.Data.Element()
oscim_element.num_tags = len(tag_idxs_in_feature)
oscim_element.tags.extend(tag_idxs_in_feature)
x,y = ll2xy(cp[0],cp[1])
oscim_element.coordinates.extend([x,y])
oscim_element.num_indices = 0
oscim_element.indices.extend([1])
oscim_element.num_indices = 1
found_points.append(oscim_element)
elif geometry_type == 'LineString':
oscim_element = TileData_v4_pb2.Data.Element()
oscim_element.num_tags = len(tag_idxs_in_feature)
oscim_element.tags.extend(tag_idxs_in_feature)
delta_xys = lls2xy(c)
oscim_element.num_indices = 1
oscim_element.indices.extend([len(delta_xys)])
flat_xys = []
for x,y in delta_xys:
flat_xys.append(x)
flat_xys.append(y)
oscim_element.coordinates.extend(flat_xys)
found_lines.append(oscim_element)
elif geometry_type == 'MultiLineString':
for cp in c:
oscim_element = TileData_v4_pb2.Data.Element()
oscim_element.num_tags = len(tag_idxs_in_feature)
oscim_element.tags.extend(tag_idxs_in_feature)
delta_xys = lls2xy(cp)
oscim_element.indices.extend([len(delta_xys)])
oscim_element.num_indices = 1
flat_xys = []
for x,y in delta_xys:
flat_xys.append(x)
flat_xys.append(y)
oscim_element.coordinates.extend(flat_xys)
found_lines.append(oscim_element)
elif geometry_type == 'Polygon':
oscim_element = TileData_v4_pb2.Data.Element()
oscim_element.num_tags = len(tag_idxs_in_feature)
oscim_element.tags.extend(tag_idxs_in_feature)
delta_xyss = llss2xy(c)
indices = []
for delta_xys in delta_xyss:
indices.append(len(delta_xys))
oscim_element.indices.extend(indices)
oscim_element.num_indices = len(indices)
flat_xys = []
for delta_xys in delta_xyss:
for x,y in delta_xys:
flat_xys.append(x)
flat_xys.append(y)
oscim_element.coordinates.extend(flat_xys)
found_polygons.append(oscim_element)
elif geometry_type == 'MultiPolygon':
for cp in c:
oscim_element = TileData_v4_pb2.Data.Element()
oscim_element.num_tags = len(tag_idxs_in_feature)
oscim_element.tags.extend(tag_idxs_in_feature)
delta_xyss = llss2xy(cp)
indices = []
for delta_xys in delta_xyss:
indices.append(len(delta_xys))
oscim_element.indices.extend(indices)
oscim_element.num_indices = len(indices)
flat_xys = []
for delta_xys in delta_xyss:
for x,y in delta_xys:
flat_xys.append(x)
flat_xys.append(y)
oscim_element.coordinates.extend(flat_xys)
found_polygons.append(oscim_element)
if len(found_points) > 0: oscim_tile.points.extend(found_points)
if len(found_polygons) > 0: oscim_tile.polygons.extend(found_polygons)
if len(found_lines) > 0: oscim_tile.lines.extend(found_lines)
oscim_tile.num_tags = int(len(serialized_tags)/2)
oscim_tile.tags.extend(serialized_tags)
oscim_tile.keys.extend(oscim_keys)
oscim_tile.num_keys = len(oscim_keys)
oscim_tile.values.extend(oscim_values)
oscim_tile.num_vals = len(oscim_values)
return b'0000'+oscim_tile.SerializeToString() # TODO: Header bytes to be fixed (although it is readable from vtm)
|
python
|
load(
"@bazel_tools//tools/jdk:toolchain_utils.bzl",
"find_java_toolchain",
)
load(
"@rules_scala_annex//rules:providers.bzl",
_ScalaConfiguration = "ScalaConfiguration",
_ZincConfiguration = "ZincConfiguration",
_ZincInfo = "ZincInfo",
)
load(
"@rules_scala_annex//rules/common:private/utils.bzl",
_resolve_execution_reqs = "resolve_execution_reqs",
)
#
# PHASE: compile
#
# Compiles Scala sources ;)
#
def phase_zinc_compile(ctx, g):
scala_configuration = ctx.attr.scala[_ScalaConfiguration]
zinc_configuration = ctx.attr.scala[_ZincConfiguration]
apis = ctx.actions.declare_file("{}/apis.gz".format(ctx.label.name))
infos = ctx.actions.declare_file("{}/infos.gz".format(ctx.label.name))
mains_file = ctx.actions.declare_file("{}.jar.mains.txt".format(ctx.label.name))
relations = ctx.actions.declare_file("{}/relations.gz".format(ctx.label.name))
setup = ctx.actions.declare_file("{}/setup.gz".format(ctx.label.name))
stamps = ctx.actions.declare_file("{}/stamps.gz".format(ctx.label.name))
used = ctx.actions.declare_file("{}/deps_used.txt".format(ctx.label.name))
tmp = ctx.actions.declare_directory("{}/tmp".format(ctx.label.name))
javacopts = [
ctx.expand_location(option, ctx.attr.data)
for option in ctx.attr.javacopts + java_common.default_javac_opts(
java_toolchain = find_java_toolchain(ctx, ctx.attr._java_toolchain),
)
]
zincs = [dep[_ZincInfo] for dep in ctx.attr.deps if _ZincInfo in dep]
args = ctx.actions.args()
args.add_all(depset(transitive = [zinc.deps for zinc in zincs]), map_each = _compile_analysis)
args.add("--compiler_bridge", zinc_configuration.compiler_bridge)
args.add_all("--compiler_classpath", g.classpaths.compiler)
args.add_all("--classpath", g.classpaths.compile)
args.add_all(scala_configuration.global_scalacopts, format_each = "--compiler_option=%s")
args.add_all(ctx.attr.scalacopts, format_each = "--compiler_option=%s")
args.add_all(javacopts, format_each = "--java_compiler_option=%s")
args.add(ctx.label, format = "--label=%s")
args.add("--main_manifest", mains_file)
args.add("--output_apis", apis)
args.add("--output_infos", infos)
args.add("--output_jar", g.classpaths.jar)
args.add("--output_relations", relations)
args.add("--output_setup", setup)
args.add("--output_stamps", stamps)
args.add("--output_used", used)
args.add_all("--plugins", g.classpaths.plugin)
args.add_all("--source_jars", g.classpaths.src_jars)
args.add("--tmp", tmp.path)
args.add("--log_level", zinc_configuration.log_level)
args.add_all("--", g.classpaths.srcs)
args.set_param_file_format("multiline")
args.use_param_file("@%s", use_always = True)
worker = zinc_configuration.compile_worker
worker_inputs, _, input_manifests = ctx.resolve_command(tools = [worker])
inputs = depset(
[zinc_configuration.compiler_bridge] + ctx.files.data + ctx.files.srcs + worker_inputs,
transitive = [
g.classpaths.plugin,
g.classpaths.compile,
g.classpaths.compiler,
] + [zinc.deps_files for zinc in zincs],
)
outputs = [g.classpaths.jar, mains_file, apis, infos, relations, setup, stamps, used, tmp]
# todo: different execution path for nosrc jar?
ctx.actions.run(
mnemonic = "ScalaCompile",
inputs = inputs,
outputs = outputs,
executable = worker.files_to_run.executable,
input_manifests = input_manifests,
execution_requirements = _resolve_execution_reqs(ctx, {"no-sandbox": "1", "supports-workers": "1"}),
use_default_shell_env = True,
arguments = [args],
)
jars = []
for jar in g.javainfo.java_info.outputs.jars:
jars.append(jar.class_jar)
jars.append(jar.ijar)
zinc_info = _ZincInfo(
apis = apis,
deps_files = depset([apis, relations], transitive = [zinc.deps_files for zinc in zincs]),
label = ctx.label,
relations = relations,
deps = depset(
[struct(
apis = apis,
jars = tuple(jars),
label = ctx.label,
relations = relations,
)],
transitive = [zinc.deps for zinc in zincs],
),
)
g.out.providers.append(zinc_info)
return struct(
mains_file = mains_file,
used = used,
# todo: see about cleaning up & generalizing fields below
zinc_info = zinc_info,
)
def _compile_analysis(analysis):
return [
"--analysis",
"_{}".format(analysis.label),
analysis.apis.path,
analysis.relations.path,
] + [jar.path for jar in analysis.jars]
|
python
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import functools
import numpy as np
import timeit
import json
from operator_benchmark import benchmark_utils
"""Performance microbenchmarks.
This module contains core functionalities for performance microbenchmark tests.
"""
# List of run modes we support.
# Each benchmark test case is associated with a run mode.
# If the value of the test case's run mode is less than the value of the
# benchmark binary's run mode, the test case will be executed, e.g. a short-mode
# test case will be executed when the binary is on either long and short
# modes; while a long-mode test case will only be executed when the binary is
# on long-mode.
RUN_MODES = {'short': 0, 'long': 1}
BENCHMARK_TESTER = [{} for _ in range(len(RUN_MODES))]
BENCHMARK_TEST_GROUP = {}
def add_benchmark_tester(framework, op_name, input_shapes, op_args, run_mode, func):
func_name = "__".join([framework, op_name, benchmark_utils.shape_to_string(input_shapes)
, str(op_args), run_mode])
run_mode = RUN_MODES[run_mode]
for mode in RUN_MODES.values():
# short mode runs with some of the input shapes for an op
# long mode runs with all the input shapes for an op
if (mode < run_mode):
continue
BENCHMARK_TESTER[mode][func_name] = func
def register_test(func):
"""Decorator to register a benchmark test group.
A benchmark test group is a function that returns a list of benchmark test
case objects to be run.
"""
BENCHMARK_TEST_GROUP[__name__ + "." + func.__name__] = func
return func
HEADER_LINE = """
# {}
# PyTorch/Caffe2 Operator Micro-benchmarks
# {}
# Run_mode : {}
"""
class BenchmarkRunner(object):
"""BenchmarkRunner is responsible for benchmarking all the registered
benchmark test groups.
Attributes:
run_mode (str): Must of one of 'short', 'long'. For long mode, the
benchmark runner takes a longer time to run since it repeats each benchmark
test case more times to reduce measured variance, and it also executes
longer running test cases that is marked as long mode.
operator (str): Only run benchmark test cases that contains
this filter string in the test case's id.
"""
def __init__(self, args):
# Depend on the run mode, set the execution contrains based of number of
# runs per measure, and number of measures.
# TODO: consider time-bound constraints as well.
self.args = args
self.iters = 100
self.has_explicit_iteration_count = False
self.multiplier = 2
self.min_time = 0.8
self.max_iters = 1e6
for test_group in BENCHMARK_TEST_GROUP.items():
test_group_func = test_group[1]
test_group_func()
if self.args.iterations:
self.has_explicit_iteration_count = True
self.iters = self.args.iterations
def _print_header(self, run_mode):
DASH_LINE = '-' * 40
print(HEADER_LINE.format(DASH_LINE, DASH_LINE, self.args.run_mode, self.iters))
print("# List of Operators to run:")
if self.args.operator is None:
ops = set()
for tester in BENCHMARK_TESTER[run_mode].items():
full_test_id = tester[0]
framework, op_name, input_shapes, args, run_mode = full_test_id.split("__")
if op_name not in ops:
print("# {}".format(op_name))
ops.add(op_name)
else:
print("# {}".format(self.args.operator))
print("\n")
def _print_perf_result(self, full_test_id, input_shapes, args, reported_run_time):
if self.args.ai_pep_format:
# Output for AI-PEP
print("Caffe2Observer " + json.dumps(
{
"type": "NET",
"metric": full_test_id,
"unit": "ms",
"value": str(reported_run_time),
}
))
else:
print("# Input Shape: {}\n"
"Execution Time (us) : {:.3f} \n"
.format(input_shapes, reported_run_time))
def _predict_num_iter_needed(self, i):
return (i * self.multiplier)
def _report_iteration_result(self, iters, run_time):
return (iters > self.max_iters or
run_time > 5 * self.min_time)
def run(self):
run_mode = RUN_MODES[self.args.run_mode]
self._print_header(run_mode)
if self.args.list_tests:
return
for tester in BENCHMARK_TESTER[run_mode].items():
full_test_id = tester[0]
benchmark_func = tester[1]
framework, op_name, input_shapes, args, run_mode = full_test_id.split("__")
# TODO: consider regex matching for test filtering.
# Currently, this is a sub-string matching.
if self.args.operator and (self.args.operator not in full_test_id):
continue
if self.args.framework and (self.args.framework not in full_test_id):
continue
# To reduce variance, fix a numpy randseed to the test case,
# so that the randomly generated input tensors remain the
# same for each test case.
# The random seed is limited to 32-bit because of numpy
# requirement.
np.random.seed(seed=hash(full_test_id) & ((1 << 32) - 1))
print("# Benchmarking {} {}".format(
framework,
op_name))
# Warmup
functools.partial(benchmark_func, self.args.warmup_iterations)
# Actual Execution
run_time = 0
iters = self.iters
while True:
# Use Python's timeit module to measure execution time (unit: second).
# Each experiment consists of repeated execution of
# the benchmark_func a number of times (self.iters)
# because otherwise the duration is too short to get
# an accurate measure. The benchmark loop is pushed
# to C++ to minimize Python overhead.
# The experiment is also repeated a number of times
# (num_repeats) and we then take the minimum execution
# time as the final measurement result (this is also
# recommended by timeit's doc).
run_time = min(timeit.repeat(functools.partial(benchmark_func, iters),
repeat=1, number=1))
# Analyze time after each run to decide if the result is stable
results_are_significant = self.has_explicit_iteration_count or \
self._report_iteration_result(iters, run_time)
if results_are_significant:
break
# Re-estimate the hopefully-sufficient
# iteration count, and run the benchmark again...
iters = self._predict_num_iter_needed(iters)
reported_run_time = (1e6 * run_time / iters)
self._print_perf_result(full_test_id, input_shapes, args, reported_run_time)
|
python
|
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
"""Tests for tink.python.tink.jwt._verified_jwt."""
import datetime
from absl.testing import absltest
from tink import jwt
ISSUED_AT = datetime.datetime.fromtimestamp(1582230020, datetime.timezone.utc)
NOT_BEFORE = datetime.datetime.fromtimestamp(1893553445, datetime.timezone.utc)
EXPIRATION = datetime.datetime.fromtimestamp(2218027244, datetime.timezone.utc)
class VerifiedJwtTest(absltest.TestCase):
def test_empty(self):
token = jwt.VerifiedJwt._create(jwt.new_raw_jwt())
with self.assertRaises(KeyError):
token.issuer()
with self.assertRaises(KeyError):
token.subject()
with self.assertRaises(KeyError):
token.jwt_id()
with self.assertRaises(KeyError):
token.audiences()
with self.assertRaises(KeyError):
token.expiration()
with self.assertRaises(KeyError):
token.issued_at()
with self.assertRaises(KeyError):
token.not_before()
with self.assertRaises(KeyError):
token.custom_claim('unknown')
self.assertFalse(token.has_issuer())
self.assertFalse(token.has_subject())
self.assertFalse(token.has_jwt_id())
self.assertFalse(token.has_audiences())
self.assertFalse(token.has_expiration())
self.assertFalse(token.has_issued_at())
self.assertFalse(token.has_not_before())
def test_full(self):
token = jwt.VerifiedJwt._create(
jwt.new_raw_jwt(
issuer='Issuer',
subject='Subject',
jwt_id='JWT ID',
audiences=['bob', 'eve'],
expiration=EXPIRATION,
issued_at=ISSUED_AT,
not_before=NOT_BEFORE))
self.assertTrue(token.has_issuer())
self.assertEqual(token.issuer(), 'Issuer')
self.assertTrue(token.has_subject())
self.assertEqual(token.subject(), 'Subject')
self.assertTrue(token.has_jwt_id())
self.assertEqual(token.jwt_id(), 'JWT ID')
self.assertTrue(token.has_audiences())
self.assertEqual(token.audiences(), ['bob', 'eve'])
self.assertTrue(token.has_expiration())
self.assertEqual(token.expiration(), EXPIRATION)
self.assertTrue(token.has_issued_at())
self.assertEqual(token.issued_at(), ISSUED_AT)
self.assertTrue(token.has_not_before())
self.assertEqual(token.not_before(), NOT_BEFORE)
def test_custom_claims(self):
custom_claims = {'string': 'value',
'boolean': True,
'number': 123.456,
'integer': 123,
'null': None,
'array': [1, None, 'Bob', 2.2, {'foo': 'bar'}],
'object': {'one': {'two': 3}}}
token = token = jwt.VerifiedJwt._create(
jwt.new_raw_jwt(custom_claims=custom_claims))
self.assertCountEqual(
token.custom_claim_names(),
{'string', 'boolean', 'number', 'integer', 'null', 'array', 'object'})
self.assertEqual(token.custom_claim('string'), 'value')
self.assertEqual(token.custom_claim('boolean'), True)
self.assertEqual(token.custom_claim('number'), 123.456)
self.assertEqual(token.custom_claim('integer'), 123)
self.assertIsNone(token.custom_claim('null'))
self.assertEqual(
token.custom_claim('array'),
[1, None, 'Bob', 2.2, {'foo': 'bar'}])
self.assertEqual(token.custom_claim('object'), {'one': {'two': 3}})
if __name__ == '__main__':
absltest.main()
|
python
|
import abc
import numpy as np
class ErrFunc(abc.ABC):
"""Base class for classification model error functions."""
@abc.abstractmethod
def apply(self, prediction, y):
"""Apply the nonconformity function.
Parameters
----------
prediction : numpy array of shape [n_samples, n_classes]
Class probability estimates for each sample.
y : numpy array of shape [n_samples]
True output labels of each sample.
Returns
-------
nc : numpy array of shape [n_samples]
Nonconformity scores of the samples.
"""
pass
class BaseModelNC:
"""Base class for nonconformity scorers based on an underlying model.
Parameters
----------
model : Underlying pretrained model
err_func : ClassificationErrFunc or RegressionErrFunc
Error function object.
normalizer : Normalizer
Normalization model.
beta : float
Normalization smoothing parameter. As the beta-value increases,
the normalized nonconformity function approaches a non-normalized
equivalent.
"""
def __init__(self, model, err_func, normalizer=None, beta=0):
super().__init__()
self.err_func = err_func
self.model = model
self.normalizer = normalizer
self.beta = beta
# If we use sklearn.base.clone (e.g., during cross-validation),
# object references get jumbled, so we need to make sure that the
# normalizer has a reference to the proper model adapter, if applicable.
if self.normalizer is not None and hasattr(self.normalizer, "base_model"):
self.normalizer.base_model = self.model
self.clean = False
def fit(self, x, y):
"""Fits the underlying model of the nonconformity scorer.
Parameters
----------
x : numpy array of shape [n_samples, n_features]
Inputs of examples for fitting the underlying model.
y : numpy array of shape [n_samples]
Outputs of examples for fitting the underlying model.
Returns
-------
None
"""
if self.normalizer is not None and not self.normalizer.is_fitted:
self.normalizer.fit(x, y)
self.clean = False
def score(self, x, y=None):
"""Calculates the nonconformity score of a set of samples.
Parameters
----------
x : numpy array of shape [n_samples, n_features]
Inputs of examples for which to calculate a nonconformity score.
y : numpy array of shape [n_samples]
Outputs of examples for which to calculate a nonconformity score.
Returns
-------
nc : numpy array of shape [n_samples]
Nonconformity scores of samples.
"""
prediction = self.model.predict(x)
n_test = x.shape[0]
if self.normalizer is not None:
norm = self.normalizer.score(x) + self.beta
else:
norm = np.ones(n_test)
return self.err_func.apply(prediction, y) / norm
|
python
|
import bpy
from math import pi
# ----------------------------------------------------------------------------------------
# Start - copied functions
# ----------------------------------------------------------------------------------------
def sun_light(
location, rotation, power=2.5, angle=135, name="Light_sun",
):
"""Sun light.
Args:
power (float, optional): [description]. Defaults to 2.5.
angle (int, optional): [description]. Defaults to 135.
name (str, optional): [description]. Defaults to "Light_sun".
location ([type], optional): [description]. Defaults to light_location.
rotation ([type], optional): [description]. Defaults to light_rotation.
Returns:
[type]: Light object
"""
light_data = bpy.data.lights.new(name, type="SUN")
light = bpy.data.objects.new(name, light_data)
bpy.context.collection.objects.link(light)
light.location = location
light.rotation_euler = rotation
light.data.energy = power
light.data.specular_factor = 0.4
light.data.angle = angle * pi / 180.0
return light
def make_material_Principled_BSDF(name, color_RGB):
"""Create a Pincipled BSDF material.
Args:
name (str): Name to give new material
color_RGB (3-element tuple or list of floats): RGB color (each element is in range of 0.0 to 1.0))
Returns:
[type]: [description]
"""
mat = bpy.data.materials.new(name=name)
mat.use_nodes = True
mat_nodes = mat.node_tree.nodes
# Set Principled BSDF values
mat_nodes["Principled BSDF"].inputs["Metallic"].default_value = 0.0
mat_nodes["Principled BSDF"].inputs["Roughness"].default_value = 0.4
mat_nodes["Principled BSDF"].inputs["Base Color"].default_value = (
*color_RGB,
1.0,
)
# Change material settings for blend method, show backface, shadow mode
mat.blend_method = "BLEND"
mat.show_transparent_back = False
mat.shadow_method = "NONE"
return mat
def make_cube(name, size, position):
"""Make cube with specified size and position. Ensure that the
bottom of the cube is at the specified z position.
Args:
name (str): Name for new cube
size (3-element tuple or list of floats): desired size of cube
position (3-element tuple or list of floats): position of center bottom of cube
"""
z_layer_size = size[2]
z_position = position[2]
bpy.ops.mesh.primitive_cube_add(size=1)
layer = bpy.context.object
layer.scale = size
layer.location = (position[0], position[1], z_layer_size / 2 + z_position)
layer.name = name
return layer
# ----------------------------------------------------------------------------------------
# New functions
# ----------------------------------------------------------------------------------------
def attach_to_parent(child_obj, parent_obj):
"""Make parent_obj the parent of child_obj.
Args:
child_obj (Blender object): Object to be the child
parent_obj (Blender object): Object to be the parent
"""
child_obj.parent = parent_obj
# Prevent parent transforms from being applied to child object
child_obj.matrix_parent_inverse = parent_obj.matrix_world.inverted()
def duplicate_object(obj, invert_y_position=True, parent_relationship=True):
"""Duplicate an object, move the duplicate in relation to the original,
and make the original the parent object of the duplicate.
Args:
obj (Blender object): Object to duplicate
invert_y_position (Boolean, optional): Whether to invert the y-position of
the duplicated object. Defaults to True.
parent (Boolean, optional): Make the original object the parent
of the duplicate.
"""
bpy.ops.object.duplicate() # linked=True)
obj_dupl = bpy.context.selected_objects[0]
if invert_y_position:
position = obj.location
obj_dupl.location = (position[0], -position[1], position[2])
if parent_relationship:
attach_to_parent(obj_dupl, obj)
def make_bulk_layer(name, layer_size, color_RGB, z_position=0.0, parent=None):
"""Create a 3D print bulk layer.
Args:
name (str): Name to give the object.
layer_size (3-element tuple or list of floats or ints): x,y,z size
color_RGB (3-element tuple or list of floats): RGB color with each value
in range 0.0-1.0.
z_position (float, optional): Where to place object in z direction.
Defaults to 0.0.
parent (Blender object, optional): Use this object as parent for new layer.
Defaults to None.
Returns:
Blender object: Newly created layer.
"""
position = (0.0, 0.0, z_position)
layer = make_cube(name, layer_size, position)
mat = make_material_Principled_BSDF(f"{name}_mat", color_RGB)
layer.data.materials.append(mat)
if parent:
attach_to_parent(layer, parent)
return layer
def make_channel_layer(
name, layer_size, channel_width, color_RGB, z_position=0.0, parent=None
):
"""Create a 3D print channel layer.
Args:
name (str): Name to give the object.
layer_size (3-element tuple or list of floats or ints): x,y,z size
channel_width (float or int): Width of channel.
color_RGB (3-element tuple or list of floats): RGB color with each value
in range 0.0-1.0.
z_position (float, optional): Where to place object in z direction.
Defaults to 0.0.
parent (Blender object, optional): Use this object as parent for new layer.
Defaults to None.
Returns:
Blender object: Newly created layer.
"""
lx, ly, lz = layer_size
c = channel_width
size = (lx, ly / 2.0 - c / 2.0, lz)
position = (0.0, -((ly / 2.0 - c / 2.0) / 2.0 + c / 2.0), z_position)
layer_chan = make_cube(name, size, position)
mat = make_material_Principled_BSDF(f"{name}_mat", color_RGB)
layer_chan.data.materials.append(mat)
duplicate_object(layer_chan)
if parent:
attach_to_parent(layer_chan, parent)
return layer_chan
def make_channelfill_layer(
name, layer_size, channel_width, color_RGB, z_position=0.0, parent=None
):
"""Create a 3D print layer that consists of filled channel.
Args:
name (str): Name to give the object.
layer_size (3-element tuple or list of floats or ints): x,y,z size
channel_width (float or int): Width of channel.
color_RGB (3-element tuple or list of floats): RGB color with each value
in range 0.0-1.0.
z_position (float, optional): Where to place object in z direction.
Defaults to 0.0.
parent (Blender object, optional): Use this object as parent for new layer.
Defaults to None.
Returns:
Blender object: Newly created layer.
"""
lx, ly, lz = layer_size
c = channel_width
size = (lx, c, lz)
position = (0.0, 0.0, z_position)
layer_chan = make_cube(name, size, position)
mat = make_material_Principled_BSDF(f"{name}_mat", color_RGB)
layer_chan.data.materials.append(mat)
if parent:
attach_to_parent(layer_chan, parent)
return layer_chan
def make_channel_eroded_layer(
name, layer_size, channel_width, edge_width, color_RGB, z_position=0.0, parent=None
):
"""Create a 3D print eroded channel layer.
Args:
name (str): Name to give the object.
layer_size (3-element tuple or list of floats or ints): x,y,z size
channel_width (float or int): Width of channel.
edge_width (float or int): Width of edge on each side of channel.
color_RGB (3-element tuple or list of floats): RGB color with each value
in range 0.0-1.0.
z_position (float, optional): Where to place object in z direction.
Defaults to 0.0.
parent (Blender object, optional): Use this object as parent for new layer.
Defaults to None.
Returns:
Blender object: Newly created layer.
"""
return make_channel_layer(
name,
layer_size,
channel_width + 2 * edge_width,
color_RGB,
z_position=z_position,
parent=parent,
)
def make_channel_edge_layer(
name, layer_size, channel_width, edge_width, color_RGB, z_position=0.0, parent=None
):
"""Create a 3D print layer with two edge objects at each side of a channel.
Args:
name (str): Name to give the object.
layer_size (3-element tuple or list of floats or ints): x,y,z size
channel_width (float or int): Width of channel.
edge_width (float or int): Width of edge on each side of channel.
color_RGB (3-element tuple or list of floats): RGB color with each value
in range 0.0-1.0.
z_position (float, optional): Where to place object in z direction.
Defaults to 0.0.
parent (Blender object, optional): Use this object as parent for new layer.
Defaults to None.
Returns:
Blender object: Newly created layer.
"""
lx, ly, lz = layer_size
c = channel_width
e = edge_width
# Make edges
size = (lx, e, lz)
position = (0, -(c / 2.0 + e / 2.0), z_position)
edge_name = f"{name}_edge"
layer_edge = make_cube(edge_name, size, position)
mat = make_material_Principled_BSDF(f"{edge_name}_mat", color_RGB)
layer_edge.data.materials.append(mat)
duplicate_object(layer_edge)
if parent:
attach_to_parent(layer_edge, parent)
return layer_edge
# ----------------------------------------------------------------------------------------
# Main code
# ----------------------------------------------------------------------------------------
# Lights
light_location = (8.1524, 2.0110, 11.808)
light_rotation = [pi * 37.3 / 180, pi * 3.16 / 180, pi * 107 / 180]
light_sun = sun_light(location=light_location, rotation=light_rotation)
xy_layer_size = 10
z_layer_size = 0.5
channel_width = 3
edge_width = 1
color_RGB_bulk = (1, 0.71, 0.2)
color_RGB_channel = (0.1, 0.4, 0.7)
color_RGB_edge = (0.7, 0.1, 0.4)
color_RGB_eroded = (0.4, 0.7, 0.1)
color_RGB_channelfill = (0.4, 0.1, 0.2)
size = (xy_layer_size, xy_layer_size, z_layer_size)
position = (0, 0, 0)
# Bulk layer
z = 0 * z_layer_size
layer = make_bulk_layer("First Layer", size, color_RGB_bulk, z)
# Channel layer
z = 1 * z_layer_size
layer_chan = make_channel_layer(
"Chan01", size, channel_width, color_RGB_channel, z, parent=layer
)
# Channel with edge dose
z = 2 * z_layer_size
layer_edge = make_channel_edge_layer(
"Edge01", size, channel_width, edge_width, color_RGB_edge, z, parent=layer
)
layer_eroded = make_channel_eroded_layer(
"Eroded01", size, channel_width, edge_width, color_RGB_eroded, z, parent=layer
)
# Roof layer
z = 3 * z_layer_size
layer_chanfill = make_channelfill_layer(
"ChanFill01", size, channel_width, color_RGB_channelfill, z, parent=layer,
)
layer_chan = make_channel_layer(
"Chan02", size, channel_width, color_RGB_channel, z, parent=layer
)
# Bulk layer
z = 4 * z_layer_size
layer_top = make_bulk_layer("Top Layer", size, color_RGB_bulk, z, parent=layer)
|
python
|
#!/bin/python
#python
import sys
import os
import shutil
import numpy
import time
import math
import threading
from scipy import ndimage
#appion
from appionlib import appionScript
from appionlib import apStack
from appionlib import apDisplay
from appionlib import appiondata
from appionlib import apEMAN
from appionlib import apFile
from appionlib import apRecon
from appionlib import apChimera
from appionlib import apProject
from appionlib import spyder
from appionlib.apTilt import apTiltPair
from appionlib.apSpider import operations, backproject
from pyami import mem, mrc
class rctVolumeScript(appionScript.AppionScript):
#=====================
def onInit(self):
self.rotmirrorcache = {}
self.fscresolution = None
self.rmeasureresolution = None
#=====================
def setupParserOptions(self):
self.parser.set_usage("Usage: %prog --cluster-id=ID --tilt-stack=# --classnums=#,#,# [options]")
### strings
self.parser.add_option("--classnums", dest="classnums", type="str",
help="Class numbers to use for rct volume, e.g. 0,1,2", metavar="#")
### integers
self.parser.add_option("--tilt-stack", dest="tiltstackid", type="int",
help="Tilted Stack ID", metavar="#")
self.parser.add_option("--cluster-id", dest="clusterid", type="int",
help="clustering stack id", metavar="ID")
self.parser.add_option("--align-id", dest="alignid", type="int",
help="alignment stack id", metavar="ID")
self.parser.add_option("--num-iters", dest="numiters", type="int", default=4,
help="Number of tilted image shift refinement iterations", metavar="#")
self.parser.add_option("--mask-rad", dest="radius", type="int",
help="Particle mask radius (in pixels)", metavar="ID")
self.parser.add_option("--tilt-bin", dest="tiltbin", type="int", default=1,
help="Binning of the tilted image", metavar="ID")
self.parser.add_option("--num-part", dest="numpart", type="int",
help="Limit number of particles, for debugging", metavar="#")
self.parser.add_option("--median", dest="median", type="int", default=3,
help="Median filter", metavar="#")
### floats
self.parser.add_option("--lowpassvol", dest="lowpassvol", type="float", default=10.0,
help="Low pass volume filter (in Angstroms)", metavar="#")
self.parser.add_option("--highpasspart", dest="highpasspart", type="float", default=600.0,
help="High pass particle filter (in Angstroms)", metavar="#")
self.parser.add_option("--lowpasspart", dest="lowpasspart", type="float",
help="Low pass particle filter (in Angstroms)", metavar="#")
self.parser.add_option("--min-score", "--min-spread", dest="minscore", type="float",
help="Minimum score/spread/cross-correlation for particles", metavar="#")
self.parser.add_option("--contour", dest="contour", type="float", default=3.0,
help="Chimera snapshot contour", metavar="#")
self.parser.add_option("--zoom", dest="zoom", type="float", default=1.1,
help="Chimera snapshot zoom", metavar="#")
self.parser.add_option("--mass", dest="mass", type="float",
help="Use mass in kDa to set Chimera snapshot contour", metavar="#")
### true/false
self.parser.add_option("--no-eotest", dest="eotest", default=True,
action="store_false", help="Do not perform eotest for resolution")
self.parser.add_option("--eotest", dest="eotest", default=True,
action="store_true", help="Perform eotest for resolution")
self.parser.add_option("--skip-chimera", dest="skipchimera", default=False,
action="store_true", help="Skip chimera imaging")
### choices
self.mirrormodes = ( "all", "yes", "no" )
self.parser.add_option("--mirror", dest="mirror",
help="Mirror mode", metavar="MODE",
type="choice", choices=self.mirrormodes, default="all" )
#=====================
def checkConflicts(self):
### parse class list
if self.params['classnums'] is None:
apDisplay.printError("class number was not defined")
rawclasslist = self.params['classnums'].split(",")
self.classlist = []
for cnum in rawclasslist:
try:
self.classlist.append(int(cnum))
except:
apDisplay.printError("could not parse: "+cnum)
### check for missing and duplicate entries
if self.params['mass'] is not None:
self.params['contour'] = 1.0
apDisplay.printMsg("Using scale by mass method")
### check for missing and duplicate entries
if self.params['alignid'] is None and self.params['clusterid'] is None:
apDisplay.printError("Please provide either --cluster-id or --align-id")
if self.params['alignid'] is not None and self.params['clusterid'] is not None:
apDisplay.printError("Please provide only one of either --cluster-id or --align-id")
### get the stack ID from the other IDs
if self.params['alignid'] is not None:
self.alignstackdata = appiondata.ApAlignStackData.direct_query(self.params['alignid'])
self.params['notstackid'] = self.alignstackdata['stack'].dbid
elif self.params['clusterid'] is not None:
self.clusterstackdata = appiondata.ApClusteringStackData.direct_query(self.params['clusterid'])
self.alignstackdata = self.clusterstackdata['clusterrun']['alignstack']
self.params['notstackid'] = self.alignstackdata['stack'].dbid
### check and make sure we got the stack id
if self.params['notstackid'] is None:
apDisplay.printError("untilted stackid was not found")
if self.params['tiltstackid'] is None:
apDisplay.printError("tilt stack ID was not defined")
if self.params['radius'] is None:
apDisplay.printError("particle mask radius was not defined")
if self.params['description'] is None:
apDisplay.printError("enter a description")
boxsize = self.getBoxSize()
if self.params['radius']*2 > boxsize-2:
apDisplay.printError("particle radius is too big for stack boxsize")
#=====================
def setRunDir(self):
stackdata = apStack.getOnlyStackData(self.params['tiltstackid'], msg=False)
path = stackdata['path']['path']
uppath = os.path.dirname(os.path.dirname(os.path.abspath(path)))
classliststr = operations.intListToString(self.classlist)
self.params['rundir'] = os.path.join(uppath, "rctvolume",
self.params['runname'] )
#=====================
def getParticleInPlaneRotation(self, tiltstackpartdata):
partid = tiltstackpartdata.dbid
if partid in self.rotmirrorcache:
### use cached value
return self.rotmirrorcache[partid]
partnum = tiltstackpartdata['particleNumber']
notstackpartdata = apTiltPair.getStackParticleTiltPair(self.params['tiltstackid'],
partnum, self.params['notstackid'])
alignpartq = appiondata.ApAlignParticleData()
alignpartq['stackpart'] = notstackpartdata
alignpartq['alignstack'] = self.alignstackdata
alignpartdatas = alignpartq.query()
if not alignpartdatas or len(alignpartdatas) != 1:
apDisplay.printError("could not get inplane rotation for particle %d"%(tiltstackpartdata['particleNumber']))
inplane = alignpartdatas[0]['rotation']
mirror = alignpartdatas[0]['mirror']
if alignpartdatas[0]['alignstack']['alignrun']['maxlikerun'] is not None:
# maxlike does mirror then rotation, and its rotation is negative relative to spider
# April 6, 2009: rotation is negative independent of mirror
inplane = -1.0*inplane
self.rotmirrorcache[partid] = (inplane, mirror)
return inplane, mirror
#=====================
def getBoxSize(self):
boxsize = apStack.getStackBoxsize(self.params['tiltstackid'])
if self.params['tiltbin'] == 1:
return boxsize
newbox = int( math.floor( boxsize / float(self.params['tiltbin']) / 2.0)* 2.0 )
return newbox
#=====================
def convertStackToSpider(self, emanstackfile):
"""
takes the stack file and creates a spider file ready for processing
"""
if not os.path.isfile(emanstackfile):
apDisplay.printError("stackfile does not exist: "+emanstackfile)
tempstack = os.path.join(self.params['rundir'], "filter"+self.timestamp+".hed")
### first high pass filter particles
apDisplay.printMsg("pre-filtering particles")
apix = apStack.getStackPixelSizeFromStackId(self.params['tiltstackid'])
boxsize = self.getBoxSize()
emancmd = ("proc2d "+emanstackfile+" "+tempstack
+" apix="+str(apix)+" ")
if self.params['highpasspart'] is not None and self.params['highpasspart'] > 0:
emancmd += "hp="+str(self.params['highpasspart'])+" "
if self.params['lowpasspart'] is not None and self.params['lowpasspart'] > 0:
emancmd += "lp="+str(self.params['lowpasspart'])+" "
if self.params['tiltbin'] > 1:
clipsize = boxsize*self.params['tiltbin']
emancmd += " shrink=%d clip=%d,%d "%(self.params['tiltbin'], clipsize, clipsize)
apEMAN.executeEmanCmd(emancmd, verbose=True)
### convert imagic stack to spider
emancmd = "proc2d "
emancmd += tempstack+" "
spiderstack = os.path.join(self.params['rundir'], "rctstack"+self.timestamp+".spi")
apFile.removeFile(spiderstack, warn=True)
emancmd += spiderstack+" "
emancmd += "spiderswap edgenorm"
starttime = time.time()
apDisplay.printColor("Running spider stack conversion this can take a while", "cyan")
apEMAN.executeEmanCmd(emancmd, verbose=True)
time.sleep(1) # wait a sec, for things to finish
apDisplay.printColor("finished eman in "+apDisplay.timeString(time.time()-starttime), "cyan")
apFile.removeStack(tempstack, warn=False)
apFile.removeStack(emanstackfile, warn=False)
if not os.path.isfile(spiderstack):
apDisplay.printError("Failed to create a spider stack")
return spiderstack
#=====================
def sortTiltParticlesData(self, a, b):
if a['particleNumber'] > b['particleNumber']:
return 1
return -1
#=====================
def insertRctRun(self, volfile):
### setup resolutions
fscresq = appiondata.ApResolutionData()
fscresq['type'] = "fsc"
fscresq['half'] = self.fscresolution
fscresq['fscfile'] = "fscdata"+self.timestamp+".fsc"
rmeasureq = appiondata.ApResolutionData()
rmeasureq['type'] = "rmeasure"
rmeasureq['half'] = self.rmeasureresolution
rmeasureq['fscfile'] = None
### insert rct run data
rctrunq = appiondata.ApRctRunData()
rctrunq['runname'] = self.params['runname']
classliststr = operations.intListToString(self.classlist)
rctrunq['classnums'] = classliststr
rctrunq['numiter'] = self.params['numiters']
rctrunq['maskrad'] = self.params['radius']
rctrunq['lowpassvol'] = self.params['lowpassvol']
rctrunq['highpasspart'] = self.params['highpasspart']
rctrunq['lowpasspart'] = self.params['lowpasspart']
rctrunq['median'] = self.params['median']
rctrunq['description'] = self.params['description']
rctrunq['path'] = appiondata.ApPathData(path=os.path.abspath(self.params['rundir']))
rctrunq['alignstack'] = self.alignstackdata
rctrunq['tiltstack'] = apStack.getOnlyStackData(self.params['tiltstackid'])
rctrunq['numpart'] = self.numpart
rctrunq['fsc_resolution'] = fscresq
rctrunq['rmeasure_resolution'] = rmeasureq
if self.params['commit'] is True:
rctrunq.insert()
### insert 3d volume density
densq = appiondata.Ap3dDensityData()
densq['rctrun'] = rctrunq
densq['path'] = appiondata.ApPathData(path=os.path.dirname(os.path.abspath(volfile)))
densq['name'] = os.path.basename(volfile)
densq['hidden'] = False
densq['norm'] = True
densq['symmetry'] = appiondata.ApSymmetryData.direct_query(25)
densq['pixelsize'] = apStack.getStackPixelSizeFromStackId(self.params['tiltstackid'])*self.params['tiltbin']
densq['boxsize'] = self.getBoxSize()
densq['lowpass'] = self.params['lowpassvol']
densq['highpass'] = self.params['highpasspart']
densq['mask'] = self.params['radius']
#densq['iterid'] = self.params['numiters']
densq['description'] = self.params['description']
densq['resolution'] = self.fscresolution
densq['rmeasure'] = self.rmeasureresolution
densq['session'] = apStack.getSessionDataFromStackId(self.params['tiltstackid'])
densq['md5sum'] = apFile.md5sumfile(volfile)
if self.params['commit'] is True:
densq.insert()
return
#=====================
def processVolume(self, spivolfile, iternum=0):
### set values
apix = apStack.getStackPixelSizeFromStackId(self.params['tiltstackid'])*self.params['tiltbin']
boxsize = self.getBoxSize()
rawspifile = os.path.join(self.params['rundir'], "rawvolume%s-%03d.spi"%(self.timestamp, iternum))
mrcvolfile = os.path.join(self.params['rundir'], "volume%s-%03d.mrc"%(self.timestamp, iternum))
lowpass = self.params['lowpassvol']
### copy original to raw file
shutil.copy(spivolfile, rawspifile)
### convert to mrc
emancmd = ("proc3d "+spivolfile+" "+mrcvolfile+" norm=0,1 apix="+str(apix))
apEMAN.executeEmanCmd(emancmd, verbose=False)
### median filter
rawvol = mrc.read(mrcvolfile)
medvol = ndimage.median_filter(rawvol, size=self.params['median'])
mrc.write(medvol, mrcvolfile)
### low pass filter
emancmd = ("proc3d "+mrcvolfile+" "+mrcvolfile+" center norm=0,1 apix="
+str(apix)+" lp="+str(lowpass))
apEMAN.executeEmanCmd(emancmd, verbose=False)
### set origin
emancmd = "proc3d "+mrcvolfile+" "+mrcvolfile+" origin=0,0,0 "
apEMAN.executeEmanCmd(emancmd, verbose=False)
### mask volume
emancmd = "proc3d "+mrcvolfile+" "+mrcvolfile+" mask="+str(self.params['radius'])
apEMAN.executeEmanCmd(emancmd, verbose=False)
### convert to spider
apFile.removeFile(spivolfile)
emancmd = "proc3d "+mrcvolfile+" "+spivolfile+" spidersingle"
apEMAN.executeEmanCmd(emancmd, verbose=False)
### image with chimera
if self.params['skipchimera'] is False:
if self.params['mass'] is not None:
apDisplay.printMsg("Using scale by mass method")
apChimera.setVolumeMass(mrcvolfile, apix=apix, mass=self.params['mass'])
apChimera.renderSnapshots(mrcvolfile, self.params['contour'], self.params['zoom'], 'c1')
return mrcvolfile
#=====================
def makeEulerDoc(self, tiltParticlesData):
count = 0
eulerfile = os.path.join(self.params['rundir'], "eulersdoc"+self.timestamp+".spi")
eulerf = open(eulerfile, "w")
apDisplay.printMsg("Creating Euler angles doc file")
starttime = time.time()
tiltParticlesData.sort(self.sortTiltParticlesData)
startmem = mem.active()
for stackpartdata in tiltParticlesData:
count += 1
if count%50 == 0:
sys.stderr.write(".")
eulerf.flush()
memdiff = (mem.active()-startmem)/count/1024.0
if memdiff > 3:
apDisplay.printColor("Memory increase: %d MB/part"%(memdiff), "red")
tiltrot, theta, notrot, tiltangle = apTiltPair.getParticleTiltRotationAngles(stackpartdata)
if tiltrot is None:
apDisplay.printError("BAD particle "+str(stackpartdata))
inplane, mirror = self.getParticleInPlaneRotation(stackpartdata)
totrot = -1.0*(notrot + inplane)
if mirror is True:
#theta flips to the back
tiltangle = -1.0 * tiltangle + 180 #tiltangle = tiltangle + 180.0 #theta
totrot = -1.0 * totrot - 180.0 #phi
tiltrot = tiltrot + 180 #tiltrot = -1.0 * tiltrot + 180.0 #psi
while totrot < 0:
totrot += 360.0
### this is the original eman part num; count is new part num
partnum = stackpartdata['particleNumber']-1
line = operations.spiderOutLine(count, [tiltrot, tiltangle, totrot])
eulerf.write(line)
eulerf.close()
apDisplay.printColor("\nFinished Euler angle doc file in "+apDisplay.timeString(time.time()-starttime), "cyan")
memdiff = (mem.active()-startmem)/count/1024.0
if memdiff > 0.1:
apDisplay.printColor("Memory increase: %.2f MB/part"%(memdiff), "red")
return eulerfile
#=====================
def getGoodAlignParticles(self):
includeParticle = []
tiltParticlesData = []
nopairParticle = 0
excludeParticle = 0
badmirror = 0
badscore = 0
apDisplay.printMsg("Sorting particles from classes at "+time.asctime())
count = 0
startmem = mem.active()
t0 = time.time()
if self.params['clusterid'] is not None:
### method 1: get particles from clustering data
clusterpartq = appiondata.ApClusteringParticleData()
clusterpartq['clusterstack'] = appiondata.ApClusteringStackData.direct_query(self.params['clusterid'])
clusterpartdatas = clusterpartq.query()
apDisplay.printMsg("Sorting "+str(len(clusterpartdatas))+" clustered particles")
for clustpart in clusterpartdatas:
count += 1
if count%50 == 0:
sys.stderr.write(".")
memdiff = (mem.active()-startmem)/count/1024.0
if memdiff > 3:
apDisplay.printColor("Memory increase: %d MB/part"%(memdiff), "red")
#write to text file
clustnum = clustpart['refnum']-1
if self.params['minscore'] is not None:
if ( clustpart['alignparticle']['score'] is not None
and clustpart['alignparticle']['score'] < self.params['minscore'] ):
badscore += 1
continue
elif ( clustpart['alignparticle']['spread'] is not None
and clustpart['alignparticle']['spread'] < self.params['minscore'] ):
badscore += 1
continue
if clustnum in self.classlist:
notstackpartnum = clustpart['alignparticle']['stackpart']['particleNumber']
tiltstackpartdata = apTiltPair.getStackParticleTiltPair(self.params['notstackid'],
notstackpartnum, self.params['tiltstackid'])
if tiltstackpartdata is None:
nopairParticle += 1
continue
tiltrot, theta, notrot, tiltangle = apTiltPair.getParticleTiltRotationAngles(tiltstackpartdata)
if tiltrot is None:
apDisplay.printWarning("BAD particle "+str(tiltstackpartdata))
nopairParticle += 1
continue
else:
inplane, mirror = self.getParticleInPlaneRotation(tiltstackpartdata)
if ( self.params['mirror'] == "all"
or (self.params['mirror'] == "no" and mirror is False)
or (self.params['mirror'] == "yes" and mirror is True) ):
emantiltstackpartnum = tiltstackpartdata['particleNumber']-1
includeParticle.append(emantiltstackpartnum)
tiltParticlesData.append(tiltstackpartdata)
if self.params['numpart'] is not None and len(includeParticle) > self.params['numpart']:
break
else:
badmirror += 1
else:
excludeParticle += 1
else:
### method 2: get particles from alignment data
alignpartq = appiondata.ApAlignParticleData()
alignpartq['alignstack'] = self.alignstackdata
alignpartdatas = alignpartq.query()
apDisplay.printMsg("Sorting "+str(len(alignpartdatas))+" aligned particles")
for alignpart in alignpartdatas:
count += 1
if count%50 == 0:
sys.stderr.write(".")
memdiff = (mem.active()-startmem)/count/1024.0
if memdiff > 3:
apDisplay.printColor("Memory increase: %d MB/part"%(memdiff), "red")
#write to text file
alignnum = alignpart['ref']['refnum']-1
if ( self.params['minscore'] is not None
and alignpart['score'] is not None
and alignpart['score'] < self.params['minscore'] ):
badscore += 1
continue
if alignnum in self.classlist:
notstackpartnum = alignpart['stackpart']['particleNumber']
tiltstackpartdata = apTiltPair.getStackParticleTiltPair(self.params['notstackid'],
notstackpartnum, self.params['tiltstackid'])
if tiltstackpartdata is None:
nopairParticle += 1
else:
inplane, mirror = self.getParticleInPlaneRotation(tiltstackpartdata)
if ( self.params['mirror'] == "all"
or (self.params['mirror'] == "no" and mirror is False)
or (self.params['mirror'] == "yes" and mirror is True) ):
emantiltstackpartnum = tiltstackpartdata['particleNumber']-1
includeParticle.append(emantiltstackpartnum)
tiltParticlesData.append(tiltstackpartdata)
if self.params['numpart'] is not None and len(includeParticle) > self.params['numpart']:
break
else:
badmirror += 1
else:
excludeParticle += 1
### end methods
includeParticle.sort()
### messages
if time.time()-t0 > 1.0:
apDisplay.printMsg("\nSorting time: "+apDisplay.timeString(time.time()-t0))
apDisplay.printMsg("Keeping "+str(len(includeParticle))+" and excluding \n\t"
+str(excludeParticle)+" particles with "+str(nopairParticle)+" unpaired particles")
if badmirror > 0:
apDisplay.printMsg("Particles with bad mirrors: %d"%(badmirror))
if badscore > 0:
apDisplay.printColor("Particles with bad scores: %d"%(badscore), "cyan")
if len(includeParticle) < 1:
apDisplay.printError("No particles were kept")
memdiff = (mem.active()-startmem)/count/1024.0
if memdiff > 0.1:
apDisplay.printColor("Memory increase: %.2f MB/part"%(memdiff), "red")
return includeParticle, tiltParticlesData
#=====================
def mirrorParticles(self, partdatas, spiderstack):
partnum = 0
mySpider = spyder.SpiderSession(dataext=".spi", logo=False, log=False)
for stackpartdata in partdatas:
partnum += 1
inplane, mirror = self.getParticleInPlaneRotation(stackpartdata)
if mirror is True:
sys.stderr.write("m")
mySpider.toSpiderQuiet("MR",
spyder.fileFilter(spiderstack)+("@%05d"%(partnum)),
"_9",
"Y",
)
mySpider.toSpiderQuiet("CP",
"_9",
spyder.fileFilter(spiderstack)+("@%05d"%(partnum)),
)
else:
sys.stderr.write(".")
sys.stderr.write("\n")
mySpider.close()
#=====================
def runEoTest(self, alignstack, eulerfile):
evenvolfile = os.path.join(self.params['rundir'], "evenvolume%s.spi"%(self.timestamp))
oddvolfile = os.path.join(self.params['rundir'], "oddvolume%s.spi"%(self.timestamp))
eveneulerfile = os.path.join(self.params['rundir'], "eveneulers%s.spi"%(self.timestamp))
oddeulerfile = os.path.join(self.params['rundir'], "oddeulers%s.spi"%(self.timestamp))
evenpartlist = os.path.join(self.params['rundir'], "evenparts%s.lst"%(self.timestamp))
oddpartlist = os.path.join(self.params['rundir'], "oddparts%s.lst"%(self.timestamp))
### Create New Doc Files
of = open(oddeulerfile, "w")
ef = open(eveneulerfile, "w")
op = open(oddpartlist, "w")
ep = open(evenpartlist, "w")
inf = open(eulerfile, "r")
evenpart = 0
oddpart = 0
for line in inf:
spidict = operations.spiderInLine(line)
if spidict:
partnum = spidict['row']
if partnum % 2 == 0:
ep.write("%d\n"%(partnum-1))
evenpart += 1
outline = operations.spiderOutLine(evenpart, spidict['floatlist'])
ef.write(outline)
elif partnum % 2 == 1:
op.write("%d\n"%(partnum-1))
oddpart += 1
outline = operations.spiderOutLine(oddpart, spidict['floatlist'])
of.write(outline)
inf.close()
of.close()
ef.close()
op.close()
ep.close()
### Create stacks
evenstack = os.path.join(self.params['rundir'], "evenstack%s.spi"%(self.timestamp))
emancmd = "proc2d %s %s list=%s spiderswap"%(alignstack,evenstack,evenpartlist)
apEMAN.executeEmanCmd(emancmd, verbose=True, showcmd=True)
oddstack = os.path.join(self.params['rundir'], "oddstack%s.spi"%(self.timestamp))
emancmd = "proc2d %s %s list=%s spiderswap"%(alignstack,oddstack,oddpartlist)
apEMAN.executeEmanCmd(emancmd, verbose=True, showcmd=True)
### Create Volumes
backproject.backproject3F(evenstack, eveneulerfile, evenvolfile, evenpart)
backproject.backproject3F(oddstack, oddeulerfile, oddvolfile, oddpart)
if not os.path.isfile(evenvolfile) or not os.path.isfile(oddvolfile):
apDisplay.printError("Even-Odd volume creation failed")
### Calculate FSC
apix = apStack.getStackPixelSizeFromStackId(self.params['tiltstackid'])*self.params['tiltbin']
emancmd = "proc3d %s %s"%(evenvolfile, evenvolfile+".mrc")
apEMAN.executeEmanCmd(emancmd, verbose=True, showcmd=True)
emancmd = "proc3d %s %s"%(oddvolfile, oddvolfile+".mrc")
apEMAN.executeEmanCmd(emancmd, verbose=True, showcmd=True)
fscfile = os.path.join(self.params['rundir'], "fscdata%s.fsc"%(self.timestamp))
emancmd = "proc3d %s %s fsc=%s"%(evenvolfile+".mrc", oddvolfile+".mrc", fscfile)
apEMAN.executeEmanCmd(emancmd, verbose=True, showcmd=True)
if not os.path.isfile(fscfile):
apDisplay.printError("Even-Odd fsc calculation failed")
boxsize = self.getBoxSize()
self.fscresolution = apRecon.getResolutionFromFSCFile(fscfile, boxsize, apix, msg=True)
apDisplay.printColor( ("Final FSC resolution: %.5f" % (self.fscresolution)), "cyan")
for fname in (evenvolfile, oddvolfile, evenstack, oddstack, eveneulerfile, oddeulerfile, evenpartlist, oddpartlist):
apFile.removeFile(fname)
#=====================
def runRmeasure(self):
finalrawvolfile = os.path.join(self.params['rundir'], "rawvolume%s-%03d.spi"%(self.timestamp, self.params['numiters']))
emancmd = "proc3d %s %s"%(finalrawvolfile, "rmeasure.mrc")
apEMAN.executeEmanCmd(emancmd, verbose=True, showcmd=True)
apix = apStack.getStackPixelSizeFromStackId(self.params['tiltstackid'])*self.params['tiltbin']
self.rmeasureresolution = apRecon.runRMeasure(apix, "rmeasure.mrc")
#apDisplay.printColor("Final Rmeasure resolution: "+str(self.rmeasureresolution), "cyan")
apFile.removeFile("rmeasure.mrc")
#=====================
def start(self):
### get stack data
notstackdata = apStack.getOnlyStackData(self.params['notstackid'])
tiltstackdata = apStack.getOnlyStackData(self.params['tiltstackid'])
### get good particle numbers
includeParticle, tiltParticlesData = self.getGoodAlignParticles()
self.numpart = len(includeParticle)
### make doc file of Euler angles
eulerfile = self.makeEulerDoc(tiltParticlesData)
### write kept particles to file
self.params['keepfile'] = os.path.join(self.params['rundir'], "keepfile"+self.timestamp+".lst")
apDisplay.printMsg("writing to keepfile "+self.params['keepfile'])
kf = open(self.params['keepfile'], "w")
for partnum in includeParticle:
kf.write(str(partnum)+"\n")
kf.close()
### make new stack of tilted particle from that run
tiltstackfile = os.path.join(tiltstackdata['path']['path'], tiltstackdata['name'])
rctstackfile = os.path.join(self.params['rundir'], "rctstack"+self.timestamp+".hed")
apFile.removeStack(rctstackfile, warn=False)
apStack.makeNewStack(tiltstackfile, rctstackfile, self.params['keepfile'])
spiderstack = self.convertStackToSpider(rctstackfile)
#self.mirrorParticles(tiltParticlesData, spiderstack)
### iterations over volume creation
### back project particles into filter volume
volfile = os.path.join(self.params['rundir'], "volume%s-%03d.spi"%(self.timestamp, 0))
backproject.backprojectCG(spiderstack, eulerfile, volfile,
numpart=self.numpart, pixrad=self.params['radius'])
alignstack = spiderstack
### center/convert the volume file
mrcvolfile = self.processVolume(volfile, 0)
for i in range(self.params['numiters']):
looptime = time.time()
iternum = i+1
apDisplay.printMsg("running backprojection iteration "+str(iternum))
### xy-shift particles to volume projections
alignstack = backproject.rctParticleShift(volfile, alignstack, eulerfile, iternum,
numpart=self.numpart, pixrad=self.params['radius'], timestamp=self.timestamp)
apFile.removeFile(volfile)
### back project particles into better volume
volfile = os.path.join(self.params['rundir'], "volume%s-%03d.spi"%(self.timestamp, iternum))
backproject.backproject3F(alignstack, eulerfile, volfile,
numpart=self.numpart)
### center/convert the volume file
mrcvolfile = self.processVolume(volfile, iternum)
apDisplay.printColor("finished volume refinement loop in "
+apDisplay.timeString(time.time()-looptime), "cyan")
### optimize Euler angles
#NOT IMPLEMENTED YET
### perform eotest
if self.params['eotest'] is True:
self.runEoTest(alignstack, eulerfile)
self.runRmeasure()
### insert volumes into DB
self.insertRctRun(mrcvolfile)
#apDisplay.printMsg("waiting for Chimera to finish")
#time.sleep(60)
#=====================
if __name__ == "__main__":
rctVolume = rctVolumeScript()
rctVolume.start()
rctVolume.close()
|
python
|
# terrascript/provider/josenk/esxi.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:15:57 UTC)
import terrascript
class esxi(terrascript.Provider):
"""Terraform-provider-esxi plugin"""
__description__ = "Terraform-provider-esxi plugin"
__namespace__ = "josenk"
__name__ = "esxi"
__source__ = "https://github.com/josenk/terraform-provider-esxi"
__version__ = "1.8.3"
__published__ = "2021-08-29T02:45:18Z"
__tier__ = "community"
__all__ = ["esxi"]
|
python
|
from .db import session_scope, Server
from datetime import datetime, timedelta
class Gateway:
def get_all_servers(self):
with session_scope() as session:
raw_servers = session.query(Server)
raw_servers_dict = []
if raw_servers:
for raw_server in raw_servers:
raw_dict = raw_server.__dict__
del raw_dict['_sa_instance_state']
raw_servers_dict.append(raw_dict)
return raw_servers_dict
def fill_db(self, servers):
with session_scope() as session:
for key in servers.keys():
server = session.query(Server).filter(Server.name == key).first()
if server:
server.number = servers[key]
else:
session.add(Server(name=key, number=servers[key], added=datetime.now()))
def get_analytics(self, hour=False, day=False, month=False):
if hour:
comparator = datetime.now() - timedelta(hours=1)
elif day:
comparator = datetime.now() - timedelta(days=1)
else:
comparator = datetime.now() - timedelta(days=30)
with session_scope() as session:
raw_servers = session.query(Server).filter(Server.added >= comparator).all()
raw_servers_dict = []
if raw_servers:
for raw_server in raw_servers:
raw_dict = raw_server.__dict__
del raw_dict['_sa_instance_state']
raw_servers_dict.append(raw_dict)
return raw_servers_dict
|
python
|
"""Utility functions."""
from typing import typevar, List, Any
T = typevar('T')
def short_type(obj: object) -> str:
"""Return the last component of the type name of an object.
If obj is None, return 'nil'. For example, if obj is 1, return 'int'.
"""
if obj is None:
return 'nil'
t = str(type(obj))
return t.split('.')[-1].rstrip("'>")
def indent(s: str, n: int) -> str:
"""Indent all the lines in s (separated by Newlines) by n spaces."""
s = ' ' * n + s
s = s.replace('\n', '\n' + ' ' * n)
return s
def array_repr(a: List[T]) -> List[str]:
"""Return the items of an array converted to strings using Repr."""
aa = [] # type: List[str]
for x in a:
aa.append(repr(x))
return aa
def dump_tagged(nodes: List[Any], tag: str) -> str:
"""Convert an array into a pretty-printed multiline string representation.
The format is
tag(
item1..
itemN)
Individual items are formatted like this:
- arrays are flattened
- pairs (str : array) are converted recursively, so that str is the tag
- other items are converted to strings and indented
"""
a = [] # type: List[str]
if tag:
a.append(tag + '(')
for n in nodes:
if isinstance(n, list):
if n:
a.append(dump_tagged(n, None))
elif isinstance(n, tuple):
s = dump_tagged(n[1], n[0])
a.append(indent(s, 2))
elif n:
a.append(indent(str(n), 2))
if tag:
a[-1] += ')'
return '\n'.join(a)
|
python
|
from abc import ABC
from abc import abstractmethod
class DatabaseQuery(ABC):
@staticmethod
def query_invoke(func):
def wrapper_method(self_instance, *args, **kwargs):
try:
self_instance.create_connection()
result = func(self_instance, *args, **kwargs)
return result
finally:
self_instance.close_connection()
return wrapper_method
@abstractmethod
def create_connection(self):
pass
@abstractmethod
def close_connection(self):
pass
@abstractmethod
def get_object_by_id(self, collection, object_id):
pass
@abstractmethod
def get_object(self, collection, key, value):
pass
@abstractmethod
def get_collection(self, collection):
pass
@abstractmethod
def get_all_item_in_collection(self, collection):
pass
@abstractmethod
def get_item_in_collection(self, collection, filter_query):
pass
@abstractmethod
def get_list_item_in_collection(self, collection, filter_query):
pass
@abstractmethod
def count_item_in_query(self, collection, filter_query):
pass
@abstractmethod
def close_client_connection(self):
pass
@abstractmethod
def close_server(self):
pass
|
python
|
# coding: utf-8
import argparse
from argparse import RawDescriptionHelpFormatter
import sys
import os
sys.path.append('.\src')
sys.path.append('..\src')
from src.main_functions import *
updateInput='u'
fullupdateInput='fu'
downloadInput='d'
statusInput='s'
compressInput='c'
def check_env():
try:
os.listdir('novel_list')
except FileNotFoundError:
os.mkdir('novel_list')
def parser():
parser = argparse.ArgumentParser(description=""" c to compress novels in zip
d to download input.txt list
s to update status.csv
u to update novels""",
formatter_class=RawDescriptionHelpFormatter)
parser.add_argument("mode",
help="put the letter of argument c/d/s/u",
type=str,default=argparse.SUPPRESS)
parser.add_argument("-r", help="regex of entree for compression selection (select * containing regex)",
type=str,default=argparse.SUPPRESS)
parser.add_argument("-o", help="output directory (only works for compression)",
type=str,default=argparse.SUPPRESS)
parser.add_argument("-f", help="force",action='store_true'
,default=argparse.SUPPRESS)
parser.add_argument("-md", help="format",action='store_true'
,default=argparse.SUPPRESS)
args = parser.parse_args()
print(args)
regex=''
keep_text_format=False
if args.mode:
if hasattr(args, 'md'):
keep_text_format=True
if hasattr(args, 'r'):
regex=args.r
if(args.mode==downloadInput):
print("downloading")
download(keep_text_format)
elif(args.mode==updateInput):
archiveUpdate(findNovel(regex),keep_text_format)
elif(args.mode==statusInput):
getFolderStatus()
elif(args.mode==fullupdateInput):
if hasattr(args, 'f'):
archiveFullUpdate(findNovel(regex),True)
else:
archiveFullUpdate(findNovel(regex))
elif(args.mode==compressInput):
print('compression')
print(args)
out=''
if hasattr(args, 'o'):
out=args.o
compressAll(regex,out)
if __name__ == '__main__':
check_env()
parser()
|
python
|
import json
from collections import defaultdict
from typing import List, Tuple, Dict
from commands.snapshot import snapshot
from drive.api import DriveFile, Snapshot, resolve_paths, ResourcePath, Resource
from drive.http import ErrorHandlingRunner, GAPIBatchRunner
from drive.misc import eprint
from drive.serializers import load_snapshot
def dedup_list(service, args):
eprint('Computing duplicates and resolving resource paths.')
duplicates, paths = compute_duplicates(service, get_snapshot(service, args))
summary = {
md5: [
{
'id': duplicate.id,
'path': str(paths[duplicate])
}
for duplicate in entries
] for md5, entries in duplicates.items()
}
if len(duplicates) == 0:
eprint('Hooray! There are no duplicates in the snapshot.')
else:
eprint('Duplicates were found.')
if args.json:
print(json.dumps(summary, indent=3))
else:
for md5, entries in summary.items():
eprint('------ %s -------' % md5)
for entry in entries:
eprint('%s (%s)' % (entry['path'], entry['id']))
eprint('')
def dedup_apply(service, args):
eprint('Now computing and removing duplicates. Prefix order is %s.' % args.prefixes)
duplicates, paths = compute_duplicates(
service, get_snapshot(service, args)
)
# Strips white spaces.
prefixes = [prefix.strip() for prefix in args.prefixes.split(',')]
# Adds trailing backlash to make prefixes unique.
prefixes = [prefix + ('/' if not prefix.endswith('/') else '') for prefix in prefixes]
runner = ErrorHandlingRunner(service, delegate=GAPIBatchRunner)
for md5, entries in duplicates.items():
preferences = list(zip(entries, list(rank(prefixes, [paths[entry] for entry in entries]))))
for duplicate, _ in sorted(preferences, key=lambda x: x[1])[1:]:
rid = '%s (%s)' % (paths[duplicate], duplicate.id)
eprint('Queue request for deleting duplicate %s' % rid)
runner.add(request_id=rid, request=duplicate.delete())
if not args.dry_run:
eprint('\n --- Now running %d deletion requests in batch.' % len(runner.requests))
for rid, result, _ in runner.execute():
eprint('Successfully deleted %s' % rid)
else:
eprint('Dry run. No changes applied.')
def rank(prefix_preferences, paths: List[ResourcePath]):
for path in paths:
for i, prefix in enumerate(prefix_preferences):
if path.startswith(prefix):
yield i
break
else:
# If the path does not match any of the prefixes, we throw an error. This can be painful to the
# user but it's better than taking an arbitrary decision for either deleting or leaving the duplicate
# behind
raise Exception('Path %s is not covered by any of the specified prefixes. Aborting.' % str(path))
def compute_duplicates(service, snapshot: Snapshot) -> Tuple[Dict[str, List[Resource]], Dict[Resource, ResourcePath]]:
by_md5 = defaultdict(list)
for entry in snapshot.entries:
if not isinstance(entry, DriveFile):
continue
by_md5[entry.md5Checksum].append(entry)
duplicates = {k: v for k, v in by_md5.items() if len(v) > 1}
paths = dict(resolve_paths(service, [
element for elements in duplicates.values() for element in elements
]))
return duplicates, paths
def get_snapshot(service, args):
return load_snapshot(service, args.snapshot) if args.snapshot else snapshot(service, [args.folder])
def register_parser(subparsers):
parser = subparsers.add_parser(
'dedup', help='Hunt down and remove duplicate files from Google Drive.')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--snapshot', help='causes _dedup_ to look for duplicates inside of a pre-existing snapshot,'
'created with the _snapshot_ command')
group.add_argument('--folder', help='causes _dedup_ to look for duplicates in an existing folder '
'in Google Drive (e.g. "/Pictures/Old/")')
subsubparsers = parser.add_subparsers()
subsubparsers.required = True
subsubparsers.dest = 'command'
compute = subsubparsers.add_parser('list', help='lists duplicates, grouped by MD5')
compute.add_argument('--json', help='Outputs listing in JSON format.', action='store_true')
compute.set_defaults(func=dedup_list)
apply = subsubparsers.add_parser('apply', help='removes duplicates')
apply.add_argument('--prefixes', help='comma-separated list of preferred prefixes, most '
'preferred come first.'
'Duplicates will be dropped from least-preferred '
'prefixes, or prefixes not present in this list. Use '
'the single prefix "/" to delete duplicates at random. If no '
'prefix can be matched, deduplication will abort with an error.',
required=True)
apply.add_argument('--dry-run', help='Prints actions but do not actually change the contents of Google Drive.',
action='store_true')
apply.set_defaults(func=dedup_apply)
|
python
|
#!/usr/bin/env python3
# -*- coding: UTF-8
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
import bs4
import requests
import re
from urllib.request import urlretrieve
import os.path
import csv
if __name__ == "__main__":
base__url = "http://pesquisa.memoriasreveladas.gov.br/mrex/consulta/"
first_url = "http://pesquisa.memoriasreveladas.gov.br/mrex/consulta/resultado_pesquisa_new.asp?v_pesquisa=&v_fundo_colecao=1278707&Pages={}"
cookies = dict(ASPSESSIONIDCCBQCQSR='EEPJMIIDAOLDBMOABLJODJAJ',ASPSESSIONIDACCRCQSQ='BPKADPKDIEABCDGGLBAAHEAK',ASPSESSIONIDCACTCQSQ='EEGDOMLCJKKNGPFIPJLCMFBI',TS01dc25d1='01770c3a9841dbb80f087c5796c0c8a70c918eb8b9a5fb7229d46b84e736c80391564a8a27de44504d56d751444c19f2040f128a02c04b95e7951acf7b4448895e221d9514')
series = ['BR RJANRIO CNV.0.ERE','BR RJANRIO CNV.0.OCO','BR RJANRIO CNV.0.PEI','BR RJANRIO CNV.0.EST','BR RJANRIO CNV.0.GRG','BR RJANRIO CNV.0.RCE']
arquivos = []
for serie in series:
payload = {'input_pesqfundocolecao': '1278707', 'input_pesqnotacao': serie,'v_fundo_colecao': '1278707', 'v_ordem': 'CodigoReferencia' }
if not os.path.exists(serie):
os.makedirs(serie)
with open('{}/{}.csv'.format(serie, serie), 'w', newline='') as f:
writer = csv.writer(f)
num_pgs = 2
pagina = 1
while pagina <= num_pgs:
url = first_url.format(pagina)
print('Serie', serie, 'lendo pagina', pagina, 'de', num_pgs)
r = requests.post(url, data=payload, cookies=cookies)
r.encoding = 'utf-8'
s1 = bs4.BeautifulSoup(r.text, "lxml")
ulres = s1.find('ul', id='resultado')
ptp = re.compile(r'var TotalPag = (\d+)')
match = ptp.search(r.text)
if match:
num_pgs = int(match.group(1))
# cnt = 0
for li in ulres.find_all('li'):
l = li.find("a", title="Fazer download do arquivo")
if l and l.find_parent('li') == li:
link = l["onclick"]
parts = link.split('\',\'')
arq = parts[0][30:]
arq_name = parts[1]
link = "{}download.asp?NomeArquivo={}&arquivo={}&apresentacao=2".format(base__url, arq_name, arq)
arquivos.append((link, arq_name, serie))
else:
arq_name = 'Sem arquivo'
link = '--'
description = li.span.text
writer.writerow((description, arq_name, link))
# cnt += 1
# print('Dados:', cnt, serie, description[1:10], arq_name)
pagina += 1
for arq_tpl in arquivos:
filename = '{}/{}'.format(arq_tpl[2], arq_tpl[1])
if not os.path.isfile(filename):
urlretrieve(arq_tpl[0], filename)
print('Carregou arquivo:', filename)
|
python
|
# 20412 - [Job Adv] (Lv.100) Mihile 4rd job adv
sm.setSpeakerID(1101002)
if sm.sendAskYesNo("Are you ready, are you okay to leave?"):
sm.warp(913070100, 0)
sm.setInstanceTime(300, 130000000)
|
python
|
##############################################################################
# Written by: Cachen Chen <[email protected]>
# Date: 09/25/2009
# Application wrapper for Moonlight combobox
# Used by the combobox-*.py tests
##############################################################################
'Application wrapper for Moonlight combobox'
from strongwind import *
from os.path import exists, dirname
from sys import path
init_dir = path[0]
uiaqa_path = dirname(dirname(init_dir))
# Variable the path of Firefox to run the application, Please install
# Firefox3.5.1 first which is accessible by accerciser
firefox_path = '/usr/bin/firefox'
def launchComboBox(exe=None):
'''Launch Moonlight combobox with accessibility enabled and return a
combobox object. Log an error and return None if something goes wrong'''
if exe is None:
# make sure we can find the sample applications
exe = '%s/samples/moonlight/ComboBox/ComboBoxSample.html' % uiaqa_path
if not exists(exe):
raise IOError, "Could not find file %s" % exe
args = [firefox_path, exe]
(app, subproc) = cache.launchApplication(args=args, name="Firefox", \
wait=config.LONG_DELAY)
combobox = ComboBox(app, subproc)
cache.addApplication(combobox)
combobox.comboBoxFrame.app = combobox
return combobox
# class to represent the application
class ComboBox(accessibles.Application):
#checkShowing=False
def __init__(self, accessible, subproc=None):
'Get a reference to the ComboBox window'
super(ComboBox, self).__init__(accessible, subproc)
self.findFrame(re.compile('^ComboBoxSample'), logName='Combo Box')
|
python
|
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Module for LocalDockerModelServerRunner."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import contextlib
import os
import socket
import time
from absl import logging
import docker
from docker import errors as docker_errors
from typing import Text
from tfx import types
from tfx.components.infra_validator import error_types
from tfx.components.infra_validator import serving_bins
from tfx.components.infra_validator.model_server_runners import base_runner
from tfx.proto import infra_validator_pb2
from tfx.utils import path_utils
_POLLING_INTERVAL_SEC = 1
def _make_docker_client(config: infra_validator_pb2.LocalDockerConfig):
params = {}
if config.client_timeout_seconds:
params['timeout'] = config.client_timeout_seconds
if config.client_base_url:
params['base_url'] = config.client_base_url
if config.client_api_version:
params['version'] = config.client_api_version
return docker.DockerClient(**params)
def _find_available_port():
"""Find available port in the host machine."""
with contextlib.closing(
socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
sock.bind(('localhost', 0))
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
_, port = sock.getsockname()
return port
def _parse_model_path(model_path: Text):
"""Parse model path into a base path, model name, and a version.
Args:
model_path: Path to the SavedModel (or other format) in the structure of
`{model_base_path}/{model_name}/{version}`, where version is an integer.
Raises:
ValueError: if the model_path does not conform to the expected directory
structure.
Returns:
`model_base_path`, `model_name`, and integer `version`.
"""
model_path, version = os.path.split(model_path)
if not version.isdigit():
raise ValueError(
'{} does not conform to tensorflow serving directory structure: '
'BASE_PATH/model_name/int_version.'.format(model_path))
base_path, model_name = os.path.split(model_path)
return base_path, model_name, int(version)
class LocalDockerRunner(base_runner.BaseModelServerRunner):
"""A model server runner that runs in a local docker runtime.
You need to pre-install docker in the machine that is running InfraValidator
component. For that reason, it is recommended to use this runner only for
testing purpose.
"""
def __init__(self, model: types.Artifact,
serving_binary: serving_bins.ServingBinary,
serving_spec: infra_validator_pb2.ServingSpec):
"""Make a local docker runner.
Args:
model: A model artifact to infra validate.
serving_binary: A ServingBinary to run.
serving_spec: A ServingSpec instance.
"""
base_path, model_name, version = _parse_model_path(
path_utils.serving_model_path(model.uri))
if model_name != serving_spec.model_name:
raise ValueError(
'ServingSpec.model_name ({}) does not match the model name ({}) from'
'the Model artifact.'.format(
serving_spec.model_name, model_name))
self._model_base_path = base_path
self._model_name = model_name
self._model_version = version
self._serving_binary = serving_binary
self._serving_spec = serving_spec
self._docker = _make_docker_client(serving_spec.local_docker)
self._container = None
self._endpoint = None
def __repr__(self):
return 'LocalDockerRunner(image: {image})'.format(
image=self._serving_binary.image)
@property
def _model_path(self):
return os.path.join(self._model_base_path, self._model_name)
@property
def _model_version_path(self):
return os.path.join(self._model_base_path, self._model_name,
str(self._model_version))
def GetEndpoint(self):
assert self._endpoint is not None, (
'Endpoint is not yet created. You should call Start() first.')
return self._endpoint
def Start(self):
assert self._container is None, (
'You cannot start model server multiple times.')
host_port = _find_available_port()
self._endpoint = 'localhost:{}'.format(host_port)
if isinstance(self._serving_binary, serving_bins.TensorFlowServing):
is_local_model = os.path.exists(self._model_version_path)
if is_local_model:
run_params = self._serving_binary.MakeDockerRunParams(
host_port=host_port,
host_model_path=self._model_path)
else:
run_params = self._serving_binary.MakeDockerRunParams(
host_port=host_port,
model_base_path=self._model_base_path)
else:
raise NotImplementedError('Unsupported serving binary {}'.format(
type(self._serving_binary).__name__))
logging.info('Running container with parameter %s', run_params)
self._container = self._docker.containers.run(**run_params)
def WaitUntilRunning(self, deadline):
assert self._container is not None, 'container has not been started.'
while time.time() < deadline:
try:
# Reload container attributes from server. This is the only right way to
# retrieve the latest container status from docker engine.
self._container.reload()
status = self._container.status
except docker_errors.NotFound:
# If the job has been aborted and container has specified auto_removal
# to True, we might get a NotFound error during container.reload().
raise error_types.JobAborted(
'Container not found. Possibly removed after the job has been '
'aborted.')
# The container is just created and not yet in the running status.
if status == 'created':
time.sleep(_POLLING_INTERVAL_SEC)
continue
# The container is running :)
if status == 'running':
return
# Docker status is one of {'created', 'restarting', 'running', 'removing',
# 'paused', 'exited', or 'dead'}. Status other than 'created' and
# 'running' indicates the job has been aborted.
raise error_types.JobAborted(
'Job has been aborted (container status={})'.format(status))
raise error_types.DeadlineExceeded(
'Deadline exceeded while waiting for the container to be running.')
def Stop(self):
if self._container:
logging.info('Stopping container.')
self._container.stop()
self._docker.close()
|
python
|
"""
Copyright (c) Open Carbon, 2020
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
backend/tools.py
Provides range of backend tools that can be run from command line:
importlocations: Imports location data from file that is used to geolocate specific locations
generategeometries: Generates multiple geometries of boundaries for multiple zoom levels using simplification
processspecialcases: Perform additional ad-hoc processing
importdata: Imports data for specific area scale and year range (assuming BEIS data)
"""
import os
import pandas
import json
import topojson as tp
import geojson
import csv
import re
from shapely.geometry import Polygon
if __name__ == '__main__':
import sys
import django
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
sys.path.append(parent_dir)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "carbonmap.settings")
django.setup()
from django.contrib.gis.db.models.functions import AsGeoJSON
from django.core.serializers.json import DjangoJSONEncoder
from django.contrib.gis.geos import GEOSException, GEOSGeometry, Point, fromstr
from django.db import connection, transaction
from django.contrib.gis.db.models import Extent
from backend.gis import get_degrees_per_pixel
from backend.models import Location, Geometry, Data, DATATYPES_CHOICES
# Number of zoom levels to cache geometries for
# We generate a target-resolution-dependent simplification for each geometry object to minimize download size
zoomrange = 15
# Paths to subregion geojson files
subregions = {
'lau1': [ 'subregions/Local_Administrative_Units_Level_1_2018.json'],
'msoa': [ "subregions/england_msoa.json",
"subregions/wales_msoa.json",
"subregions/scotland_ig.json"],
'lsoa': [ "subregions/england_lsoa.json",
"subregions/wales_lsoa.json",
"subregions/scotland_dz.json"],
}
subregion_scotland_correction = "subregions/Counties_and_Unitary_Authorities_GB_2018.json"
non_decimal = re.compile(r'[^\d.]+')
def getlargestpolygon(areatype):
"""
Get largest area for particular area type
Ad-hoc function used to determine minimum zoom levels when MSOA/IG and LSOA/DZ appear
"""
maxvalue = 0
areacode = ''
geometries = Geometry.objects.filter(zoom=15, type=areatype).annotate(Extent('geometry')).values('code', 'geometry__extent')
for geometry in geometries:
lng_west, lat_south, lng_east, lat_north = geometry['geometry__extent']
lat_dif = lat_north - lat_south
lng_dif = lng_east - lng_west
if (lng_dif > maxvalue):
maxvalue = lng_dif
areacode = geometry['code']
if (lat_dif > maxvalue):
maxvalue = lat_dif
areacode = geometry['code']
return areacode
def get_yearsuffix_from_filepath(filepath):
"""
Get year suffix from file path of boundary file
"""
re_match = re.search(r"(\d{4})", filepath)
if re_match:
year = re_match.group(1)
return year[2:]
else: return None
def get_feature_name_code(properties, yearsuffix):
"""
Get name and code from GeoJSON feature
"""
code = None
if 'code' in properties: code = properties['code']
elif ('lau1' + yearsuffix + 'cd') in properties: code = properties['lau1' + yearsuffix + 'cd']
elif ('ctyua' + yearsuffix + 'cd') in properties: code = properties['ctyua' + yearsuffix + 'cd']
name = None
if 'Name' in properties: name = properties['Name']
elif 'name' in properties: name = properties['name']
elif ('lau1' + yearsuffix + 'nm') in properties: name = properties['lau1' + yearsuffix + 'nm']
elif ('ctyua' + yearsuffix + 'nm') in properties: name = properties['ctyua' + yearsuffix + 'nm']
return {'name': name, 'code': code}
def processspecialcases():
"""
Perform additional ad-hoc processing
- Replace Scotland LAU1s with separate local authority boundaries as BEIS data uses non-standard LAU1 naming
"""
# Replace Scotland LAU1s with separate unitary authority boundaries as BEIS data uses unitary authorities for Scotland data at large scale
scottishareas = Geometry.objects.filter(code__startswith="S", type='lau1').delete()
print("Loading supplemental file for Scottish LAs", subregion_scotland_correction)
with open(subregion_scotland_correction) as f:
geojson_codes, topologysafe_codes = [], []
yearsuffix = get_yearsuffix_from_filepath(subregion_scotland_correction)
geometrydata = geojson.load(f)
# Create a list of all feature codes for entire file
for feature in geometrydata['features']:
feature_namecode = get_feature_name_code(feature['properties'], yearsuffix)
if feature_namecode['code']: geojson_codes.append(feature_namecode['code'])
geometrytopology = tp.Topology(geometrydata)
# Create a list of all feature codes that topojson processed successfully
topologysafefeatures = json.loads(geometrytopology.to_geojson())
for feature in topologysafefeatures['features']:
feature_namecode = get_feature_name_code(feature['properties'], yearsuffix)
if feature_namecode['code']: topologysafe_codes.append(feature_namecode['code'])
# Get difference of feature codes between original file and topojson successfully processed feature codes
code_diff = list(set(geojson_codes) - set(topologysafe_codes))
# Create a custom feature set from the features that topojson failed to process
# TODO: investigate why topojson fails on certain polygons
diff_features = []
for feature in geometrydata['features']:
feature_namecode = get_feature_name_code(feature['properties'], yearsuffix)
if feature_namecode['code'] in code_diff:
diff_features.append(feature)
print("Number of polygons topojson failed on =", len(diff_features))
for zoom in range(0, zoomrange + 1):
print("Creating identical polygons for all zoom levels for polygons topojson was not able to process", len(diff_features))
for feature in diff_features:
feature_namecode = get_feature_name_code(feature['properties'], yearsuffix)
if feature_namecode['code'][:1] == 'S': # Is scottish feature
try:
geometry = GEOSGeometry(str(feature['geometry']))
print("Saving geometry for", feature_namecode['code'], "zoom level", zoom)
geometryobject = Geometry(name=feature_namecode['name'], type='lau1', code=feature_namecode['code'], zoom=zoom, geometry=geometry)
geometryobject.save()
except:
print("Failed to create geometry object - probably too small for zoom level", code, "zoom level", zoom, "degree resolution", zoomepsilon)
zoomepsilon = get_degrees_per_pixel(zoom)
print("Simplifying", subregion_scotland_correction, "for zoom level", zoom, "equivalent to degree resolution", zoomepsilon)
simplifiedfeatures = json.loads(geometrytopology.toposimplify(
epsilon=zoomepsilon,
simplify_algorithm='dp',
prevent_oversimplify=True
).to_geojson())
count = 0
for feature in simplifiedfeatures['features']:
feature_namecode = get_feature_name_code(feature['properties'], yearsuffix)
geometry = GEOSGeometry(str(feature['geometry']))
if feature_namecode['code'][:1] == 'S': # Is scottish feature
print("Saving geometry for", feature_namecode['code'], feature_namecode['name'])
geometryobject = Geometry(name=feature_namecode['name'], type='lau1', code=feature_namecode['code'], zoom=zoom, geometry=geometry)
geometryobject.save()
def generategeometries():
"""
Generates multiple geometries of boundaries for multiple zoom levels using simplification
"""
for areatype in subregions:
Geometry.objects.filter(type=areatype).delete()
for areafile in subregions[areatype]:
print("Loading area file", areafile)
with open(areafile) as f:
geojson_codes, topologysafe_codes = [], []
yearsuffix = get_yearsuffix_from_filepath(areafile)
geometrydata = geojson.load(f)
# Create a list of all feature codes for entire file
for feature in geometrydata['features']:
feature_namecode = get_feature_name_code(feature['properties'], yearsuffix)
if feature_namecode['code']: geojson_codes.append(feature_namecode['code'])
geometrytopology = tp.Topology(geometrydata)
# Create a list of all feature codes that topojson processed successfully
topologysafefeatures = json.loads(geometrytopology.to_geojson())
for feature in topologysafefeatures['features']:
feature_namecode = get_feature_name_code(feature['properties'], yearsuffix)
if feature_namecode['code']: topologysafe_codes.append(feature_namecode['code'])
# Get difference of feature codes between original file and topojson successfully processed feature codes
code_diff = list(set(geojson_codes) - set(topologysafe_codes))
# Create a custom feature set from the features that topojson failed to process
# TODO: investigate why topojson fails on certain polygons
diff_features = []
for feature in geometrydata['features']:
feature_namecode = get_feature_name_code(feature['properties'], yearsuffix)
if feature_namecode['code'] in code_diff:
diff_features.append(feature)
print("Number of polygons topojson failed on =", len(diff_features))
for zoom in range(0, zoomrange + 1):
print("Creating identical polygons for all zoom levels for polygons topojson was not able to process", len(diff_features))
for feature in diff_features:
feature_namecode = get_feature_name_code(feature['properties'], yearsuffix)
try:
geometry = GEOSGeometry(str(feature['geometry']))
print("Saving geometry for", feature_namecode['code'], "zoom level", zoom)
geometryobject = Geometry(name=feature_namecode['name'], type=areatype, code=feature_namecode['code'], zoom=zoom, geometry=geometry)
geometryobject.save()
except:
print("Failed to create geometry object - probably too small for zoom level", code, "zoom level", zoom, "degree resolution", zoomepsilon)
zoomepsilon = get_degrees_per_pixel(zoom)
print("Simplifying", areafile, "for zoom level", zoom, "equivalent to degree resolution", zoomepsilon)
simplifiedfeatures = json.loads(geometrytopology.toposimplify(
epsilon=zoomepsilon,
simplify_algorithm='dp',
prevent_oversimplify=True
).to_geojson())
for feature in simplifiedfeatures['features']:
feature_namecode = get_feature_name_code(feature['properties'], yearsuffix)
try:
geometry = GEOSGeometry(str(feature['geometry']))
print("Saving geometry for", feature_namecode['code'], "zoom level", zoom, "degree resolution", zoomepsilon)
geometryobject = Geometry(name=feature_namecode['name'], type=areatype, code=feature_namecode['code'], zoom=zoom, geometry=geometry)
geometryobject.save()
except:
print("Failed to create geometry object - probably too small for zoom level", code, "zoom level", zoom, "degree resolution", zoomepsilon)
processspecialcases()
def importdatabygeometrytype(geometrytype, year, datatype):
"""
Import data for a specific geometry type and year
"""
datatypecode = 'ELEC'
if datatype == 1: datatypecode = 'GAS'
geometry_prefix = 'LSOA'
geometrycode_row = 'LSOACode'
multiplier_meter = 1
multiplier_value = 1
if geometrytype == 'msoa':
geometry_prefix = 'MSOA'
geometrycode_row = 'MSOACode'
if geometrytype == 'lau1':
geometry_prefix = 'LAU1'
geometrycode_row = 'LA Code'
multiplier_meter = 1000
multiplier_value = 1000000
filepath = 'BEIS/' + geometry_prefix + '_' + datatypecode + '_' + str(year) + '.csv'
Data.objects.filter(geometrytype=geometrytype, year=year, type=datatype).delete()
count = 0
if os.path.isfile(filepath):
with open(filepath, 'r' ) as fileobj:
reader = csv.DictReader(fileobj)
for row in reader:
count += 1
print("Importing line", count, filepath)
geometrycode = row[geometrycode_row].strip()
if geometrytype == 'lau1':
if row['Total consumption'] == '..': continue
if row['Total consumption'] == ' - ': continue
value = float(non_decimal.sub("", row['Total consumption']))
meters = float(row['Total number of meters'])
else:
value = float(row['KWH'])
meters = float(row['METERS'])
meters = meters * multiplier_meter
value = value * multiplier_value
data = Data(
type=datatype,
year=str(year),
value=value,
meters=meters,
geometrycode=geometrycode,
geometrytype=geometrytype)
data.save()
print("Imported " + geometry_prefix + " for type " + str(datatype) + " for " + str(year))
else:
print(filepath, "not found")
def importdata(geometrytype, yearstart, yearend):
"""
Import data for specify geometry type and year range
"""
for year in range(int(yearstart), 1 + int(yearend)):
print ("Importing data for year", year)
for datatype in DATATYPES_CHOICES:
importdatabygeometrytype(geometrytype, year, datatype[0])
def checkgeometries():
"""
Check to see if any geometries corrupted
"""
allgeometries = Geometry.objects.all().annotate(json=AsGeoJSON('geometry')).values('name', 'code', 'zoom', 'type', 'json').order_by('code', 'type', 'zoom')
for geometry in allgeometries:
print("Checking geometry", geometry['code'], geometry['type'], geometry['zoom'])
json_data = json.dumps(list(geometry), cls=DjangoJSONEncoder)
def renameduplicateshortcodes():
"""
Runs custom piece of SQL to rename duplicate shortcodes in location table
"""
cursor = connection.cursor()
cursor.execute("""
UPDATE backend_location
SET shortcode = CONCAT(shortcode, REPLACE(LOWER(county), ' ', ''))
WHERE shortcode IN
(
SELECT s.shortcode
FROM
(
SELECT shortcode,COUNT(*) AS num
FROM backend_location GROUP BY shortcode
) AS s
WHERE s.num > 1
);
""", [])
transaction.commit()
def computescale(population):
"""
Computes appropriate scale to show locations with specific population
"""
if population == '': population = 0
population = int(population)
if population < 20000: return 15
if population < 40000: return 14.5
if population < 60000: return 14
if population < 80000: return 13.5
if population < 100000: return 13
if population < 200000: return 12.5
if population < 400000: return 12
if population < 600000: return 11.5
if population < 800000: return 11
if population < 1000000: return 10.5
return 10
def importlocations():
"""
Imports location data from file that is used to geolocate specific locations
"""
with open('Towns_List_Extended.csv') as csvfile:
reader = csv.DictReader(csvfile)
count = 0
Location.objects.all().delete()
for row in reader:
shortcode = row['Town'].lower()
shortcode = re.sub("[ ]", "", shortcode)
scale = computescale(row['Population'])
p = Location( shortcode=shortcode,
town=row['Town'],
county=row['County'],
country=row['Country'],
population=row['Population'],
longitude=row['Longitude'],
latitude=row['Latitude'],
url=row['url'],
scale=scale)
p.save()
count += 1
renameduplicateshortcodes()
print("Import locations finished, imported: " + str(count))
if len(sys.argv) == 1:
print("""
****** Carbon Map Batch Processing *******
Possible arguments are:
checkgeometries
Check whether any geometries are corrupted
importlocations
Imports location data from file that is used to geolocate specific locations
generategeometries
Generates multiple geometries of boundaries for multiple zoom levels using simplification
processspecialcases
Perform additional ad-hoc processing
importdata [lsoa/msoa/lau1] [yearstart] [yearend]
Imports data for specific area scale and year range (assuming BEIS data)
Leaving off [yearend] will only import for [yearstart]
""")
else:
primaryargument = sys.argv[1]
if primaryargument == "checkgeometries":
checkgeometries()
if primaryargument == "importlocations":
importlocations()
if primaryargument == "generategeometries":
generategeometries()
if primaryargument == "processspecialcases":
processspecialcases()
if primaryargument == "importdata":
if len(sys.argv) >= 4:
yearstart = sys.argv[3]
yearend = yearstart
if len(sys.argv) == 5: yearend = sys.argv[4]
geometrytype = sys.argv[2]
importdata(geometrytype, yearstart, yearend)
else:
print("Not enough arguments provided for importdata. Format is importdata lsoa/msoa/lau1 yearstart yearend")
|
python
|
"""This module contains definitions and data structures for 2-, 4-, and 8-valued logic operations.
8 logic values are defined as integer constants.
* For 2-valued logic: ``ZERO`` and ``ONE``
* 4-valued logic adds: ``UNASSIGNED`` and ``UNKNOWN``
* 8-valued logic adds: ``RISE``, ``FALL``, ``PPULSE``, and ``NPULSE``.
The bits in these constants have the following meaning:
* bit 0: Final/settled binary value of a signal
* bit 1: Initial binary value of a signal
* bit 2: Activity or transitions are present on a signal
Special meaning is given to values where bits 0 and 1 differ, but bit 2 (activity) is 0.
These values are interpreted as ``UNKNOWN`` or ``UNASSIGNED`` in 4-valued and 8-valued logic.
In general, 2-valued logic only considers bit 0, 4-valued logic considers bits 0 and 1, and 8-valued logic
considers all 3 bits.
The only exception is constant ``ONE=0b11`` which has two bits set for all logics including 2-valued logic.
"""
import math
from collections.abc import Iterable
import numpy as np
from . import numba, hr_bytes
ZERO = 0b000
"""Integer constant ``0b000`` for logic-0. ``'0'``, ``0``, ``False``, ``'L'``, and ``'l'`` are interpreted as ``ZERO``.
"""
UNKNOWN = 0b001
"""Integer constant ``0b001`` for unknown or conflict. ``'X'``, or any other value is interpreted as ``UNKNOWN``.
"""
UNASSIGNED = 0b010
"""Integer constant ``0b010`` for unassigned or high-impedance. ``'-'``, ``None``, ``'Z'``, and ``'z'`` are
interpreted as ``UNASSIGNED``.
"""
ONE = 0b011
"""Integer constant ``0b011`` for logic-1. ``'1'``, ``1``, ``True``, ``'H'``, and ``'h'`` are interpreted as ``ONE``.
"""
PPULSE = 0b100
"""Integer constant ``0b100`` for positive pulse, meaning initial and final values are 0, but there is some activity
on a signal. ``'P'``, ``'p'``, and ``'^'`` are interpreted as ``PPULSE``.
"""
RISE = 0b101
"""Integer constant ``0b110`` for a rising transition. ``'R'``, ``'r'``, and ``'/'`` are interpreted as ``RISE``.
"""
FALL = 0b110
"""Integer constant ``0b101`` for a falling transition. ``'F'``, ``'f'``, and ``'\\'`` are interpreted as ``FALL``.
"""
NPULSE = 0b111
"""Integer constant ``0b111`` for negative pulse, meaning initial and final values are 1, but there is some activity
on a signal. ``'N'``, ``'n'``, and ``'v'`` are interpreted as ``NPULSE``.
"""
def interpret(value):
"""Converts characters, strings, and lists of them to lists of logic constants defined above.
:param value: A character (string of length 1), Boolean, Integer, None, or Iterable.
Iterables (such as strings) are traversed and their individual characters are interpreted.
:return: A logic constant or a (possibly multi-dimensional) list of logic constants.
"""
if isinstance(value, Iterable) and not (isinstance(value, str) and len(value) == 1):
return list(map(interpret, value))
if value in [0, '0', False, 'L', 'l']:
return ZERO
if value in [1, '1', True, 'H', 'h']:
return ONE
if value in [None, '-', 'Z', 'z']:
return UNASSIGNED
if value in ['R', 'r', '/']:
return RISE
if value in ['F', 'f', '\\']:
return FALL
if value in ['P', 'p', '^']:
return PPULSE
if value in ['N', 'n', 'v']:
return NPULSE
return UNKNOWN
_bit_in_lut = np.array([2 ** x for x in range(7, -1, -1)], dtype='uint8')
@numba.njit
def bit_in(a, pos):
return a[pos >> 3] & _bit_in_lut[pos & 7]
class MVArray:
"""An n-dimensional array of m-valued logic values.
This class wraps a numpy.ndarray of type uint8 and adds support for encoding and
interpreting 2-valued, 4-valued, and 8-valued logic values.
Each logic value is stored as an uint8, manipulations of individual values are cheaper than in
:py:class:`BPArray`.
:param a: If a tuple is given, it is interpreted as desired shape. To make an array of ``n`` vectors
compatible with a simulator ``sim``, use ``(len(sim.interface), n)``. If a :py:class:`BPArray` or
:py:class:`MVArray` is given, a deep copy is made. If a string, a list of strings, a list of characters,
or a list of lists of characters are given, the data is interpreted best-effort and the array is
initialized accordingly.
:param m: The arity of the logic. Can be set to 2, 4, or 8. If None is given, the arity of a given
:py:class:`BPArray` or :py:class:`MVArray` is used, or, if the array is initialized differently, 8 is used.
"""
def __init__(self, a, m=None):
self.m = m or 8
assert self.m in [2, 4, 8]
# Try our best to interpret given a.
if isinstance(a, MVArray):
self.data = a.data.copy()
"""The wrapped 2-dimensional ndarray of logic values.
* Axis 0 is PI/PO/FF position, the length of this axis is called "width".
* Axis 1 is vector/pattern, the length of this axis is called "length".
"""
self.m = m or a.m
elif hasattr(a, 'data'): # assume it is a BPArray. Can't use isinstance() because BPArray isn't declared yet.
self.data = np.zeros((a.width, a.length), dtype=np.uint8)
self.m = m or a.m
for i in range(a.data.shape[-2]):
self.data[...] <<= 1
self.data[...] |= np.unpackbits(a.data[..., -i-1, :], axis=1)[:, :a.length]
if a.data.shape[-2] == 1:
self.data *= 3
elif isinstance(a, int):
self.data = np.full((a, 1), UNASSIGNED, dtype=np.uint8)
elif isinstance(a, tuple):
self.data = np.full(a, UNASSIGNED, dtype=np.uint8)
else:
if isinstance(a, str): a = [a]
self.data = np.asarray(interpret(a), dtype=np.uint8)
self.data = self.data[:, np.newaxis] if self.data.ndim == 1 else np.moveaxis(self.data, -2, -1)
# Cast data to m-valued logic.
if self.m == 2:
self.data[...] = ((self.data & 0b001) & ((self.data >> 1) & 0b001) | (self.data == RISE)) * ONE
elif self.m == 4:
self.data[...] = (self.data & 0b011) & ((self.data != FALL) * ONE) | ((self.data == RISE) * ONE)
elif self.m == 8:
self.data[...] = self.data & 0b111
self.length = self.data.shape[-1]
self.width = self.data.shape[-2]
def __repr__(self):
return f'<MVArray length={self.length} width={self.width} m={self.m} mem={hr_bytes(self.data.nbytes)}>'
def __str__(self):
return str([self[idx] for idx in range(self.length)])
def __getitem__(self, vector_idx):
"""Returns a string representing the desired vector."""
chars = ["0", "X", "-", "1", "P", "R", "F", "N"]
return ''.join(chars[v] for v in self.data[:, vector_idx])
def __len__(self):
return self.length
def mv_cast(*args, m=8):
return [a if isinstance(a, MVArray) else MVArray(a, m=m) for a in args]
def mv_getm(*args):
return max([a.m for a in args if isinstance(a, MVArray)] + [0]) or 8
def _mv_not(m, out, inp):
np.bitwise_xor(inp, 0b11, out=out) # this also exchanges UNASSIGNED <-> UNKNOWN
if m > 2:
np.putmask(out, (inp == UNKNOWN), UNKNOWN) # restore UNKNOWN
def mv_not(x1, out=None):
"""A multi-valued NOT operator.
:param x1: An :py:class:`MVArray` or data the :py:class:`MVArray` constructor accepts.
:param out: Optionally an :py:class:`MVArray` as storage destination. If None, a new :py:class:`MVArray`
is returned.
:return: An :py:class:`MVArray` with the result.
"""
m = mv_getm(x1)
x1 = mv_cast(x1, m=m)[0]
out = out or MVArray(x1.data.shape, m=m)
_mv_not(m, out.data, x1.data)
return out
def _mv_or(m, out, *ins):
if m > 2:
any_unknown = (ins[0] == UNKNOWN) | (ins[0] == UNASSIGNED)
for inp in ins[1:]: any_unknown |= (inp == UNKNOWN) | (inp == UNASSIGNED)
any_one = (ins[0] == ONE)
for inp in ins[1:]: any_one |= (inp == ONE)
out[...] = ZERO
np.putmask(out, any_one, ONE)
for inp in ins:
np.bitwise_or(out, inp, out=out, where=~any_one)
np.putmask(out, (any_unknown & ~any_one), UNKNOWN)
else:
out[...] = ZERO
for inp in ins: np.bitwise_or(out, inp, out=out)
def mv_or(x1, x2, out=None):
"""A multi-valued OR operator.
:param x1: An :py:class:`MVArray` or data the :py:class:`MVArray` constructor accepts.
:param x2: An :py:class:`MVArray` or data the :py:class:`MVArray` constructor accepts.
:param out: Optionally an :py:class:`MVArray` as storage destination. If None, a new :py:class:`MVArray`
is returned.
:return: An :py:class:`MVArray` with the result.
"""
m = mv_getm(x1, x2)
x1, x2 = mv_cast(x1, x2, m=m)
out = out or MVArray(np.broadcast(x1.data, x2.data).shape, m=m)
_mv_or(m, out.data, x1.data, x2.data)
return out
def _mv_and(m, out, *ins):
if m > 2:
any_unknown = (ins[0] == UNKNOWN) | (ins[0] == UNASSIGNED)
for inp in ins[1:]: any_unknown |= (inp == UNKNOWN) | (inp == UNASSIGNED)
any_zero = (ins[0] == ZERO)
for inp in ins[1:]: any_zero |= (inp == ZERO)
out[...] = ONE
np.putmask(out, any_zero, ZERO)
for inp in ins:
np.bitwise_and(out, inp | 0b100, out=out, where=~any_zero)
if m > 4: np.bitwise_or(out, inp & 0b100, out=out, where=~any_zero)
np.putmask(out, (any_unknown & ~any_zero), UNKNOWN)
else:
out[...] = ONE
for inp in ins: np.bitwise_and(out, inp, out=out)
def mv_and(x1, x2, out=None):
"""A multi-valued AND operator.
:param x1: An :py:class:`MVArray` or data the :py:class:`MVArray` constructor accepts.
:param x2: An :py:class:`MVArray` or data the :py:class:`MVArray` constructor accepts.
:param out: Optionally an :py:class:`MVArray` as storage destination. If None, a new :py:class:`MVArray`
is returned.
:return: An :py:class:`MVArray` with the result.
"""
m = mv_getm(x1, x2)
x1, x2 = mv_cast(x1, x2, m=m)
out = out or MVArray(np.broadcast(x1.data, x2.data).shape, m=m)
_mv_and(m, out.data, x1.data, x2.data)
return out
def _mv_xor(m, out, *ins):
if m > 2:
any_unknown = (ins[0] == UNKNOWN) | (ins[0] == UNASSIGNED)
for inp in ins[1:]: any_unknown |= (inp == UNKNOWN) | (inp == UNASSIGNED)
out[...] = ZERO
for inp in ins:
np.bitwise_xor(out, inp & 0b011, out=out)
if m > 4: np.bitwise_or(out, inp & 0b100, out=out)
np.putmask(out, any_unknown, UNKNOWN)
else:
out[...] = ZERO
for inp in ins: np.bitwise_xor(out, inp, out=out)
def mv_xor(x1, x2, out=None):
"""A multi-valued XOR operator.
:param x1: An :py:class:`MVArray` or data the :py:class:`MVArray` constructor accepts.
:param x2: An :py:class:`MVArray` or data the :py:class:`MVArray` constructor accepts.
:param out: Optionally an :py:class:`MVArray` as storage destination. If None, a new :py:class:`MVArray`
is returned.
:return: An :py:class:`MVArray` with the result.
"""
m = mv_getm(x1, x2)
x1, x2 = mv_cast(x1, x2, m=m)
out = out or MVArray(np.broadcast(x1.data, x2.data).shape, m=m)
_mv_xor(m, out.data, x1.data, x2.data)
return out
def mv_transition(init, final, out=None):
"""Computes the logic transitions from the initial values of ``init`` to the final values of ``final``.
Pulses in the input data are ignored. If any of the inputs are ``UNKNOWN``, the result is ``UNKNOWN``.
If both inputs are ``UNASSIGNED``, the result is ``UNASSIGNED``.
:param init: An :py:class:`MVArray` or data the :py:class:`MVArray` constructor accepts.
:param final: An :py:class:`MVArray` or data the :py:class:`MVArray` constructor accepts.
:param out: Optionally an :py:class:`MVArray` as storage destination. If None, a new :py:class:`MVArray`
is returned.
:return: An :py:class:`MVArray` with the result.
"""
m = mv_getm(init, final)
init, final = mv_cast(init, final, m=m)
init = init.data
final = final.data
out = out or MVArray(np.broadcast(init, final).shape, m=8)
out.data[...] = (init & 0b010) | (final & 0b001)
out.data[...] |= ((out.data << 1) ^ (out.data << 2)) & 0b100
unknown = (init == UNKNOWN) | (init == UNASSIGNED) | (final == UNKNOWN) | (final == UNASSIGNED)
unassigned = (init == UNASSIGNED) & (final == UNASSIGNED)
np.putmask(out.data, unknown, UNKNOWN)
np.putmask(out.data, unassigned, UNASSIGNED)
return out
class BPArray:
"""An n-dimensional array of m-valued logic values that uses bit-parallel storage.
The primary use of this format is in aiding efficient bit-parallel logic simulation.
The secondary benefit over :py:class:`MVArray` is its memory efficiency.
Accessing individual values is more expensive than with :py:class:`MVArray`.
Therefore it may be more efficient to unpack the data into an :py:class:`MVArray` and pack it again into a
:py:class:`BPArray` for simulation.
See :py:class:`MVArray` for constructor parameters.
"""
def __init__(self, a, m=None):
if not isinstance(a, MVArray) and not isinstance(a, BPArray):
a = MVArray(a, m)
self.m = a.m
if isinstance(a, MVArray):
if m is not None and m != a.m:
a = MVArray(a, m) # cast data
self.m = a.m
assert self.m in [2, 4, 8]
nwords = math.ceil(math.log2(self.m))
nbytes = (a.data.shape[-1] - 1) // 8 + 1
self.data = np.zeros(a.data.shape[:-1] + (nwords, nbytes), dtype=np.uint8)
"""The wrapped 3-dimensional ndarray.
* Axis 0 is PI/PO/FF position, the length of this axis is called "width".
* Axis 1 has length ``ceil(log2(m))`` for storing all bits.
* Axis 2 are the vectors/patterns packed into uint8 words.
"""
for i in range(self.data.shape[-2]):
self.data[..., i, :] = np.packbits((a.data >> i) & 1, axis=-1)
else: # we have a BPArray
self.data = a.data.copy() # TODO: support conversion to different m
self.m = a.m
self.length = a.length
self.width = a.width
def __repr__(self):
return f'<BPArray length={self.length} width={self.width} m={self.m} mem={hr_bytes(self.data.nbytes)}>'
def __len__(self):
return self.length
def bp_buf(out, inp):
md = out.shape[-2]
assert md == inp.shape[-2]
if md > 1:
unknown = inp[..., 0, :] ^ inp[..., 1, :]
if md > 2: unknown &= ~inp[..., 2, :]
out[..., 0, :] = inp[..., 0, :] | unknown
out[..., 1, :] = inp[..., 1, :] & ~unknown
if md > 2: out[..., 2, :] = inp[..., 2, :] & ~unknown
else:
out[..., 0, :] = inp[..., 0, :]
def bp_not(out, inp):
md = out.shape[-2]
assert md == inp.shape[-2]
if md > 1:
unknown = inp[..., 0, :] ^ inp[..., 1, :]
if md > 2: unknown &= ~inp[..., 2, :]
out[..., 0, :] = ~inp[..., 0, :] | unknown
out[..., 1, :] = ~inp[..., 1, :] & ~unknown
if md > 2: out[..., 2, :] = inp[..., 2, :] & ~unknown
else:
out[..., 0, :] = ~inp[..., 0, :]
def bp_or(out, *ins):
md = out.shape[-2]
for inp in ins: assert md == inp.shape[-2]
out[...] = 0
if md == 1:
for inp in ins: out[..., 0, :] |= inp[..., 0, :]
elif md == 2:
any_unknown = ins[0][..., 0, :] ^ ins[0][..., 1, :]
for inp in ins[1:]: any_unknown |= inp[..., 0, :] ^ inp[..., 1, :]
any_one = ins[0][..., 0, :] & ins[0][..., 1, :]
for inp in ins[1:]: any_one |= inp[..., 0, :] & inp[..., 1, :]
for inp in ins:
out[..., 0, :] |= inp[..., 0, :] | any_unknown
out[..., 1, :] |= inp[..., 1, :] & (~any_unknown | any_one)
else:
any_unknown = (ins[0][..., 0, :] ^ ins[0][..., 1, :]) & ~ins[0][..., 2, :]
for inp in ins[1:]: any_unknown |= (inp[..., 0, :] ^ inp[..., 1, :]) & ~inp[..., 2, :]
any_one = ins[0][..., 0, :] & ins[0][..., 1, :] & ~ins[0][..., 2, :]
for inp in ins[1:]: any_one |= inp[..., 0, :] & inp[..., 1, :] & ~inp[..., 2, :]
for inp in ins:
out[..., 0, :] |= inp[..., 0, :] | any_unknown
out[..., 1, :] |= inp[..., 1, :] & (~any_unknown | any_one)
out[..., 2, :] |= inp[..., 2, :] & (~any_unknown | any_one) & ~any_one
def bp_and(out, *ins):
md = out.shape[-2]
for inp in ins: assert md == inp.shape[-2]
out[...] = 0xff
if md == 1:
for inp in ins: out[..., 0, :] &= inp[..., 0, :]
elif md == 2:
any_unknown = ins[0][..., 0, :] ^ ins[0][..., 1, :]
for inp in ins[1:]: any_unknown |= inp[..., 0, :] ^ inp[..., 1, :]
any_zero = ~ins[0][..., 0, :] & ~ins[0][..., 1, :]
for inp in ins[1:]: any_zero |= ~inp[..., 0, :] & ~inp[..., 1, :]
for inp in ins:
out[..., 0, :] &= inp[..., 0, :] | (any_unknown & ~any_zero)
out[..., 1, :] &= inp[..., 1, :] & ~any_unknown
else:
any_unknown = (ins[0][..., 0, :] ^ ins[0][..., 1, :]) & ~ins[0][..., 2, :]
for inp in ins[1:]: any_unknown |= (inp[..., 0, :] ^ inp[..., 1, :]) & ~inp[..., 2, :]
any_zero = ~ins[0][..., 0, :] & ~ins[0][..., 1, :] & ~ins[0][..., 2, :]
for inp in ins[1:]: any_zero |= ~inp[..., 0, :] & ~inp[..., 1, :] & ~inp[..., 2, :]
out[..., 2, :] = 0
for inp in ins:
out[..., 0, :] &= inp[..., 0, :] | (any_unknown & ~any_zero)
out[..., 1, :] &= inp[..., 1, :] & ~any_unknown
out[..., 2, :] |= inp[..., 2, :] & (~any_unknown | any_zero) & ~any_zero
def bp_xor(out, *ins):
md = out.shape[-2]
for inp in ins: assert md == inp.shape[-2]
out[...] = 0
if md == 1:
for inp in ins: out[..., 0, :] ^= inp[..., 0, :]
elif md == 2:
any_unknown = ins[0][..., 0, :] ^ ins[0][..., 1, :]
for inp in ins[1:]: any_unknown |= inp[..., 0, :] ^ inp[..., 1, :]
for inp in ins: out[...] ^= inp
out[..., 0, :] |= any_unknown
out[..., 1, :] &= ~any_unknown
else:
any_unknown = (ins[0][..., 0, :] ^ ins[0][..., 1, :]) & ~ins[0][..., 2, :]
for inp in ins[1:]: any_unknown |= (inp[..., 0, :] ^ inp[..., 1, :]) & ~inp[..., 2, :]
for inp in ins:
out[..., 0, :] ^= inp[..., 0, :]
out[..., 1, :] ^= inp[..., 1, :]
out[..., 2, :] |= inp[..., 2, :]
out[..., 0, :] |= any_unknown
out[..., 1, :] &= ~any_unknown
out[..., 2, :] &= ~any_unknown
|
python
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 1 14:46:51 2020
@author: gabriel
"""
#%% MATLAB Code to reproduce
# function thresh_calc(nbeg,nend,n_noise,sig_fact,necdf_flag,nlbound)
# % Calculate the threshold using one of two methods
# % P=mean|W| + c sigma
# % P is computed from the empirical cdf of the noise signal at some
# % desired confidence level
# %
# % Experimental version for bc v1.1, March 6, 2019
# %
# global Wx as Wx_old Wx_new as_old as_new t na n clim_orig
# global M S P
# if necdf_flag == 1
# % Compute empirical cdf statistics and noise threshold
# [nrow,ncol]=size(Wx_new)
# conf=1.0 - nlbound.*0.01;
# % For each row in the matrix
# for k=1:nrow
# W(1:n_noise)=abs(Wx_new(k,nbeg:nend))';
# [f,x]=ecdf(W);
# % % plot every 10th cdf
# % kmod=floor(k/10);
# % if k == 1 || k == kmod.*10
# % scale=as_new(k);
# % str_scale=num2str(scale);
# % figure;
# % plot(x,f);
# % tdum=strcat('ECDF for k=',num2str(k),' scale=',str_scale);
# % title(tdum);
# % xlabel('Data Value');
# % ylabel('Probability');
# % end
# P(k)=interp1(f,x,conf);
# end
# M=mean(abs(Wx_new(:,nbeg:nend)'));
# % P=P';
# % plot the results in a figure
# figure('Name','ECDF Threshold');
# hold on
# aslg=log10(as_new);
# % length(M)
# % length(P)
# % length(aslg)
# plot(aslg,M,'-k');
# plot(aslg,P,'-r');
# hold off
# xlabel('log10 Scale (s)');
# ylabel('Coefficient Amplitude');
# legend('mean','threshold');
# tdum=strcat(num2str(conf.*100),'% Confidence Level');
# title(tdum);
# else
# % Compute Gaussian noise statistics and noise threshold
# M=mean(abs(Wx_new(:,nbeg:nend)'));
# S=std(abs(Wx_new(:,nbeg:nend)'));
# P=M + sig_fact.*S;
# Ekur=sqrt(.9).*(kurtosis(abs(Wx_new(:,nbeg:nend)'))-3.0)./sqrt(24.0./n_noise);
# % plot the results in a figure
# % changed 2/19/19 to show the Threshold defined by sig_fact
# figure('Name','Noise Mean and Threshold');
# hold on
# aslg=log10(as_new);
# plot(aslg,M,'-k');
# plot(aslg,P,'-r');
# hold off
# xlabel('log10 Scale (s)');
# ylabel('Coefficient Amplitude');
# legend('mean','threshold');
# % plot the Excess kurtosis statistic in a figure
# figure('Name','Noise Estimate Excess Kurtosis');
# aslg=log10(as_new);
# naslg=length(aslg);
# hold on
# plot(aslg,Ekur,'-k');
# plot([aslg(1) aslg(naslg)],[1.0 1.0],'-k');
# plot([aslg(1) aslg(naslg)],[-1.0 -1.0],'-k');
# hold off
# xlabel('log10 Scale (s)');
# ylabel('Non-Gaussianity');
# axis([-2.5 2.5 -50 50]);
# grid on
# end
# end
#%% Python Implementation
def threshold_calc(nbeg,nend,n_noise,sig_fact,necdf_flag,nlbound):
return
|
python
|
from torch.utils import data
import yaml
from argparse import ArgumentParser
from typing import Any, List, Tuple
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.distributions as dist
from torch.utils.data import DataLoader, RandomSampler
from torchvision import transforms as transform_lib
from torchvision.datasets import MNIST, ImageFolder, SVHN
from infogan.components import InfoGANGenerator, InfoGANDiscriminator, QNetwork
from infogan.utils import TensorboardGenerativeModelImageSampler, CodeLatentDimInterpolator
class InfoGAN(pl.LightningModule):
"""
InfoGAN Implementation
"""
def __init__(self,
lambda_coeff: float = 1,
betas_opt: List[float] = [0.5, 0.999],
feature_maps_gen: List = [64, ],
feature_maps_disc: List = [64, 128],
fc_layers_gen: List = [1024, ],
fc_layers_disc: List = [1024, ],
img_channels: int = 1,
noise_dim: int = 62,
categ_code_dims: list = [10, ],
cont_code_dim: int = 2,
conv_start_shape_gen: List = [128, 7, 7],
conv_end_shape_disc: List = [128, 5, 5],
hinge_loss: bool = False,
learning_rate_gen: float = 1e-3,
learning_rate_disc: float = 2e-4,
num_gen_opts: int = 1,
**kwargs: Any,
) -> None:
"""
Args:
lambda_coeff - Weight of the MI term in the objective fn
beats_opt - Beta values for Adam optimizer
feature_maps_gen - Feature map size for each deconv layer in the generator
feature_maps_disc - Feature map size for each conv layer in the discriminator
fc_layers_gen - Fully connected layer dimensions prior to deconv blocks in the generator
fc_layers_disc - Fully connected layer dimensions after the conv blocks in the discriminator
img_channels - Number of channels in the image
noise_dim - Dimension of random noise variables
categ_code_dims - A list with the number of categories in each categorical distribution of the
latent code variable
cont_code_dim - Number of variables in the gaussina code
conv_start_shape_gen - Shape of the input to the deconv block in the generator (for batch size=1)
conv_end_shape_disc - Shape of the output form the conv_layers in the discriminator (for batch size=1)
hinge_loss - Use Hinge loss instead of the standard GAN loss
learning_rate_gen - learning rate for the generator
learning_rate_disc - learning rate for the discriminator
"""
super().__init__()
self.save_hyperparameters()
self.automatic_optimization = False
self.generator = InfoGANGenerator(noise_dim,
sum(categ_code_dims)+cont_code_dim,
feature_maps_gen,
img_channels,
conv_start_shape=conv_start_shape_gen,
fc_layers=fc_layers_gen)
self.generator.apply(self._initialize_weights)
self.discriminator = InfoGANDiscriminator(sum(categ_code_dims),
cont_code_dim,
feature_maps_disc,
img_channels,
conv_end_shape_disc,
fc_layers=fc_layers_disc,
sn=self.hparams.hinge_loss)
self.q_network = QNetwork(self.discriminator.base_feat_dim,
sum(categ_code_dims),
cont_code_dim)
self.q_network.apply(self._initialize_weights)
if not hinge_loss:
self.discriminator.apply(self._initialize_weights)
self._initialize_samplers()
if not hinge_loss:
self.adverserial_loss = nn.BCEWithLogitsLoss()
if len(categ_code_dims) > 0:
self.categorical_loss = nn.CrossEntropyLoss()
if cont_code_dim > 0:
self.gaussian_loss = nn.MSELoss()
def _initialize_samplers(self) -> None:
if len(self.hparams.categ_code_dims) > 0:
self.categ_dists = [dist.OneHotCategorical(logits=torch.ones(c_dim))
for c_dim in self.hparams.categ_code_dims]
if self.hparams.cont_code_dim > 0:
self._normal_dist = dist.MultivariateNormal(torch.zeros(self.hparams.cont_code_dim),
torch.eye(self.hparams.cont_code_dim))
@staticmethod
def _initialize_weights(module) -> None:
classname = module.__class__.__name__
if classname.find("Conv") != -1 or classname.find("Linear") != -1:
torch.nn.init.normal_(module.weight, 0.0, 0.02)
if module.bias is not None:
torch.nn.init.zeros_(module.bias)
elif classname.find("BatchNorm") != -1:
torch.nn.init.normal_(module.weight, 1.0, 0.02)
torch.nn.init.zeros_(module.bias)
def configure_optimizers(self) -> Tuple[List[optim.Optimizer], List]:
gen_opt = optim.Adam(self.generator.parameters(),
lr=self.hparams.learning_rate_gen,
betas=self.hparams.betas_opt)
disc_opt = optim.Adam([*self.discriminator.parameters(), *self.q_network.parameters()],
lr=self.hparams.learning_rate_disc,
betas=self.hparams.betas_opt)
return ([gen_opt, disc_opt], [])
def forward(self, z: torch.Tensor, c: torch.Tensor) -> torch.Tensor:
"""
Generates an image
Args:
z - Noise vector
c - Latent code
"""
return self.generator(z, c)
def training_step(self,
batch: Tuple,
batch_idx: int) -> torch.Tensor:
gen_opt, disc_opt = self.optimizers(use_pl_optimizer=True)
real_img, _ = batch
gen_loss = torch.zeros([], device=self.device)
for i in range(self.hparams.num_gen_opts):
gen_loss_iter = self._get_gen_loss(len(real_img))
gen_opt.zero_grad()
self.manual_backward(gen_loss_iter)
gen_opt.step()
gen_loss += gen_loss_iter
gen_loss /= self.hparams.num_gen_opts
self.log("gen_train/loss", gen_loss, on_epoch=True)
disc_loss = self._get_disc_loss(real_img)
disc_opt.zero_grad()
self.manual_backward(disc_loss)
disc_opt.step()
self.log("disc_train/loss", disc_loss, on_epoch=True)
return {"gen_loss": gen_loss.detach(), "disc_loss": disc_loss.detach()}
def sample_noise(self, batch_size: int) -> torch.Tensor:
return torch.randn((batch_size, self.hparams.noise_dim), device=self.device)
def sample_code(self, batch_size: int) -> torch.Tensor:
cat_code = cont_code = None
if len(self.hparams.categ_code_dims) > 0:
cat_codes = [categ_dist.sample([batch_size])
for categ_dist in self.categ_dists]
cat_code = torch.cat(cat_codes, dim=-1)
if self.hparams.cont_code_dim > 0:
cont_code = self._normal_dist.sample([batch_size])
return torch.cat([code for code in [cat_code, cont_code]
if code is not None], dim=-1).to(self.device)
def _get_latents(self, batch_size: int) -> Tuple[torch.Tensor, torch.Tensor]:
z = self.sample_noise(batch_size)
c = self.sample_code(batch_size)
return z, c
def _get_gen_loss(self, batch_size: int) -> torch.Tensor:
# Calculate adverserial loss
z, c = self._get_latents(batch_size)
fake_img = self.generator(z, c)
fake_pred, disc_latents = self.discriminator(fake_img)
q_pred = self.q_network(disc_latents)
if self.hparams.hinge_loss:
adv_loss = -fake_pred.mean()
else:
target = torch.ones_like(fake_pred)
adv_loss = self.adverserial_loss(fake_pred, target)
q_categ_loss, q_gauss_loss = (torch.zeros([], device=self.device),
torch.zeros([], device=self.device))
# Calculate loss from categorical latent code prediction
start_dim = 0
if len(self.hparams.categ_code_dims) > 0:
for c_dim in self.hparams.categ_code_dims:
end_dim = start_dim + c_dim
categ_posterior = self.categorical_loss(q_pred['categ'][:, start_dim:end_dim],
c[:, start_dim:end_dim].argmax(dim=-1))
categ_prior = - \
torch.log(torch.ones_like(categ_posterior) / c_dim)
q_categ_loss -= (categ_prior - categ_posterior)
start_dim += c_dim
q_categ_loss = q_categ_loss/len(self.hparams.categ_code_dims)
# Calculate loss from gaussian latent code prediction
if self.hparams.cont_code_dim > 0:
q_gauss = dist.Independent(dist.Normal(
q_pred['gauss_mean'], q_pred['gauss_std']), reinterpreted_batch_ndims=1)
q_gauss_loss = self.gaussian_loss(
q_gauss.rsample(), c[:, start_dim:])
mi_loss = q_categ_loss + q_gauss_loss
self.log("gen_train/adv_loss", adv_loss, on_epoch=False)
self.log("gen_train/categ_info_loss", q_categ_loss, on_epoch=False)
self.log("gen_train/gauss_info_loss", q_gauss_loss, on_epoch=False)
return adv_loss + self.hparams.lambda_coeff * mi_loss
def _get_disc_loss(self, real_img: torch.Tensor) -> torch.Tensor:
# Calculate adverserial loss from real images
real_pred = self.discriminator(real_img, need_base_feat=False)
if self.hparams.hinge_loss:
real_loss = F.relu(1-real_pred).mean()
else:
real_target = torch.ones_like(real_pred)
real_loss = self.adverserial_loss(real_pred, real_target)
# Calculate adverserial loss from fake images
z, c = self._get_latents(len(real_img))
fake_img = self.generator(z, c)
fake_pred, disc_latents = self.discriminator(fake_img)
q_pred = self.q_network(disc_latents.detach())
if self.hparams.hinge_loss:
fake_loss = F.relu(1+fake_pred).mean()
else:
fake_target = torch.zeros_like(fake_pred)
fake_loss = self.adverserial_loss(fake_pred, fake_target)
adv_loss = real_loss + fake_loss
q_categ_loss, q_gauss_loss = (torch.zeros([], device=self.device),
torch.zeros([], device=self.device))
# Calculate loss from categorical latent code prediction
start_dim = 0
if len(self.hparams.categ_code_dims) > 0:
for c_dim in self.hparams.categ_code_dims:
end_dim = start_dim + c_dim
categ_posterior = self.categorical_loss(q_pred['categ'][:, start_dim:end_dim],
c[:, start_dim:end_dim].argmax(dim=-1))
categ_prior = - \
torch.log(torch.ones_like(categ_posterior) / c_dim)
q_categ_loss -= (categ_prior - categ_posterior)
start_dim += c_dim
q_categ_loss = q_categ_loss/len(self.hparams.categ_code_dims)
# Calculate loss from gaussian latent code prediction
if self.hparams.cont_code_dim > 0:
q_gauss = dist.Independent(dist.Normal(
q_pred['gauss_mean'], q_pred['gauss_std']), reinterpreted_batch_ndims=1)
q_gauss_loss = self.gaussian_loss(
q_gauss.rsample(), c[:, start_dim:])
mi_loss = q_categ_loss + q_gauss_loss
self.log("disc_train/adv_loss", adv_loss, on_epoch=False)
self.log("disc_train/categ_info_loss", q_categ_loss, on_epoch=False)
self.log("disc_train/gauss_info_loss", q_gauss_loss, on_epoch=False)
return adv_loss + self.hparams.lambda_coeff * mi_loss
def cli_main(args=None):
parser = ArgumentParser()
parser.add_argument("--dataset", type=str, default='mnist')
parser.add_argument("--batch_size", type=int, default=128)
parser.add_argument("--data_dir", type=str, default="./data/")
parser.add_argument("--gpus", type=int, default=1)
parser.add_argument("--num_workers", type=int, default=6)
parser.add_argument("--max_epochs", type=int, default=100)
parser.add_argument("--seed", type=int, default=1234)
script_args, _ = parser.parse_known_args(args)
pl.seed_everything(script_args.seed)
if script_args.dataset == 'mnist':
transforms = transform_lib.Compose([
transform_lib.Resize((28, 28)),
transform_lib.ToTensor(),
transform_lib.Normalize((0.5,), (0.5,)),
])
dataset = MNIST(root=script_args.data_dir,
download=True, transform=transforms)
elif script_args.dataset in ['celeba', 'svhn']:
transforms = transform_lib.Compose([
transform_lib.Resize((32, 32)),
transform_lib.ToTensor(),
transform_lib.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
if script_args.dataset == 'celeba':
dataset = ImageFolder(root=script_args.data_dir+script_args.dataset,
transform=transforms)
elif script_args.dataset == 'svhn':
dataset = SVHN(root=script_args.data_dir,
download=True, transform=transforms)
args = parser.parse_args(args)
with open('configs/%s.yml' % (script_args.dataset), 'r') as cfg:
config_args = yaml.safe_load(cfg)
for k, v in config_args.items():
args.__setattr__(k, v)
num_batches = args.num_batches if args.num_batches is not None else len(
dataset) // args.batch_size
sampler = RandomSampler(dataset, True, num_batches * args.batch_size)
dataloader = DataLoader(dataset, batch_size=script_args.batch_size,
sampler=sampler, num_workers=script_args.num_workers)
model = InfoGAN(**vars(args))
callbacks = [
TensorboardGenerativeModelImageSampler(
num_samples=5, log_epoch_interval=5),
CodeLatentDimInterpolator(epoch_interval=10)
]
trainer = pl.Trainer.from_argparse_args(args, callbacks=callbacks)
trainer.fit(model, dataloader)
if __name__ == "__main__":
cli_main()
|
python
|
"""
Code for defining the architecture of the Encoder and the Decoder blocks.
"""
import tensorflow as tf
class Encoder():
def __init__(self, vocab_size, embedding_dim, encoder_units):
# print(vocab_size, embedding_dim, encoder_units, "##########################################ENCODER########################")
self.encoder_units = encoder_units
self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim, mask_zero=True)
self.gru = tf.keras.layers.GRU(self.encoder_units,
return_sequences=True,
return_state=True,
recurrent_initializer='glorot_uniform')
def __call__(self, x, hidden):
x = self.embedding(x)
output, state = self.gru(x, initial_state = hidden)
return output, state
class Decoder():
def __init__(self, vocab_size, embedding_dim, decoder_units):
self.decoder_units = decoder_units
self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim, mask_zero=True)
self.gru = tf.keras.layers.GRU(self.decoder_units,
return_sequences=True,
return_state=True,
recurrent_initializer='glorot_uniform')
self.fc = tf.keras.layers.Dense(vocab_size)
# used for attention
self.attention = BahdanauAttention(self.decoder_units)
def __call__(self, x, hidden, enc_output):
# enc_output shape == (batch_size, max_length, hidden_size)
context_vector, attention_weights = self.attention(hidden, enc_output)
# x shape after passing through embedding == (batch_size, 1, embedding_dim)
x = self.embedding(x)
# x shape after concatenation == (batch_size, 1, embedding_dim + hidden_size)
x = tf.concat([tf.expand_dims(context_vector, 1), x], axis=-1)
# passing the concatenated vector to the GRU
output, state = self.gru(x)
# output shape == (batch_size * 1, hidden_size)
output = tf.reshape(output, (-1, output.shape[2]))
# output shape == (batch_size, vocab)
x = self.fc(output)
return x, state, attention_weights
class BahdanauAttention():
def __init__(self, units):
self.W1 = tf.keras.layers.Dense(units)
self.W2 = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
def __call__(self, query, values):
# query hidden state shape == (batch_size, hidden size)
# query_with_time_axis shape == (batch_size, 1, hidden size)
# values shape == (batch_size, max_len, hidden size)
# we are doing this to broadcast addition along the time axis to calculate the score
query_with_time_axis = tf.expand_dims(query, 1)
# score shape == (batch_size, max_length, 1)
# we get 1 at the last axis because we are applying score to self.V
# the shape of the tensor before applying self.V is (batch_size, max_length, units)
score = self.V(tf.nn.tanh(
self.W1(query_with_time_axis) + self.W2(values)))
# attention_weights shape == (batch_size, max_length, 1)
attention_weights = tf.nn.softmax(score, axis=1)
# context_vector shape after sum == (batch_size, hidden_size)
context_vector = attention_weights * values
context_vector = tf.reduce_sum(context_vector, axis=1)
return context_vector, attention_weights
#TODO: Attribute tensorflow guys
|
python
|
'''
Created on Mar 13, 2018
@author: abelit
'''
import os
import json
from utils import filepath
project_settings = {
# 项目信息配置
'package': 'dev',
'version':'3.14',
'name':'__dbreport__.py',
'author':'abelit',
'email':'[email protected]',
'description':'',
}
path_settings = {
'image': filepath.get_root_path(project_settings['name']) + os.sep + 'images' + os.sep,
'log': filepath.get_root_path(project_settings['name']) + os.sep + 'logs' + os.sep,
'font': filepath.get_root_path(project_settings['name']) + os.sep + 'fonts' + os.sep,
'resource': filepath.get_root_path(project_settings['name']) + os.sep + 'resource' + os.sep,
'config': filepath.get_root_path(project_settings['name']) + os.sep + 'config' + os.sep,
}
USERCONF = path_settings['config']+'dbreport.json'
if __name__ == '__main__':
print(USERCONF)
|
python
|
# -*- coding: utf-8 -*-
# [email protected]
from .timer import timer
|
python
|
import base64
import json
import cv2
import numpy as np
from decouple import config
from flask import Flask, request
from api.face import FaceVerification
from db.mongo import FaceEncodings
app = Flask(__name__)
face_verification = FaceVerification(
FaceEncodings(
config("DATABASE_URI")
)
)
@app.route('/register', methods=["POST"])
def register_post():
username = request.form.get('username')
image = request.form['image']
img = base64.b64decode(image)
img = cv2.imdecode(np.fromstring(img, np.uint8), cv2.IMREAD_ANYCOLOR)
registration_response = face_verification.registration(image=np.array(img), username=username)
if registration_response['success']:
registration_response.update({"code": 200})
else:
registration_response.update({"code": 400})
return json.dumps(registration_response)
@app.route('/login', methods=["POST"])
def login_post():
username = None
if request.form['username']:
username = request.form.get('username')
image = request.form['image']
img = base64.b64decode(image)
img = cv2.imdecode(np.fromstring(img, np.uint8), cv2.IMREAD_ANYCOLOR)
auth_response = face_verification.authenticate(image=np.array(img), username=username)
if auth_response['success']:
auth_response.update({"code": 200})
else:
auth_response.update({"code": 400})
return json.dumps(auth_response)
@app.route('/', methods=["GET"])
def health_check():
return {"success": True}
|
python
|
import pocketcasts as pc
import requests
import re
import configparser
from pathlib import Path
def get_valid_filename(s):
s = str(s).strip()
return re.sub(r"(?u)[^-\w. ]", "", s)
def get_extension(url):
if "?" in url:
url, _ = url.split("?", 1)
return url.split(".")[-1]
print("Reading configuration file config.ini.")
config = configparser.ConfigParser()
config.read("config.ini")
print("Connecting to Pocketcasts API.")
api = pc.Api(config["pocketcasts"]["user"], config["pocketcasts"]["password"])
print("Fetching all starred episodes.")
starred = api.starred_episodes()
print("Downloading starred episodes.")
total_size = len(starred)
Path("podcasts/").mkdir(parents=True, exist_ok=True)
for index, i in enumerate(starred, 1):
print("########## Processing :")
# print(i)
filename = get_valid_filename(
f"{i._published_at.strftime('%Y%m%d')} - {i._podcast._title} - {i._title}.{get_extension(i._url)}"
)
if not Path(filename).is_file():
print(f"Downloading {index}/{total_size} : {filename}")
r = requests.get(i._url)
with open("podcasts/" + filename, "wb") as f:
f.write(r.content)
else:
print(f"{filename} already exists. Skipping.")
|
python
|
import numpy as np
from config import handTrackConfig as htconf
from math import sin, cos, sqrt, atan2, radians
import cv2
# 8 12 16 20
# | | | |
# 7 11 15 19
# 4 | | | |
# | 6 10 14 18
# 3 | | | |
# | 5---9---13--17
# 2 \ /
# \ \ /
# 1 \ /
# \ \ /
# ------0-
threshold = [
(-0.90, -1), # 0, 1, 2, 3
(0, -0.85, -1), # 0, 1, 2
(0.7, -0.85, -1), # 0, 1, 2
(0.7, -0.85, -1), # 0, 1, 2
(0.7, -0.85, -1) # 0, 1, 2
]
pos = [
[(3, 2, 1), (4, 3, 2)],
[(8, 6, 0)],
[(12, 10, 0)],
[(16, 14, 0)],
[(20, 18, 0)]
]
record = {
# '0': [[0, 0, 0, 0, 0]],
'1': [[0, 2, 0, 0, 0]],
'2': [[0, 2, 2, 0, 0]],
'3': [[0, 2, 2, 2, 0]],
'4': [[0, 2, 2, 2, 2]],
'5': [[1, 2, 2, 2, 2]],
'OK': [[0, 0, 2, 2, 2]],
'GOOD': [[1, 0, 0, 0, 0]],
'8': [[1, 2, 0, 0, 0], [1, 1, 0, 0, 0]],
}
def cal_finger_angle(points):
res = []
for p in pos:
temp = []
for i in p:
start, mid, end = i
v1 = points[start] - points[mid]
v1 /= np.linalg.norm(v1)
v2 = points[end] - points[mid]
v2 /= np.linalg.norm(v2)
cos_ang = v1.dot(v2)
temp.append(cos_ang)
res.append(sum(temp) / len(temp))
# print(res)
return res
def recog_gesture(points):
if get_distance(points[4], points[8]) < 30:
return "CATCH"
conf = cal_finger_angle(points)
res = []
for i, pred in enumerate(conf):
thre = threshold[i]
for c, t in enumerate(thre):
if pred > t:
res.append(c)
break
# print(res)
for k, v in record.items():
for v1 in v:
if v1 == res:
return k
return None
def get_vis_gesture_map(map, points, vis_window_shape):
points[:, 0] -= points[:, 0].min()
points[:, 1] -= points[:, 1].min()
points[:, 0] /= points[:, 0].max()
points[:, 1] /= points[:, 1].max()
points += 0.1
points *= 0.8 * vis_window_shape[0]
for i, point in enumerate(points):
x, y = point
cv2.circle(map, (int(x), int(y)), htconf.THICKNESS, htconf.POINT_COLOR, htconf.THICKNESS)
for connection in htconf.connections:
x0, y0 = points[connection[0]]
x1, y1 = points[connection[1]]
cv2.line(map, (int(x0), int(y0)), (int(x1), int(y1)), htconf.CONNECTION_COLOR, htconf.THICKNESS)
return map
def get_distance(point1, point2):
result = ((((point2[0] - point1[0]) ** 2) + ((point2[1] - point1[1]) ** 2)) ** 0.5)
return result
|
python
|
"""
This module provides various utility functions.
"""
# -----------------------------------------------------------------------------
# IMPORTS
# -----------------------------------------------------------------------------
from typing import Tuple
import numpy as np
# -----------------------------------------------------------------------------
# FUNCTION DEFINITIONS
# -----------------------------------------------------------------------------
def crop_center(array: np.ndarray,
size: Tuple[int, ...]) -> np.ndarray:
"""
Crop an n-dimensional array to the given size around its center.
Args:
array: The numpy array to be cropped.
size: A tuple containing the size of the cropped array. To not
crop along a specific axis, you can specify the size of
that axis as -1.
Returns:
The input array, cropped to the desired size around its center.
"""
# Ensure that the the array shape and the size variable match
assert array.ndim == len(size), \
'Length of size must match number of dimensions of array!'
# Loop over the the axes of the array to create slices
slices = list()
for old_len, new_len in zip(array.shape, size):
# Compute start and end position for axis
start = old_len // 2 - new_len // 2 if new_len != -1 else None
end = start + new_len if start is not None else None
# Create a slice object for axis
slices.append(slice(start, end))
return array[tuple(slices)]
def get_subaperture_centers(
grid_size: int,
) -> Tuple[np.ndarray, np.ndarray]:
"""
Compute the positions of the centers of the subapertures of the
sensor. This assumes a simple geometry, where the sensor is taken
to be the largest square that can fit inside the unit circle, and
consists of a grid of `grid_size` x `grid_size` subapertures.
Args:
grid_size: An integer specifying the size of the (quadratic)
grid of subapertures in the HSWFS sensor.
Returns:
A mesh grid, consisting of two numpy arrays which specify the
`x` and `y` positions of the centers of the subapertures.
"""
x = np.linspace((1 / grid_size - 1), (1 - 1 / grid_size), grid_size)
x = 1 / np.sqrt(2) * np.repeat(x.reshape(1, -1), grid_size, axis=0)
y = np.linspace((1 - 1 / grid_size), (1 / grid_size - 1), grid_size)
y = 1 / np.sqrt(2) * np.repeat(y.reshape(-1, 1), grid_size, axis=1)
return x, y
def get_unit_disk_meshgrid(
resolution: int,
) -> Tuple[np.array, np.array]:
"""
Get a (Cartesian) mesh grid of positions on the unit disk, that is,
all positions with with a Euclidean distance <= 1 from (0, 0).
Args:
resolution: An integer specifying the size of the mesh grid,
that is, the number of points in each dimensions.
Returns:
A mesh grid consisting of the tuple `x_0`, `y_0`, which are each
numpy arrays of shape `(resolution, resolution)`. For positions
that are on the unit disk, they contain the coordinates of the
position; otherwise, they contain `np.nan`.
"""
# Create a meshgrid of (Cartesian) positions: [-1, 1] x [-1, 1]
x_0, y_0 = np.meshgrid(np.linspace(-1, 1, resolution),
np.linspace(-1, 1, resolution))
# Create a mask for the unit disk (only select position with radius <= 1)
unit_disk_mask = np.sqrt(x_0**2 + y_0**2) <= 1
# Mask out all the position that are not on the unit disk
x_0[~unit_disk_mask] = np.nan
y_0[~unit_disk_mask] = np.nan
return x_0, y_0
|
python
|
"""
Based on https://github.com/ikostrikov/pytorch-a2c-ppo-acktr
"""
import gym
import torch
import random
from environments.env_utils.vec_env import VecEnvWrapper
from environments.env_utils.vec_env.dummy_vec_env import DummyVecEnv
from environments.env_utils.vec_env.subproc_vec_env import SubprocVecEnv
from environments.env_utils.vec_env.vec_normalize import VecNormalize
from environments.wrappers import TimeLimitMask, VariBadWrapper
def make_env(env_id, seed, rank, episodes_per_task, tasks, add_done_info, **kwargs):
def _thunk():
env = gym.make(env_id, **kwargs)
if tasks is not None:
env.unwrapped.reset_task = lambda x: env.unwrapped.set_task(random.choice(tasks))
if seed is not None:
env.seed(seed + rank)
if str(env.__class__.__name__).find('TimeLimit') >= 0:
env = TimeLimitMask(env)
env = VariBadWrapper(env=env, episodes_per_task=episodes_per_task, add_done_info=add_done_info)
return env
return _thunk
def make_vec_envs(env_name, seed, num_processes, gamma,
device, episodes_per_task,
normalise_rew, ret_rms, tasks,
rank_offset=0,
add_done_info=None,
**kwargs):
"""
:param ret_rms: running return and std for rewards
"""
envs = [make_env(env_id=env_name, seed=seed, rank=rank_offset + i,
episodes_per_task=episodes_per_task,
tasks=tasks,
add_done_info=add_done_info,
**kwargs)
for i in range(num_processes)]
if len(envs) > 1:
envs = SubprocVecEnv(envs)
else:
envs = DummyVecEnv(envs)
if len(envs.observation_space.shape) == 1:
if gamma is None:
envs = VecNormalize(envs, normalise_rew=normalise_rew, ret_rms=ret_rms)
else:
envs = VecNormalize(envs, normalise_rew=normalise_rew, ret_rms=ret_rms, gamma=gamma)
envs = VecPyTorch(envs, device)
return envs
class VecPyTorch(VecEnvWrapper):
def __init__(self, venv, device):
"""Return only every `skip`-th frame"""
super(VecPyTorch, self).__init__(venv)
self.device = device
# TODO: Fix data types
def reset_mdp(self, index=None):
obs = self.venv.reset_mdp(index=index)
if isinstance(obs, list):
obs = [torch.from_numpy(o).float().to(self.device) for o in obs]
else:
obs = torch.from_numpy(obs).float().to(self.device)
return obs
def reset(self, index=None, task=None):
if task is not None:
assert isinstance(task, list)
state = self.venv.reset(index=index, task=task)
if isinstance(state, list):
state = [torch.from_numpy(s).float().to(self.device) for s in state]
else:
state = torch.from_numpy(state).float().to(self.device)
return state
def step_async(self, actions):
# actions = actions.squeeze(1).cpu().numpy()
actions = actions.cpu().numpy()
self.venv.step_async(actions)
def step_wait(self):
state, reward, done, info = self.venv.step_wait()
if isinstance(state, list): # raw + normalised
state = [torch.from_numpy(s).float().to(self.device) for s in state]
else:
state = torch.from_numpy(state).float().to(self.device)
if isinstance(reward, list): # raw + normalised
reward = [torch.from_numpy(r).unsqueeze(dim=1).float().to(self.device) for r in reward]
else:
reward = torch.from_numpy(reward).unsqueeze(dim=1).float().to(self.device)
return state, reward, done, info
def __getattr__(self, attr):
""" If env does not have the attribute then call the attribute in the wrapped_env """
if attr in ['_max_episode_steps', 'task_dim', 'belief_dim', 'num_states']:
return self.unwrapped.get_env_attr(attr)
try:
orig_attr = self.__getattribute__(attr)
except AttributeError:
orig_attr = self.unwrapped.__getattribute__(attr)
if callable(orig_attr):
def hooked(*args, **kwargs):
result = orig_attr(*args, **kwargs)
return result
return hooked
else:
return orig_attr
|
python
|
"""
Sets permission for the API (ONLY)
"""
from rest_framework import permissions
# TODO: Add restriction to users (get token, refresh token, verify token, post request)
class IsReadOnly(permissions.DjangoModelPermissions):
"""
Custom permission to only allow reading.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
class IsOwnerOrReadOnly(permissions.DjangoModelPermissions):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
# Write permissions are only allowed to the owner of the snippet.
return obj.user == request.user
class IsOwner(permissions.DjangoModelPermissions):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_object_permission(self, request, view, obj):
# Permissions are only allowed to the owner of the snippet.
return obj.user == request.user
|
python
|
###############################################################################
##
## Copyright 2011 Tavendo GmbH
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
##
###############################################################################
import sys, shelve
from twisted.python import log
from twisted.internet import reactor
from autobahn.websocket import listenWS
from autobahn.wamp import exportRpc, WampServerFactory, WampServerProtocol
class KeyValue:
"""
Simple, persistent key-value store.
"""
def __init__(self, filename):
self.store = shelve.open(filename)
@exportRpc
def set(self, key = None, value = None):
if key is not None:
k = str(key)
if value is not None:
self.store[k] = value
else:
if self.store.has_key(k):
del self.store[k]
else:
self.store.clear()
@exportRpc
def get(self, key = None):
if key is None:
return self.store.items()
else:
return self.store.get(str(key), None)
@exportRpc
def keys(self):
return self.store.keys()
class KeyValueServerProtocol(WampServerProtocol):
"""
Demonstrates creating a server with Autobahn WebSockets that provides
a persistent key-value store which can we access via RPCs.
"""
def onSessionOpen(self):
## register the key-value store, which resides on the factory within
## this connection
self.registerForRpc(self.factory.keyvalue, "http://example.com/simple/keyvalue#")
class KeyValueServerFactory(WampServerFactory):
protocol = KeyValueServerProtocol
def __init__(self, url):
WampServerFactory.__init__(self, url)
## the key-value store resides on the factory object, since it is to
## be shared among all client connections
self.keyvalue = KeyValue("keyvalue.dat")
if __name__ == '__main__':
log.startLogging(sys.stdout)
factory = KeyValueServerFactory("ws://localhost:9000")
listenWS(factory)
reactor.run()
|
python
|
from typing import Set, List, Tuple, Dict
def fibonacci(n: int) -> int:
"""
Returns n-th Fibonacci number
n must be more than 0, otherwise it raise a ValueError.
>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(2)
1
>>> fibonacci(10)
55
>>> fibonacci(-2)
Traceback (most recent call last):
...
ValueError: n must be more or equal than 0
"""
if n < 0:
raise ValueError('n must be more or equal than 0')
elif n == 0:
return 0
fib = [0, 1] + [0] * (n - 1)
for i in range(2, n + 1):
fib[i] = fib[i - 1] + fib[i - 2]
return fib[n]
def count_trajectories(n: int) -> int:
"""
The Grasshopper is in position 1.
The Grasshopper may jump to +1, +2 or +3.
How many possible trajectories does the grasshopper have to get to position n?
If n<=1, consider that the Grasshopper has 0 possible trajectory.
>>> count_trajectories(0)
0
>>> count_trajectories(1)
0
>>> count_trajectories(2)
1
>>> count_trajectories(3)
2
>>> count_trajectories(4)
3
>>> count_trajectories(7)
20
>>> count_trajectories(-3)
0
"""
if n <= 1:
return 0
trajectories = [0, 0, 1, 2, 3] + [0] * (n - 4)
for i in range(5, n + 1):
trajectories[i] = trajectories[i - 1] + trajectories[i - 2] + trajectories[i - 3]
return trajectories[n]
def count_trajectories_with_forbidden_cells(n: int, forbidden_cells: Set[int]) -> int:
"""
The Grasshopper is in position 1.
The Grasshopper may jump to +1, +2 or +3.
The function receives a set of numbers of cells that cannot be jumped.
How many possible trajectories does the grasshopper have to get to position n?
If n<=1, consider that the Grasshopper has 0 possible trajectory.
If 1 is forbidden, consider that the Grasshopper has 0 possible trajectory.
>>> count_trajectories_with_forbidden_cells(0, set())
0
>>> count_trajectories_with_forbidden_cells(1, set())
0
>>> count_trajectories_with_forbidden_cells(2, set())
1
>>> count_trajectories_with_forbidden_cells(3, set())
2
>>> count_trajectories_with_forbidden_cells(4, set())
3
>>> count_trajectories_with_forbidden_cells(4, {2})
2
>>> count_trajectories_with_forbidden_cells(4, {3})
2
>>> count_trajectories_with_forbidden_cells(4, {4})
0
>>> count_trajectories_with_forbidden_cells(9, {2,6,7})
3
>>> count_trajectories_with_forbidden_cells(12, {3,6,7,10})
9
>>> count_trajectories_with_forbidden_cells(8, {5})
13
>>> count_trajectories_with_forbidden_cells(8, {1})
0
>>> count_trajectories_with_forbidden_cells(-3, set())
0
"""
if n <= 1 or 1 in forbidden_cells:
return 0
trajectories = [0] * 5
for i in range(2, 5):
if i not in forbidden_cells:
for k in range(i-1, 0, -1):
if k not in forbidden_cells:
trajectories[i] = trajectories[k]+1
break
trajectories += [0] * (n - 4)
for i in range(5, n + 1):
if i not in forbidden_cells:
trajectories[i] = trajectories[i - 1] + trajectories[i - 2] + trajectories[i - 3]
return trajectories[n]
def count_min_cost(n: int, prices: Dict[int, int]) -> Tuple[int, List[int]]:
"""The Grasshopper is in position 1.
The Grasshopper may jump to +1, +2 or +3.
The function returns the tuple with the lowest cost to reach n and with a list of points to visit.
The function gets a dict of visit prices for each point.
If there is no value in the prices for the desired point, it is assumed that the visiting price is 0.
If there are several trajectories with minimal cost, it returns any of them.
If n<0, it is considered that the Grasshopper could have visited only the first point.
>>> count_min_cost(11, {1:1, 2:2, 3:1, 4:3, 5:1, 6:1, 7:2, 8:3, 9:3, 10:2, 11:1})
(7, [1, 3, 5, 8, 11])
>>> count_min_cost(-2, {1:2, 2:1, 3:2, 4:1})
(2, [1])
>>> count_min_cost(6, {2:2, 3:2, 5:1})
(0, [1, 4, 6])
>>> count_min_cost(6, {1:3, 2:-5, 3:1, 4:-3, 5:5, 6:1})
(-4, [1, 2, 4, 6])
>>> count_min_cost(5, {})
(0, [1, 2, 5])
"""
if n <= 1:
return prices.get(1, 0), [1]
trajectories = [
(0, [0]),
(prices.get(1, 0), [1]),
(prices.get(2, 0) + prices.get(1, 0), [1, 2])
]
min_cost_trajectory = min(trajectories[1], trajectories[2])
trajectories.append((min_cost_trajectory[0] + prices.get(3, 0), min_cost_trajectory[1] + [3]))
for i in range(4, n+1):
min_cost_trajectory = min(trajectories[i-1], trajectories[i-2], trajectories[i-3])
trajectories.append((min_cost_trajectory[0] + prices.get(i, 0), min_cost_trajectory[1] + [i]))
return trajectories[n]
def largest_common_subsequence(sequence_1: List[int], sequence_2:List[int]) -> int:
"""
For two p-sequences of numbers it returns the length of the largest common subsequence.
If there is no common subsequence, it returns 0.
Note: a subsequence is not a substring.
For sequence 1,2,3,4,5 the sequence 1,3,5 is a subsequence (although it is not a substring).
>>> largest_common_subsequence([1,2,3,4,5],[1,2,3,4,5])
5
>>> largest_common_subsequence([1,2,3,4,5],[4,8,1,2,3,4,6,9])
4
>>> largest_common_subsequence([0,3,6,1,2,3,8,9],[1,2,3,4,5])
3
>>> largest_common_subsequence([1,2,0,3,4,5],[1,2,3,4,5])
5
>>> largest_common_subsequence([1,2,3,0,5],[1,2,3,4,5])
4
>>> largest_common_subsequence([1,2,3,4,5],[6,7,8,9])
0
>>> largest_common_subsequence([],[1,2,3,4,5])
0
"""
res = [[0]*(len(sequence_2)+1) for _ in range(len(sequence_1)+1)]
for i in range(1, len(sequence_1)+1):
for j in range(1, len(sequence_2)+1):
if sequence_1[i-1] == sequence_2[j-1]:
res[i][j] = 1 + res[i-1][j-1]
else:
res[i][j] = max(res[i-1][j], res[i][j-1])
return res[-1][-1]
def largest_increasing_subsequence(sequence: List[int]) -> int:
"""
Returns the length of the longest increasing subsequence.
Note: a subsequence is not a substring.
For sequence 2,0,3,1,5 the sequence 2,3,5 is a subsequence (although it is not a substring).
>>> largest_increasing_subsequence([2,0,3,1,5])
3
>>> largest_increasing_subsequence([5,4,3,2,1])
1
>>> largest_increasing_subsequence([5,10,6,12,3,24,7,8])
4
>>> largest_increasing_subsequence([])
0
"""
return largest_common_subsequence(sequence_1=sequence, sequence_2=sorted(sequence))
if __name__ == "__main__":
import doctest
doctest.testmod()
|
python
|
from functools import wraps
from . import environment as env
import wx, os
class VirtualEnvMustExistDecorator:
"""装饰器:虚拟环境必须存在!!!"""
def __init__(self, *args, **kwargs): ...
def __call__(self, func, e=None):
@wraps(func)
def decorator(obj, *args, **kwargs):
env_path = env.getPython3Env()
if '' == env_path.strip() or not os.path.exists(env_path):
wx.MessageBox(f'虚拟环境未绑定,或绑定失败!', "错误警告", wx.OK | wx.ICON_INFORMATION)
return
if len(args) > 0:
e = args[0]
return func(obj, e)
return decorator
class RegisterOriginOrderDecorator:
"""系统命令装饰"""
def __init__(self, *args, **kwargs):
self.cmdCodes = []
self.info_cmdCodes = {}
if 'msg' in kwargs:
self.msg = kwargs['msg']
else:
self.msg = 'UnKnown'
def __call__(self, func, e=None):
@wraps(func)
def decorator(obj, *args, **kwargs):
if len(args) > 0:
e = args[0]
func_return = func(obj, e)
if not func_return:
return
cmdObj, self.cmdCodes, self.info_cmdCodes = func_return
self.cmdCodes.append(cmdObj)
self.info_cmdCodes[cmdObj] = self.msg
return decorator
|
python
|
import os, json, sys, shutil, distutils
from distutils import dir_util
if_block_template = '\tif(!strcmp(cmd, "{}")){{\n\
\t\treturn {}(argv, argc);\n\
\t}}else '
ending = '{\n\
\t\tstde("Not a command:");\n\
\t\tstde(argv[0]);\n\
\t}'
set_driver_template = "\tdrivers[{}] = &{};\n"
include_template = '#include "{}"\n'
call_template = '\t{}();\n'
def list_programs(d='./programs/'):
out = []
for i in os.listdir(d):
if not i.startswith('prg_'):
continue
i = os.path.join(d,i)
if os.path.isdir(i):
out.append(i)
return out
def list_drivers(d='./drivers/'):
out = []
for i in os.listdir(d):
if not i.startswith('drv_'):
continue
i = os.path.join(d,i)
if os.path.isdir(i):
out.append(i)
return out
def setup_programs():
with open('.//programs/programs.tplt') as f:
template = f.read()
program_dirs = list_programs()
output_ifs = ''
include_str = ''
inits = ''
for i in program_dirs:
with open(os.path.join(i, 'conf.json')) as f:
conf = json.load(f)
if 'disabled' in conf.keys() and conf['disabled']:
continue # skip it
cmd = conf['cmd']
func = conf['entry']
inc = os.path.basename(i)+'/'+conf['include']
output_ifs+=if_block_template.format(cmd, func)
include_str+=include_template.format(inc)
if 'init' in conf.keys():
inits+=call_template.format(conf['init'])
output_ifs+=ending
with open('./programs/program.c', 'w') as f:
f.write(template.format(include_str, output_ifs, inits))
def setup_drivers():
with open('./drivers/drivers.tplt') as f:
template = f.read()
driver_dirs = list_drivers()
driver_set = ''
preinits = ''
inits = ''
postinits = ''
include_str = ''
n_drivers = 0
for i in driver_dirs:
with open(os.path.join(i, 'conf.json')) as f:
conf = json.load(f)
if 'disabled' in conf.keys() and conf['disabled']:
continue # skip it
inc = os.path.basename(i)+'/'+conf['include']
include_str+=include_template.format(inc)
if 'preinit' in conf.keys():
preinits+=call_template.format(conf['preinit'])
if 'init' in conf.keys():
inits+=call_template.format(conf['init'])
if 'postinit' in conf.keys():
postinits+=call_template.format(conf['postinit'])
driver_set+=set_driver_template.format(n_drivers, conf['name'])
n_drivers+=1
with open('./drivers/drivers.c', 'w') as f:
f.write(template.format(include_str, n_drivers, driver_set, preinits, inits, postinits))
setup_programs()
setup_drivers()
|
python
|
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
from typing import Dict
import torch
from torch import optim
from datasets import Dataset
from models import CP, ComplEx
from regularizers import N2, N3
from optimizers import KBCOptimizer
big_datasets = ['FB15K', 'WN', 'WN18RR', 'FB237', 'YAGO3-10']
datasets = big_datasets
parser = argparse.ArgumentParser(
description="Relational learning contraption"
)
parser.add_argument(
'--dataset', choices=datasets,
help="Dataset in {}".format(datasets)
)
models = ['CP', 'ComplEx']
parser.add_argument(
'--model', choices=models,
help="Model in {}".format(models)
)
regularizers = ['N3', 'N2']
parser.add_argument(
'--regularizer', choices=regularizers, default='N3',
help="Regularizer in {}".format(regularizers)
)
optimizers = ['Adagrad', 'Adam', 'SGD']
parser.add_argument(
'--optimizer', choices=optimizers, default='Adagrad',
help="Optimizer in {}".format(optimizers)
)
parser.add_argument(
'--max_epochs', default=50, type=int,
help="Number of epochs."
)
parser.add_argument(
'--valid', default=3, type=float,
help="Number of epochs before valid."
)
parser.add_argument(
'--rank', default=1000, type=int,
help="Factorization rank."
)
parser.add_argument(
'--batch_size', default=1000, type=int,
help="Batch size."
)
parser.add_argument(
'--reg', default=0, type=float,
help="Regularization weight"
)
parser.add_argument(
'--init', default=1e-3, type=float,
help="Initial scale"
)
parser.add_argument(
'--learning_rate', default=1e-1, type=float,
help="Learning rate"
)
parser.add_argument(
'--decay1', default=0.9, type=float,
help="decay rate for the first moment estimate in Adam"
)
parser.add_argument(
'--decay2', default=0.999, type=float,
help="decay rate for second moment estimate in Adam"
)
args = parser.parse_args()
dataset = Dataset(args.dataset)
examples = torch.from_numpy(dataset.get_train().astype('int64'))
print(dataset.get_shape())
model = {
'CP': lambda: CP(dataset.get_shape(), args.rank, args.init),
'ComplEx': lambda: ComplEx(dataset.get_shape(), args.rank, args.init),
}[args.model]()
regularizer = {
'N2': N2(args.reg),
'N3': N3(args.reg),
}[args.regularizer]
device = 'cuda'
model.to(device)
optim_method = {
'Adagrad': lambda: optim.Adagrad(model.parameters(), lr=args.learning_rate),
'Adam': lambda: optim.Adam(model.parameters(), lr=args.learning_rate, betas=(args.decay1, args.decay2)),
'SGD': lambda: optim.SGD(model.parameters(), lr=args.learning_rate)
}[args.optimizer]()
optimizer = KBCOptimizer(model, regularizer, optim_method, args.batch_size)
def avg_both(mrrs: Dict[str, float], hits: Dict[str, torch.FloatTensor]):
"""
aggregate metrics for missing lhs and rhs
:param mrrs: d
:param hits:
:return:
"""
m = (mrrs['lhs'] + mrrs['rhs']) / 2.
h = (hits['lhs'] + hits['rhs']) / 2.
return {'MRR': m, 'hits@[1,3,10]': h}
cur_loss = 0
curve = {'train': [], 'valid': [], 'test': []}
for e in range(args.max_epochs):
cur_loss = optimizer.epoch(examples)
if (e + 1) % args.valid == 0:
valid, test, train = [
avg_both(*dataset.eval(model, split, -1 if split != 'train' else 50000))
for split in ['valid', 'test', 'train']
]
curve['valid'].append(valid)
curve['test'].append(test)
curve['train'].append(train)
print("\t TRAIN: ", train)
print("\t VALID : ", valid)
results = dataset.eval(model, 'test', -1)
print("\n\nTEST : ", results)
|
python
|
# Author : BIZZOZZERO Nicolas
# Completed on Sun, 24 Jan 2016, 23:11
#
# This program find the solution of the problem 5 of the Project Euler.
# The problem is the following :
#
# 2520 is the smallest number that can be divided by each of the
# numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible
# by all of the numbers from 1 to 20?
#
# The answer to this problem is :
# 232792560
# The easiest solution is to print 2*2*2*2*3*3*5*7*11*13*17*19
# But here's the bruteforce method
def isEvenlyDivisibleByAllTheNumbersFrom1To20(n):
for i in range(1, 21):
if n % i:
return False
return True
def main():
i = 1
while 1:
print(i)
if isEvenlyDivisibleByAllTheNumbersFrom1To20(i):
print(i)
break
i += 1
if __name__ == '__main__':
print(2 * 2 * 2 * 2 * 3 * 3 * 5 * 7 * 11 * 13 * 17 * 19)
|
python
|
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import numpy as np
from communication import Communication
import math
from dataBase import data_base
from PyQt5.QtWidgets import QPushButton
pg.setConfigOption('background', (33, 33, 33))
pg.setConfigOption('foreground', (197, 198, 199))
# Interface variables
app = QtGui.QApplication([])
view = pg.GraphicsView()
Layout = pg.GraphicsLayout()
view.setCentralItem(Layout)
view.show()
view.setWindowTitle('Flight monitoring')
view.resize(1200, 700)
# declare object for serial Communication
ser = Communication()
# declare object for storage in CSV
data_base = data_base()
# Fonts for text items
font = QtGui.QFont()
font.setPixelSize(90)
# Title at top
text = """
Flight monitoring interface for cansats and OBC's <br>
developed at the Universidad Distrital FJC.
"""
Layout.addLabel(text, col=1, colspan=21)
Layout.nextRow()
# Put vertical label on left side
Layout.addLabel('LIDER - ATL research hotbed',
angle=-90, rowspan=3)
Layout.nextRow()
# Save data buttons
# buttons style
style = "background-color:rgb(29, 185, 84);color:rgb(0,0,0);font-size:14px;"
lb = Layout.addLayout(colspan=21)
proxy = QtGui.QGraphicsProxyWidget()
save_button = QtGui.QPushButton('Start storage')
save_button.setStyleSheet(style)
save_button.clicked.connect(data_base.start)
proxy.setWidget(save_button)
lb.addItem(proxy)
lb.nextCol()
proxy2 = QtGui.QGraphicsProxyWidget()
end_save_button = QtGui.QPushButton('Stop storage')
end_save_button.setStyleSheet(style)
end_save_button.clicked.connect(data_base.stop)
proxy2.setWidget(end_save_button)
lb.addItem(proxy2)
Layout.nextRow()
# Altitude graph
l1 = Layout.addLayout(colspan=20, rowspan=2)
l11 = l1.addLayout(rowspan=1, border=(83, 83, 83))
p1 = l11.addPlot(title="Altitude (m)")
altitude_plot = p1.plot(pen=(29, 185, 84))
altitude_data = np.linspace(0, 0, 30)
ptr1 = 0
def update_altitude(value_chain):
global altitude_plot, altitude_data, ptr1
altitude_data[:-1] = altitude_data[1:]
altitude_data[-1] = float(value_chain[1])
ptr1 += 1
altitude_plot.setData(altitude_data)
altitude_plot.setPos(ptr1, 0)
# Speed graph
p2 = l11.addPlot(title="Speed (m/s)")
vel_plot = p2.plot(pen=(29, 185, 84))
vel_data = np.linspace(0, 0, 30)
ptr6 = 0
vx = 0
vy = 0
vz = 0
vel = 0
def update_vel(value_chain):
global vel_plot, vel_data, ptr6, vx, vy, vz, vel
# 500 es dt
i = 0
if(i == 0):
vzo = float(value_chain[10])
i += 1
vx += (float(value_chain[8])) * 500
vy += (float(value_chain[9])) * 500
vz += (float(value_chain[10]) - vzo) * 500
sum = math.pow(vx, 2) + math.pow(vy, 2) + math.pow(vz, 2)
vel = math.sqrt(sum)
vel_data[:-1] = vel_data[1:]
vel_data[-1] = vel
ptr6 += 1
vel_plot.setData(vel_data)
vel_plot.setPos(ptr6, 0)
l1.nextRow()
l12 = l1.addLayout(rowspan=1, border=(83, 83, 83))
# Acceleration graph
acc_graph = l12.addPlot(title="Accelerations (m/s²)")
# adding legend
acc_graph.addLegend()
acc_graph.hideAxis('bottom')
accX_plot = acc_graph.plot(pen=(102, 252, 241), name="X")
accY_plot = acc_graph.plot(pen=(29, 185, 84), name="Y")
accZ_plot = acc_graph.plot(pen=(203, 45, 111), name="Z")
accX_data = np.linspace(0, 0)
accY_data = np.linspace(0, 0)
accZ_data = np.linspace(0, 0)
ptr2 = 0
def update_acc(value_chain):
global accX_plot, accY_plot, accZ_plot, accX_data, accY_data, accZ_data, ptr2
accX_data[:-1] = accX_data[1:]
accY_data[:-1] = accY_data[1:]
accZ_data[:-1] = accZ_data[1:]
accX_data[-1] = float(value_chain[8])
accY_data[-1] = float(value_chain[9])
accZ_data[-1] = float(value_chain[10])
ptr2 += 1
accX_plot.setData(accX_data)
accY_plot.setData(accY_data)
accZ_plot.setData(accZ_data)
accX_plot.setPos(ptr2, 0)
accY_plot.setPos(ptr2, 0)
accZ_plot.setPos(ptr2, 0)
# Gyro graph
gyro_graph = l12.addPlot(title="Gyro")
gyro_graph.hideAxis('bottom')
# adding legend
gyro_graph.addLegend()
pitch_plot = gyro_graph.plot(pen=(102, 252, 241), name="Pitch")
roll_plot = gyro_graph.plot(pen=(29, 185, 84), name="Roll")
yaw_plot = gyro_graph.plot(pen=(203, 45, 111), name="Yaw")
pitch_data = np.linspace(0, 0)
roll_data = np.linspace(0, 0)
yaw_data = np.linspace(0, 0)
ptr3 = 0
def update_gyro(value_chain):
global pitch_plot, roll_plot, yaw_plot, pitch_data, roll_data, yaw_data, ptr3
pitch_data[:-1] = pitch_data[1:]
roll_data[:-1] = roll_data[1:]
yaw_data[:-1] = yaw_data[1:]
pitch_data[-1] = float(value_chain[5])
roll_data[-1] = float(value_chain[6])
yaw_data[-1] = float(value_chain[7])
ptr3 += 1
pitch_plot.setData(pitch_data)
roll_plot.setData(roll_data)
yaw_plot.setData(yaw_data)
pitch_plot.setPos(ptr3, 0)
roll_plot.setPos(ptr3, 0)
yaw_plot.setPos(ptr3, 0)
# Pressure Graph
pressure_graph = l12.addPlot(title="Barometric pressure")
pressure_plot = pressure_graph.plot(pen=(102, 252, 241))
pressure_data = np.linspace(0, 0, 30)
ptr4 = 0
def update_pressure(value_chain):
global pressure_plot, pressure_data, ptr4
pressure_data[:-1] = pressure_data[1:]
pressure_data[-1] = float(value_chain[4])
ptr4 += 1
pressure_plot.setData(pressure_data)
pressure_plot.setPos(ptr4, 0)
# Temperature graph
graf_temp = l12.addPlot(title="Temperature (ºc)")
temp_plot = graf_temp.plot(pen=(29, 185, 84))
temp_data = np.linspace(0, 0, 30)
ptr5 = 0
def update_temp(value_chain):
global temp_plot, temp_data, ptr5
temp_data[:-1] = temp_data[1:]
temp_data[-1] = float(value_chain[3])
ptr5 += 1
temp_plot.setData(temp_data)
temp_plot.setPos(ptr5, 0)
# Time, battery and free fall graphs
l2 = Layout.addLayout(border=(83, 83, 83))
# Time graph
time_graph = l2.addPlot(title="Time (min)")
time_graph.hideAxis('bottom')
time_graph.hideAxis('left')
time_text = pg.TextItem("test", anchor=(0.5, 0.5), color="w")
time_text.setFont(font)
time_graph.addItem(time_text)
def update_time(value_chain):
global time_text
time_text.setText('')
tiempo = round(int(value_chain[0]) / 60000, 2)
time_text.setText(str(tiempo))
l2.nextRow()
# Battery graph
battery_graph = l2.addPlot(title="battery satus")
battery_graph.hideAxis('bottom')
battery_graph.hideAxis('left')
battery_text = pg.TextItem("test", anchor=(0.5, 0.5), color="w")
battery_text.setFont(font)
battery_graph.addItem(battery_text)
def update_battery(value_chain):
pass
l2.nextRow()
freeFall_graph = l2.addPlot(title="Free fall")
freeFall_graph.hideAxis('bottom')
freeFall_graph.hideAxis('left')
freeFall_text = pg.TextItem("test", anchor=(0.5, 0.5), color="w")
freeFall_text.setFont(font)
freeFall_graph.addItem(freeFall_text)
def update_freeFall(value_chain):
global freeFall_text
freeFall_text.setText('')
if(value_chain[2] == '0'):
freeFall_text.setText('No')
else:
freeFall_text.setText('Yes')
def update():
try:
value_chain = []
value_chain = ser.getData()
update_altitude(value_chain)
update_vel(value_chain)
update_time(value_chain)
update_acc(value_chain)
update_gyro(value_chain)
update_pressure(value_chain)
update_temp(value_chain)
update_freeFall(value_chain)
data_base.guardar(value_chain)
except IndexError:
print('starting, please wait a moment')
# desconozco si es necesario esto
# QtGui.QApplication.processEvents()
if(ser.isOpen()) or (ser.dummyMode()):
timer = pg.QtCore.QTimer()
timer.timeout.connect(update)
timer.start(500)
else:
print("something is wrong with the update call")
# Start Qt event loop unless running in interactive mode.
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
|
python
|
import sys
import click
import os
import datetime
from unittest import TestCase, main
from frigate.video import process_frames, start_or_restart_ffmpeg, capture_frames, get_frame_shape
from frigate.util import DictFrameManager, SharedMemoryFrameManager, EventsPerSecond, draw_box_with_label
from frigate.motion import MotionDetector
from frigate.edgetpu import LocalObjectDetector
from frigate.objects import ObjectTracker
import multiprocessing as mp
import numpy as np
import cv2
from frigate.object_processing import COLOR_MAP, CameraState
class ProcessClip():
def __init__(self, clip_path, frame_shape, config):
self.clip_path = clip_path
self.frame_shape = frame_shape
self.camera_name = 'camera'
self.frame_manager = DictFrameManager()
# self.frame_manager = SharedMemoryFrameManager()
self.frame_queue = mp.Queue()
self.detected_objects_queue = mp.Queue()
self.camera_state = CameraState(self.camera_name, config, self.frame_manager)
def load_frames(self):
fps = EventsPerSecond()
skipped_fps = EventsPerSecond()
stop_event = mp.Event()
detection_frame = mp.Value('d', datetime.datetime.now().timestamp()+100000)
current_frame = mp.Value('d', 0.0)
ffmpeg_cmd = f"ffmpeg -hide_banner -loglevel panic -i {self.clip_path} -f rawvideo -pix_fmt rgb24 pipe:".split(" ")
ffmpeg_process = start_or_restart_ffmpeg(ffmpeg_cmd, self.frame_shape[0]*self.frame_shape[1]*self.frame_shape[2])
capture_frames(ffmpeg_process, self.camera_name, self.frame_shape, self.frame_manager, self.frame_queue, 1, fps, skipped_fps, stop_event, detection_frame, current_frame)
ffmpeg_process.wait()
ffmpeg_process.communicate()
def process_frames(self, objects_to_track=['person'], object_filters={}):
mask = np.zeros((self.frame_shape[0], self.frame_shape[1], 1), np.uint8)
mask[:] = 255
motion_detector = MotionDetector(self.frame_shape, mask)
object_detector = LocalObjectDetector(labels='/labelmap.txt')
object_tracker = ObjectTracker(10)
process_fps = mp.Value('d', 0.0)
detection_fps = mp.Value('d', 0.0)
current_frame = mp.Value('d', 0.0)
stop_event = mp.Event()
process_frames(self.camera_name, self.frame_queue, self.frame_shape, self.frame_manager, motion_detector, object_detector, object_tracker, self.detected_objects_queue,
process_fps, detection_fps, current_frame, objects_to_track, object_filters, mask, stop_event, exit_on_empty=True)
def objects_found(self, debug_path=None):
obj_detected = False
top_computed_score = 0.0
def handle_event(name, obj):
nonlocal obj_detected
nonlocal top_computed_score
if obj['computed_score'] > top_computed_score:
top_computed_score = obj['computed_score']
if not obj['false_positive']:
obj_detected = True
self.camera_state.on('new', handle_event)
self.camera_state.on('update', handle_event)
while(not self.detected_objects_queue.empty()):
camera_name, frame_time, current_tracked_objects = self.detected_objects_queue.get()
if not debug_path is None:
self.save_debug_frame(debug_path, frame_time, current_tracked_objects.values())
self.camera_state.update(frame_time, current_tracked_objects)
for obj in self.camera_state.tracked_objects.values():
print(f"{frame_time}: {obj['id']} - {obj['computed_score']} - {obj['score_history']}")
self.frame_manager.delete(self.camera_state.previous_frame_id)
return {
'object_detected': obj_detected,
'top_score': top_computed_score
}
def save_debug_frame(self, debug_path, frame_time, tracked_objects):
current_frame = self.frame_manager.get(f"{self.camera_name}{frame_time}", self.frame_shape)
# draw the bounding boxes on the frame
for obj in tracked_objects:
thickness = 2
color = (0,0,175)
if obj['frame_time'] != frame_time:
thickness = 1
color = (255,0,0)
else:
color = (255,255,0)
# draw the bounding boxes on the frame
box = obj['box']
draw_box_with_label(current_frame, box[0], box[1], box[2], box[3], obj['label'], f"{int(obj['score']*100)}% {int(obj['area'])}", thickness=thickness, color=color)
# draw the regions on the frame
region = obj['region']
draw_box_with_label(current_frame, region[0], region[1], region[2], region[3], 'region', "", thickness=1, color=(0,255,0))
cv2.imwrite(f"{os.path.join(debug_path, os.path.basename(self.clip_path))}.{int(frame_time*1000000)}.jpg", cv2.cvtColor(current_frame, cv2.COLOR_RGB2BGR))
@click.command()
@click.option("-p", "--path", required=True, help="Path to clip or directory to test.")
@click.option("-l", "--label", default='person', help="Label name to detect.")
@click.option("-t", "--threshold", default=0.85, help="Threshold value for objects.")
@click.option("--debug-path", default=None, help="Path to output frames for debugging.")
def process(path, label, threshold, debug_path):
clips = []
if os.path.isdir(path):
files = os.listdir(path)
files.sort()
clips = [os.path.join(path, file) for file in files]
elif os.path.isfile(path):
clips.append(path)
config = {
'snapshots': {
'show_timestamp': False,
'draw_zones': False
},
'zones': {},
'objects': {
'track': [label],
'filters': {
'person': {
'threshold': threshold
}
}
}
}
results = []
for c in clips:
frame_shape = get_frame_shape(c)
config['frame_shape'] = frame_shape
process_clip = ProcessClip(c, frame_shape, config)
process_clip.load_frames()
process_clip.process_frames(objects_to_track=config['objects']['track'])
results.append((c, process_clip.objects_found(debug_path)))
for result in results:
print(f"{result[0]}: {result[1]}")
positive_count = sum(1 for result in results if result[1]['object_detected'])
print(f"Objects were detected in {positive_count}/{len(results)}({positive_count/len(results)*100:.2f}%) clip(s).")
if __name__ == '__main__':
process()
|
python
|
"""
This module performs all basic DFA operations.
It is an interface for pyfst.
"""
# /usr/bin/python
from operator import attrgetter
import fst
from alphabet import createalphabet
EPSILON = fst.EPSILON
def TropicalWeight(param):
"""
Returns fst TropicalWeight
Args:
param (str): The input
Returns:
bool: The arc weight
"""
return fst.TropicalWeight(param)
class FstDFA(fst.StdAcceptor):
"""
Contains extra method to consume input and produce outputs.
The underline library is pyfst, the python bindings of openFST library.
"""
def __init__(self, alphabet = createalphabet()):
"""
Args:
alphabet (list): pyfst input symbol list
Returns:
None
"""
isyms = None
self.alphabet = alphabet
fst.StdAcceptor.__init__(self, isyms)
num = 1
for char in self.alphabet:
self.isyms.__setitem__(char, num)
num = num + 1
def fixminimized(self, alphabet):
"""
After pyfst minimization,
all unused arcs are removed,
and all sink states are removed.
However this may break compatibility.
Args:
alphabet (list): The input alphabet
Returns:
None
"""
endstate = len(list(self.states))
for state in self.states:
for char in alphabet:
found = 0
for arc in state.arcs:
if self.isyms.find(arc.ilabel) == char:
found = 1
break
if found == 0:
self.add_arc(state.stateid, endstate, char)
self[endstate].final = TropicalWeight(float('inf'))
for char in alphabet:
self.add_arc(endstate, endstate, char)
def _addsink(self, alphabet):
"""
Adds a sink state
Args:
alphabet (list): The input alphabet
Returns:
None
"""
endstate = len(list(self.states))
for state in self.states:
for char in alphabet:
found = 0
for arc in state.arcs:
if self.isyms.find(arc.ilabel) == char:
found = 1
break
if found == 0:
self.add_arc(state.stateid, endstate, char)
self[endstate].final = TropicalWeight(float('inf'))
for char in alphabet:
self.add_arc(endstate, endstate, char)
def _path_to_str(self, path):
"""
Convert a path to the string representing the path
Args:
path (tuple): A tuple of arcs
Returns:
inp (str): The path concatenated as as string
"""
inp = ''
for arc in path:
i = self.isyms.find(arc.ilabel)
# Ignore \epsilon transitions both on input
if i != fst.EPSILON:
inp += i
return inp
def init_from_acceptor(self, acceptor):
"""
Adds a sink state
Args:
alphabet (list): The input alphabet
Returns:
None
"""
states = sorted(
acceptor.states,
key=attrgetter('initial'),
reverse=True)
for state in states:
for arc in state.arcs:
itext = acceptor.isyms.find(arc.ilabel)
if itext in self.alphabet:
self.add_arc(state.stateid, arc.nextstate, itext)
if state.final:
self[state.stateid].final = True
if state.initial:
self[state.stateid].initial = True
def consume_input(self, inp):
"""
Return True/False if the machine accepts/reject the input.
Args:
inp (str): input string to be consumed
Returns:
bool: A true or false value depending on if the DFA
accepts the provided input
"""
cur_state = sorted(
self.states,
key=attrgetter('initial'),
reverse=True)[0]
while len(inp) > 0:
found = False
for arc in cur_state.arcs:
if self.isyms.find(arc.ilabel) == inp[0]:
cur_state = self[arc.nextstate]
inp = inp[1:]
found = True
break
if not found:
return False
return cur_state.final != TropicalWeight(float('inf'))
def empty(self):
"""""
Return True if the DFA accepts the empty language.
"""
return len(list(self.states)) == 0
def random_strings(self, string_length=1):
"""
Generate string_length random strings that belong to the automaton.
Args:
string_length (integer): The size of the random string
Returns:
str: The generated string
"""
str_list = []
for path in self.uniform_generate(string_length):
str_list.append(self._path_to_str(path))
return str_list
def complement(self, alphabet):
"""
Generate the complement of a DFA automaton
Args:
alphabet (list): The input alphabet
Returns:
None
"""
self._addsink(alphabet)
states = sorted(self.states, key=attrgetter('initial'), reverse=True)
for state in states:
if state.final:
state.final = False
else:
state.final = True
def save(self, txt_fst_filename):
"""
Save the machine in the openFST format in the file denoted by
txt_fst_filename.
Args:
txt_fst_filename (str): The name of the file
Returns:
None
"""
txt_fst = open(txt_fst_filename, 'w+')
states = sorted(self.states, key=attrgetter('initial'), reverse=True)
for state in states:
for arc in state.arcs:
itext = self.isyms.find(arc.ilabel)
otext = self.osyms.find(arc.ilabel)
txt_fst.write(
'{}\t{}\t{}\t{}\n'.format(
state.stateid,
arc.nextstate,
itext.encode('hex'),
otext.encode('hex')))
if state.final:
txt_fst.write('{}\n'.format(state.stateid))
txt_fst.close()
def load(self, txt_fst_filename):
"""
Save the transducer in the text file format of OpenFST.
The format is specified as follows:
arc format: src dest ilabel olabel [weight]
final state format: state [weight]
lines may occur in any order except initial state must be first line
Args:
txt_fst_filename (string): The name of the file
Returns:
None
"""
with open(txt_fst_filename, 'r') as txt_fst:
for line in txt_fst:
line = line.strip()
splitted_line = line.split()
if len(splitted_line) == 1:
self[int(splitted_line[0])].final = True
else:
self.add_arc(int(splitted_line[0]), int(
splitted_line[1]), splitted_line[2].decode('hex'))
|
python
|
from singlecellmultiomics.universalBamTagger.digest import DigestFlagger
from singlecellmultiomics.tagtools import tagtools
class NlaIIIFlagger(DigestFlagger):
def __init__(self, **kwargs):
DigestFlagger.__init__(self, **kwargs)
def addSite(self, reads, strand, restrictionChrom, restrictionPos):
if not reads[0].has_tag(
self.sampleTag) or not reads[0].has_tag(
self.umiTag):
return
sample = reads[0].get_tag(self.sampleTag)
umi = reads[0].get_tag(self.umiTag)
allele = None if not reads[0].has_tag(
self.alleleTag) else reads[0].get_tag(
self.alleleTag)
siteInfo = tuple([x for x in [strand, allele, umi] if x is not None])
moleculeId = self.increaseAndRecordOversequencing(
sample, restrictionChrom, restrictionPos, siteInfo=siteInfo)
for read in reads:
if read is None:
continue
self.setSiteOversequencing(read, moleculeId)
self.setSiteCoordinate(read, restrictionPos)
self.setSource(read, 'NLA'), {}
if allele is not None:
self.setAllele(read, allele)
self.setStrand(read, '+' if strand ==
1 else ('-' if strand == 0 else '?'))
def digest(self, reads):
if len(reads) != 2:
if len(reads) == 1:
self.setRejectionReason(reads[0], 'unmapped mate')
else:
self.setRejectionReason(reads[0], 'nopair')
return None # Only made for mate pair
R1, R2 = reads
self.addAlleleInfo([read for read in reads if read is not None])
""" Valid configs:
CATG######## R1 ########## ^ ########## R2 ##########
############ R2 ########## ^ ########### R1 #####CATG reverse case
!BWA inverts the query sequence if it maps to the negative strand!
or R2.is_unmapped:
if R1.is_unmapped and R2.is_unmapped:
self.setRejectionReason(R1, 'unmapped R1;R2')
elif R1.is_unmapped:
self.setRejectionReason(R1, 'unmapped R1')
self.setRejectionReason(R2, 'unmapped R1')
else:
self.setRejectionReason(R1, 'unmapped R2')
self.setRejectionReason(R2, 'unmapped R2')
return(None)
"""
# Obtain RT hexamer:
if R2 is not None:
hstart, hseq = tagtools.getRandomPrimerHash(
R2, onStart=True, primerLength=6)
self.setRandomPrimer(R1, R2, hstart, hseq)
if R1 is None or R1.is_unmapped:
self.setRejectionReason(R1, 'unmapped R1')
self.setRejectionReason(R2, 'unmapped R1')
return None
if R1.seq[:4] == 'CATG' and not R1.is_reverse:
rpos = (R1.reference_name, R1.reference_start)
self.addSite([R1, R2], strand=0,
restrictionChrom=rpos[0], restrictionPos=rpos[1])
self.setRecognizedSequence(R1, 'CATG')
self.setRecognizedSequence(R2, 'CATG')
return(rpos)
elif R1.seq[-4:] == 'CATG' and R1.is_reverse:
rpos = (R1.reference_name, R1.reference_end - 4)
self.addSite([R1, R2], strand=1,
restrictionChrom=rpos[0], restrictionPos=rpos[1])
self.setRecognizedSequence(R1, 'CATG')
self.setRecognizedSequence(R2, 'CATG')
return(rpos)
# Sometimes the cycle is off
elif R1.seq[:3] == 'ATG' and not R1.is_reverse:
rpos = (R1.reference_name, R1.reference_start - 1)
self.addSite([R1, R2], strand=0,
restrictionChrom=rpos[0], restrictionPos=rpos[1])
self.setRecognizedSequence(R1, 'ATG')
self.setRecognizedSequence(R2, 'ATG')
return(rpos)
elif R1.seq[-3:] == 'CAT' and R1.is_reverse: # First base was trimmed or lost
rpos = (R1.reference_name, R1.reference_end - 3)
self.addSite([R1, R2], strand=1,
restrictionChrom=rpos[0], restrictionPos=rpos[1])
self.setRecognizedSequence(R1, 'CAT')
self.setRecognizedSequence(R2, 'CAT')
return(rpos)
else:
if R1.seq[:4] == 'CATG' and R1.is_reverse:
self.setRejectionReason(R1, 'found CATG R1 REV exp FWD')
self.setRejectionReason(R2, 'found CATG R1 REV exp FWD')
elif R1.seq[-4:] == 'CATG' and not R1.is_reverse:
self.setRejectionReason(R1, 'found CATG R1 FWD exp REV')
self.setRejectionReason(R2, 'found CATG R1 FWD exp REV')
else:
self.setRejectionReason(R1, 'no CATG')
self.setRejectionReason(R2, 'no CATG')
return None
try:
start, end = tagtools.getPairGenomicLocations(
R1, R2, R1PrimerLength=4, R2PrimerLength=6)
self.setFragmentSize(R1, end - start)
self.setFragmentSize(R2, end - start)
self.setFragmentTrust(R1, start, end)
self.setFragmentTrust(R2, start, end)
except Exception as e:
self.setFragmentSize(R1, 'unknown')
self.setFragmentSize(R2, 'unknown')
"""
if R1.seq[:4]=='CATG' and R1.reference_start<=R2.reference_start: # Site on the start of R1, R2 should map behind
self.addSite( [R1,R2], strand=0, restrictionChrom=R1.reference_name, restrictionPos=R1.reference_start )
return(( R1.reference_name, R1.reference_start))
if R1.seq[-4:]=='CATG' and R1.reference_start>=R2.reference_start: # Site on the end of R1, R2 should map before
self.addSite( [R1,R2], strand=1, restrictionChrom=R1.reference_name, restrictionPos=R1.reference_end-4 )
return( (R1.reference_name, R1.reference_end-4))
"""
|
python
|
#!/usr/bin/env python2
import sys
import time
import logging
import argparse
def main():
"""
Tumor Map Calc Agent
"""
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument("-i", "--interval", type=int, default=0,
help="Minutes between calc, default calc once and exits")
args = parser.parse_args()
while True:
start = time.time()
logging.info("Starting calc at {}".format(time.asctime(time.localtime(start))))
try:
logging.info("Do something here")
end = time.time()
logging.info("Finished calc at {} taking {} seconds".format(
time.asctime(time.localtime(end)), end - start))
except Exception as e:
logging.error("Problems calc: {}".format(e))
if args.interval:
logging.info("Sleeping for {} minutes...".format(args.interval))
time.sleep(args.interval * 60)
else:
break
if __name__ == '__main__':
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
main()
|
python
|
# -*- coding: utf-8 -*-
"""SOG run processor.
Do various operations related to running the the SOG bio-physical
model of deep estuaries. Most notably, run the model.
This module provides services to the SOG command processor.
:Author: Doug Latornell <[email protected]>
:License: Apache License, Version 2.0
Copyright 2010-2014 Doug Latornell and The University of British Columbia
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
)
import os
from tempfile import NamedTemporaryFile
from textwrap import TextWrapper
from time import sleep
from .infile_processor import create_infile
__all__ = ['dry_run', 'prepare', 'watch_outfile']
def prepare(args):
"""Return the command line string that will execute the requested SOG run.
"""
if not args.outfile:
args.outfile = os.path.abspath(os.path.basename(args.infile) + '.out')
if not os.path.exists(args.infile):
raise IOError('infile not found: {0.infile}'.format(args))
else:
if args.legacy_infile:
infile = args.infile
else:
if args.dry_run:
infile = NamedTemporaryFile(suffix='.infile').name
else:
infile = create_infile(args.infile, args.editfile)
if not os.path.exists(args.SOG_exec):
raise IOError('SOG executable not found: {0.SOG_exec}'.format(args))
else:
cmd = (
'nice -n {0.nice} {0.SOG_exec} < {infile} > {0.outfile} 2>&1'
.format(args, infile=infile))
return cmd
def dry_run(cmd, args):
"""Dry-run handler for `SOG run` command.
"""
wrapper = TextWrapper()
print(wrapper.fill('Command that would have been used to run SOG:'))
print(' {0}'.format(cmd))
if args.watch:
print(wrapper.fill(
'Contents of {0} would have been shown on screen while '
'SOG run was in progress.'.format(args.outfile))
)
def watch_outfile(proc, outfile_name):
"""Generator that yields lines from SOG run outfile while run is
in progress, and continues yielding the lines that are flushed
when the run finishes.
"""
# Wait for the SOG process to create the outfile
sleep(0.1)
with open(outfile_name) as outfile:
while proc.poll() is None:
# Echo lines flushed to outfile while SOG is running
line = outfile.readline()
if not line:
sleep(0.1)
continue
yield line
else:
# Echo lines flushed to outfile when SOG run finishes
for line in outfile:
yield line
|
python
|
import datetime
from dataclasses import asdict
from dataclasses import dataclass
from dataclasses import field
from enum import Enum
from typing import List
from typing import Union
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
from pglet import BarChart
from pglet import Checkbox
from pglet import Dialog
from pglet import Form
from pglet import SpinButton
from pglet import Stack
from pglet import Text
from pglet.barchart import Point
from pydantic import BaseModel
from pydantic import EmailStr
from pydantic import Field
try:
from replit import db
except ImportError:
db = dict()
class Content:
def introduction(self):
"""
# Easy web development for Python developers
Web technologies are available everywhere, and they seem like a good way to create a graphical user interface
for your Python application, either on the desktop or on the web. Unfortunately, most Python coders like
Python, and would like to avoid using a lot of other languages (HTML, Javascript and CSS) just to get a UI
created.
Pglet ("pagelet") is a web server that is written in Go and uses Fluent UI React components. Actual applications
("clients") provide the content and react to events using a proprietary protocol.
None of the above is visible to a Python developer, since the server comes nicely bundled in the client install.
All you need is:
`pip install pglet`
and you are off to creating a web-enabled UI in pure Python (3.7+).
As a taste of what pglet-python code looks like, this is the code for the box on the right:
[code]
```
pglet.page().add(main_view)
```
As another example, this site has also been created with pglet-python, with no HTML and no CSS in the code.
For more details, supported controls and a tutorial, see the [pglet Python docs](https://pglet.io/docs/).
# Easy forms
One of the most-repeated type of UI is some kind of form for entering and updating information. While creating
forms is easy in pglet, it is nevertheless a task that provides little programming joy. The next pages
show how to create forms using a Form control that eats annotated Python classes, for example, Python's
[dataclasses](https://docs.python.org/3/library/dataclasses.html).
# Easy forms with validation
Typically you also need to somehow validate user input before you can use it for anything: you need to check
that necessary values have been provided, check that numbers are numbers, check dates etc.
You can avoid this repetitive code by giving the Form control a [pydantic](https://pydantic-docs.helpmanual.io/)
object. Validation defined on the object is performed before the data is returned to you. In some cases,
you can use the exact same data definition with your APIs (e.g. FastAPI) or when writing to a document or SQL
data store.
"""
from pglet import Image, Stack, Text
main_view = Stack(
horizontal_align="center",
padding=20, gap=20,
controls=[
Image(width="50%", src="https://www.python.org/static/img/[email protected]"),
Image(width="30%", src="https://pglet.io/img/logo_dark.svg"),
Text(value="pydantic", bold=True, size="xxLarge"),
],
)
return main_view
def data_first_forms(self):
"""
Using the Form control, form definition focuses on the data you need out of it, so we define a class with
necessary information as attributes, information types as annotations, and default values as assignements.
Python dataclasses are convenient for this, as we do not need to spend time creating the `__init__` and other
boilerplate.
To create the form, all we need to do is give the class definition to the Form control:
[code]
You can see the resulting form on the right. Change values, and click "OK" to see the data you would get.
Form control understands the following data types explicitly, others will be by default be represented with a
basic text box on the form:
- str (see later for how you can decide between single line and multiline controls for text)
- int
- float
- bool
- datetime
- date (current DatePicker timezone restrictions prevent using it here)
- time
- Decimal (current SpinButton restrictions prevent using it here)
"""
@dataclass
class DataclassDataModel:
name: str = "Dataclass Person"
birthdate: datetime.datetime = "2000-01-01"
address: str = "Some Street 1, Some Town, Some Country"
age: int = 33
happy_today: bool = True
email: str = "[email protected]"
def show_data_on_submit(event):
event.control.page.add(Dialog(
open=True,
title="Submitted data",
blocking=True,
controls=[
Text(value=str(event.control.value.__dict__))
]
))
form = Form(
value=DataclassDataModel,
width=500,
on_submit=show_data_on_submit
)
return form
data_first_forms.display_name = "Data-first forms"
def selecting_values(self):
"""
Python enums are supported for selecting from a specific set of values.
[code]
"""
class ContactOption(str, Enum):
EMAIL = 'email'
PHONE = 'phone'
@dataclass
class DataclassDataModel:
name: str = "Dataclass Person"
ok_to_contact: bool = True
contact_option: ContactOption = ContactOption.EMAIL
return Form(value=DataclassDataModel, width=500, on_submit=show_submitted_data)
def more_values(self):
"""
If there are more than 3 values, we switch to a dropdown. The threshold is configurable with the
`threshold_for_dropdown` Form attribute.
"""
class ContactOption(str, Enum):
EMAIL = 'email'
PHONE = 'phone'
MESSAGE = 'message'
DOVE = 'dove'
@dataclass
class DataclassDataModel:
name: str = "Dataclass Person"
ok_to_contact: bool = True
contact_option: ContactOption = ContactOption.EMAIL
return Form(value=DataclassDataModel, width=500, on_submit=show_submitted_data)
def selecting_multiple_values(self):
"""
Annotating a field with a **list** of enums allows for multiple selection.
[code]
"""
class ContactOption(str, Enum):
EMAIL = "email"
PHONE = "phone"
PIGEON = "pigeon"
SMOKE_SIGNALS = "smoke signals"
@dataclass
class DataclassDataModel:
contact_option: List[ContactOption] = field(
default_factory=lambda: [ContactOption.EMAIL]
)
return Form(value=DataclassDataModel, width=500, on_submit=show_submitted_data)
def lists_of_fields(self):
"""
Field with a list annotation of other type than an enum is turned into a list control.
"""
@dataclass
class DataclassDataModel:
alphabet: List[str] = field(
default_factory=lambda: ["a", "b", "c"]
)
return Form(value=DataclassDataModel, width=500, on_submit=show_submitted_data)
def nested_class_definitions(self):
"""
Often we need to reuse parts of data structures. Form control supports nested class definitions, like `Movie`
in the example below.
[code]
"""
@dataclass
class Movie:
title: str
year: int
@dataclass
class DataclassDataModel:
name: str = "Dataclass Person"
email: str = "[email protected]"
favorite_movie: Movie = Movie(
title="My Little Pony: The Movie",
year=2017,
)
return Form(value=DataclassDataModel, width=500, on_submit=show_submitted_data)
def several_nested_objects(self):
"""
Several nested objects are supported with a List annotation. Lists rely on a sensible `str()` implementation to
display nicely, open up in a separate panel for editing, and support adding and deleting items.
[code]
Note that to support adding more movies, we need to provide default values for Movie attributes.
"""
@dataclass
class Movie:
title: str = ""
year: int = 2000
def __str__(self):
return f"{self.title} ({self.year})"
movies = [
Movie(title="The Name of the Rose", year=1986),
Movie(title="My Little Pony: The Movie", year=2017),
]
@dataclass
class DataclassDataModel:
name: str = "Dataclass Person"
email: str = "[email protected]"
favorite_movies: List[Movie] = field(default_factory=lambda: movies)
return Form(value=DataclassDataModel, width=500, on_submit=show_submitted_data)
def styling_and_dimensions(self):
"""
Form is a Stack control, and inherits all the
[attributes of Stacks](https://pglet.io/docs/controls/stack#properties).
You can toggle the switch on the left to experiment with the light and dark themes.
Example below shows using:
- `title` to add a form title at the top,
- `control_style` to define an alternative general style, with underlined text boxes,
- `toggle_for_bool` to use a toggle instead of a checkbox for boolean values, and
- a standard Stack attribute `gap` to add extra space between the lines.
[code]
"""
@dataclass
class DataclassDataModel:
name: str = "Dataclass Person"
birthdate: datetime.date = "2000-01-01"
address: str = "Some Street 1, Some Town, Some Country"
age: int = 33
happy_today: bool = True
email: str = "[email protected]"
form = Form(
value=DataclassDataModel,
title="Your information",
control_style="line",
toggle_for_bool=True,
gap=24,
width=500,
on_submit=show_submitted_data,
)
return form
def customizing_controls(self):
"""
There are several ways to customize controls in a `Form`:
1. Additional parameters for a specific field, as part of the data definition
2. Additional parameters for a specific field, in an `__init__` parameter
3. Map a data type to a specific control, for a single form
4. Map a data type to a specific control, globally
Example below covers the first 3:
1. For dataclasses, the contents of the pglet metadata dictionary is passed as parameters for the control.
Here we turn a single-line Textbox into a multiline one.
2. If you do not want to mix your data model with UI specifics, you can pass a parameter to the Form,
containing extra control initialization kwargs by field name.
3. If you want to set all fields of a type to be mapped to a specific control, provide additional type to
control mappings to Form. Here we want all `Amount`s have two decimals in the UI.
[code]
For option #4, you can set a type/control mapping globally by updating the mapping in the `Form` class directly,
like this:
```
Form.default_data_to_control_mapping["Amount"] = partial(
SpinButton, step=.01,
)
```
... or, of course, by subclassing the Form and setting values in the subclass `__init__`.
"""
from dataclasses import field
from functools import partial
from typing import NewType
Amount = NewType('Amount', float)
@dataclass
class DataclassDataModel:
item: str = field(
default="",
metadata={"pglet": {
"multiline": True # <<< 1
}}
)
description: str = ""
amount: Amount = Amount(0)
form = Form(
value=DataclassDataModel,
control_kwargs={
'description': {'multiline': True} # <<< 2
},
control_mapping={
"Amount": partial( # <<< 3
SpinButton, step=.01,
)
},
width=500,
on_submit=show_submitted_data,
)
return form
def introducing_pydantic(self):
"""
Pydantic is not a dependency of pglet nor of the Form control, so you need to install it separately with:
```
pip install pydantic
```
If you need validation of email addresses, you should also install:
```
pip install pydantic[email]
```
Once you have pydantic, your data can inherit from `pydantic.BaseModel` instead of being decorated as a `dataclass`.
[code]
Next pages will cover the benefits of having pydantic in place.
"""
from pydantic import BaseModel
class PydanticDataModel(BaseModel):
name: str = "Pydantic Person"
email: str = "[email protected]"
return Form(value=PydanticDataModel(), width=500, on_submit=show_submitted_data)
def change_the_labels(self):
"""
Normally, the labels on each line derived from the attribute names in your data. If you need something
different, for example punctuation, use `Field.title`.
[code]
See pydantic docs for the full documentation on the
[Field function](https://pydantic-docs.helpmanual.io/usage/schema/#field-customization).
"""
from pydantic import Field
class PydanticDataModel(BaseModel):
name: str = "Pydantic Person"
happy: bool = Field(True, title="Are you happy today?")
return Form(value=PydanticDataModel(), width=500, on_submit=show_submitted_data)
def placeholders(self):
"""
If an input does not have text, a placeholder is shown, defined by `Field.description`.
"""
class PydanticDataModel(BaseModel):
name: str = "Pydantic Person"
email: str = Field("", description="Enter a valid email address")
return Form(value=PydanticDataModel(), width=500, on_submit=show_submitted_data)
def customizing_pydantic_fields(self):
"""
Pydantic equivalent of the `dataclasses.field.metadata["pglet"]` is `Field.pglet`.
Here we use this option for the `notes` attribute to get a multiline `Textbox`.
[code]
"""
class PydanticDataModel(BaseModel):
name: str = "Pydantic Person"
notes: str = Field("", pglet={'multiline': True})
return Form(value=PydanticDataModel(), width=500, on_submit=show_submitted_data)
def validation(self):
"""
Main benefit of adding pydantic is that get your data validated with the minimum of boilerplate code.
Experiment with this view to see how the validation works.
[code]
Errors are pydantic validation errors, in English.
Check pydantic documentation on the available
[validating field types](https://pydantic-docs.helpmanual.io/usage/types/) and their usage.
Form control currently maps the field types below to specific controls - everything else is a Textbox.
- ConstrainedDecimal
- ConstrainedFloat
- ConstrainedInt
- EmailStr
- FutureDate
- NegativeFloat
- NegativeInt
- PastDate
- PositiveFloat
- PositiveInt
- StrictBool
- StrictFloat
- StrictInt
"""
from pydantic import conint
from pydantic import EmailStr
class PydanticDataModel(BaseModel):
name: str = "Pydantic Person"
birthdate: datetime.date = "2000-01-01"
age: conint(ge=0, lt=150) = 0
email: EmailStr = Field("", description="Enter a valid email address")
return Form(value=PydanticDataModel(), width=500, on_submit=show_submitted_data)
def cross_field_validation(self):
"""
Pydantic supports defining more complex relationships between fields.
In this example, email must be filled (and a valid email) if newsletters have been requested.
If validator returns an error, the capitalised str value of the error is shown to the user as the error
message under the field. Pydantic standard validation errors are in English.
[code]
Again, pydantic docs contain a lot more information about
[validators](https://pydantic-docs.helpmanual.io/usage/validators/).
"""
from pydantic import validator
class PydanticDataModel(BaseModel):
name: str = "Pydantic Person"
newsletter_ok: bool = Field(
False, title="Send me the monthly newsletter"
)
email: Union[EmailStr, Literal[""]] = Field("", description="Valid email needed for newsletter")
@validator('email', pre=True, allow_reuse=True)
def email_filled_if_needed(cls, value, values):
if values.get("newsletter_ok") and not value:
raise ValueError("Need email for newsletter")
return value
return Form(value=PydanticDataModel(), width=500, on_submit=show_submitted_data)
cross_field_validation.display_name = "Cross-field validation"
def status(self):
"""
The status of the Form control is: **early Proof of Concept for discussion and feedback**
*Some* todo items remain.
[no code]
"""
todo = '''
Ordering of lists
Slider option for number ranges
Proper Documentation
Responsive layout
Align/integrate with Grid control
Dates with DatePicker
Manage decimal.Decimal values
'''
done = '''
Lists for basic types
Toggle as an alternative for Checkbox
Support custom control parameters (e.g. multiline)
Support customising controls for types
Multiple selection from enums
Some tests
Documentation in the shape of this demo
'''
return Stack(
padding=20,
width=400,
controls=[
Checkbox(label=label.strip(), value=False, disabled=True)
for label in todo.strip().splitlines()
] + [
Checkbox(label=label.strip(), value=True, disabled=True)
for label in done.strip().splitlines()
]
)
def grande_finale(self):
"""
As one last thing, let's combine the Form control, replit database utility and the pglet graph control into a
quick poll.
Please select the options you are interested in and click "OK".
[code]
The `db` object here is a replit database that is essentially a dict with per-program persistent contents.
"""
@dataclass
class PollData:
pglet: bool = False
python: bool = False
pglet_with_python: bool = False
pglet_with_some_other_language: bool = False
pglet_with_forms: bool = False
pydantic: bool = False
pydantic_form_validation: bool = False
chart = BarChart(
data_mode='fraction',
padding=20,
width=210,
points=[]
)
def update_chart():
chart.points.clear()
values = list(reversed(sorted(
[
(field, db.get(field, 0))
for field in PollData.__annotations__
if field != "answers"
],
key=lambda value: value[1]
)))
max_value = values[0][1]
for field, value in values:
display_name = field.replace("_", " ").capitalize()
chart.points.append(
Point(legend=display_name, x=value, y=max_value),
)
update_chart()
poll = Form(
value=PollData,
title="I am interested in...",
width=300,
label_width="100%",
control_width="fit-content",
)
def update_db_values(event):
value = event.control.value
for key, value in asdict(value).items():
if value:
db[key] = db.get("key", 0) + 1
db["answers"] = db.get("answers", 0) + 1
update_chart()
poll.submit_button.disabled = True
event.control.page.update()
poll.on_submit = update_db_values
stack = Stack(controls=[poll, chart])
return stack
grande_finale.display_name = "Grande Finale"
def show_submitted_data(event):
value = event.control.value
event.control.page.add(Dialog(open=True, title="Submitted data", blocking=True, controls=[
Text(value=str(value.__dict__))
]))
content = [value for attribute, value in Content.__dict__.items() if callable(value)]
|
python
|
from .home import bp as home
from .dashboard import bp as dashboard
from .api import bp as api
# the .home syntax direct the program to find the module name home then import BP routes.
|
python
|
"""A class to hold data parsed from PDFs."""
import dataclasses
@dataclasses.dataclass
class Datum:
"""A class to hold data parsed from PDFs."""
text: str = ""
traits: list[dict] = dataclasses.field(default_factory=list)
reject: bool = False
|
python
|
import sounddevice as sd
from scipy.io import wavfile
from scipy import signal
import sys
import matplotlib.pyplot as plt
import os
import subprocess as sp
from collections import defaultdict, Counter
import pyprind
import numpy as np
import random
from .utils import readwav
output_seconds = 5
n_gram = 2
fname = 'Night_And_Day.flac'
fs, data, outname = readwav(fname)
def show_pcm(d):
x = np.arange(d.shape[0])
plt.plot(x, d)
plt.ylabel('PCM')
plt.xlabel('Time [sec]')
plt.show()
def show_spectrogram(d):
# from matplotlib.pyplot import specgram
# specgram(d, NFFT=256, Fs=fs)
f, t, Sxx = signal.spectrogram(d, fs, nperseg=256)
plt.pcolormesh(t, f, Sxx)
plt.ylabel('Frequency [Hz]')
plt.xlabel('Time [sec]')
plt.show()
def show_fft(d):
fft = np.fft.fft(d)
x = np.arange(d.shape[0])
plt.plot(x, fft)
plt.ylabel('FFT')
plt.xlabel('Time [sec]')
plt.show()
sample = data[fs * 70:fs * 80]
wavfile.write('sample.wav', fs, sample)
# sd.play(sample, fs, blocking=True)
# show_pcm(data)
# show_fft(data)
show_spectrogram(data)
if input("cont: ").lower() == 'n':
exit()
output_frames = fs * output_seconds
print(fs)
# data = np.fft.fft(data)
def find_ngrams(input_list, n):
return zip(*[input_list[i:] for i in range(n)])
# for each step, take each pair an
transitionsL = defaultdict(Counter)
# transitionsR = defaultdict(Counter)
bs = 1
# sd.play(sample, fs, blocking=True)
print("Training")
prog = pyprind.ProgBar(sample.shape[0], stream=1)
for gram in find_ngrams(sample, n_gram):
# learn the difference between each step given a history
transitionsL[gram[0]][gram[1] - gram[0]] += 1
prog.update()
# transitionsR[gram[0][1]][gram[1][1]] += 1
generated = np.zeros_like(data[:output_frames])
# choose a random starting frame from the transition table
# stateL = np.random.choice(list(transitionsL.keys()))
all_states = list(transitionsL.keys())
stateL = random.choice(all_states)
prog = pyprind.ProgBar(output_frames + 1, width=64, stream=1)
print("\nGenerating")
restarts = 0
for i in range(output_frames):
node = transitionsL[stateL]
if len(node) == 0:
restarts += 1
stateL = random.choice(all_states)
node = transitionsL[stateL]
counts = np.array(list(node.values()), dtype=np.float32)
keys = list(node.keys())
key_idxs = np.arange(len(keys))
ps = counts / counts.sum()
col_idx = np.random.choice(key_idxs, p=ps)
generated[i] = stateL + keys[col_idx]
generated[i] *= bs
stateL = stateL + keys[col_idx]
# stateR
prog.update()
print("Restarts={}".format(restarts / output_frames))
# generated = np.fft.ifft(generated).real
print("\nPlaying")
all_frames = np.concatenate((sample, generated))
sd.play(generated, fs, blocking=True)
print("Finished playing")
wavfile.write(outname, fs, all_frames)
print(sp.check_output([ffmpeg, '-i', outname, '-vn',
'-ar', '44100', '-ac', '2', '-ab', '192k', '-y', '-f', 'mp3', outname[:-4] + '.mp3']))
|
python
|
#!/usr/bin/python3.7
import subprocess
import sys
v = sys.argv[1]
subprocess.call(["amixer", "sset", "Speaker", v + "%"])
|
python
|
from PyQt5.QtWidgets import QWidget, QGridLayout, QComboBox, \
QLabel, QVBoxLayout, QSizePolicy, \
QCheckBox, QLineEdit, QPushButton, QHBoxLayout, \
QSpinBox, QTabWidget, QMessageBox
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtGui import QFont
from utils import HSep, VSep
from constants import COMP_MODE__QUALIFYING_LAPS, \
COMP_MODE__QUALIFYING_TIME, \
COMP_MODE__QUALIFYING_LAPS_SEQ, \
COMP_MODE__QUALIFYING_TIME_SEQ, \
COMP_MODE__RACE_LAPS, \
COMP_MODE__RACE_TIME, \
DUMMY_IDS
class CompTime(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.vbox = QVBoxLayout(self)
self.dtext = QLabel(self.tr('Duration in minutes:'))
self.vbox.addWidget(self.dtext)
self.duration = QSpinBox()
self.duration.setMinimum(1)
self.duration.setSuffix(self.tr(' Minutes'))
self.duration.setValue(10)
self.vbox.addWidget(self.duration)
self.setLayout(self.vbox)
class CompLaps(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.vbox = QVBoxLayout(self)
self.dtext = QLabel(self.tr('Duration in laps'))
self.vbox.addWidget(self.dtext)
self.duration = QSpinBox()
self.duration.setMinimum(1)
self.duration.setSuffix(self.tr(' Laps'))
self.duration.setValue(20)
self.vbox.addWidget(self.duration)
self.setLayout(self.vbox)
class RaceParams(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.vbox = QVBoxLayout(self)
self.modetab = QTabWidget()
self.vbox.addWidget(self.modetab)
self.complaps = CompLaps()
self.modetab.addTab(self.complaps, self.tr('Laps'))
self.comptime = CompTime()
self.modetab.addTab(self.comptime, self.tr('Time'))
self.setLayout(self.vbox)
def getCompMode(self):
if self.modetab.currentWidget() == self.complaps:
return COMP_MODE__RACE_LAPS
if self.modetab.currentWidget() == self.comptime:
return COMP_MODE__RACE_TIME
def getDuration(self):
if self.modetab.currentWidget() == self.complaps:
return self.complaps.duration.value()
if self.modetab.currentWidget() == self.comptime:
return self.comptime.duration.value()
class QualifyingParams(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.vbox = QVBoxLayout(self)
self.modetab = QTabWidget()
self.vbox.addWidget(self.modetab)
self.complaps = CompLaps()
self.modetab.addTab(self.complaps, self.tr('Laps'))
self.comptime = CompTime()
self.modetab.addTab(self.comptime, self.tr('Time'))
self.sequential = QCheckBox()
self.sequential.setText(self.tr('Sequential'))
self.vbox.addWidget(self.sequential)
self.setLayout(self.vbox)
def getCompMode(self):
if self.modetab.currentWidget() == self.complaps:
if self.sequential.isChecked():
return COMP_MODE__QUALIFYING_LAPS_SEQ
return COMP_MODE__QUALIFYING_LAPS
if self.modetab.currentWidget() == self.comptime:
if self.sequential.isChecked():
return COMP_MODE__QUALIFYING_TIME_SEQ
return COMP_MODE__QUALIFYING_TIME
def getDuration(self):
if self.modetab.currentWidget() == self.complaps:
return self.complaps.duration.value()
if self.modetab.currentWidget() == self.comptime:
return self.comptime.duration.value()
class ControllerSet(QWidget):
def __init__(self, parent=None, database=None):
super().__init__(parent)
self.database = database
self.controller = QGridLayout()
self.controller_ok = []
self.controller_name = []
self.controller_car = []
cars = self.database.getAllCars()
self.carlbl = self.tr('Select Car')
self.carsep = '---'
for i in range(0, 6):
ok = QCheckBox()
ok.setSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Maximum)
ok.setText(self.tr('Controller ') + str(i+1))
self.controller.addWidget(ok, 0, i)
self.controller_ok.append(ok)
name = QLineEdit()
name.setSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Maximum)
self.controller.addWidget(name, 1, i)
self.controller_name.append(name)
car = QComboBox()
car.addItem(self.carlbl)
car.addItem(self.carsep)
for c in cars:
car.addItem(c.name)
self.controller.addWidget(car, 2, i)
self.controller_car.append(car)
self.setLayout(self.controller)
def getCar(self, addr):
t = self.controller_car[addr].currentText()
if t in [self.carlbl, self.carsep]:
QMessageBox.information(
self,
self.tr("No car selected"),
str(self.tr("Please select a car for Controller ")
+ str(addr+1) + '.'),
QMessageBox.Ok)
raise KeyError
return self.controller_car[addr].currentText()
def getOk(self, addr):
return self.controller_ok[addr].isChecked()
def getName(self, addr):
name = self.controller_name[addr].text()
if name is None or len(name) <= 0:
QMessageBox.information(
self,
self.tr("Driver name missing"),
str(self.tr("Please enter a driver name for Controller ")
+ str(addr+1) + '.'),
QMessageBox.Ok)
raise KeyError
return name
def setCar(self, addr, car):
index = self.controller_car[addr].findText(car)
if index >= 0:
self.controller_car[addr].setCurrentIndex(index)
def setOk(self, addr, checked):
self.controller_ok[addr].setChecked(checked)
def setName(self, addr, name):
self.controller_name[addr].setText(name)
def buildCarList(self):
cars = self.database.getAllCars()
for i in range(0, 6):
cw = self.controller_car[i]
car = cw.currentText()
cw.clear()
cw.addItem(self.carlbl)
cw.addItem(self.carsep)
for c in cars:
cw.addItem(c.name)
index = cw.findText(car)
if index >= 0:
cw.setCurrentIndex(index)
class Home(QWidget):
def __init__(self, parent=None, database=None):
super().__init__(parent)
self.database = database
self.initUI()
def initUI(self):
self.controller = ControllerSet(self, self.database)
self.vml = QVBoxLayout()
self.vml.setSpacing(10)
self.headFont = QFont()
self.headFont.setPointSize(45)
self.headFont.setBold(True)
self.headline = QLabel(self.tr('Carrera RMS'))
self.headline.setFont(self.headFont)
self.vml.addWidget(self.headline)
self.vml.addWidget(HSep())
self.vml.addWidget(self.controller)
self.vml.addWidget(HSep())
self.starts = QHBoxLayout()
self.vml.addLayout(self.starts)
self.vml.addWidget(HSep())
self.start_training = QPushButton()
self.start_training.setText(self.tr('Training'))
self.start_training.clicked.connect(self.startTraining_click)
self.start_training.setSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Expanding)
self.starts.addWidget(self.start_training)
self.starts.addWidget(VSep())
self.qualifyingparams = QualifyingParams()
self.qualifyingparams.setSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Maximum)
self.qhbox = QVBoxLayout()
self.qhbox.addWidget(self.qualifyingparams)
self.start_qualifying = QPushButton()
self.start_qualifying.setText(self.tr('Qualifying'))
self.start_qualifying.clicked.connect(self.startQualifying_click)
self.start_qualifying.setSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Expanding)
self.qhbox.addWidget(self.start_qualifying)
self.starts.addLayout(self.qhbox)
self.starts.addWidget(VSep())
self.raceparams = RaceParams()
self.raceparams.setSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Maximum)
self.rhbox = QVBoxLayout()
self.rhbox.addWidget(self.raceparams)
self.start_race = QPushButton()
self.start_race.setText(self.tr('Race'))
self.start_race.clicked.connect(self.startRace_click)
self.start_race.setSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Expanding)
self.rhbox.addWidget(self.start_race)
self.starts.addLayout(self.rhbox)
self.btnrow = QHBoxLayout()
self.fullscreen = QPushButton()
self.fullscreen.setText(self.tr('Fullscreen'))
self.fullscreen.clicked.connect(self.fullscreen_click)
self.btnrow.addWidget(self.fullscreen)
self.statistics = QPushButton()
self.statistics.setText(self.tr('Statistics'))
self.btnrow.addWidget(self.statistics)
self.settings = QPushButton()
self.settings.setText(self.tr('Settings'))
self.settings.clicked.connect(self.settings_click)
self.btnrow.addWidget(self.settings)
self.vml.addLayout(self.btnrow)
self.exitrms = QPushButton()
self.exitrms.setText(self.tr('Exit'))
self.exitrms.clicked.connect(self.exitrms_click)
self.vml.addWidget(self.exitrms)
self.setLayout(self.vml)
@pyqtSlot()
def settings_click(self):
self.parent().parent().showSettings()
@pyqtSlot()
def exitrms_click(self):
self.parent().parent().close()
@pyqtSlot()
def fullscreen_click(self):
if self.parent().parent().windowState() & Qt.WindowFullScreen:
if self.parent().parent().cuv not in DUMMY_IDS:
self.parent().parent().showMaximized()
else:
self.parent().parent().showNormal()
self.fullscreen.setText(self.tr('Fullscreen'))
else:
self.parent().parent().showFullScreen()
self.fullscreen.setText(self.tr('Exit Fullscreen'))
def getDrivers(self):
d = {}
for i in range(0, 6):
if self.getOk(i):
c = self.getCar(i)
p = {'pos': 0, 'name': self.getName(i), 'car': c}
if self.qualifyingparams.getCompMode() in [
COMP_MODE__QUALIFYING_LAPS_SEQ,
COMP_MODE__QUALIFYING_TIME_SEQ]:
p['qualifying_cu_driver'] = None
d[i] = p
return d
@pyqtSlot()
def startRace_click(self):
try:
self.parent().parent().drivers = self.getDrivers()
self.parent().parent().startRace(self.raceparams.getCompMode(),
self.raceparams.getDuration())
except KeyError:
pass
@pyqtSlot()
def startQualifying_click(self):
try:
self.parent().parent().drivers = self.getDrivers()
self.parent().parent().startQualifying(
self.qualifyingparams.getCompMode(),
self.qualifyingparams.getDuration())
except KeyError:
pass
@pyqtSlot()
def startTraining_click(self):
try:
self.parent().parent().drivers = self.getDrivers()
self.parent().parent().startTraining()
except KeyError:
pass
def getCar(self, addr):
return self.controller.getCar(addr)
def getOk(self, addr):
return self.controller.getOk(addr)
def getName(self, addr):
return self.controller.getName(addr)
def setCar(self, addr, car):
self.controller.setCar(addr, car)
def setOk(self, addr, checked):
self.controller.setOk(addr, checked)
def setName(self, addr, name):
self.controller.setName(addr, name)
def buildCarList(self):
self.controller.buildCarList()
|
python
|
import twoLSTMcuda as t
model = t.torch.load(open("twoLSTMentireModel.npy", 'rb'))
print(t.checkAcc(model, t.data, t.labels))
print(t.checkAcc(model, t.valData, t.valLabels))
|
python
|
###
### Copyright (C) 2018-2019 Intel Corporation
###
### SPDX-License-Identifier: BSD-3-Clause
###
from ....lib import *
from ..util import *
import os
@slash.requires(have_ffmpeg)
@slash.requires(have_ffmpeg_vaapi_accel)
class TranscoderTest(slash.Test):
def before(self):
self.refctx = []
def transcode_1to1(self):
self.decoded = get_media()._test_artifact(
"{case}_{width}x{height}_{mode}.{dstextension}".format(**vars(self)))
if vars(self).get("mode", None) == 'hwhw':
self.output = call(
"ffmpeg -hwaccel vaapi -hwaccel_device /dev/dri/renderD128 -v verbose"
" -hwaccel_output_format vaapi -i {source} -an -c:v {mcodec}"
" -vframes {frames} -y {decoded}".format(**vars(self)))
elif vars(self).get("mode", None) == 'hwsw':
self.output = call(
"ffmpeg -hwaccel vaapi -hwaccel_device /dev/dri/renderD128 -v verbose"
" -hwaccel_output_format vaapi -i {source} -vf 'hwdownload,format=nv12' -an -c:v {mcodec}"
" -vframes {frames} -y {decoded}".format(**vars(self)))
elif vars(self).get("mode", None) == 'swhw':
self.output = call(
"ffmpeg -vaapi_device /dev/dri/renderD128 -v verbose "
"-i {source} -vf 'format=nv12,hwupload' -an -c:v {mcodec}"
" -vframes {frames} -y {decoded}".format(**vars(self)))
else:
assert "non supported transcoding"
self.check_output()
self.convert_toyuv()
self.check_metrics()
def check_output(self):
m = re.search(
"not supported for hardware decode", self.output, re.MULTILINE)
assert m is None, "Failed to use hardware decode"
m = re.search(
"hwaccel initialisation returned error", self.output, re.MULTILINE)
assert m is None, "Failed to use hardware decode"
def convert_toyuv(self):
self.decodedYUV = get_media()._test_artifact(
"{case}_{width}x{height}_{mode}_{mcodec}.yuv".format(**vars(self)))
call("ffmpeg -i {decoded} -pix_fmt yuv420p -vframes {frames} -y {decodedYUV}".format(**vars(self)))
#src file to yuv
self.referenceFile = get_media()._test_artifact(
"{case}_{width}x{height}_{mode}_ref.yuv".format(**vars(self)))
call("ffmpeg -i {source} -pix_fmt yuv420p -vframes {frames} -y {referenceFile}".format(**vars(self)))
def check_metrics(self):
get_media().baseline.check_psnr(
psnr = calculate_psnr(
self.referenceFile, self.decodedYUV,
self.width, self.height,
self.frames),
context = self.refctx,
)
|
python
|
from django.shortcuts import *
from django.http import *
from django.shortcuts import *
from django.urls import *
import traceback
import json
from .models import *
from django.db.utils import IntegrityError
from django.db.models import F
from .crypto import *
import math
from account_info.models import User
from wallet_info.models import Wallet
from task_info.models import Task
from accept_task_info.models import AcceptTask
# Create your views here.
MAX_PAGE_ITEMS = 6
def dealResponse(status_code, res_text={}):
traceback.print_exc()
dic = {
400 : 'Decode Failed',
406 : 'Verification Failed',
200 : 'Standard Successed',
201 : 'Create Resource Successed',
409 : 'Confict Field or MultipleAcceptance',
500 : 'Unknown Server Error',
404 : 'Not Exist',
416 : 'OutOfRange or CompletedTask',
401 : 'Unauthorized',
403 : 'TaskBeenFinished'
}
traceback.print_exc()
print('[+] ' + dic[status_code])
res_text['status_code'] = status_code
resp = HttpResponse(encrypt(json.dumps(res_text)))
# resp.status_code = status_code
return resp
def operate_task(request):
"""
if not request.method == 'GET' and not request.method == 'POST':
put = QueryDict(request.body)
id = put.get('taskID')
username = put.get('issuer')
print(put)
print(id)
print(username)
return dealResponse(200)
"""
if request.method == 'GET':
try:
id = decrypt(request.GET['taskID'])
except:
return dealResponse(400)
try:
result = Task.objects.get(taskID=id)
except Task.DoesNotExist:
return dealResponse(404)
res_text = {
'data':{
'title' : result.title,
'content' : result.content,
'type' : result.types,
'issuer' : result.issuer.username,
'reward' : result.reward,
'deadline' : result.deadline,
'repeatTime' : result.repeatTime,
'isCompleted' : result.isCompleted,
}
}
return dealResponse(200, res_text)
elif request.method == 'POST':
try:
raw_string = decrypt(str(request.body, 'utf-8'))
content = json.loads(raw_string)
ttitle = content['title']
tcontent = content['content']
ttype = content['type']
tissuer = content['issuer']
treward = content['reward']
trepeatTime = content['repeatTime']
tdeadline = content['deadline']
except:
return dealResponse(400)
try:
user = User.objects.get(username=tissuer)
except User.DoesNotExist:
return dealResponse(404)
task = Task(title=ttitle, content=tcontent, types=ttype,\
issuer=user, reward=treward, repeatTime=trepeatTime,\
deadline=tdeadline, )
task.save()
return dealResponse(201, {"data":{"taskID":task.taskID}})
"""
elif request.method == 'DELETE':
try:
id = decrypt(request.DELETE['taskID'])
username = decrypt(request.DELETE['issuer'])
except:
return dealResponse(400)
try:
result = Task.objects.get(taskID=id)
except Task.DoesNotExist:
return dealResponse(404)
if result.issuer.username != username:
return dealResponse(401)
result.isCompleted = True
result.save()
return dealResponse(200)
"""
def task_finished(request):
try:
# id = decrypt(request.POST['taskID'])
# username = decrypt(request.POST['issuer'])
raw_string = decrypt(str(request.body, 'utf-8'))
content = json.loads(raw_string)
id = content['taskID']
username = content['issuer']
except:
return dealResponse(400)
try:
result = Task.objects.get(taskID=id)
except Task.DoesNotExist:
return dealResponse(404)
if result.issuer.username != username:
return dealResponse(401)
result.isCompleted = True
result.save()
return dealResponse(200)
def get_tasks(request):
try:
page = int(decrypt(request.GET['page']))
title = decrypt(request.GET.get('title', default=''))
types = decrypt(request.GET.get('type', default=''))
issuer = decrypt(request.GET.get('issuer', default=''))
content = decrypt(request.GET.get('content', default=''))
isCompleted = decrypt(request.GET.get('isComplete', default=''))
except:
return dealResponse(400)
dic = {}
if title != '':
dic['title'] = title
if types != '':
dic['types'] = types
if issuer != '':
dic['issuer'] = issuer
if content != '':
dic['content'] = content
if isCompleted != '':
if isCompleted == 'true':
dic['isCompleted'] = True
elif isCompleted == 'false':
dic['isCompleted'] = False
result = Task.objects.filter(**dic)
# for item in result:
# print(item.taskID)
max_pages = math.ceil(float(len(result)) / MAX_PAGE_ITEMS)
if page > max_pages or page <= 0:
return dealResponse(416, {"data": {"max_pages": max_pages}})
page = page - 1
resp = {"data" : {
"tasks" : [],
"max_pages" : max_pages
}
}
startid = page * MAX_PAGE_ITEMS
endid = min(len(result), (page+1)*MAX_PAGE_ITEMS)
for i in range(startid, endid):
oner = {
"taskID": result[i].taskID,
"title": result[i].title,
"content": result[i].content,
"type": result[i].types,
"issuer": result[i].issuer.username,
"reward": result[i].reward,
"deadline": result[i].deadline,
"repeatTime": result[i].repeatTime,
# "isCompleted": result[i].isCompleted,
}
resp['data']['tasks'].append(oner)
return dealResponse(200, resp)
def operate_created_tasks(request):
if request.method == 'GET':
try:
page = int(decrypt(request.GET['page']))
tusername = decrypt(request.GET['issuer'])
except:
return dealResponse(400)
try:
fuser = User.objects.get(username=tusername)
except User.DoesNotExist:
return dealResponse(404)
result = Task.objects.filter(issuer=fuser)
max_pages = math.ceil(float(len(result)) / MAX_PAGE_ITEMS)
if page > max_pages or page <= 0:
return dealResponse(416, {"data": {"max_pages": max_pages}})
page = page - 1
resp = {"data" : {
"tasks" : [],
"max_pages" : max_pages
}
}
startid = page * MAX_PAGE_ITEMS
endid = min(len(result), (page+1)*MAX_PAGE_ITEMS)
for i in range(startid, endid):
oner = {
"taskID": result[i].taskID,
"title": result[i].title,
"content": result[i].content,
"type": result[i].types,
"issuer": result[i].issuer.username,
"reward": result[i].reward,
"deadline": result[i].deadline,
"repeatTime": result[i].repeatTime,
"isFinished": result[i].isCompleted,
}
resp['data']['tasks'].append(oner)
return dealResponse(200, resp)
elif request.method == 'POST':
try:
raw_string = decrypt(str(request.body, 'utf-8'))
content = json.loads(raw_string)
ttaskID = content['taskID']
ttitle = content['title']
tissuer = content['issuer']
treward = content['reward']
tdeadline = content['deadline']
except:
return dealResponse(400)
try:
task = Task.objects.get(taskID=ttaskID)
user = User.objects.get(username=tissuer)
except(Task.DoesNotExist, User.DoesNotExist):
return dealResponse(404)
if user != task.issuer:
return dealResponse(401)
task.title = ttitle
task.reward = treward
task.deadline = tdeadline
task.save()
return dealResponse(200)
|
python
|
#!/usr/bin/python
import unittest
from utils.logger import Logger
class UtLogger(unittest.TestCase):
def setUp(self):
self.logger = Logger().getLogger("test.utils.UtLogger")
def testLogger(self):
self.logger.debug("1")
self.logger.info("2")
self.logger.warn("3")
self.logger.error("4")
self.logger.critical("5")
if __name__ == '__main__': unittest.main()
|
python
|
from base_n_treble import db, auth
from base_n_treble.models.user import User
def setup_admin():
from tests.fixtures import TEST_ADMIN
db._adapter.reconnect()
admins = auth.id_group("admin") if auth.id_group("admin") else auth.add_group("admin")
print("Admin group id: '{}'".format(admins))
db._adapter.reconnect()
admin = db.User.validate_and_insert(
email=TEST_ADMIN.email,
first_name=TEST_ADMIN.first_name,
last_name=TEST_ADMIN.last_name,
password=TEST_ADMIN.password
)
db.commit()
db._adapter.reconnect()
auth.add_membership(admins, admin.id)
print("Admin created: \n{}".format(admin.as_dict()))
db.commit()
return admin
def remove_admin():
from tests.fixtures import TEST_ADMIN
db._adapter.reconnect()
print("\nRemoving test admin.")
dev_admin = db(User.email == TEST_ADMIN.email).select()
print("Admin: {}\n".format(dev_admin.as_dict()))
db(User.email == TEST_ADMIN.email).delete()
print("Test admin successfully deleted.")
db.commit()
def setup_user():
from tests.fixtures import TEST_USER
db._adapter.reconnect()
user = db.User.validate_and_insert(
email=TEST_USER.email,
first_name=TEST_USER.first_name,
last_name=TEST_USER.last_name,
password=TEST_USER.password
)
db.commit()
return user
def remove_user():
from tests.fixtures import TEST_USER
db._adapter.reconnect()
print("\nRemoving test user.")
dev_user = db(User.email == TEST_USER.email).select()
print("Admin: {}\n".format(dev_user.as_dict()))
db(User.email == TEST_USER.email).delete()
print("Test user successfully deleted.")
db.commit()
|
python
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash
from contextlib import closing
# configuration
DATABASE = "/tmp/flaskr.db"
DEBUG = True
SECRET_KEY = "development key"
USERNAME= "admin"
PASSWORD = "default"
JSON_AS_ASCII = False
app = Flask(__name__)
app.config.from_object(__name__)
def connect_db():
return sqlite3.connect(app.config["DATABASE"])
def init_db():
with closing(connect_db()) as db:
with app.open_resource("schema.sql", mode="r") as f:
db.cursor().executescript(f.read())
db.commit()
@app.before_request
def before_request():
g.db = connect_db()
@app.teardown_request
def teardown_request(exception):
db = getattr(g, "db", None)
if db is not None:
db.close()
@app.route("/")
def show_entries():
cur = g.db.execute("SELECT title, text FROM entries ORDER BY id DESC")
entries = [dict(title=row[0],text=row[1]) for row in cur.fetchall()]
return render_template("show_entries.html", entries=entries)
@app.route("/add", methods=["POST"])
def add_entry():
if not session.get("logged_in"):
abort(401)
g.db.execute("INSERT INTO entries (title, text) values (?, ?)", [request.form["title"], request.form["text"]])
g.db.commit()
flash(u"新しいエントリが投稿されました. New entry was successfully posted.")
return redirect(url_for("show_entries"))
@app.route("/login", methods=["GET", "POST"])
def login():
error = None
if request.method == "POST":
if request.form["username"] != app.config["USERNAME"]:
error = u"Invalid username, user nameが間違っています"
elif request.form["password"] != app.config["PASSWORD"]:
error = u"Invalid password, パスワードが間違っています"
else:
session["logged_in"] = True
flash(u"You were logged in, ログインしました")
return redirect(url_for("show_entries"))
return render_template("login.html", error=error)
@app.route("/logout")
def logout():
session.pop("logged_in", None)
flash(u"Your were logged out, ログアウトしました")
return redirect(url_for("show_entries"))
if __name__ == "__main__":
app.run()
|
python
|
#! /usr/bin/env python
import sys
import os
import disttools
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
from strparser import *
from filehdl import *
from pyparser import *
def make_string_slash_ok(s):
sarr = re.split('\n', s)
rets = ''
for l in sarr:
l = l.rstrip('\r\n')
cexpr = None
if len(l) > 0 and l[-1] == '\\':
cexpr = get_random_name(20)
cont = True
while cont:
cont = False
matchl = re.sub(cexpr, '', l)
if matchl != l:
cont = True
cexpr = get_random_name(20)
l = re.sub('\\$', cexpr, l)
l = re.sub(r'\\', r'\\\\', l)
if cexpr is not None:
l = re.sub(cexpr, r'\\', l)
rets += '%s\n'%(l)
return rets
def get_import_file(fname):
rets = ''
started = False
with open(fname,'r+b') as f:
for l in f:
if sys.version[0] == '3':
l = l.decode('utf8')
l = l.rstrip('\r\n')
if not started:
if l.startswith('##extractcode_start'):
started = True
else:
if l.startswith('##extractcode_end'):
started = False
else:
rets += l
rets += '\n'
return rets
def make_filters_out(ims,files):
cont = True
jdx = 0
idx = 0
while cont:
cont = False
idx = 0
while idx < len(ims) and not cont:
jdx = 0
while jdx < len(files) and not cont:
if ims[idx].frommodule == files[jdx]:
cont = True
logging.info('del [%d] jdx [%d] [%s]'%(idx,jdx,ims[idx]))
del ims[idx]
logging.info('%s'%(ims))
break
jdx += 1
idx += 1
return ims
def fromat_ext_import_files(origfile,files):
curbase = re.sub('\.py$','',os.path.basename(origfile))
allims = []
for f in files:
allims.extend(get_import_names(f))
curims= get_import_names(origfile)
curims = packed_import(curims)
curims = make_filters_out(curims, files)
logging.info('curims %s'%(curims))
allims = packed_import(allims)
allims = make_filters_out(allims, files)
logging.info('allims %s'%(allims))
cont = True
seccont = True
while cont:
cont = False
idx = 0
while idx < len(allims) :
jdx = 0
while jdx < len(curims) :
if allims[idx].frommodule == curims[jdx].frommodule and \
allims[idx].module == curims[jdx].module:
cont = True
#logging.info('del [%d] %s'%(idx,allims[idx]))
del allims[idx]
break
jdx += 1
if cont:
break
idx += 1
rets = ''
for m in allims:
rets += '%s\n'%(format_import(m))
return rets
class ReleaseFiles(object):
def __init__(self, basefile=__file__):
self.__includes = []
self.__basefile = basefile
self.__repls = dict()
return
def add_python_file(self,path,rex):
c = get_import_file(path)
self.__repls[rex] = make_string_slash_ok(c)
self.__includes.append(path)
return
def add_repls(self,k,v):
self.__repls[k]= v
return
def get_repls(self):
return self.__repls
def get_includes(self):
return self.__includes
|
python
|
import pytest
import abjad
import abjadext.nauert
class Job:
### INITIALIZER ###
def __init__(self, number):
self.number = number
### SPECIAL METHODS ###
def __call__(self):
self.result = [
x for x in abjad.math.yield_all_compositions_of_integer(self.number)
]
@pytest.mark.skip()
def test_ParallelJobHandler___call___01():
jobs = [Job(x) for x in range(1, 11)]
job_handler = abjadext.nauert.ParallelJobHandler()
job_handler(jobs)
@pytest.mark.skip()
def test_ParallelJobHandler___call___02():
job_id = 1
definition = {2: {2: {2: None}, 3: None}, 5: None}
search_tree = abjadext.nauert.UnweightedSearchTree(definition)
q_event_proxies = [
abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent(0, ["A"], index=1), 0, 1
),
abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent((1, 5), ["B"], index=2), 0, 1
),
abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent((1, 4), ["C"], index=3), 0, 1
),
abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent((1, 3), ["D"], index=4), 0, 1
),
abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent((2, 5), ["E"], index=5), 0, 1
),
abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent((1, 2), ["F"], index=6), 0, 1
),
abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent((3, 5), ["G"], index=7), 0, 1
),
abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent((2, 3), ["H"], index=8), 0, 1
),
abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent((3, 4), ["I"], index=9), 0, 1
),
abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent((4, 5), ["J"], index=10), 0, 1
),
abjadext.nauert.QEventProxy(
abjadext.nauert.SilentQEvent(1, ["K"], index=11), 0, 1
),
]
job_a = abjadext.nauert.QuantizationJob(job_id, search_tree, q_event_proxies)
job_b = abjadext.nauert.QuantizationJob(job_id, search_tree, q_event_proxies)
assert job_a == job_b
a_jobs = abjadext.nauert.SerialJobHandler()([job_a])
b_jobs = abjadext.nauert.ParallelJobHandler()([job_b])
assert len(a_jobs) == len(b_jobs)
a_rtms = sorted([q_grid.root_node.rtm_format for q_grid in a_jobs[0].q_grids])
b_rtms = sorted([q_grid.root_node.rtm_format for q_grid in b_jobs[0].q_grids])
assert a_rtms == b_rtms
assert sorted(a_jobs[0].q_grids, key=lambda x: x.root_node.rtm_format) == sorted(
b_jobs[0].q_grids, key=lambda x: x.root_node.rtm_format
)
|
python
|
"""
===========
04. Run ICA
===========
This fits ICA on epoched data filtered with 1 Hz highpass,
for this purpose only using fastICA. Separate ICAs are fitted and stored for
MEG and EEG data.
To actually remove designated ICA components from your data, you will have to
run 05a-apply_ica.py.
"""
import itertools
import logging
from typing import List, Optional, Iterable, Literal
from tqdm import tqdm
import pandas as pd
import numpy as np
import mne
from mne.report import Report
from mne.preprocessing import ICA, create_ecg_epochs, create_eog_epochs
from mne.parallel import parallel_func
from mne_bids import BIDSPath
import config
from config import make_epochs, gen_log_message, on_error, failsafe_run
logger = logging.getLogger('mne-bids-pipeline')
def filter_for_ica(
*,
raw: mne.io.BaseRaw,
subject: str,
session: str,
run: Optional[str] = None
) -> None:
"""Apply a high-pass filter if needed."""
if config.ica_l_freq is None:
msg = (f'Not applying high-pass filter (data is already filtered, '
f'cutoff: {raw.info["highpass"]} Hz).')
logger.info(gen_log_message(message=msg, step=4, subject=subject,
session=session, run=run))
else:
msg = f'Applying high-pass filter with {config.ica_l_freq} Hz cutoff …'
logger.info(gen_log_message(message=msg, step=4, subject=subject,
session=session, run=run))
raw.filter(l_freq=config.ica_l_freq, h_freq=None)
def fit_ica(epochs, subject, session):
algorithm = config.ica_algorithm
fit_params = None
if algorithm == 'picard':
fit_params = dict(fastica_it=5)
elif algorithm == 'extended_infomax':
algorithm = 'infomax'
fit_params = dict(extended=True)
ica = ICA(method=algorithm, random_state=config.random_state,
n_components=config.ica_n_components, fit_params=fit_params,
max_iter=config.ica_max_iterations)
ica.fit(epochs, decim=config.ica_decim, reject=config.get_ica_reject())
explained_var = (ica.pca_explained_variance_[:ica.n_components_].sum() /
ica.pca_explained_variance_.sum())
msg = (f'Fit {ica.n_components_} components (explaining '
f'{round(explained_var * 100, 1)}% of the variance) in '
f'{ica.n_iter_} iterations.')
logger.info(gen_log_message(message=msg, step=4, subject=subject,
session=session))
return ica
def make_ecg_epochs(
*,
raw: mne.io.BaseRaw,
subject: str,
session: str,
run: Optional[str] = None
) -> Optional[mne.Epochs]:
# ECG either needs an ecg channel, or avg of the mags (i.e. MEG data)
if ('ecg' in raw.get_channel_types() or 'meg' in config.ch_types or
'mag' in config.ch_types):
msg = 'Creating ECG epochs …'
logger.info(gen_log_message(message=msg, step=4, subject=subject,
session=session, run=run))
# Do not reject epochs based on amplitude.
ecg_epochs = create_ecg_epochs(raw, reject=None,
baseline=(None, -0.2),
tmin=-0.5, tmax=0.5)
if len(ecg_epochs) == 0:
msg = ('No ECG events could be found. Not running ECG artifact '
'detection.')
logger.info(gen_log_message(message=msg, step=4, subject=subject,
session=session, run=run))
ecg_epochs = None
else:
msg = ('No ECG or magnetometer channels are present. Cannot '
'automate artifact detection for ECG')
logger.info(gen_log_message(message=msg, step=4, subject=subject,
session=session, run=run))
ecg_epochs = None
return ecg_epochs
def make_eog_epochs(
*,
raw: mne.io.BaseRaw,
eog_channels: Optional[Iterable[str]],
subject: str,
session: str,
run: Optional[str] = None
) -> Optional[mne.Epochs]:
if eog_channels:
ch_names = eog_channels
assert all([ch_name in raw.ch_names
for ch_name in ch_names])
else:
ch_idx = mne.pick_types(raw.info, meg=False, eog=True)
ch_names = [raw.ch_names[i] for i in ch_idx]
del ch_idx
if ch_names:
msg = 'Creating EOG epochs …'
logger.info(gen_log_message(message=msg, step=4, subject=subject,
session=session, run=run))
# Create the epochs. It's important not to reject epochs based on
# amplitude!
eog_epochs = create_eog_epochs(raw, ch_name=ch_names,
baseline=(None, -0.2))
if len(eog_epochs) == 0:
msg = ('No EOG events could be found. Not running EOG artifact '
'detection.')
logger.warning(gen_log_message(message=msg, step=4,
subject=subject,
session=session, run=run))
eog_epochs = None
else:
msg = ('No EOG channel is present. Cannot automate IC detection '
'for EOG')
logger.info(gen_log_message(message=msg, step=4, subject=subject,
session=session, run=run))
eog_epochs = None
return eog_epochs
def detect_bad_components(
*,
which: Literal['eog', 'ecg'],
epochs: mne.BaseEpochs,
ica: mne.preprocessing.ICA,
subject: str,
session: str,
report: mne.Report
) -> List[int]:
evoked = epochs.average()
artifact = which.upper()
msg = f'Performing automated {artifact} artifact detection …'
logger.info(gen_log_message(message=msg, step=4, subject=subject,
session=session))
if which == 'eog':
inds, scores = ica.find_bads_eog(
epochs,
threshold=config.ica_eog_threshold
)
else:
inds, scores = ica.find_bads_ecg(
epochs, method='ctps',
threshold=config.ica_ctps_ecg_threshold
)
if not inds:
adjust_setting = ('ica_eog_threshold' if which == 'eog'
else 'config.ica_ctps_ecg_threshold')
warn = (f'No {artifact}-related ICs detected, this is highly '
f'suspicious. A manual check is suggested. You may wish to '
f'lower "{adjust_setting}".')
logger.warning(gen_log_message(message=warn, step=4,
subject=subject,
session=session))
else:
msg = (f'Detected {len(inds)} {artifact}-related ICs in '
f'{len(epochs)} {artifact} epochs.')
logger.info(gen_log_message(message=msg, step=4, subject=subject,
session=session))
# Mark the artifact-related components for removal
ica.exclude = inds
# Plot scores
fig = ica.plot_scores(scores, labels=which, show=config.interactive)
report.add_figs_to_section(figs=fig, captions=f'Scores - {artifact}',
section=f'sub-{subject}')
# Plot source time course
fig = ica.plot_sources(evoked, show=config.interactive)
report.add_figs_to_section(figs=fig,
captions=f'Source time course - {artifact}',
section=f'sub-{subject}')
# Plot original & corrected data
fig = ica.plot_overlay(evoked, show=config.interactive)
report.add_figs_to_section(figs=fig, captions=f'Corrections - {artifact}',
section=f'sub-{subject}')
return inds
def run_ica(subject, session=None):
"""Run ICA."""
task = config.get_task()
bids_basename = BIDSPath(subject=subject,
session=session,
task=task,
acquisition=config.acq,
recording=config.rec,
space=config.space,
datatype=config.get_datatype(),
root=config.get_deriv_root(),
check=False)
raw_fname = bids_basename.copy().update(processing='filt', suffix='raw')
ica_fname = bids_basename.copy().update(suffix='ica', extension='.fif')
ica_components_fname = bids_basename.copy().update(processing='ica',
suffix='components',
extension='.tsv')
report_fname = bids_basename.copy().update(processing='ica+components',
suffix='report',
extension='.html')
# Generate a list of raw data paths (i.e., paths of individual runs)
# we want to create epochs from.
raw_fnames = []
for run in config.get_runs(subject=subject):
raw_fname.run = run
if raw_fname.copy().update(split='01').fpath.exists():
raw_fname.update(split='01')
raw_fnames.append(raw_fname)
# Generate a unique event name -> event code mapping that can be used
# across all runs.
event_name_to_code_map = config.annotations_to_events(raw_paths=raw_fnames)
# Now, generate epochs from each individual run
epochs_all_runs = []
eog_epochs_all_runs = []
ecg_epochs_all_runs = []
for run, raw_fname in zip(config.get_runs(subject=subject), raw_fnames):
msg = f'Loading filtered raw data from {raw_fname} and creating epochs'
logger.info(gen_log_message(message=msg, step=3, subject=subject,
session=session, run=run))
raw = mne.io.read_raw_fif(raw_fname, preload=True)
# EOG epochs
eog_epochs = make_eog_epochs(raw=raw, eog_channels=config.eog_channels,
subject=subject, session=session, run=run)
if eog_epochs is not None:
eog_epochs_all_runs.append(eog_epochs)
# ECG epochs
ecg_epochs = make_ecg_epochs(raw=raw, subject=subject, session=session,
run=run)
if ecg_epochs is not None:
ecg_epochs_all_runs.append(ecg_epochs)
# Produce high-pass filtered version of the data for ICA.
# Sanity check – make sure we're using the correct data!
if config.resample_sfreq is not None:
assert np.allclose(raw.info['sfreq'], config.resample_sfreq)
if config.l_freq is not None:
assert np.allclose(raw.info['highpass'], config.l_freq)
filter_for_ica(raw=raw, subject=subject, session=session, run=run)
# Only keep the subset of the mapping that applies to the current run
event_id = event_name_to_code_map.copy()
for event_name in event_id.copy().keys():
if event_name not in raw.annotations.description:
del event_id[event_name]
msg = 'Creating task-related epochs …'
logger.info(gen_log_message(message=msg, step=3, subject=subject,
session=session, run=run))
epochs = make_epochs(
raw=raw,
event_id=event_id,
tmin=config.epochs_tmin,
tmax=config.epochs_tmax,
metadata_tmin=config.epochs_metadata_tmin,
metadata_tmax=config.epochs_metadata_tmax,
metadata_keep_first=config.epochs_metadata_keep_first,
metadata_keep_last=config.epochs_metadata_keep_last,
event_repeated=config.event_repeated,
decim=config.decim
)
epochs_all_runs.append(epochs)
del raw, epochs, eog_epochs, ecg_epochs # free memory
# Lastly, we can concatenate the epochs and set an EEG reference
epochs = mne.concatenate_epochs(epochs_all_runs)
if eog_epochs_all_runs:
epochs_eog = mne.concatenate_epochs(eog_epochs_all_runs)
else:
epochs_eog = None
if ecg_epochs_all_runs:
epochs_ecg = mne.concatenate_epochs(ecg_epochs_all_runs)
else:
epochs_ecg = None
del epochs_all_runs, eog_epochs_all_runs, ecg_epochs_all_runs
epochs.load_data()
if "eeg" in config.ch_types:
projection = True if config.eeg_reference == 'average' else False
epochs.set_eeg_reference(config.eeg_reference, projection=projection)
# Now actually perform ICA.
msg = 'Calculating ICA solution.'
logger.info(gen_log_message(message=msg, step=4, subject=subject,
session=session))
ica = fit_ica(epochs, subject=subject, session=session)
# Start a report
title = f'ICA – sub-{subject}'
if session is not None:
title += f', ses-{session}'
if task is not None:
title += f', task-{task}'
report = Report(info_fname=epochs, title=title, verbose=False)
# ECG and EOG component detection
if epochs_ecg:
ecg_ics = detect_bad_components(which='ecg', epochs=epochs_ecg,
ica=ica,
subject=subject, session=session,
report=report)
else:
ecg_ics = []
if epochs_eog:
eog_ics = detect_bad_components(which='eog', epochs=epochs_eog,
ica=ica,
subject=subject, session=session,
report=report)
else:
eog_ics = []
# Save ICA to disk.
# We also store the automatically identified ECG- and EOG-related ICs.
msg = 'Saving ICA solution and detected artifacts to disk.'
logger.info(gen_log_message(message=msg, step=4, subject=subject,
session=session))
ica.exclude = sorted(set(ecg_ics + eog_ics))
ica.save(ica_fname)
# Create TSV.
tsv_data = pd.DataFrame(
dict(component=list(range(ica.n_components_)),
type=['ica'] * ica.n_components_,
description=['Independent Component'] * ica.n_components_,
status=['good'] * ica.n_components_,
status_description=['n/a'] * ica.n_components_))
for component in ecg_ics:
row_idx = tsv_data['component'] == component
tsv_data.loc[row_idx, 'status'] = 'bad'
tsv_data.loc[row_idx,
'status_description'] = 'Auto-detected ECG artifact'
for component in eog_ics:
row_idx = tsv_data['component'] == component
tsv_data.loc[row_idx, 'status'] = 'bad'
tsv_data.loc[row_idx,
'status_description'] = 'Auto-detected EOG artifact'
tsv_data.to_csv(ica_components_fname, sep='\t', index=False)
# Lastly, plot all ICs, and add them to the report for manual inspection.
msg = 'Adding diagnostic plots for all ICs to the HTML report …'
logger.info(gen_log_message(message=msg, step=4, subject=subject,
session=session))
for component_num in tqdm(range(ica.n_components_)):
fig = ica.plot_properties(epochs,
picks=component_num,
psd_args={'fmax': 60},
show=False)
caption = f'IC {component_num}'
if component_num in eog_ics and component_num in ecg_ics:
caption += ' (EOG & ECG)'
elif component_num in eog_ics:
caption += ' (EOG)'
elif component_num in ecg_ics:
caption += ' (ECG)'
report.add_figs_to_section(fig, section=f'sub-{subject}',
captions=caption)
open_browser = True if config.interactive else False
report.save(report_fname, overwrite=True, open_browser=open_browser)
msg = (f"ICA completed. Please carefully review the extracted ICs in the "
f"report {report_fname.basename}, and mark all components you wish "
f"to reject as 'bad' in {ica_components_fname.basename}")
logger.info(gen_log_message(message=msg, step=4, subject=subject,
session=session))
@failsafe_run(on_error=on_error)
def main():
"""Run ICA."""
msg = 'Running Step 4: Compute ICA'
logger.info(gen_log_message(step=4, message=msg))
if config.spatial_filter == 'ica':
parallel, run_func, _ = parallel_func(run_ica, n_jobs=config.N_JOBS)
parallel(run_func(subject, session) for subject, session in
itertools.product(config.get_subjects(),
config.get_sessions()))
msg = 'Completed Step 4: Compute ICA'
logger.info(gen_log_message(step=4, message=msg))
if __name__ == '__main__':
main()
|
python
|
import logging
import typing
import copy
from typing import Any, Dict, List, Text
from rasa.nlu.components import Component
from rasa.nlu.config import RasaNLUModelConfig
from rasa.nlu.tokenizers.tokenizer import Token, Tokenizer
from rasa.nlu.training_data import Message, TrainingData
logger = logging.getLogger(__name__)
if typing.TYPE_CHECKING:
pass
class MicroAddonsTokenizer(Tokenizer):
provides = ["tokens"]
language_list = ["zh"]
defaults = {
# default don't load custom dictionary
"custom_dict": None,
# Flag to check whether to split intents
"intent_tokenization_flag": False,
# Symbol on which intent should be split
"intent_split_symbol": "_",
}
def __init__(self, component_config: Dict[Text, Any] = None) -> None:
self.custom_dict = component_config.pop("custom_dict", None)
if self.custom_dict:
self.load_custom_dictionary(self.custom_dict)
super().__init__(component_config)
@staticmethod
def load_custom_dictionary(custom_dict: Text) -> None:
import MicroTokenizer
MicroTokenizer.load_userdict(custom_dict)
@classmethod
def required_packages(cls) -> List[Text]:
return ["MicroTokenizer"]
def tokenize(self, message: Message, attribute: Text) -> List[Token]:
import MicroTokenizer
text = message.get(attribute)
tokenized = MicroTokenizer.cut(text)
tokens = []
offset = 0
for word in tokenized:
tokens.append(Token(word, offset))
offset += len(word)
return tokens
|
python
|
import datetime
import enum
from sqlalchemy import (
Column,
Integer,
String,
Enum,
TIMESTAMP,
ForeignKey,
Index,
Float,
)
from sqlalchemy.orm import relationship
from .base import Base
class SystemUpdate(Base):
__tablename__ = "system_update"
pk = Column(Integer, primary_key=True)
system_pk = Column(Integer, ForeignKey("system.pk"))
class Status(enum.Enum):
SCHEDULED = 1
IN_PROGRESS = 2
SUCCESS = 3
FAILED = 4
status = Column(Enum(Status, native_enum=False), nullable=False)
status_message = Column(String) # TODO: rename stack trace?
total_duration = Column(Float)
scheduled_at = Column(TIMESTAMP(timezone=True), default=datetime.datetime.utcnow)
completed_at = Column(TIMESTAMP(timezone=True))
config = Column(String)
config_template = Column(String)
config_parameters = Column(String)
config_source_url = Column(String)
transiter_version = Column(String)
system = relationship("System", back_populates="updates")
__table_args__ = (
Index("system_update_system_pk_system_update_pk_idx", system_pk, pk),
)
|
python
|
from italian_csv_type_prediction.simple_types import IntegerType
import numpy as np
def test_integer_type():
predictor = IntegerType()
valids = [
3,
6,
0,
"1.000.000.00"
]
invalids = [
"ciao",
"12.12.94",
"12.12.1994",
False,
True,
None,
np.nan
]
for valid in valids:
assert predictor.validate(valid)
assert predictor.validate(str(valid))
for invalid in invalids:
assert not predictor.validate(invalid)
assert not predictor.validate(str(invalid))
|
python
|
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, data):
new_node = Node(data)
if self.root == None:
self.root = new_node
else:
current_node = self.root
while True:
if data < current_node.data:
if current_node.left == None:
current_node.left = new_node
return
else:
current_node = current_node.left
elif data > current_node.data:
if current_node.right == None:
current_node.right = new_node
return
else:
current_node = current_node.right
def lookup(self, data):
current_node = self.root
while True:
if current_node == None:
return False
if current_node.data == data:
return True
elif data < current_node.data:
current_node = current_node.left
else:
current_node = current_node.right
def dfs_in_order(self, current_node, my_list):
if current_node.left:
self.dfs_in_order(current_node.left, my_list)
my_list.append(current_node.data)
if current_node.right:
self.dfs_in_order(current_node.right, my_list)
return my_list
def dfs_pre_order(self, current_node, my_list):
my_list.append(current_node.data)
if current_node.left:
self.dfs_pre_order(current_node.left, my_list)
if current_node.right:
self.dfs_pre_order(current_node.right, my_list)
return my_list
def dfs_post_order(self, current_node, my_list):
if current_node.left:
self.dfs_post_order(current_node.left, my_list)
if current_node.right:
self.dfs_post_order(current_node.right, my_list)
my_list.append(current_node.data)
return my_list
binary_search_tree = BinarySearchTree()
binary_search_tree.insert(9)
binary_search_tree.insert(4)
binary_search_tree.insert(6)
binary_search_tree.insert(20)
binary_search_tree.insert(170)
binary_search_tree.insert(15)
binary_search_tree.insert(1)
print(binary_search_tree.dfs_in_order(binary_search_tree.root, []))
print(binary_search_tree.dfs_pre_order(binary_search_tree.root, []))
print(binary_search_tree.dfs_post_order(binary_search_tree.root, []))
|
python
|
"""Parameters for the model of marine particle microbial degradation
and coupling of degradation with sinking speed, part of the paper
"Sinking enhances the degradation of organic particle by marine bacteria"
Uria Alcolombri, François J. Peaudecerf, Vicente Fernandez, Lars Behrendt, Kang Soo Lee, Roman Stocker
Nature Geosciences (2021)
See Extended Data for more details on chosen parameter values.
Author: Francois Peaudecerf
Creation: 25.02.2019
History of modification
08.10.2019: modification of chosen parameter values
26.11.2019: modification of value of gamma_1 following new fit of experimental data
05.07.2021: editing for publication on Github
"""
# from __future__ import division
###### Numerical parameters #########
mu = 1e-3 # kg/m/s, dynamic viscosity of water
Drho = 0.54 # kg/m^3, difference of volumic mass
g = 10 # m/s^2, gravity
R_0 = 4.4e-4 # m, initial radius in experiments
gamma = 1.06e-10 # m/s, radius shrinking rate from experiments with no flow
R_l = 125e-6 # m, minimum cut-off radius for size distribution
R_g = 750e-6 # m, maximum cut-off radius for size distribution
z_0 = 100 # m, depth of particle distribution
C = 200e3 # m-3, total particle abundance
beta = 4.0 # power law parameter for particle distribution
omega = 0.26 # exponent in the power law for settling velocity with radius (Alldredge 1988)
B = 4.18e-3 # m^(1-omega) s-1, pre-factor for settling velocity with radius (Alldredge 1988)
nu = 1.20e-6 # m2/s, kinematic viscosity modified for sea water at 15 degrees C in v1
D = 1e-9 # m2/s, diffusivity for Peclet estimation
delta = 0.412 # exponent in the Sherwood expression
gamma1= 4.35e-10 # coefficient in the fit of degradation rate with Sh
gamma2= 0.619*gamma1*(nu/D)**(1.0/3.0)*(2.0/nu)**delta # aggregate coefficient for gamma
E = 4.55e-5 # kg/m^{chi}, pre-factor in the power law for dry mass as function of size (Alldredge 1988)
chi = 1.125 # exponent in the power law for dry mass as function of size (Alldredge 1988)
rho_dry= 15 # kg/m^3, dry mass per unit volume of alginate particles
# Alldredge 1988: Alldredge, A. L. & Gotschalk, C. In situ settling behavior of marine snow. Limnol. Ocean. 33, 339–35 (1988)
|
python
|
import os
import json
import shutil
import grp
from pathlib import Path
def change_key(my_json, old_key, new_key):
if old_key in my_json:
# store the value
val = my_json[old_key]
# delete the old key/value pair
del my_json[old_key]
# error checking
if new_key in my_json:
print ("ERROR: new_key "+new_key+" is already in the dictionary")
# re-add the value with the new key
my_json[new_key] = val
else:
print ("ERROR: old_key "+old_key+" is not in the dictionary")
def change_value(my_json, old_key, new_value):
if old_key in my_json:
my_json[old_key] = new_value
else:
print ("ERROR: old_key "+old_key+" is not in the dictionary")
def up(config):
submitty_filename = str(Path(config.submitty['submitty_install_dir'], 'config', 'submitty.json'))
submitty_filename_tmp = str(Path(config.submitty['submitty_install_dir'], 'config', 'submitty_tmp.json'))
submitty_users_filename = str(Path(config.submitty['submitty_install_dir'], 'config', 'submitty_users.json'))
submitty_users_filename_tmp = str(Path(config.submitty['submitty_install_dir'], 'config', 'submitty_users_tmp.json'))
killall_path = Path(config.submitty['submitty_install_dir'], 'sbin', 'killall.py')
INSTALL_SUBMITTY_filename = str(Path(config.submitty['submitty_install_dir'], '.setup', 'INSTALL_SUBMITTY.sh'))
print ("my path",killall_path)
# stop the old scheduler daemon, if it is still in use -- was deprecated in early Spring 2018
os.system("systemctl stop submitty_grading_scheduler")
try:
os.remove("/etc/systemd/system/submitty_grading_scheduler.service")
except OSError:
pass
# stop all jobs that are using hwphp and hwcron
os.system("systemctl stop submitty_autograding_worker")
os.system("systemctl stop submitty_autograding_shipper")
os.system("systemctl stop apache2.service")
os.system("systemctl stop php7.0-fpm.service")
os.system("su -c 'crontab -r' hwcron")
os.system("su -c '"+str(killall_path)+"' hwcron")
# change the usernames
os.system("usermod -l submitty_php hwphp")
os.system("usermod -l submitty_cgi hwcgi")
os.system("usermod -l submitty_daemon hwcron")
# change the group names
os.system("groupmod --new-name submitty_daemon hwcron")
os.system("groupmod --new-name submitty_php hwphp")
os.system("groupmod --new-name submitty_cgi hwcgi")
os.system("groupmod --new-name submitty_daemonphp hwcronphp")
os.system("groupmod --new-name submitty_course_builders course_builders")
# cannot restart until the submitty code is installed
print ("WARNING: You will need to manually restart the website/shipper/worker")
print (" systemctl start apache2.service")
print (" systemctl start php7.0-fpm.service")
print (" systemctl start submitty_autograding_shipper")
print (" systemctl start submitty_autograding_worker")
if os.path.exists("/home/hwcron"):
shutil.move("/home/hwcron","/home/submitty_daemon")
if os.path.exists("/home/hwphp"):
shutil.move("/home/hwphp","/home/submitty_php")
if os.path.exists("/home/hwcgi"):
shutil.move("/home/hwcgi","/home/submitty_cgi")
# edit the variables stored by configure submitty/installation
with open (submitty_filename,"r") as open_file:
my_json = json.load(open_file)
change_value(my_json,"submitty_repository","/usr/local/submitty/GIT_CHECKOUT/Submitty")
with open (submitty_filename_tmp,"w") as open_file:
json.dump(my_json,open_file,indent=4)
# write to another file & then remove the write permissions
shutil.move(submitty_filename_tmp,submitty_filename)
os.chmod(submitty_filename, 0o440)
os.chown(submitty_filename, os.getuid(), grp.getgrnam('submitty_daemonphp').gr_gid)
with open (submitty_users_filename,"r") as open_file:
my_json = json.load(open_file)
change_key(my_json,"hwcron_uid","daemon_uid")
change_key(my_json,"hwcron_gid","daemon_gid")
change_key(my_json,"hwcron_user","daemon_user")
change_value(my_json,"daemon_user","submitty_daemon")
change_value(my_json,"course_builders_group","submitty_course_builders")
change_key(my_json,"hwphp_uid","php_uid")
change_key(my_json,"hwphp_gid","php_gid")
change_key(my_json,"hwphp_user","php_user")
change_value(my_json,"php_user","submitty_php")
change_key(my_json,"hwcgi_user","cgi_user")
change_value(my_json,"cgi_user","submitty_cgi")
change_key(my_json,"hwcronphp_group","daemonphp_group")
change_value(my_json,"daemonphp_group","submitty_daemonphp")
with open (submitty_users_filename_tmp,"w") as open_file:
json.dump(my_json,open_file,indent=4)
# write to another file & then remove the write permissions
shutil.move(submitty_users_filename_tmp,submitty_users_filename)
os.chmod(submitty_users_filename, 0o440)
os.chown(submitty_users_filename, os.getuid(), grp.getgrnam('submitty_daemonphp').gr_gid)
os.chmod(INSTALL_SUBMITTY_filename, 0o700)
os.system("sed -i -e \"s|'course_builders'|'submitty_course_builders'|g\" "+INSTALL_SUBMITTY_filename)
os.system("sed -i -e \"s|HWCRON_USER='hwcron'|DAEMON_USER='submitty_daemon'|g\" "+INSTALL_SUBMITTY_filename)
os.system("sed -i -e \"s|HWCRON_UID|DAEMON_UID|g\" "+INSTALL_SUBMITTY_filename)
os.system("sed -i -e \"s|HWCRON_GID|DAEMON_GID|g\" "+INSTALL_SUBMITTY_filename)
os.system("sed -i -e \"s|HWPHP_USER='hwphp'|PHP_USER='submitty_php'|g\" "+INSTALL_SUBMITTY_filename)
os.system("sed -i -e \"s|HWPHP_UID|PHP_UID|g\" "+INSTALL_SUBMITTY_filename)
os.system("sed -i -e \"s|HWPHP_GID|PHP_GID|g\" "+INSTALL_SUBMITTY_filename)
os.system("sed -i -e \"s|HWCGI_USER='hwcgi'|CGI_USER='submitty_cgi'|g\" "+INSTALL_SUBMITTY_filename)
os.system("sed -i -e \"s|HWCRONPHP_GROUP='hwcronphp'|DAEMONPHP_GROUP='submitty_daemonphp'|g\" "+INSTALL_SUBMITTY_filename)
os.chmod(INSTALL_SUBMITTY_filename, 0o500)
# repair & restart apache & phpfpm
APACHE_FILENAME="/etc/apache2/sites-enabled/submitty.conf"
os.system("sed -i -e \"s|hwcgi|submitty_cgi|g\" "+APACHE_FILENAME)
APACHE_FILENAME2="/etc/apache2/sites-enabled/submitty_http.conf"
os.system("sed -i -e \"s|hwcgi|submitty_cgi|g\" "+APACHE_FILENAME2)
APACHE_FILENAME3="/etc/apache2/sites-enabled/vcs.conf"
os.system("sed -i -e \"s|hwcgi|submitty_cgi|g\" "+APACHE_FILENAME3)
PHPFPM_FILENAME="/etc/php/7.0/fpm/pool.d/submitty.conf"
os.system("sed -i -e \"s|hwphp|submitty_php|g\" "+PHPFPM_FILENAME)
os.system("systemctl start apache2.service")
os.system("systemctl start php7.0-fpm.service")
print ("finished migration changing system user names")
pass
def down(config):
submitty_users_filename = str(Path(config.submitty['submitty_install_dir'], 'config', 'submitty_users.json'))
submitty_users_filename_tmp = str(Path(config.submitty['submitty_install_dir'], 'config', 'submitty_users_tmp.json'))
killall_path = Path(config.submitty['submitty_install_dir'], 'sbin', 'killall.py')
INSTALL_SUBMITTY_filename = str(Path(config.submitty['submitty_install_dir'], '.setup', 'INSTALL_SUBMITTY.sh'))
# stop all jobs that are using submitty_php and submitty_daemon
os.system("systemctl stop submitty_autograding_worker")
os.system("systemctl stop submitty_autograding_shipper")
os.system("systemctl stop apache2.service")
os.system("systemctl stop php7.0-fpm.service")
os.system("su -c 'crontab -r' submitty_daemon")
os.system("su -c '"+str(killall_path)+"' submitty_daemon")
# change the usernames
os.system("usermod -l hwphp submitty_php")
os.system("usermod -l hwcgi submitty_cgi")
os.system("usermod -l hwcron submitty_daemon")
# change the group names
os.system("groupmod --new-name hwcron submitty_daemon")
os.system("groupmod --new-name hwphp submitty_php")
os.system("groupmod --new-name hwcgi submitty_cgi")
os.system("groupmod --new-name hwcronphp submitty_daemonphp")
os.system("groupmod --new-name course_builders submitty_course_builders")
# cannot restart until the submitty code is installed
print ("WARNING: You will need to manually restart the website/shipper/worker")
print (" systemctl start apache2.service")
print (" systemctl start php7.0-fpm.service")
print (" systemctl start submitty_autograding_shipper")
print (" systemctl start submitty_autograding_worker")
if os.path.exists("/home/submitty_daemon"):
shutil.move("/home/submitty_daemon","/home/hwcron")
if os.path.exists("/home/submitty_php"):
shutil.move("/home/submitty_php","/home/hwphp")
if os.path.exists("/home/submitty_cgi"):
shutil.move("/home/submitty_cgi","/home/hwcgi")
# edit the variables stored by configure submitty/installation
with open (submitty_users_filename,"r") as open_file:
my_json = json.load(open_file)
change_key(my_json,"daemon_uid","hwcron_uid")
change_key(my_json,"daemon_gid","hwcron_gid")
change_key(my_json,"daemon_user","hwcron_user")
change_value(my_json,"hwcron_user","hwcron")
change_value(my_json,"course_builders_group","course_builders")
change_key(my_json,"php_uid","hwphp_uid")
change_key(my_json,"php_gid","hwphp_gid")
change_key(my_json,"php_user","hwphp_user")
change_value(my_json,"hwphp_user","hwphp")
change_key(my_json,"cgi_user","hwcgi_user")
change_value(my_json,"hwcgi_user","hwcgi")
change_key(my_json,"daemonphp_group","hwcronphp_group")
change_value(my_json,"hwcronphp_group","hwcronphp")
# write to another file & then remove the write permissions
with open (submitty_users_filename_tmp,"w") as open_file:
json.dump(my_json,open_file,indent=4)
shutil.move(submitty_users_filename_tmp,submitty_users_filename)
os.chmod(submitty_users_filename, 0o440)
os.chown(submitty_users_filename, os.getuid(), grp.getgrnam('hwcronphp').gr_gid)
os.chmod(INSTALL_SUBMITTY_filename, 0o700)
os.system("sed -i -e \"s|'submitty_course_builders'|'course_builders'|g\" "+INSTALL_SUBMITTY_filename)
os.system("sed -i -e \"s|DAEMON_USER='submitty_daemon'|HWCRON_USER='hwcron'|g\" "+INSTALL_SUBMITTY_filename)
os.system("sed -i -e \"s|DAEMON_UID|HWCRON_UID|g\" "+INSTALL_SUBMITTY_filename)
os.system("sed -i -e \"s|DAEMON_GID|HWCRON_GID|g\" "+INSTALL_SUBMITTY_filename)
os.system("sed -i -e \"s|PHP_USER='submitty_php'|HWPHP_USER='hwphp'|g\" "+INSTALL_SUBMITTY_filename)
os.system("sed -i -e \"s|PHP_UID|HWPHP_UID|g\" "+INSTALL_SUBMITTY_filename)
os.system("sed -i -e \"s|PHP_GID|HWPHP_GID|g\" "+INSTALL_SUBMITTY_filename)
os.system("sed -i -e \"s|CGI_USER='submitty_cgi'|HWCGI_USER='hwcgi'|g\" "+INSTALL_SUBMITTY_filename)
os.system("sed -i -e \"s|DAEMONPHP_GROUP='submitty_daemonphp'|HWCRONPHP_GROUP='hwcronphp'|g\" "+INSTALL_SUBMITTY_filename)
os.chmod(INSTALL_SUBMITTY_filename, 0o500)
# repair & restart apache & phpfpm
APACHE_FILENAME="/etc/apache2/sites-enabled/submitty.conf"
os.system("sed -i -e \"s|submitty_cgi|hwcgi|g\" "+APACHE_FILENAME)
APACHE_FILENAME2="/etc/apache2/sites-enabled/submitty_http.conf"
os.system("sed -i -e \"s|submitty_cgi|hwcgi|g\" "+APACHE_FILENAME2)
APACHE_FILENAME3="/etc/apache2/sites-enabled/vcs.conf"
os.system("sed -i -e \"s|submitty_cgi|hwcgi|g\" "+APACHE_FILENAME3)
PHPFPM_FILENAME="/etc/php/7.0/fpm/pool.d/submitty.conf"
os.system("sed -i -e \"s|submitty_php|hwphp|g\" "+PHPFPM_FILENAME)
os.system("systemctl start apache2.service")
os.system("systemctl start php7.0-fpm.service")
print ("finished rollback of migration changing system user names")
pass
|
python
|
from pytari2600.pytari2600 import new_atari
emulator = new_atari("../../roms/dragster.a26", headless=False)
while True:
emulator.core.step()
# print("---AFTER EXECUTION---" + str(emulator.stella.clocks.system_clock))
# print(emulator.stella.display_cache)
|
python
|
# # -*- coding: utf-8 -*-
# """
# Created on Fri May 8 17:08:43 2020
#%%
import numpy as np
import matplotlib.pyplot as plt
from scipy.constants import pi, c
from numpy.fft import fft, ifft, fftshift
#%%
def calculate_spectrum(z, E, H, f=3.7e9):
k0 = 2*pi*f/c
lambda0 = c/f
# fourier domain points
B = 2**18
Efft = np.fft.fftshift(np.fft.fft(E,B))
Hfft = np.fft.fftshift(np.fft.fft(H,B))
# fourier domain bins
dz = z[1] - z[0] # assumes spatial period is constant
df = 1/(B*dz)
K = np.arange(-B/2,+B/2)
# spatial frequency bins
Fz= K*df
# parallel index is kz/k0
nz= (2*pi/k0)*Fz
# ~ power density spectrum
p = (dz)**2/lambda0 * (1/2*Efft*np.conj(Hfft))
return(nz,p)
#%%
def spectrum_from_HFSS_file(Ereal, Eimag, Hreal, Himag, f):
x,y,z,Ex_re,Ey_re,Ez_re = np.loadtxt(Ereal, skiprows=2, unpack=True)
x,y,z,Ex_im,Ey_im,Ez_im = np.loadtxt(Eimag, skiprows=2, unpack=True)
x,y,z,Hx_re,Hy_re,Hz_re = np.loadtxt(Hreal, skiprows=2, unpack=True)
x,y,z,Hx_im,Hy_im,Hz_im = np.loadtxt(Himag, skiprows=2, unpack=True)
# create a curvilinear
_s = np.sqrt((x - x[0])**2 + (y - y[0])**2 + (z - z[0])**2)
_Ex = Ex_re + 1j*Ex_im
_Ey = Ey_re + 1j*Ey_im
_Ez = Ez_re + 1j*Ez_im
_Hx = Hx_re + 1j*Hx_im
_Hy = Hy_re + 1j*Hy_im
_Hz = Hz_re + 1j*Hz_im
# replace NaN with 0
_Ex = np.nan_to_num(_Ex)
_Ey = np.nan_to_num(_Ey)
_Ez = np.nan_to_num(_Ez)
_Hx = np.nan_to_num(_Hx)
_Hy = np.nan_to_num(_Hy)
_Hz = np.nan_to_num(_Hz)
# nextpow 2
nb_s = int(2**np.ceil(np.log2(len(_s))))
s = np.linspace(np.min(_s), np.max(_s), num=nb_s)
# interpolated field on this regular mesh
Ex = np.interp(s, _s, _Ex)
Ey = np.interp(s, _s, _Ey)
Ez = np.interp(s, _s, _Ez)
Hx = np.interp(s, _s, _Hx)
Hy = np.interp(s, _s, _Hy)
Hz = np.interp(s, _s, _Hz)
N = 1000
s = np.pad(s, N, mode='reflect', reflect_type='odd')
Ey = np.pad(Ey, N)
Hx = np.pad(Ey, N)
nz, p = calculate_spectrum(s, Ey, -Hx, f=f0)
return p, nz
#%% monopole and dipole in curved model
f0 = 55e6
w0 = 2*pi*f0
k0 = w0/c
Ereal = 'WEST_ICRH_Curved_Vacuum_monopole_Ereal.fld'
Eimag = 'WEST_ICRH_Curved_Vacuum_monopole_Eimag.fld'
Hreal = 'WEST_ICRH_Curved_Vacuum_monopole_Hreal.fld'
Himag = 'WEST_ICRH_Curved_Vacuum_monopole_Himag.fld'
p_curved_monopole, nz_curved_monopole = spectrum_from_HFSS_file(Ereal, Eimag, Hreal, Himag, f=f0)
Ereal = 'WEST_ICRH_Curved_Vacuum_dipole_Ereal.fld'
Eimag = 'WEST_ICRH_Curved_Vacuum_dipole_Eimag.fld'
Hreal = 'WEST_ICRH_Curved_Vacuum_dipole_Hreal.fld'
Himag = 'WEST_ICRH_Curved_Vacuum_dipole_Himag.fld'
p_curved_dipole, nz_curved_dipole = spectrum_from_HFSS_file(Ereal, Eimag, Hreal, Himag, f=f0)
#%%
# cut values over than |k|>100
_kz_all = np.real(k0*nz_curved_dipole)
_kz = _kz_all[np.abs(_kz_all)<100]
_pz = p_curved_dipole[np.abs(_kz_all)<100]
np.savetxt('WEST_ICRH_Spectrum_vacuum.csv', np.vstack([_kz, _pz]).T, header='kz \t 1D power density spectrum [a.u.]')
#%%
fig, ax = plt.subplots()
# ax.plot(k0*nz_flat, np.abs(p_flat)/np.max(np.abs(p_flat)) )
# ax.plot(k0*nz_curved_dipole, np.abs(p_curved_dipole)/np.max(np.abs(p_curved_dipole)), lw=2 )
# ax.plot(k0*nz_curved_monopole, np.abs(p_curved_monopole)/np.max(np.abs(p_curved_monopole)), lw=2 )
ax.plot(k0*nz_curved_dipole, np.abs(p_curved_dipole), lw=2 )
# ax.plot(k0*nz_curved_monopole, np.abs(p_curved_monopole), lw=2 )
ax.set_xlim(-30, +30)
ax.set_ylabel('Power spectrum density [a.u.]', fontsize=14)
ax.set_xlabel('Toroidal wavenumber $k_z$ [$m^{-1}$]', fontsize=14)
ax.set_title('WEST ICRH Antenna Power Spectrum Density (Vacuum)', fontsize=14)
ax.tick_params(labelsize=14)
ax.grid(True, alpha=0.2)
fig.tight_layout()
fig.savefig('WEST_ICRH_Spectrum_Vacuum.png', dpi=150)
# % Power conservation checking
# disp(['Power conservation checking : total transmited power [W] :', num2str(dnz*sum(real(dP_nz)))])
# #%% flat model - dielectric medium
# Ereal = 'WEST_ICRH_Flat_Dielectric_Ereal.fld'
# Eimag = 'WEST_ICRH_Flat_Dielectric_Eimag.fld'
# Hreal = 'WEST_ICRH_Flat_Dielectric_Hreal.fld'
# Himag = 'WEST_ICRH_Flat_Dielectric_Himag.fld'
# p_flat_dielectric, nz_flat_dielectric = spectrum_from_HFSS_file(Ereal, Eimag, Hreal, Himag, f=f0)
# #%%
# fig, ax = plt.subplots()
# ax.plot(k0*nz_flat_dielectric, np.abs(p_flat_dielectric)/np.max(np.abs(p_flat_dielectric)) )
# ax.set_xlim(-30, +30)
# ax.set_ylabel('Power spectrum density [a.u.]', fontsize=14)
# ax.set_xlabel('Toroidal wavenumber $k_z$ [$m^{-1}$]', fontsize=14)
# ax.set_title('WEST ICRH Antenna Power Spectrum Density (Vacuum)', fontsize=14)
# ax.tick_params(labelsize=14)
# ax.grid(True, alpha=0.2)
# fig.tight_layout()
|
python
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.