hexsha stringlengths 40 40 | size int64 4 996k | ext stringclasses 8
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 4 996k | avg_line_length float64 1.33 58.2k | max_line_length int64 2 323k | alphanum_fraction float64 0 0.97 | content_no_comment stringlengths 0 946k | is_comment_constant_removed bool 2
classes | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f723771491b01e370b7732388f7bebf64ae3b41f | 793 | py | Python | HellowWorldO0.py | RobertMillward/pythonlearn | 8406fb5d03b48bfacdb286de551a291ce58fb0cc | [
"MIT"
] | null | null | null | HellowWorldO0.py | RobertMillward/pythonlearn | 8406fb5d03b48bfacdb286de551a291ce58fb0cc | [
"MIT"
] | null | null | null | HellowWorldO0.py | RobertMillward/pythonlearn | 8406fb5d03b48bfacdb286de551a291ce58fb0cc | [
"MIT"
] | null | null | null | """
HelloWorldO0.py
Copyright (c) 2020 by Robert Russell Millward. All rights reserved.
"""
from tkinter import *
class GenResearch(Frame):
def sayHi(self):
print("hi Bob");
def createWidgits(self):
self.QUIT = Button(self);
self.QUIT["text"] = "Quit";
self.QUIT["fg"] = "red";
self.QUIT["command"] = self.quit;
self.QUIT.pack({"side": "left"});
self.hi_there = Button(self);
self.hi_there["text"] = "Hello",
self.hi_there["command"] = self.sayHi;
self.hi_there.pack({"side": "left"});
def __init__(self, master=None):
Frame.__init__(self, master);
self.pack();
self.createWidgits();
root = Tk();
app = GenResearch(master=root);
app.mainloop();
root.destroy();
#END
| 20.333333 | 67 | 0.581337 |
from tkinter import *
class GenResearch(Frame):
def sayHi(self):
print("hi Bob");
def createWidgits(self):
self.QUIT = Button(self);
self.QUIT["text"] = "Quit";
self.QUIT["fg"] = "red";
self.QUIT["command"] = self.quit;
self.QUIT.pack({"side": "left"});
self.hi_there = Button(self);
self.hi_there["text"] = "Hello",
self.hi_there["command"] = self.sayHi;
self.hi_there.pack({"side": "left"});
def __init__(self, master=None):
Frame.__init__(self, master);
self.pack();
self.createWidgits();
root = Tk();
app = GenResearch(master=root);
app.mainloop();
root.destroy();
| true | true |
f72377c45b0d0f5af5cd0bddd9687f941ba094d9 | 4,862 | py | Python | train.py | MaxCodeXTC/symmetrynet | f42810be95ecaa85a32a836213cb8d0687184574 | [
"MIT"
] | 1 | 2020-06-21T07:59:02.000Z | 2020-06-21T07:59:02.000Z | train.py | MaxCodeXTC/symmetrynet | f42810be95ecaa85a32a836213cb8d0687184574 | [
"MIT"
] | null | null | null | train.py | MaxCodeXTC/symmetrynet | f42810be95ecaa85a32a836213cb8d0687184574 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
"""Training and Evaluate the Neural Network
Usage:
train.py [options] <yaml-config>
train.py (-h | --help )
Arguments:
yaml-config Path to the yaml hyper-parameter file
Options:
-h --help Show this screen.
-d --devices <devices> Comma seperated GPU devices [default: 0]
-i --identifier <identifier> Folder name [default: default-identifier]
--from <checkpoint> Path to a checkpoint
--ignore-optim Ignore optim when restoring from a checkpoint
"""
import datetime
import glob
import os
import os.path as osp
import platform
import pprint
import random
import shlex
import shutil
import signal
import subprocess
import sys
import threading
import numpy as np
import torch
import yaml
from docopt import docopt
import sym
from sym.config import CI, CM, CO, C, load_config
from sym.datasets import ShapeNetDataset
def git_hash():
cmd = 'git log -n 1 --pretty="%h"'
ret = subprocess.check_output(shlex.split(cmd)).strip()
if isinstance(ret, bytes):
ret = ret.decode()
return ret
def get_outdir(identifier):
# load config
name = str(datetime.datetime.now().strftime("%y%m%d-%H%M%S"))
name += "-%s" % git_hash()
name += "-%s" % identifier
outdir = osp.join(osp.expanduser(CI.logdir), name)
if not osp.exists(outdir):
os.makedirs(outdir)
C.to_yaml(osp.join(outdir, "config.yaml"))
os.system(f"git diff HEAD > {outdir}/gitdiff.patch")
os.system(f"find -name '*.py' -print0 | tar -cJf {outdir}/src.tar.xz --null -T -")
return outdir
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
def main():
args = docopt(__doc__)
config_file = args["<yaml-config>"] or "config/shapenet.yaml"
C.update(C.from_yaml(filename=config_file))
if args["--from"]:
C.io.resume_from = args["--from"]
CI.update(C.io)
CM.update(C.model)
CO.update(C.optim)
pprint.pprint(C, indent=4)
resume_from = CI.resume_from
# WARNING: still not deterministic
random.seed(0)
np.random.seed(0)
torch.manual_seed(0)
device_name = "cpu"
num_gpus = args["--devices"].count(",") + 1
os.environ["CUDA_VISIBLE_DEVICES"] = args["--devices"]
if torch.cuda.is_available():
device_name = "cuda"
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.deterministic = True
torch.cuda.manual_seed(0)
print("Let's use", torch.cuda.device_count(), "GPU(s)!")
else:
print("CUDA is not available")
device = torch.device(device_name)
# 1. dataset
batch_size = CM.batch_size * num_gpus
datadir = CI.datadir
kwargs = {
"batch_size": batch_size,
"num_workers": CI.num_workers,
"pin_memory": True,
}
if CI.dataset == "ShapeNet":
Dataset = ShapeNetDataset
else:
raise NotImplementedError
train_loader = torch.utils.data.DataLoader(
Dataset(datadir, split="train"), shuffle=True, **kwargs
)
val_loader = torch.utils.data.DataLoader(
Dataset(datadir, split="valid"), shuffle=False, **kwargs
)
if resume_from:
print("Restoring from", resume_from)
checkpoint = torch.load(resume_from)
# 2. model
model = sym.models.SymmetryNet().to(device)
print("# of params:", count_parameters(model))
model = sym.utils.MyDataParallel(
model, device_ids=list(range(args["--devices"].count(",") + 1))
)
if resume_from:
for module_name in list(checkpoint["model_state_dict"].keys()):
if module_name.startswith("module.backbone.volume_network.fc"):
del checkpoint["model_state_dict"][module_name]
model.load_state_dict(checkpoint["model_state_dict"], strict=False)
# 3. optimizer
if CO.name == "Adam":
optim = torch.optim.Adam(model.parameters(), **CO.params)
elif CO.name == "SGD":
optim = torch.optim.SGD(model.parameters(), **CO.params)
else:
raise NotImplementedError
if resume_from and not args["--ignore-optim"]:
optim.load_state_dict(checkpoint["optim_state_dict"])
outdir = get_outdir(args["--identifier"])
shutil.copyfile(config_file, osp.join(outdir, "config_origin.yaml"))
print("outdir:", outdir)
try:
trainer = sym.trainer.Trainer(
device=device,
model=model,
optimizer=optim,
train_loader=train_loader,
val_loader=val_loader,
batch_size=batch_size,
out=outdir,
)
trainer.train()
except BaseException:
if len(glob.glob(f"{outdir}/viz/*")) <= 1:
shutil.rmtree(outdir)
raise
if __name__ == "__main__":
main()
| 29.113772 | 86 | 0.629988 |
import datetime
import glob
import os
import os.path as osp
import platform
import pprint
import random
import shlex
import shutil
import signal
import subprocess
import sys
import threading
import numpy as np
import torch
import yaml
from docopt import docopt
import sym
from sym.config import CI, CM, CO, C, load_config
from sym.datasets import ShapeNetDataset
def git_hash():
cmd = 'git log -n 1 --pretty="%h"'
ret = subprocess.check_output(shlex.split(cmd)).strip()
if isinstance(ret, bytes):
ret = ret.decode()
return ret
def get_outdir(identifier):
name = str(datetime.datetime.now().strftime("%y%m%d-%H%M%S"))
name += "-%s" % git_hash()
name += "-%s" % identifier
outdir = osp.join(osp.expanduser(CI.logdir), name)
if not osp.exists(outdir):
os.makedirs(outdir)
C.to_yaml(osp.join(outdir, "config.yaml"))
os.system(f"git diff HEAD > {outdir}/gitdiff.patch")
os.system(f"find -name '*.py' -print0 | tar -cJf {outdir}/src.tar.xz --null -T -")
return outdir
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
def main():
args = docopt(__doc__)
config_file = args["<yaml-config>"] or "config/shapenet.yaml"
C.update(C.from_yaml(filename=config_file))
if args["--from"]:
C.io.resume_from = args["--from"]
CI.update(C.io)
CM.update(C.model)
CO.update(C.optim)
pprint.pprint(C, indent=4)
resume_from = CI.resume_from
random.seed(0)
np.random.seed(0)
torch.manual_seed(0)
device_name = "cpu"
num_gpus = args["--devices"].count(",") + 1
os.environ["CUDA_VISIBLE_DEVICES"] = args["--devices"]
if torch.cuda.is_available():
device_name = "cuda"
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.deterministic = True
torch.cuda.manual_seed(0)
print("Let's use", torch.cuda.device_count(), "GPU(s)!")
else:
print("CUDA is not available")
device = torch.device(device_name)
# 1. dataset
batch_size = CM.batch_size * num_gpus
datadir = CI.datadir
kwargs = {
"batch_size": batch_size,
"num_workers": CI.num_workers,
"pin_memory": True,
}
if CI.dataset == "ShapeNet":
Dataset = ShapeNetDataset
else:
raise NotImplementedError
train_loader = torch.utils.data.DataLoader(
Dataset(datadir, split="train"), shuffle=True, **kwargs
)
val_loader = torch.utils.data.DataLoader(
Dataset(datadir, split="valid"), shuffle=False, **kwargs
)
if resume_from:
print("Restoring from", resume_from)
checkpoint = torch.load(resume_from)
# 2. model
model = sym.models.SymmetryNet().to(device)
print("# of params:", count_parameters(model))
model = sym.utils.MyDataParallel(
model, device_ids=list(range(args["--devices"].count(",") + 1))
)
if resume_from:
for module_name in list(checkpoint["model_state_dict"].keys()):
if module_name.startswith("module.backbone.volume_network.fc"):
del checkpoint["model_state_dict"][module_name]
model.load_state_dict(checkpoint["model_state_dict"], strict=False)
# 3. optimizer
if CO.name == "Adam":
optim = torch.optim.Adam(model.parameters(), **CO.params)
elif CO.name == "SGD":
optim = torch.optim.SGD(model.parameters(), **CO.params)
else:
raise NotImplementedError
if resume_from and not args["--ignore-optim"]:
optim.load_state_dict(checkpoint["optim_state_dict"])
outdir = get_outdir(args["--identifier"])
shutil.copyfile(config_file, osp.join(outdir, "config_origin.yaml"))
print("outdir:", outdir)
try:
trainer = sym.trainer.Trainer(
device=device,
model=model,
optimizer=optim,
train_loader=train_loader,
val_loader=val_loader,
batch_size=batch_size,
out=outdir,
)
trainer.train()
except BaseException:
if len(glob.glob(f"{outdir}/viz/*")) <= 1:
shutil.rmtree(outdir)
raise
if __name__ == "__main__":
main()
| true | true |
f72378220e9039ed041d978348918d27193da39e | 15,363 | py | Python | host-client/host.py | maxtheaxe/zoom-education-suite | e2939916df574eccb5c4107d6623fe4e84044661 | [
"Apache-2.0"
] | null | null | null | host-client/host.py | maxtheaxe/zoom-education-suite | e2939916df574eccb5c4107d6623fe4e84044661 | [
"Apache-2.0"
] | 1 | 2020-09-23T04:52:31.000Z | 2020-09-23T04:52:31.000Z | host-client/host.py | maxtheaxe/zoom-education-suite | e2939916df574eccb5c4107d6623fe4e84044661 | [
"Apache-2.0"
] | 1 | 2020-12-22T08:25:25.000Z | 2020-12-22T08:25:25.000Z | # Zoom Host Client - Zoom Education Suite - HooHacks2020 - maxtheaxe
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
# from bs4 import BeautifulSoup as bs
import sys
import re
import urllib.request as urlr
import time
import random
# launch() - launch sequence to get driver started, logged in, and prepared to work
def launch(room_link, headless = True):
print("\n\t--- Zoom Education Suite | Host Client ---\n")
driver = start_driver(headless) # start the driver and store it (will be returned)
login(driver, room_link) # log into the room with the room link
open_participants(driver) # open participants panel so data can be collected
return driver # return driver so it can be stored and worked on within GUI program
# start_driver() - starts the webdriver and returns it
# reference: https://browsersize.com/
# reference: https://stackoverflow.com/questions/23381324/how-can-i-control-chromedriver-open-window-size
def start_driver(headless = True):
# setup webdriver settings
options = webdriver.ChromeOptions() # hiding startup info that pollutes terminal
options.headless = headless # headless or not, passed as arg
options.add_experimental_option('excludeSwitches', ['enable-logging'])
# make window size bigger to see all buttons
options.add_argument("--window-size=1600,1200")
# start webdriver
return webdriver.Chrome(options=options)
# prompt() - prompts the host to enter the room link
def prompt():
# should probably be a tkinter window, don't know how packaging works with cmd line
return
# link_builder() - builds web link from og link to skip local app prompt
# future: add password support (for locked rooms)
def link_builder(room_link):
# replaces /j/ with /wc/join/ to open web client directly
web_link = re.sub("/j/", "/wc/join/", room_link)
return web_link
# login() - logs into the room
# reference: https://crossbrowsertesting.com/blog/test-automation/automate-login-with-selenium/
# reference: https://stackoverflow.com/questions/19035186/how-to-select-element-using-xpath-syntax-on-selenium-for-python
# future: add password support (for locked rooms)
def login(driver, room_link):
print("\tLogging in...\n")
web_link = link_builder(room_link) # convert to web client link
try: # try opening the given link, logging in
driver.get(web_link) # open zoom meeting login page
driver.find_element_by_id('inputname').send_keys("zoom edu bot") # enter bot name
# might need to account for room passwords if using private rooms
driver.find_element_by_id('joinBtn').click() # click login button
# driver.send_keys(u'\ue007') # press enter key (alt login method)
except: # bad link, try again
print("\tError: Login Failed. Check the link and try again.\n")
sys.exit()
try: # wait and make sure we're logged in, loaded into the room
wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'footer__leave-btn')))
if EC.visibility_of(driver.find_element_by_class_name("footer__leave-btn")):
print("\tSuccessfully logged in.\n")
except: # something went wrong, we weren't able to load into the room
print("\tError: Login Failed. Verify that you're connecting to the right room.\n")
sys.exit()
# click_participants() - click on the participants button
# originally always left open, made this to allow for closing to avoid interference
# refactor: combine this with click_chat() to make general menu opener
def click_participants(driver):
time.sleep(2)
try: # try to click it right away
# find it using the participants icon
driver.find_element_by_class_name("footer-button__participants-icon").click()
except: # if it isn't clickable (sometimes takes a sec to load properly)
print("\tFailed. Trying again, please wait...\n")
time.sleep(7)
driver.find_element_by_class_name("footer-button__participants-icon").click()
return
# open_participants() - opens the participants menu, loads all members
def open_participants(driver):
print("\tOpening participants list...\n")
click_participants(driver)
print("\tOpened participants list.\n")
return
# close_participants() - opens the participants menu, loads all members
def close_participants(driver):
print("\tClosing participants list...\n")
click_participants(driver)
print("\tClosed participants list.\n")
return
# count_reaction() - counts the number of a chosen reaction at a given time
def count_reaction(driver, reaction_name = "participants-icon__participants-raisehand"):
# find elements of given reaction class (hand raise by default)
react_list = driver.find_elements_by_class_name(reaction_name)
print("\tNumber of hands raised: " , len(react_list), "\n") # print total
return len(react_list) # return number of reactions
# who_participates() - checks who is currently participating (via reactions)
# reference: https://stackoverflow.com/questions/18079765/how-to-find-parent-elements-by-python-webdriver
def who_participates(driver, reaction_name = "participants-icon__participants-raisehand"):
participant_list = [] # empty list to hold participants
# find elements of given reaction class (hand raise by default)
react_list = driver.find_elements_by_class_name(reaction_name)
for i in range(len(react_list)): # for each reaction element (belongs to a person)
# go to grandparent element, so we can check the name (store in curr element)
react_list[i] = react_list[i].find_element_by_xpath("../..")
# get the name element (store in curr element)
react_list[i] = react_list[i].find_element_by_class_name("participants-item__display-name")
# refine to name string (store in curr element)
react_list[i] = react_list[i].get_attribute("innerHTML")
print("\tPeople raising hands: " , react_list, "\n") # print total
return react_list # return list of people reacting
# call_on() - calls on the first person to raise their hand; if it can't tell, randomizes
def call_on(driver):
hand_raiser_list = who_participates(driver) # check who is raising their hand rn
if (len(hand_raiser_list) == 0): # if no-one is raising their hand
print("\tYou can't call on anyone if no-one is raising their hand!\n")
return # return no-one
elif (len(hand_raiser_list) == 1): # if one person is raising their hand
print("\tThey raised their hand first, so you called on:",
hand_raiser_list[0], "\n") # print selection
return hand_raiser_list[0] # return the one person raising their hand
else: # if more than one person is raising their hand
chosen_person = random.choice(hand_raiser_list) # choose someone randomly
print("\tYou didn't see who was first, so you guessed and called on:",
chosen_person, "\n") # print selection
return chosen_person # return your "guess" at who was first
# identify_host() - identifies the name of the host
def identify_host(driver):
# creates target variable to hold element that is current subject of focus
target = driver.find_element_by_xpath(
"//*[contains(text(), '(Host)')]") # find the host's webElement
# "//*[text()='(Host)']") # find the host's webElement
# tried to accomodate for fake hosts, but had issues--not worth time in hackathon
if (target.get_attribute("class") != "participants-item__name-label"):
print("\tSome jerk named themself host to screw with this program.",
"Make them change their name.\n")
raise ValueError("Too complicated to handle fake hosts during hackathon.\n")
target = target.find_element_by_xpath("./..") # go to parent element
# get other child element of parent; contains host's name
target = target.find_element_by_class_name("participants-item__display-name")
# get innerHTML of actual host's name
recipient_name = target.get_attribute("innerHTML")
print("\tThe name of the host is:", recipient_name, "\n")
return recipient_name
# click_chat(driver) - opens or closes chat window
# refactor: combine this with open_participants to make general menu opener
def click_chat(driver):
time.sleep(2)
# had to handle making window size bigger because participants list cut off button
# see driver_start() for solution
try: # try to click it right away
# find it using the chat icon
driver.find_element_by_class_name("footer-button__chat-icon").click()
except: # if it isn't clickable (sometimes takes a sec to load properly)
print("\tFailed. Trying again, please wait...\n")
time.sleep(7)
driver.find_element_by_class_name("footer-button__chat-icon").click()
return # successfully clicked (hopefully)
# open_chat() - opens chat popup
def open_chat(driver):
print("\tOpening chat menu...\n")
click_chat(driver) # click on the chat button
print("\tOpened chat menu.\n")
return
# close_chat() - closes chat popup
def close_chat(driver):
print("\tClosing chat menu...\n")
click_chat(driver) # click on the chat button
print("\tClosed chat menu.\n")
return
# choose_recipient() - selects the chosen recipient from the dropdown
# reference: https://www.guru99.com/xpath-selenium.html
# reference: https://stackoverflow.com/questions/29346595/python-selenium-element-is-not-currently-interactable-and-may-not-be-manipulat
def choose_recipient(driver, recipient_name):
print("\tFinding target recipient.\n")
# open the dropdown menu
try: # try to find it right away
# find the dropdown menu
dropdown = driver.find_element_by_class_name(
# "chat-receiver-list__chat-control-receiver ax-outline-blue-important dropdown-toggle btn btn-default")
"chat-receiver-list__chat-control-receiver")
except: # if it isn't clickable (sometimes takes a sec to load properly)
print("\tFailed. Trying again, please wait...\n")
time.sleep(7)
dropdown = driver.find_element_by_class_name(
# "chat-receiver-list__chat-control-receiver ax-outline-blue-important dropdown-toggle btn btn-default")
"chat-receiver-list__chat-control-receiver")
dropdown.click() # click the dropdown menu
time.sleep(2) # lazy way to wait for it to load
# now find and click on the actual recipient
# first, focus on the actual dropdown menu of potential recipients
dropdown = driver.find_element_by_class_name("chat-receiver-list__scrollbar-height")
# find the element with our recipient's name
# dropdown.find_element_by_xpath('//dd[@data-value="' + recipient_name + '"])').click()
# build our string for xpath (probably a better way, but oh well)
xpath_string = "//a[contains(text(), '" + recipient_name + "')]"
# print("testing name:\n", xpath_string)
dropdown_element = dropdown.find_element_by_xpath(xpath_string)
# now go up a level to the clickable parent
dropdown_element = dropdown_element.find_element_by_xpath("./..")
# now actually click the element so we can send 'em a message
dropdown_element.click()
# time.sleep(1) # just to be sure (testing)
return
# type_message() - types out message in chatbox and sends it
def type_message(driver, message):
# grab chatbox by its class name
chatbox = driver.find_element_by_class_name("chat-box__chat-textarea")
# type out the given message in the chatbox
chatbox.send_keys(message)
# hit enter in the chatbox to send the message
chatbox.send_keys(u'\ue007')
return
# send_message() - have the bot send someone (by default the host) a message
# random string of numbers for default host string accounts for "funny" students
# who might name themselves "host." This string is never visible, so they'd have to guess
# reference: https://stackoverflow.com/questions/12323403/how-do-i-find-an-element-that-contains-specific-text-in-selenium-webdriver-pyth
def send_message(driver, recipient = "host_69974030947301", message = "I'm a bot!"):
open_chat(driver) # open the chat menu, to enable sending a message
recipient_name = "" # temporary storage for recipient name
# participants-item__name-label
if (recipient == "host_69974030947301"): # if the recipient is default
# call identify_host() to get host's name
recipient_name = identify_host(driver) # set host's name to recipient name
else:
recipient_name = recipient # set recipient_name to input name
choose_recipient(driver, recipient_name)
type_message(driver, message)
print("\tSending message to:", recipient_name, "\n")
close_chat(driver) # close the chat menu, since you're done sending a message
return recipient_name
# take_attendance() - take attendance of who is there at current time
# I'd have avoided the second list creation, but attendee list was polluted by bot names
# could add filtering out prof later, but requires searching addditional elements
def take_attendance(driver):
# collect all attendees into list by looking for spans with the following class
attendee_list = driver.find_elements_by_class_name("participants-item__display-name")
new_attendee_list = [] # for storing refined list (filters out self)
for i in range(len(attendee_list)): # for each webElement in list of attendees
if (attendee_list[i].get_attribute("innerHTML") != "zoom edu bot"): # if not bot
# then refine to name and add to the new list
new_attendee_list.append(attendee_list[i].get_attribute("innerHTML"))
print("\tStudents: ", new_attendee_list, "\n") # print list of attendee names
return new_attendee_list # return attendee list
# leave_meeting() - leaves the meeting
# primarily to save sanity during testing--there are currently so many old bots logged in
# broken: clicks getting intercepted(??) for some reason, non-essential feature
def leave_meeting(driver):
print("\tLeaving meeting...\n")
driver.find_element_by_class_name("footer__leave-btn").click()
time.sleep(2) # wait a sec, doesn't need to be great
# hit tab twice to go to button, could be done better
# go away, it's just a sanity saver
# actions = ActionChains(driver)
# actions.send_keys(Keys.TAB).perform() # press tab key
# time.sleep(1)
# actions.send_keys(Keys.TAB).perform() # press tab key again
# time.sleep(1)
# actions.send_keys(Keys.TAB).perform() # press tab key again
# time.sleep(1)
# actions.send_keys(Keys.ENTER).perform() # press enter key
# target = driver.find_element_by_xpath("//*[contains(text(), 'Leave Meeting')]")
print("\tSuccessfully left the meeting. See you next time!\n")
return
# call_first() - calls on the first person to raise their hand and notifies them
def call_first(driver, message = "You're up!"):
chosen_person = call_on(driver) # calls on the first person to raise hand and stores
send_message(driver, chosen_person, message) # sends the person who was called on the given message
return
def main(argv):
print("\n\t--- Zoom Education Suite | Host Client ---\n")
# testing
# link_builder() testing
# print("original link: ", argv[1])
# print("\n new link: ", link_builder(argv[1]))
# start the webdriver (True = headless mode)
driver = start_driver(True)
# run program
login(driver, argv[1])
open_participants(driver)
count_reaction(driver)
take_attendance(driver)
who_participates(driver)
call_on(driver)
send_message(driver, "Everyone", "I'm ready to rumble, baby!") # opens and closes chat within the func
time.sleep(2)
# leave_meeting() is broken, but non-essential
# leave_meeting(driver)
time.sleep(10)
print("\tFinished.\n")
if __name__ == '__main__':
main(sys.argv) | 48.617089 | 137 | 0.757795 |
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import sys
import re
import urllib.request as urlr
import time
import random
def launch(room_link, headless = True):
print("\n\t--- Zoom Education Suite | Host Client ---\n")
driver = start_driver(headless)
login(driver, room_link)
open_participants(driver)
return driver
def start_driver(headless = True):
options = webdriver.ChromeOptions()
options.headless = headless
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_argument("--window-size=1600,1200")
return webdriver.Chrome(options=options)
def prompt():
return
# link_builder() - builds web link from og link to skip local app prompt
# future: add password support (for locked rooms)
def link_builder(room_link):
# replaces /j/ with /wc/join/ to open web client directly
web_link = re.sub("/j/", "/wc/join/", room_link)
return web_link
# login() - logs into the room
# reference: https://crossbrowsertesting.com/blog/test-automation/automate-login-with-selenium/
# reference: https://stackoverflow.com/questions/19035186/how-to-select-element-using-xpath-syntax-on-selenium-for-python
# future: add password support (for locked rooms)
def login(driver, room_link):
print("\tLogging in...\n")
web_link = link_builder(room_link) # convert to web client link
try: # try opening the given link, logging in
driver.get(web_link) # open zoom meeting login page
driver.find_element_by_id('inputname').send_keys("zoom edu bot") # enter bot name
# might need to account for room passwords if using private rooms
driver.find_element_by_id('joinBtn').click() # click login button
# driver.send_keys(u'\ue007') # press enter key (alt login method)
except: # bad link, try again
print("\tError: Login Failed. Check the link and try again.\n")
sys.exit()
try: # wait and make sure we're logged in, loaded into the room
wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'footer__leave-btn')))
if EC.visibility_of(driver.find_element_by_class_name("footer__leave-btn")):
print("\tSuccessfully logged in.\n")
except:
print("\tError: Login Failed. Verify that you're connecting to the right room.\n")
sys.exit()
def click_participants(driver):
time.sleep(2)
try:
driver.find_element_by_class_name("footer-button__participants-icon").click()
except:
print("\tFailed. Trying again, please wait...\n")
time.sleep(7)
driver.find_element_by_class_name("footer-button__participants-icon").click()
return
# open_participants() - opens the participants menu, loads all members
def open_participants(driver):
print("\tOpening participants list...\n")
click_participants(driver)
print("\tOpened participants list.\n")
return
# close_participants() - opens the participants menu, loads all members
def close_participants(driver):
print("\tClosing participants list...\n")
click_participants(driver)
print("\tClosed participants list.\n")
return
# count_reaction() - counts the number of a chosen reaction at a given time
def count_reaction(driver, reaction_name = "participants-icon__participants-raisehand"):
# find elements of given reaction class (hand raise by default)
react_list = driver.find_elements_by_class_name(reaction_name)
print("\tNumber of hands raised: " , len(react_list), "\n") # print total
return len(react_list) # return number of reactions
# who_participates() - checks who is currently participating (via reactions)
# reference: https://stackoverflow.com/questions/18079765/how-to-find-parent-elements-by-python-webdriver
def who_participates(driver, reaction_name = "participants-icon__participants-raisehand"):
participant_list = [] # empty list to hold participants
# find elements of given reaction class (hand raise by default)
react_list = driver.find_elements_by_class_name(reaction_name)
for i in range(len(react_list)): # for each reaction element (belongs to a person)
# go to grandparent element, so we can check the name (store in curr element)
react_list[i] = react_list[i].find_element_by_xpath("../..")
# get the name element (store in curr element)
react_list[i] = react_list[i].find_element_by_class_name("participants-item__display-name")
# refine to name string (store in curr element)
react_list[i] = react_list[i].get_attribute("innerHTML")
print("\tPeople raising hands: " , react_list, "\n") # print total
return react_list # return list of people reacting
# call_on() - calls on the first person to raise their hand; if it can't tell, randomizes
def call_on(driver):
hand_raiser_list = who_participates(driver)
if (len(hand_raiser_list) == 0):
print("\tYou can't call on anyone if no-one is raising their hand!\n")
return # return no-one
elif (len(hand_raiser_list) == 1): # if one person is raising their hand
print("\tThey raised their hand first, so you called on:",
hand_raiser_list[0], "\n") # print selection
return hand_raiser_list[0] # return the one person raising their hand
else: # if more than one person is raising their hand
chosen_person = random.choice(hand_raiser_list) # choose someone randomly
print("\tYou didn't see who was first, so you guessed and called on:",
chosen_person, "\n")
return chosen_person
def identify_host(driver):
target = driver.find_element_by_xpath(
"//*[contains(text(), '(Host)')]")
# "//*[text()='(Host)']") # find the host's webElement
if (target.get_attribute("class") != "participants-item__name-label"):
print("\tSome jerk named themself host to screw with this program.",
"Make them change their name.\n")
raise ValueError("Too complicated to handle fake hosts during hackathon.\n")
target = target.find_element_by_xpath("./..")
target = target.find_element_by_class_name("participants-item__display-name")
# get innerHTML of actual host's name
recipient_name = target.get_attribute("innerHTML")
print("\tThe name of the host is:", recipient_name, "\n")
return recipient_name
def click_chat(driver):
time.sleep(2)
try:
driver.find_element_by_class_name("footer-button__chat-icon").click()
except:
print("\tFailed. Trying again, please wait...\n")
time.sleep(7)
driver.find_element_by_class_name("footer-button__chat-icon").click()
return # successfully clicked (hopefully)
# open_chat() - opens chat popup
def open_chat(driver):
print("\tOpening chat menu...\n")
click_chat(driver) # click on the chat button
print("\tOpened chat menu.\n")
return
# close_chat() - closes chat popup
def close_chat(driver):
print("\tClosing chat menu...\n")
click_chat(driver) # click on the chat button
print("\tClosed chat menu.\n")
return
# choose_recipient() - selects the chosen recipient from the dropdown
# reference: https://www.guru99.com/xpath-selenium.html
# reference: https://stackoverflow.com/questions/29346595/python-selenium-element-is-not-currently-interactable-and-may-not-be-manipulat
def choose_recipient(driver, recipient_name):
print("\tFinding target recipient.\n")
# open the dropdown menu
try: # try to find it right away
# find the dropdown menu
dropdown = driver.find_element_by_class_name(
# "chat-receiver-list__chat-control-receiver ax-outline-blue-important dropdown-toggle btn btn-default")
"chat-receiver-list__chat-control-receiver")
except: # if it isn't clickable (sometimes takes a sec to load properly)
print("\tFailed. Trying again, please wait...\n")
time.sleep(7)
dropdown = driver.find_element_by_class_name(
"chat-receiver-list__chat-control-receiver")
dropdown.click()
time.sleep(2)
dropdown = driver.find_element_by_class_name("chat-receiver-list__scrollbar-height")
# dropdown.find_element_by_xpath('//dd[@data-value="' + recipient_name + '"])').click()
# build our string for xpath (probably a better way, but oh well)
xpath_string = "//a[contains(text(), '" + recipient_name + "')]"
# print("testing name:\n", xpath_string)
dropdown_element = dropdown.find_element_by_xpath(xpath_string)
# now go up a level to the clickable parent
dropdown_element = dropdown_element.find_element_by_xpath("./..")
# now actually click the element so we can send 'em a message
dropdown_element.click()
(driver, message):
chatbox = driver.find_element_by_class_name("chat-box__chat-textarea")
chatbox.send_keys(message)
chatbox.send_keys(u'\ue007')
return
# reference: https://stackoverflow.com/questions/12323403/how-do-i-find-an-element-that-contains-specific-text-in-selenium-webdriver-pyth
def send_message(driver, recipient = "host_69974030947301", message = "I'm a bot!"):
open_chat(driver)
recipient_name = ""
if (recipient == "host_69974030947301"):
recipient_name = identify_host(driver) # set host's name to recipient name
else:
recipient_name = recipient
choose_recipient(driver, recipient_name)
type_message(driver, message)
print("\tSending message to:", recipient_name, "\n")
close_chat(driver)
return recipient_name
# take_attendance() - take attendance of who is there at current time
# I'd have avoided the second list creation, but attendee list was polluted by bot names
def take_attendance(driver):
attendee_list = driver.find_elements_by_class_name("participants-item__display-name")
new_attendee_list = []
for i in range(len(attendee_list)):
if (attendee_list[i].get_attribute("innerHTML") != "zoom edu bot"):
new_attendee_list.append(attendee_list[i].get_attribute("innerHTML"))
print("\tStudents: ", new_attendee_list, "\n")
return new_attendee_list
def leave_meeting(driver):
print("\tLeaving meeting...\n")
driver.find_element_by_class_name("footer__leave-btn").click()
time.sleep(2)
# hit tab twice to go to button, could be done better
# go away, it's just a sanity saver
\n")
return
def call_first(driver, message = "You're up!"):
chosen_person = call_on(driver) # calls on the first person to raise hand and stores
send_message(driver, chosen_person, message) # sends the person who was called on the given message
return
def main(argv):
print("\n\t--- Zoom Education Suite | Host Client ---\n")
# testing
# link_builder() testing
# print("original link: ", argv[1])
# print("\n new link: ", link_builder(argv[1]))
# start the webdriver (True = headless mode)
driver = start_driver(True)
# run program
login(driver, argv[1])
open_participants(driver)
count_reaction(driver)
take_attendance(driver)
who_participates(driver)
call_on(driver)
send_message(driver, "Everyone", "I'm ready to rumble, baby!")
time.sleep(2)
time.sleep(10)
print("\tFinished.\n")
if __name__ == '__main__':
main(sys.argv) | true | true |
f72379fae5f3003967b64fa675df2b543eea99bb | 1,334 | py | Python | beginner/01_led_one_blink.py | manfre-lorson/raspberrypi | 5581ad0c670ce765d8035e1bdb7e82c9b613a061 | [
"Apache-2.0"
] | null | null | null | beginner/01_led_one_blink.py | manfre-lorson/raspberrypi | 5581ad0c670ce765d8035e1bdb7e82c9b613a061 | [
"Apache-2.0"
] | null | null | null | beginner/01_led_one_blink.py | manfre-lorson/raspberrypi | 5581ad0c670ce765d8035e1bdb7e82c9b613a061 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/python3
"""
Created on Wed Mar 25 16:26:10 2020
@author: manfre-lorson
@work: ansteuern einer diode 10 mal blinken
"""
##########################################################################
##########################################################################
"""
def schaltplan():
'''
show schaltplan
'''
import sys
sys.path.append('path to diretory of file')
import gpio_board as gb
# plot board
gb.plot_board()
# plot connections and elements
gb.con([gb.pp.j, -3, gb.pp.j, -35], 'b')
gb.diode(gb.pp.g, -33)
gb.resistor(gb.pp.h, -29, 'R1')
gb.con([gb.pp.i, -29, gb.pp.i, gb.bcm('spice1')], 'y')
# plot legende
gb.diode(gb.pp.j + 4, -3)
gb.anno(gb.pp.j + 4, -4, 'LED red' )
gb.resistor(gb.pp.j + 4, -6, 'R1')
gb.anno(gb.pp.j + 4, - 8, '120 Ohm')
# show schaltplan:
schaltplan()
"""
##########################################################################
##########################################################################
import RPi.GPIO as gpio
import time
if __name__=="__main__":
gpio.setmode(gpio.BOARD)
gpio.setup(26, gpio.OUT)
for i in range(10):
gpio.output(26, gpio.HIGH)
time.sleep(1)
gpio.output(26, gpio.LOW)
time.sleep(1)
gpio.cleanup()
| 22.610169 | 74 | 0.437781 | true | true | |
f7237b065e7ba4230639c9afd16ab70cabf6e7be | 942 | py | Python | tests/test_entropy.py | williamscales/pytopocomplexity | f739b7695066f5da40a9610d21579983a12e76ad | [
"Apache-2.0"
] | null | null | null | tests/test_entropy.py | williamscales/pytopocomplexity | f739b7695066f5da40a9610d21579983a12e76ad | [
"Apache-2.0"
] | null | null | null | tests/test_entropy.py | williamscales/pytopocomplexity | f739b7695066f5da40a9610d21579983a12e76ad | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for `pytopocomplexity.entropy`"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import (ascii, bytes, chr, dict, filter, hex, input, int,
map, next, oct, open, pow, range, round, str,
super, zip)
import numpy as np
from numpy.random import random_sample
from pytopocomplexity.entropy import estimate_entropy
def test_entropy_is_zero_for_unimodal_function():
"""Test that the entropy of a function with one extremum is zero."""
def func_one_min(x):
"""Objective function with global minimum at ``x == 0``."""
return x**2
#initial_models = 2*random_sample((100,100)) - 1
initial_models = 2*random_sample(100) - 1
entropy = estimate_entropy(func_one_min, initial_models, 1e-8, 1e5)
assert entropy == 0
| 36.230769 | 78 | 0.654989 |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import (ascii, bytes, chr, dict, filter, hex, input, int,
map, next, oct, open, pow, range, round, str,
super, zip)
import numpy as np
from numpy.random import random_sample
from pytopocomplexity.entropy import estimate_entropy
def test_entropy_is_zero_for_unimodal_function():
def func_one_min(x):
return x**2
initial_models = 2*random_sample(100) - 1
entropy = estimate_entropy(func_one_min, initial_models, 1e-8, 1e5)
assert entropy == 0
| true | true |
f7237b4f0638bf5245e8c7fd5d3e680e53b43e49 | 1,163 | py | Python | course_catalog/migrations/0005_course_last_modified.py | mitodl/open-discussions | ab6e9fac70b8a1222a84e78ba778a7a065c20541 | [
"BSD-3-Clause"
] | 12 | 2017-09-27T21:23:27.000Z | 2020-12-25T04:31:30.000Z | course_catalog/migrations/0005_course_last_modified.py | mitodl/open-discussions | ab6e9fac70b8a1222a84e78ba778a7a065c20541 | [
"BSD-3-Clause"
] | 3,293 | 2017-06-30T18:16:01.000Z | 2022-03-31T18:01:34.000Z | course_catalog/migrations/0005_course_last_modified.py | mitodl/open-discussions | ab6e9fac70b8a1222a84e78ba778a7a065c20541 | [
"BSD-3-Clause"
] | 1 | 2020-04-13T12:19:57.000Z | 2020-04-13T12:19:57.000Z | # Generated by Django 2.0.8 on 2019-01-11 00:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("course_catalog", "0004_make_short_description_nullable_20190110_2018")
]
operations = [
migrations.AddField(
model_name="course",
name="last_modified",
field=models.DateTimeField(null=True),
),
migrations.AlterField(
model_name="course",
name="instructors",
field=models.ManyToManyField(
blank=True, related_name="courses", to="course_catalog.CourseInstructor"
),
),
migrations.AlterField(
model_name="course",
name="prices",
field=models.ManyToManyField(
blank=True, related_name="courses", to="course_catalog.CoursePrice"
),
),
migrations.AlterField(
model_name="course",
name="topics",
field=models.ManyToManyField(
blank=True, related_name="courses", to="course_catalog.CourseTopic"
),
),
]
| 29.075 | 88 | 0.568358 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("course_catalog", "0004_make_short_description_nullable_20190110_2018")
]
operations = [
migrations.AddField(
model_name="course",
name="last_modified",
field=models.DateTimeField(null=True),
),
migrations.AlterField(
model_name="course",
name="instructors",
field=models.ManyToManyField(
blank=True, related_name="courses", to="course_catalog.CourseInstructor"
),
),
migrations.AlterField(
model_name="course",
name="prices",
field=models.ManyToManyField(
blank=True, related_name="courses", to="course_catalog.CoursePrice"
),
),
migrations.AlterField(
model_name="course",
name="topics",
field=models.ManyToManyField(
blank=True, related_name="courses", to="course_catalog.CourseTopic"
),
),
]
| true | true |
f7237b7e3bfc0ef4f29563b378b6e0e0f7ae24c4 | 421 | py | Python | python/benchmark/utils/powerset.py | jkomyno/lattice-submodular-maximization | e03c8bcc5fcf5bf79a6ae81f145757cf3fdff7cb | [
"MIT"
] | 1 | 2021-11-16T18:16:42.000Z | 2021-11-16T18:16:42.000Z | python/benchmark/utils/powerset.py | jkomyno/lattice-submodular-maximization | e03c8bcc5fcf5bf79a6ae81f145757cf3fdff7cb | [
"MIT"
] | null | null | null | python/benchmark/utils/powerset.py | jkomyno/lattice-submodular-maximization | e03c8bcc5fcf5bf79a6ae81f145757cf3fdff7cb | [
"MIT"
] | null | null | null | import numpy as np
import itertools
from nptyping import NDArray
from typing import Iterator
from ..objective import Objective
def powerset(f: Objective) -> Iterator[NDArray[int]]:
"""
Inumerate b^n possible vectors in the integer lattice.
:param f: integer-lattice submodular function objective
"""
return map(lambda t: np.array([*t]),
itertools.product(range(f.b + 1), repeat=f.n))
| 28.066667 | 61 | 0.698337 | import numpy as np
import itertools
from nptyping import NDArray
from typing import Iterator
from ..objective import Objective
def powerset(f: Objective) -> Iterator[NDArray[int]]:
return map(lambda t: np.array([*t]),
itertools.product(range(f.b + 1), repeat=f.n))
| true | true |
f7237c54fd1c0013c860e853edef75dfbd133a53 | 7,668 | py | Python | examples/basic_tutorials/tutorial_cifar10_placeholder.py | JingqingZ/tensorlayer2 | 289a0402bd64f6a423aa574f10ac8ad8efcb7b66 | [
"Apache-2.0"
] | null | null | null | examples/basic_tutorials/tutorial_cifar10_placeholder.py | JingqingZ/tensorlayer2 | 289a0402bd64f6a423aa574f10ac8ad8efcb7b66 | [
"Apache-2.0"
] | null | null | null | examples/basic_tutorials/tutorial_cifar10_placeholder.py | JingqingZ/tensorlayer2 | 289a0402bd64f6a423aa574f10ac8ad8efcb7b66 | [
"Apache-2.0"
] | null | null | null | #! /usr/bin/python
# -*- coding: utf-8 -*-
import time
import numpy as np
import tensorflow as tf
import tensorlayer as tl
from tensorlayer.layers import *
tf.logging.set_verbosity(tf.logging.DEBUG)
tl.logging.set_verbosity(tl.logging.DEBUG)
sess = tf.InteractiveSession()
X_train, y_train, X_test, y_test = tl.files.load_cifar10_dataset(shape=(-1, 32, 32, 3), plotable=False)
def model(x, y_, reuse):
W_init = tf.truncated_normal_initializer(stddev=5e-2)
W_init2 = tf.truncated_normal_initializer(stddev=0.04)
b_init2 = tf.constant_initializer(value=0.1)
with tf.variable_scope("model", reuse=reuse):
net = InputLayer(x, name='input')
net = Conv2d(net, 64, (5, 5), (1, 1), act=tf.nn.relu, padding='SAME', W_init=W_init, name='cnn1')
net = MaxPool2d(net, (3, 3), (2, 2), padding='SAME', name='pool1')
net = LocalResponseNormLayer(net, depth_radius=4, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name='norm1')
net = Conv2d(net, 64, (5, 5), (1, 1), act=tf.nn.relu, padding='SAME', W_init=W_init, name='cnn2')
net = LocalResponseNormLayer(net, depth_radius=4, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name='norm2')
net = MaxPool2d(net, (3, 3), (2, 2), padding='SAME', name='pool2')
net = FlattenLayer(net, name='flatten')
net = DenseLayer(net, 384, act=tf.nn.relu, W_init=W_init2, b_init=b_init2, name='d1relu')
net = DenseLayer(net, 192, act=tf.nn.relu, W_init=W_init2, b_init=b_init2, name='d2relu')
net = DenseLayer(net, 10, act=None, W_init=W_init2, name='output')
y = net.outputs
ce = tl.cost.cross_entropy(y, y_, name='cost')
# L2 for the MLP, without this, the accuracy will be reduced by 15%.
L2 = 0
for p in tl.layers.get_variables_with_name('relu/W', True, True):
L2 += tf.contrib.layers.l2_regularizer(0.004)(p)
cost = ce + L2
correct_prediction = tf.equal(tf.argmax(y, 1), y_)
acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
return net, cost, acc
def model_batch_norm(x, y_, reuse, is_train):
"""Batch normalization should be placed before rectifier."""
W_init = tf.truncated_normal_initializer(stddev=5e-2)
W_init2 = tf.truncated_normal_initializer(stddev=0.04)
b_init2 = tf.constant_initializer(value=0.1)
with tf.variable_scope("model", reuse=reuse):
net = InputLayer(x, name='input')
net = Conv2d(net, 64, (5, 5), (1, 1), padding='SAME', W_init=W_init, b_init=None, name='cnn1')
net = BatchNormLayer(net, decay=0.99, is_train=is_train, act=tf.nn.relu, name='batch1')
net = MaxPool2d(net, (3, 3), (2, 2), padding='SAME', name='pool1')
net = Conv2d(net, 64, (5, 5), (1, 1), padding='SAME', W_init=W_init, b_init=None, name='cnn2')
net = BatchNormLayer(net, decay=0.99, is_train=is_train, act=tf.nn.relu, name='batch2')
net = MaxPool2d(net, (3, 3), (2, 2), padding='SAME', name='pool2')
net = FlattenLayer(net, name='flatten') # output: (batch_size, 2304)
net = DenseLayer(net, 384, act=tf.nn.relu, W_init=W_init2, b_init=b_init2, name='d1relu')
net = DenseLayer(net, 192, act=tf.nn.relu, W_init=W_init2, b_init=b_init2, name='d2relu')
net = DenseLayer(net, 10, act=None, W_init=W_init2, name='output')
y = net.outputs
ce = tl.cost.cross_entropy(y, y_, name='cost')
# L2 for the MLP, without this, the accuracy will be reduced by 15%.
L2 = 0
for p in tl.layers.get_variables_with_name('relu/W', True, True):
L2 += tf.contrib.layers.l2_regularizer(0.004)(p)
cost = ce + L2
correct_prediction = tf.equal(tf.argmax(y, 1), y_)
acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
return net, cost, acc
def distort_fn(x, is_train=False):
"""
The images are processed as follows:
.. They are cropped to 24 x 24 pixels, centrally for evaluation or randomly for training.
.. They are approximately whitened to make the model insensitive to dynamic range.
For training, we additionally apply a series of random distortions to
artificially increase the data set size:
.. Randomly flip the image from left to right.
.. Randomly distort the image brightness.
"""
# print('begin',x.shape, np.min(x), np.max(x))
x = tl.prepro.crop(x, 24, 24, is_random=is_train)
# print('after crop',x.shape, np.min(x), np.max(x))
if is_train:
# x = tl.prepro.zoom(x, zoom_range=(0.9, 1.0), is_random=True)
# print('after zoom', x.shape, np.min(x), np.max(x))
x = tl.prepro.flip_axis(x, axis=1, is_random=True)
# print('after flip',x.shape, np.min(x), np.max(x))
x = tl.prepro.brightness(x, gamma=0.1, gain=1, is_random=True)
# print('after brightness',x.shape, np.min(x), np.max(x))
# tmp = np.max(x)
# x += np.random.uniform(-20, 20)
# x /= tmp
# normalize the image
x = (x - np.mean(x)) / max(np.std(x), 1e-5) # avoid values divided by 0
# print('after norm', x.shape, np.min(x), np.max(x), np.mean(x))
return x
x = tf.placeholder(dtype=tf.float32, shape=[None, 24, 24, 3], name='x')
y_ = tf.placeholder(dtype=tf.int64, shape=[None], name='y_')
# using local response normalization
# network, cost, _ = model(x, y_, False)
# _, cost_test, acc = model(x, y_, True)
# you may want to try batch normalization
network, cost, _ = model_batch_norm(x, y_, False, is_train=True)
_, cost_test, acc = model_batch_norm(x, y_, True, is_train=False)
# train
n_epoch = 50000
learning_rate = 0.0001
print_freq = 1
batch_size = 128
train_params = network.all_params
train_op = tf.train.AdamOptimizer(learning_rate, beta1=0.9, beta2=0.999, epsilon=1e-08,
use_locking=False).minimize(cost, var_list=train_params)
sess.run(tf.global_variables_initializer())
network.print_params(False)
network.print_layers()
print(' learning_rate: %f' % learning_rate)
print(' batch_size: %d' % batch_size)
for epoch in range(n_epoch):
start_time = time.time()
for X_train_a, y_train_a in tl.iterate.minibatches(X_train, y_train, batch_size, shuffle=True):
X_train_a = tl.prepro.threading_data(X_train_a, fn=distort_fn, is_train=True) # data augmentation for training
sess.run(train_op, feed_dict={x: X_train_a, y_: y_train_a})
if epoch + 1 == 1 or (epoch + 1) % print_freq == 0:
print("Epoch %d of %d took %fs" % (epoch + 1, n_epoch, time.time() - start_time))
# train_loss, train_acc, n_batch = 0, 0, 0
# for X_train_a, y_train_a in tl.iterate.minibatches(
# X_train, y_train, batch_size, shuffle=True):
# X_train_a = tl.prepro.threading_data(X_train_a, fn=distort_fn, is_train=False) # central crop
# err, ac = sess.run([cost_test, acc], feed_dict={x: X_train_a, y_: y_train_a})
# train_loss += err; train_acc += ac; n_batch += 1
# print(" train loss: %f" % (train_loss/ n_batch))
# print(" train acc: %f" % (train_acc/ n_batch))
test_loss, test_acc, n_batch = 0, 0, 0
for X_test_a, y_test_a in tl.iterate.minibatches(X_test, y_test, batch_size, shuffle=False):
X_test_a = tl.prepro.threading_data(X_test_a, fn=distort_fn, is_train=False) # central crop
err, ac = sess.run([cost_test, acc], feed_dict={x: X_test_a, y_: y_test_a})
test_loss += err
test_acc += ac
n_batch += 1
print(" test loss: %f" % (test_loss / n_batch))
print(" test acc: %f" % (test_acc / n_batch))
| 45.372781 | 119 | 0.638237 |
import time
import numpy as np
import tensorflow as tf
import tensorlayer as tl
from tensorlayer.layers import *
tf.logging.set_verbosity(tf.logging.DEBUG)
tl.logging.set_verbosity(tl.logging.DEBUG)
sess = tf.InteractiveSession()
X_train, y_train, X_test, y_test = tl.files.load_cifar10_dataset(shape=(-1, 32, 32, 3), plotable=False)
def model(x, y_, reuse):
W_init = tf.truncated_normal_initializer(stddev=5e-2)
W_init2 = tf.truncated_normal_initializer(stddev=0.04)
b_init2 = tf.constant_initializer(value=0.1)
with tf.variable_scope("model", reuse=reuse):
net = InputLayer(x, name='input')
net = Conv2d(net, 64, (5, 5), (1, 1), act=tf.nn.relu, padding='SAME', W_init=W_init, name='cnn1')
net = MaxPool2d(net, (3, 3), (2, 2), padding='SAME', name='pool1')
net = LocalResponseNormLayer(net, depth_radius=4, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name='norm1')
net = Conv2d(net, 64, (5, 5), (1, 1), act=tf.nn.relu, padding='SAME', W_init=W_init, name='cnn2')
net = LocalResponseNormLayer(net, depth_radius=4, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name='norm2')
net = MaxPool2d(net, (3, 3), (2, 2), padding='SAME', name='pool2')
net = FlattenLayer(net, name='flatten')
net = DenseLayer(net, 384, act=tf.nn.relu, W_init=W_init2, b_init=b_init2, name='d1relu')
net = DenseLayer(net, 192, act=tf.nn.relu, W_init=W_init2, b_init=b_init2, name='d2relu')
net = DenseLayer(net, 10, act=None, W_init=W_init2, name='output')
y = net.outputs
ce = tl.cost.cross_entropy(y, y_, name='cost')
L2 = 0
for p in tl.layers.get_variables_with_name('relu/W', True, True):
L2 += tf.contrib.layers.l2_regularizer(0.004)(p)
cost = ce + L2
correct_prediction = tf.equal(tf.argmax(y, 1), y_)
acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
return net, cost, acc
def model_batch_norm(x, y_, reuse, is_train):
W_init = tf.truncated_normal_initializer(stddev=5e-2)
W_init2 = tf.truncated_normal_initializer(stddev=0.04)
b_init2 = tf.constant_initializer(value=0.1)
with tf.variable_scope("model", reuse=reuse):
net = InputLayer(x, name='input')
net = Conv2d(net, 64, (5, 5), (1, 1), padding='SAME', W_init=W_init, b_init=None, name='cnn1')
net = BatchNormLayer(net, decay=0.99, is_train=is_train, act=tf.nn.relu, name='batch1')
net = MaxPool2d(net, (3, 3), (2, 2), padding='SAME', name='pool1')
net = Conv2d(net, 64, (5, 5), (1, 1), padding='SAME', W_init=W_init, b_init=None, name='cnn2')
net = BatchNormLayer(net, decay=0.99, is_train=is_train, act=tf.nn.relu, name='batch2')
net = MaxPool2d(net, (3, 3), (2, 2), padding='SAME', name='pool2')
net = FlattenLayer(net, name='flatten')
net = DenseLayer(net, 384, act=tf.nn.relu, W_init=W_init2, b_init=b_init2, name='d1relu')
net = DenseLayer(net, 192, act=tf.nn.relu, W_init=W_init2, b_init=b_init2, name='d2relu')
net = DenseLayer(net, 10, act=None, W_init=W_init2, name='output')
y = net.outputs
ce = tl.cost.cross_entropy(y, y_, name='cost')
L2 = 0
for p in tl.layers.get_variables_with_name('relu/W', True, True):
L2 += tf.contrib.layers.l2_regularizer(0.004)(p)
cost = ce + L2
correct_prediction = tf.equal(tf.argmax(y, 1), y_)
acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
return net, cost, acc
def distort_fn(x, is_train=False):
x = tl.prepro.crop(x, 24, 24, is_random=is_train)
if is_train:
x = tl.prepro.flip_axis(x, axis=1, is_random=True)
x = tl.prepro.brightness(x, gamma=0.1, gain=1, is_random=True)
x = (x - np.mean(x)) / max(np.std(x), 1e-5)
return x
x = tf.placeholder(dtype=tf.float32, shape=[None, 24, 24, 3], name='x')
y_ = tf.placeholder(dtype=tf.int64, shape=[None], name='y_')
network, cost, _ = model_batch_norm(x, y_, False, is_train=True)
_, cost_test, acc = model_batch_norm(x, y_, True, is_train=False)
n_epoch = 50000
learning_rate = 0.0001
print_freq = 1
batch_size = 128
train_params = network.all_params
train_op = tf.train.AdamOptimizer(learning_rate, beta1=0.9, beta2=0.999, epsilon=1e-08,
use_locking=False).minimize(cost, var_list=train_params)
sess.run(tf.global_variables_initializer())
network.print_params(False)
network.print_layers()
print(' learning_rate: %f' % learning_rate)
print(' batch_size: %d' % batch_size)
for epoch in range(n_epoch):
start_time = time.time()
for X_train_a, y_train_a in tl.iterate.minibatches(X_train, y_train, batch_size, shuffle=True):
X_train_a = tl.prepro.threading_data(X_train_a, fn=distort_fn, is_train=True)
sess.run(train_op, feed_dict={x: X_train_a, y_: y_train_a})
if epoch + 1 == 1 or (epoch + 1) % print_freq == 0:
print("Epoch %d of %d took %fs" % (epoch + 1, n_epoch, time.time() - start_time))
test_loss, test_acc, n_batch = 0, 0, 0
for X_test_a, y_test_a in tl.iterate.minibatches(X_test, y_test, batch_size, shuffle=False):
X_test_a = tl.prepro.threading_data(X_test_a, fn=distort_fn, is_train=False)
err, ac = sess.run([cost_test, acc], feed_dict={x: X_test_a, y_: y_test_a})
test_loss += err
test_acc += ac
n_batch += 1
print(" test loss: %f" % (test_loss / n_batch))
print(" test acc: %f" % (test_acc / n_batch))
| true | true |
f7237d73459ad926cb28691c03a0070109cbaebf | 2,391 | py | Python | censys/transforms/search_https_body_hash_to_ip.py | netsec/censys-maltego | f2a1b20565df3174eda1e35cfe23077291b753c6 | [
"Apache-2.0"
] | 1 | 2019-08-07T09:57:09.000Z | 2019-08-07T09:57:09.000Z | censys/transforms/search_https_body_hash_to_ip.py | netsec/censys-maltego | f2a1b20565df3174eda1e35cfe23077291b753c6 | [
"Apache-2.0"
] | null | null | null | censys/transforms/search_https_body_hash_to_ip.py | netsec/censys-maltego | f2a1b20565df3174eda1e35cfe23077291b753c6 | [
"Apache-2.0"
] | 1 | 2019-08-07T09:57:10.000Z | 2019-08-07T09:57:10.000Z | import argparse
import json
import logging
import os
from censys_maltego import Censys
from maltego_trx.transform import DiscoverableTransform
log_file_path = os.path.dirname(os.path.realpath(__file__))
log_file_name = 'censys_maltego_transform.log'
logging.basicConfig(filename=os.path.join(log_file_path, log_file_name), level=logging.INFO)
def get_credentials():
try:
credentials_path = os.path.dirname(os.path.realpath(__file__))
credentials_file = '.env'
cred_dict = None
with open(os.path.join(credentials_path, credentials_file), 'r') as creds_file:
cred_dict = json.loads(creds_file.read())
return cred_dict
except Exception as e:
logging.critical("Please enter your credentials in the .env file in the transforms directory.")
raise e
class search_https_body_hash_to_ip(DiscoverableTransform):
@classmethod
def create_entities(cls, request, response):
env_config = get_credentials()
api_id, api_secret = env_config.get('censys_api_id'), env_config.get('censys_api_secret')
ev = request.Value
ep = request.Properties
response = Censys(api_id, api_secret, max_pages=env_config.get('max_pages', 1)).search_https_body_hash_to_ip(
body_text=ev,
object_properties=ep
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--censys_api_id",
required=False,
metavar='XXXXXXXXXX',
help="(optional) You must provide your Censys API ID here or as an environmental variable CENSYS_API_ID")
parser.add_argument("--censys_api_secret",
required=False,
metavar='XXXXXXXXXX',
help="(optional) You must provide your Censys API SECRET here or as an environmental variable CENSYS_API_SECRET")
parser.add_argument('entity_value')
parser.add_argument('entity_properties')
args = parser.parse_args()
censys_api_id = os.getenv('CENSYS_API_ID', args.censys_api_id)
censys_api_secret = os.getenv('CENSYS_API_SECRET', args.censys_api_secret)
ev = args.entity_value
ep = args.entity_properties
Censys(censys_api_id, censys_api_secret).search_https_body_hash_to_ip(
body_text=ev, object_properties=ep
)
| 31.88 | 137 | 0.686742 | import argparse
import json
import logging
import os
from censys_maltego import Censys
from maltego_trx.transform import DiscoverableTransform
log_file_path = os.path.dirname(os.path.realpath(__file__))
log_file_name = 'censys_maltego_transform.log'
logging.basicConfig(filename=os.path.join(log_file_path, log_file_name), level=logging.INFO)
def get_credentials():
try:
credentials_path = os.path.dirname(os.path.realpath(__file__))
credentials_file = '.env'
cred_dict = None
with open(os.path.join(credentials_path, credentials_file), 'r') as creds_file:
cred_dict = json.loads(creds_file.read())
return cred_dict
except Exception as e:
logging.critical("Please enter your credentials in the .env file in the transforms directory.")
raise e
class search_https_body_hash_to_ip(DiscoverableTransform):
@classmethod
def create_entities(cls, request, response):
env_config = get_credentials()
api_id, api_secret = env_config.get('censys_api_id'), env_config.get('censys_api_secret')
ev = request.Value
ep = request.Properties
response = Censys(api_id, api_secret, max_pages=env_config.get('max_pages', 1)).search_https_body_hash_to_ip(
body_text=ev,
object_properties=ep
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--censys_api_id",
required=False,
metavar='XXXXXXXXXX',
help="(optional) You must provide your Censys API ID here or as an environmental variable CENSYS_API_ID")
parser.add_argument("--censys_api_secret",
required=False,
metavar='XXXXXXXXXX',
help="(optional) You must provide your Censys API SECRET here or as an environmental variable CENSYS_API_SECRET")
parser.add_argument('entity_value')
parser.add_argument('entity_properties')
args = parser.parse_args()
censys_api_id = os.getenv('CENSYS_API_ID', args.censys_api_id)
censys_api_secret = os.getenv('CENSYS_API_SECRET', args.censys_api_secret)
ev = args.entity_value
ep = args.entity_properties
Censys(censys_api_id, censys_api_secret).search_https_body_hash_to_ip(
body_text=ev, object_properties=ep
)
| true | true |
f7237e2b4bf76760511938d4522cfebdec21948a | 798 | py | Python | bin/gen/generate_css_for_a_board_with_hexcodes.py | luanlv/anabim2 | be66567e953aee4a58cab75dddc4325ace2ef96e | [
"MIT"
] | null | null | null | bin/gen/generate_css_for_a_board_with_hexcodes.py | luanlv/anabim2 | be66567e953aee4a58cab75dddc4325ace2ef96e | [
"MIT"
] | 1 | 2016-10-02T23:56:17.000Z | 2016-10-02T23:56:17.000Z | bin/gen/generate_css_for_a_board_with_hexcodes.py | luanlv/anabim2 | be66567e953aee4a58cab75dddc4325ace2ef96e | [
"MIT"
] | null | null | null | #! /usr/bin/python2
#config
themes = {
'grey': ['#fff', '#c4c4c4'],
'green': ['#ffffdd', '#86a666'],
'blue': ['#dee3e6', '#8ca2ad'],
'brown': ['#f0d9b5', '#b58863']
}
blackPattern = 'body.{name} #GameBoard td.blackSquare, body.{name} #GameBoard td.highlightBlackSquare, body.{name} div.lcs.black, #top div.lcs.black.{name} { background: {black}; }'
whitePattern = 'body.{name} #GameBoard td.whiteSquare, body.{name} #GameBoard td.highlightWhiteSquare, body.{name} div.lcs.white, #top div.lcs.white.{name}, body.{name} div.lichess_board { background: {white}; }'
for name in themes:
def formatCss(pattern):
return pattern.replace('{name}', name).replace('{white}', themes[name][0]).replace('{black}', themes[name][1])
print formatCss(whitePattern)
print formatCss(blackPattern)
| 42 | 212 | 0.674185 |
themes = {
'grey': ['#fff', '#c4c4c4'],
'green': ['#ffffdd', '#86a666'],
'blue': ['#dee3e6', '#8ca2ad'],
'brown': ['#f0d9b5', '#b58863']
}
blackPattern = 'body.{name} #GameBoard td.blackSquare, body.{name} #GameBoard td.highlightBlackSquare, body.{name} div.lcs.black, #top div.lcs.black.{name} { background: {black}; }'
whitePattern = 'body.{name} #GameBoard td.whiteSquare, body.{name} #GameBoard td.highlightWhiteSquare, body.{name} div.lcs.white, #top div.lcs.white.{name}, body.{name} div.lichess_board { background: {white}; }'
for name in themes:
def formatCss(pattern):
return pattern.replace('{name}', name).replace('{white}', themes[name][0]).replace('{black}', themes[name][1])
print formatCss(whitePattern)
print formatCss(blackPattern)
| false | true |
f7237e57eaff82db467a825946465ee33ed0585d | 805 | py | Python | ManifestEditor/Util.py | CodyGit/ManifestEditor | c06dfaa8a60b955cb1833c852da8866c24b0b1fa | [
"MIT"
] | 21 | 2020-06-12T02:24:59.000Z | 2022-02-03T06:34:36.000Z | ManifestEditor/Util.py | CodyGit/ManifestEditor | c06dfaa8a60b955cb1833c852da8866c24b0b1fa | [
"MIT"
] | 7 | 2020-08-18T02:05:10.000Z | 2021-07-19T09:53:38.000Z | ManifestEditor/Util.py | CodyGit/ManifestEditor | c06dfaa8a60b955cb1833c852da8866c24b0b1fa | [
"MIT"
] | 13 | 2020-06-24T02:09:17.000Z | 2022-03-10T02:22:07.000Z | #!/usr/bin/python3
#coding=utf-8
#author: cody
def create_reader(byte_arr, offset):
f = offset
b_arr = byte_arr
def read(count):
nonlocal f
nonlocal b_arr
b = b_arr[f:f + count]
f = f + count
return b
return read
def bytes_to_int(b):
return int.from_bytes(b, byteorder='little',signed=True)
def int_to_bytes(i, l=4):
return i.to_bytes(length=l, byteorder='little',signed=True)
def float_to_bytes(f):
import ctypes
i = ctypes.c_uint.from_buffer(ctypes.c_float(f)).value
return self.int_to_bytes(i)
def bytes_to_hex(b, byteorder='little'):
new_bytes = b
if byteorder == "little":
new_bytes = bytearray(b)
new_bytes.reverse()
return "0x" + new_bytes.hex()
else:
return "0x" + b.hex() | 23.676471 | 63 | 0.627329 |
def create_reader(byte_arr, offset):
f = offset
b_arr = byte_arr
def read(count):
nonlocal f
nonlocal b_arr
b = b_arr[f:f + count]
f = f + count
return b
return read
def bytes_to_int(b):
return int.from_bytes(b, byteorder='little',signed=True)
def int_to_bytes(i, l=4):
return i.to_bytes(length=l, byteorder='little',signed=True)
def float_to_bytes(f):
import ctypes
i = ctypes.c_uint.from_buffer(ctypes.c_float(f)).value
return self.int_to_bytes(i)
def bytes_to_hex(b, byteorder='little'):
new_bytes = b
if byteorder == "little":
new_bytes = bytearray(b)
new_bytes.reverse()
return "0x" + new_bytes.hex()
else:
return "0x" + b.hex() | true | true |
f7237fdb4b85456c4780c1536a64e9885a19dbc2 | 17,280 | py | Python | tests/test_finance.py | hotchilianalytics/zipline-broker | fb475cf89ec8886db4ee6420bd9aca70c1821eab | [
"Apache-2.0"
] | 9 | 2020-10-31T20:23:24.000Z | 2022-03-29T02:59:45.000Z | tests/test_finance.py | hotchilianalytics/zipline-broker | fb475cf89ec8886db4ee6420bd9aca70c1821eab | [
"Apache-2.0"
] | null | null | null | tests/test_finance.py | hotchilianalytics/zipline-broker | fb475cf89ec8886db4ee6420bd9aca70c1821eab | [
"Apache-2.0"
] | 1 | 2021-02-05T07:06:36.000Z | 2021-02-05T07:06:36.000Z | #
# Copyright 2013 Quantopian, Inc.
#
# 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.
"""
Tests for the zipline.finance package
"""
from datetime import datetime, timedelta
import os
from nose.tools import timed
from nose.tools import nottest
import numpy as np
import pandas as pd
import pytz
from six import iteritems
from six.moves import range
from testfixtures import TempDirectory
from zipline.finance.blotter.simulation_blotter import SimulationBlotter
from zipline.finance.execution import MarketOrder, LimitOrder
from zipline.finance.metrics import MetricsTracker, load as load_metrics_set
from zipline.finance.trading import SimulationParameters
from zipline.data.us_equity_pricing import BcolzDailyBarReader
from zipline.data.minute_bars import BcolzMinuteBarReader
from zipline.data.data_portal import DataPortal
from zipline.data.us_equity_pricing import BcolzDailyBarWriter
from zipline.finance.slippage import FixedSlippage, FixedBasisPointsSlippage
from zipline.finance.asset_restrictions import NoRestrictions
from zipline.protocol import BarData
from zipline.testing import write_bcolz_minute_data
import zipline.testing.fixtures as zf
import zipline.utils.factory as factory
DEFAULT_TIMEOUT = 15 # seconds
EXTENDED_TIMEOUT = 90
_multiprocess_can_split_ = False
class FinanceTestCase(zf.WithAssetFinder,
zf.WithTradingCalendars,
zf.ZiplineTestCase):
ASSET_FINDER_EQUITY_SIDS = 1, 2, 133
start = START_DATE = pd.Timestamp('2006-01-01', tz='utc')
end = END_DATE = pd.Timestamp('2006-12-31', tz='utc')
def init_instance_fixtures(self):
super(FinanceTestCase, self).init_instance_fixtures()
self.zipline_test_config = {'sid': 133}
# TODO: write tests for short sales
# TODO: write a test to do massive buying or shorting.
@timed(DEFAULT_TIMEOUT)
@nottest
def test_partially_filled_orders(self):
# create a scenario where order size and trade size are equal
# so that orders must be spread out over several trades.
params = {
'trade_count': 360,
'trade_interval': timedelta(minutes=1),
'order_count': 2,
'order_amount': 100,
'order_interval': timedelta(minutes=1),
# because we placed two orders for 100 shares each, and the volume
# of each trade is 100, and by default you can take up 10% of the
# bar's volume (per FixedBasisPointsSlippage, the default slippage
# model), the simulator should spread the order into 20 trades of
# 10 shares per order.
'expected_txn_count': 20,
'expected_txn_volume': 2 * 100,
'default_slippage': True
}
self.transaction_sim(**params)
# same scenario, but with short sales
params2 = {
'trade_count': 360,
'trade_interval': timedelta(minutes=1),
'order_count': 2,
'order_amount': -100,
'order_interval': timedelta(minutes=1),
'expected_txn_count': 20,
'expected_txn_volume': 2 * -100,
'default_slippage': True
}
self.transaction_sim(**params2)
@timed(DEFAULT_TIMEOUT)
@nottest
def test_collapsing_orders(self):
# create a scenario where order.amount <<< trade.volume
# to test that several orders can be covered properly by one trade,
# but are represented by multiple transactions.
params1 = {
'trade_count': 6,
'trade_interval': timedelta(hours=1),
'order_count': 24,
'order_amount': 1,
'order_interval': timedelta(minutes=1),
# because we placed an orders totaling less than 25% of one trade
# the simulator should produce just one transaction.
'expected_txn_count': 24,
'expected_txn_volume': 24
}
self.transaction_sim(**params1)
# second verse, same as the first. except short!
params2 = {
'trade_count': 6,
'trade_interval': timedelta(hours=1),
'order_count': 24,
'order_amount': -1,
'order_interval': timedelta(minutes=1),
'expected_txn_count': 24,
'expected_txn_volume': -24
}
self.transaction_sim(**params2)
# Runs the collapsed trades over daily trade intervals.
# Ensuring that our delay works for daily intervals as well.
params3 = {
'trade_count': 6,
'trade_interval': timedelta(days=1),
'order_count': 24,
'order_amount': 1,
'order_interval': timedelta(minutes=1),
'expected_txn_count': 24,
'expected_txn_volume': 24
}
self.transaction_sim(**params3)
@timed(DEFAULT_TIMEOUT)
@nottest
def test_alternating_long_short(self):
# create a scenario where we alternate buys and sells
params1 = {
'trade_count': int(6.5 * 60 * 4),
'trade_interval': timedelta(minutes=1),
'order_count': 4,
'order_amount': 10,
'order_interval': timedelta(hours=24),
'alternate': True,
'complete_fill': True,
'expected_txn_count': 4,
'expected_txn_volume': 0 # equal buys and sells
}
self.transaction_sim(**params1)
def transaction_sim(self, **params):
"""This is a utility method that asserts expected
results for conversion of orders to transactions given a
trade history
"""
trade_count = params['trade_count']
trade_interval = params['trade_interval']
order_count = params['order_count']
order_amount = params['order_amount']
order_interval = params['order_interval']
expected_txn_count = params['expected_txn_count']
expected_txn_volume = params['expected_txn_volume']
# optional parameters
# ---------------------
# if present, alternate between long and short sales
alternate = params.get('alternate')
# if present, expect transaction amounts to match orders exactly.
complete_fill = params.get('complete_fill')
asset1 = self.asset_finder.retrieve_asset(1)
with TempDirectory() as tempdir:
if trade_interval < timedelta(days=1):
sim_params = factory.create_simulation_parameters(
start=self.start,
end=self.end,
data_frequency="minute"
)
minutes = self.trading_calendar.minutes_window(
sim_params.first_open,
int((trade_interval.total_seconds() / 60) * trade_count)
+ 100)
price_data = np.array([10.1] * len(minutes))
assets = {
asset1.sid: pd.DataFrame({
"open": price_data,
"high": price_data,
"low": price_data,
"close": price_data,
"volume": np.array([100] * len(minutes)),
"dt": minutes
}).set_index("dt")
}
write_bcolz_minute_data(
self.trading_calendar,
self.trading_calendar.sessions_in_range(
self.trading_calendar.minute_to_session_label(
minutes[0]
),
self.trading_calendar.minute_to_session_label(
minutes[-1]
)
),
tempdir.path,
iteritems(assets),
)
equity_minute_reader = BcolzMinuteBarReader(tempdir.path)
data_portal = DataPortal(
self.asset_finder, self.trading_calendar,
first_trading_day=equity_minute_reader.first_trading_day,
equity_minute_reader=equity_minute_reader,
)
else:
sim_params = factory.create_simulation_parameters(
data_frequency="daily"
)
days = sim_params.sessions
assets = {
1: pd.DataFrame({
"open": [10.1] * len(days),
"high": [10.1] * len(days),
"low": [10.1] * len(days),
"close": [10.1] * len(days),
"volume": [100] * len(days),
"day": [day.value for day in days]
}, index=days)
}
path = os.path.join(tempdir.path, "testdata.bcolz")
BcolzDailyBarWriter(path, self.trading_calendar, days[0],
days[-1]).write(
assets.items()
)
equity_daily_reader = BcolzDailyBarReader(path)
data_portal = DataPortal(
self.asset_finder, self.trading_calendar,
first_trading_day=equity_daily_reader.first_trading_day,
equity_daily_reader=equity_daily_reader,
)
if "default_slippage" not in params or \
not params["default_slippage"]:
slippage_func = FixedBasisPointsSlippage()
else:
slippage_func = None
blotter = SimulationBlotter(slippage_func)
start_date = sim_params.first_open
if alternate:
alternator = -1
else:
alternator = 1
tracker = MetricsTracker(
trading_calendar=self.trading_calendar,
first_session=sim_params.start_session,
last_session=sim_params.end_session,
capital_base=sim_params.capital_base,
emission_rate=sim_params.emission_rate,
data_frequency=sim_params.data_frequency,
asset_finder=self.asset_finder,
metrics=load_metrics_set('none'),
)
# replicate what tradesim does by going through every minute or day
# of the simulation and processing open orders each time
if sim_params.data_frequency == "minute":
ticks = minutes
else:
ticks = days
transactions = []
order_list = []
order_date = start_date
for tick in ticks:
blotter.current_dt = tick
if tick >= order_date and len(order_list) < order_count:
# place an order
direction = alternator ** len(order_list)
order_id = blotter.order(
asset1,
order_amount * direction,
MarketOrder(),
)
order_list.append(blotter.orders[order_id])
order_date = order_date + order_interval
# move after market orders to just after market next
# market open.
if order_date.hour >= 21:
if order_date.minute >= 00:
order_date = order_date + timedelta(days=1)
order_date = order_date.replace(hour=14, minute=30)
else:
bar_data = BarData(
data_portal=data_portal,
simulation_dt_func=lambda: tick,
data_frequency=sim_params.data_frequency,
trading_calendar=self.trading_calendar,
restrictions=NoRestrictions(),
)
txns, _, closed_orders = blotter.get_transactions(bar_data)
for txn in txns:
tracker.process_transaction(txn)
transactions.append(txn)
blotter.prune_orders(closed_orders)
for i in range(order_count):
order = order_list[i]
self.assertEqual(order.asset, asset1)
self.assertEqual(order.amount, order_amount * alternator ** i)
if complete_fill:
self.assertEqual(len(transactions), len(order_list))
total_volume = 0
for i in range(len(transactions)):
txn = transactions[i]
total_volume += txn.amount
if complete_fill:
order = order_list[i]
self.assertEqual(order.amount, txn.amount)
self.assertEqual(total_volume, expected_txn_volume)
self.assertEqual(len(transactions), expected_txn_count)
if total_volume == 0:
self.assertRaises(KeyError, lambda: tracker.positions[asset1])
else:
cumulative_pos = tracker.positions[asset1]
self.assertEqual(total_volume, cumulative_pos.amount)
# the open orders should not contain the asset.
oo = blotter.open_orders
self.assertNotIn(
asset1,
oo,
"Entry is removed when no open orders"
)
def test_blotter_processes_splits(self):
blotter = SimulationBlotter(equity_slippage=FixedSlippage())
# set up two open limit orders with very low limit prices,
# one for sid 1 and one for sid 2
asset1 = self.asset_finder.retrieve_asset(1)
asset2 = self.asset_finder.retrieve_asset(2)
asset133 = self.asset_finder.retrieve_asset(133)
blotter.order(asset1, 100, LimitOrder(10, asset=asset1))
blotter.order(asset2, 100, LimitOrder(10, asset=asset2))
# send in splits for assets 133 and 2. We have no open orders for
# asset 133 so it should be ignored.
blotter.process_splits([(asset133, 0.5), (asset2, 0.3333)])
for asset in [asset1, asset2]:
order_lists = blotter.open_orders[asset]
self.assertIsNotNone(order_lists)
self.assertEqual(1, len(order_lists))
asset1_order = blotter.open_orders[1][0]
asset2_order = blotter.open_orders[2][0]
# make sure the asset1 order didn't change
self.assertEqual(100, asset1_order.amount)
self.assertEqual(10, asset1_order.limit)
self.assertEqual(1, asset1_order.asset)
# make sure the asset2 order did change
# to 300 shares at 3.33
self.assertEqual(300, asset2_order.amount)
self.assertEqual(3.33, asset2_order.limit)
self.assertEqual(2, asset2_order.asset)
class SimParamsTestCase(zf.WithTradingCalendars, zf.ZiplineTestCase):
"""
Tests for date management utilities in zipline.finance.trading.
"""
def test_simulation_parameters(self):
sp = SimulationParameters(
start_session=pd.Timestamp("2008-01-01", tz='UTC'),
end_session=pd.Timestamp("2008-12-31", tz='UTC'),
capital_base=100000,
trading_calendar=self.trading_calendar,
)
self.assertTrue(sp.last_close.month == 12)
self.assertTrue(sp.last_close.day == 31)
@timed(DEFAULT_TIMEOUT)
def test_sim_params_days_in_period(self):
# January 2008
# Su Mo Tu We Th Fr Sa
# 1 2 3 4 5
# 6 7 8 9 10 11 12
# 13 14 15 16 17 18 19
# 20 21 22 23 24 25 26
# 27 28 29 30 31
params = SimulationParameters(
start_session=pd.Timestamp("2007-12-31", tz='UTC'),
end_session=pd.Timestamp("2008-01-07", tz='UTC'),
capital_base=100000,
trading_calendar=self.trading_calendar,
)
expected_trading_days = (
datetime(2007, 12, 31, tzinfo=pytz.utc),
# Skip new years
# holidays taken from: http://www.nyse.com/press/1191407641943.html
datetime(2008, 1, 2, tzinfo=pytz.utc),
datetime(2008, 1, 3, tzinfo=pytz.utc),
datetime(2008, 1, 4, tzinfo=pytz.utc),
# Skip Saturday
# Skip Sunday
datetime(2008, 1, 7, tzinfo=pytz.utc)
)
num_expected_trading_days = 5
self.assertEquals(
num_expected_trading_days,
len(params.sessions)
)
np.testing.assert_array_equal(expected_trading_days,
params.sessions.tolist())
| 37.647059 | 79 | 0.572396 |
from datetime import datetime, timedelta
import os
from nose.tools import timed
from nose.tools import nottest
import numpy as np
import pandas as pd
import pytz
from six import iteritems
from six.moves import range
from testfixtures import TempDirectory
from zipline.finance.blotter.simulation_blotter import SimulationBlotter
from zipline.finance.execution import MarketOrder, LimitOrder
from zipline.finance.metrics import MetricsTracker, load as load_metrics_set
from zipline.finance.trading import SimulationParameters
from zipline.data.us_equity_pricing import BcolzDailyBarReader
from zipline.data.minute_bars import BcolzMinuteBarReader
from zipline.data.data_portal import DataPortal
from zipline.data.us_equity_pricing import BcolzDailyBarWriter
from zipline.finance.slippage import FixedSlippage, FixedBasisPointsSlippage
from zipline.finance.asset_restrictions import NoRestrictions
from zipline.protocol import BarData
from zipline.testing import write_bcolz_minute_data
import zipline.testing.fixtures as zf
import zipline.utils.factory as factory
DEFAULT_TIMEOUT = 15
EXTENDED_TIMEOUT = 90
_multiprocess_can_split_ = False
class FinanceTestCase(zf.WithAssetFinder,
zf.WithTradingCalendars,
zf.ZiplineTestCase):
ASSET_FINDER_EQUITY_SIDS = 1, 2, 133
start = START_DATE = pd.Timestamp('2006-01-01', tz='utc')
end = END_DATE = pd.Timestamp('2006-12-31', tz='utc')
def init_instance_fixtures(self):
super(FinanceTestCase, self).init_instance_fixtures()
self.zipline_test_config = {'sid': 133}
@timed(DEFAULT_TIMEOUT)
@nottest
def test_partially_filled_orders(self):
params = {
'trade_count': 360,
'trade_interval': timedelta(minutes=1),
'order_count': 2,
'order_amount': 100,
'order_interval': timedelta(minutes=1),
# model), the simulator should spread the order into 20 trades of
# 10 shares per order.
'expected_txn_count': 20,
'expected_txn_volume': 2 * 100,
'default_slippage': True
}
self.transaction_sim(**params)
# same scenario, but with short sales
params2 = {
'trade_count': 360,
'trade_interval': timedelta(minutes=1),
'order_count': 2,
'order_amount': -100,
'order_interval': timedelta(minutes=1),
'expected_txn_count': 20,
'expected_txn_volume': 2 * -100,
'default_slippage': True
}
self.transaction_sim(**params2)
@timed(DEFAULT_TIMEOUT)
@nottest
def test_collapsing_orders(self):
# create a scenario where order.amount <<< trade.volume
# to test that several orders can be covered properly by one trade,
# but are represented by multiple transactions.
params1 = {
'trade_count': 6,
'trade_interval': timedelta(hours=1),
'order_count': 24,
'order_amount': 1,
'order_interval': timedelta(minutes=1),
# because we placed an orders totaling less than 25% of one trade
# the simulator should produce just one transaction.
'expected_txn_count': 24,
'expected_txn_volume': 24
}
self.transaction_sim(**params1)
# second verse, same as the first. except short!
params2 = {
'trade_count': 6,
'trade_interval': timedelta(hours=1),
'order_count': 24,
'order_amount': -1,
'order_interval': timedelta(minutes=1),
'expected_txn_count': 24,
'expected_txn_volume': -24
}
self.transaction_sim(**params2)
# Runs the collapsed trades over daily trade intervals.
# Ensuring that our delay works for daily intervals as well.
params3 = {
'trade_count': 6,
'trade_interval': timedelta(days=1),
'order_count': 24,
'order_amount': 1,
'order_interval': timedelta(minutes=1),
'expected_txn_count': 24,
'expected_txn_volume': 24
}
self.transaction_sim(**params3)
@timed(DEFAULT_TIMEOUT)
@nottest
def test_alternating_long_short(self):
# create a scenario where we alternate buys and sells
params1 = {
'trade_count': int(6.5 * 60 * 4),
'trade_interval': timedelta(minutes=1),
'order_count': 4,
'order_amount': 10,
'order_interval': timedelta(hours=24),
'alternate': True,
'complete_fill': True,
'expected_txn_count': 4,
'expected_txn_volume': 0 # equal buys and sells
}
self.transaction_sim(**params1)
def transaction_sim(self, **params):
trade_count = params['trade_count']
trade_interval = params['trade_interval']
order_count = params['order_count']
order_amount = params['order_amount']
order_interval = params['order_interval']
expected_txn_count = params['expected_txn_count']
expected_txn_volume = params['expected_txn_volume']
# optional parameters
# ---------------------
# if present, alternate between long and short sales
alternate = params.get('alternate')
# if present, expect transaction amounts to match orders exactly.
complete_fill = params.get('complete_fill')
asset1 = self.asset_finder.retrieve_asset(1)
with TempDirectory() as tempdir:
if trade_interval < timedelta(days=1):
sim_params = factory.create_simulation_parameters(
start=self.start,
end=self.end,
data_frequency="minute"
)
minutes = self.trading_calendar.minutes_window(
sim_params.first_open,
int((trade_interval.total_seconds() / 60) * trade_count)
+ 100)
price_data = np.array([10.1] * len(minutes))
assets = {
asset1.sid: pd.DataFrame({
"open": price_data,
"high": price_data,
"low": price_data,
"close": price_data,
"volume": np.array([100] * len(minutes)),
"dt": minutes
}).set_index("dt")
}
write_bcolz_minute_data(
self.trading_calendar,
self.trading_calendar.sessions_in_range(
self.trading_calendar.minute_to_session_label(
minutes[0]
),
self.trading_calendar.minute_to_session_label(
minutes[-1]
)
),
tempdir.path,
iteritems(assets),
)
equity_minute_reader = BcolzMinuteBarReader(tempdir.path)
data_portal = DataPortal(
self.asset_finder, self.trading_calendar,
first_trading_day=equity_minute_reader.first_trading_day,
equity_minute_reader=equity_minute_reader,
)
else:
sim_params = factory.create_simulation_parameters(
data_frequency="daily"
)
days = sim_params.sessions
assets = {
1: pd.DataFrame({
"open": [10.1] * len(days),
"high": [10.1] * len(days),
"low": [10.1] * len(days),
"close": [10.1] * len(days),
"volume": [100] * len(days),
"day": [day.value for day in days]
}, index=days)
}
path = os.path.join(tempdir.path, "testdata.bcolz")
BcolzDailyBarWriter(path, self.trading_calendar, days[0],
days[-1]).write(
assets.items()
)
equity_daily_reader = BcolzDailyBarReader(path)
data_portal = DataPortal(
self.asset_finder, self.trading_calendar,
first_trading_day=equity_daily_reader.first_trading_day,
equity_daily_reader=equity_daily_reader,
)
if "default_slippage" not in params or \
not params["default_slippage"]:
slippage_func = FixedBasisPointsSlippage()
else:
slippage_func = None
blotter = SimulationBlotter(slippage_func)
start_date = sim_params.first_open
if alternate:
alternator = -1
else:
alternator = 1
tracker = MetricsTracker(
trading_calendar=self.trading_calendar,
first_session=sim_params.start_session,
last_session=sim_params.end_session,
capital_base=sim_params.capital_base,
emission_rate=sim_params.emission_rate,
data_frequency=sim_params.data_frequency,
asset_finder=self.asset_finder,
metrics=load_metrics_set('none'),
)
# replicate what tradesim does by going through every minute or day
# of the simulation and processing open orders each time
if sim_params.data_frequency == "minute":
ticks = minutes
else:
ticks = days
transactions = []
order_list = []
order_date = start_date
for tick in ticks:
blotter.current_dt = tick
if tick >= order_date and len(order_list) < order_count:
# place an order
direction = alternator ** len(order_list)
order_id = blotter.order(
asset1,
order_amount * direction,
MarketOrder(),
)
order_list.append(blotter.orders[order_id])
order_date = order_date + order_interval
# move after market orders to just after market next
# market open.
if order_date.hour >= 21:
if order_date.minute >= 00:
order_date = order_date + timedelta(days=1)
order_date = order_date.replace(hour=14, minute=30)
else:
bar_data = BarData(
data_portal=data_portal,
simulation_dt_func=lambda: tick,
data_frequency=sim_params.data_frequency,
trading_calendar=self.trading_calendar,
restrictions=NoRestrictions(),
)
txns, _, closed_orders = blotter.get_transactions(bar_data)
for txn in txns:
tracker.process_transaction(txn)
transactions.append(txn)
blotter.prune_orders(closed_orders)
for i in range(order_count):
order = order_list[i]
self.assertEqual(order.asset, asset1)
self.assertEqual(order.amount, order_amount * alternator ** i)
if complete_fill:
self.assertEqual(len(transactions), len(order_list))
total_volume = 0
for i in range(len(transactions)):
txn = transactions[i]
total_volume += txn.amount
if complete_fill:
order = order_list[i]
self.assertEqual(order.amount, txn.amount)
self.assertEqual(total_volume, expected_txn_volume)
self.assertEqual(len(transactions), expected_txn_count)
if total_volume == 0:
self.assertRaises(KeyError, lambda: tracker.positions[asset1])
else:
cumulative_pos = tracker.positions[asset1]
self.assertEqual(total_volume, cumulative_pos.amount)
# the open orders should not contain the asset.
oo = blotter.open_orders
self.assertNotIn(
asset1,
oo,
"Entry is removed when no open orders"
)
def test_blotter_processes_splits(self):
blotter = SimulationBlotter(equity_slippage=FixedSlippage())
# set up two open limit orders with very low limit prices,
# one for sid 1 and one for sid 2
asset1 = self.asset_finder.retrieve_asset(1)
asset2 = self.asset_finder.retrieve_asset(2)
asset133 = self.asset_finder.retrieve_asset(133)
blotter.order(asset1, 100, LimitOrder(10, asset=asset1))
blotter.order(asset2, 100, LimitOrder(10, asset=asset2))
# send in splits for assets 133 and 2. We have no open orders for
# asset 133 so it should be ignored.
blotter.process_splits([(asset133, 0.5), (asset2, 0.3333)])
for asset in [asset1, asset2]:
order_lists = blotter.open_orders[asset]
self.assertIsNotNone(order_lists)
self.assertEqual(1, len(order_lists))
asset1_order = blotter.open_orders[1][0]
asset2_order = blotter.open_orders[2][0]
# make sure the asset1 order didn't change
self.assertEqual(100, asset1_order.amount)
self.assertEqual(10, asset1_order.limit)
self.assertEqual(1, asset1_order.asset)
self.assertEqual(300, asset2_order.amount)
self.assertEqual(3.33, asset2_order.limit)
self.assertEqual(2, asset2_order.asset)
class SimParamsTestCase(zf.WithTradingCalendars, zf.ZiplineTestCase):
def test_simulation_parameters(self):
sp = SimulationParameters(
start_session=pd.Timestamp("2008-01-01", tz='UTC'),
end_session=pd.Timestamp("2008-12-31", tz='UTC'),
capital_base=100000,
trading_calendar=self.trading_calendar,
)
self.assertTrue(sp.last_close.month == 12)
self.assertTrue(sp.last_close.day == 31)
@timed(DEFAULT_TIMEOUT)
def test_sim_params_days_in_period(self):
params = SimulationParameters(
start_session=pd.Timestamp("2007-12-31", tz='UTC'),
end_session=pd.Timestamp("2008-01-07", tz='UTC'),
capital_base=100000,
trading_calendar=self.trading_calendar,
)
expected_trading_days = (
datetime(2007, 12, 31, tzinfo=pytz.utc),
datetime(2008, 1, 2, tzinfo=pytz.utc),
datetime(2008, 1, 3, tzinfo=pytz.utc),
datetime(2008, 1, 4, tzinfo=pytz.utc),
datetime(2008, 1, 7, tzinfo=pytz.utc)
)
num_expected_trading_days = 5
self.assertEquals(
num_expected_trading_days,
len(params.sessions)
)
np.testing.assert_array_equal(expected_trading_days,
params.sessions.tolist())
| true | true |
f72380691d56192882fe83950359d2235067b832 | 4,991 | py | Python | Tests/attribution_calculation/ShapleyExcess/iterate_drug.py | anonymous29387491/iclr2022 | 60c5727f8519e64610b632d074510587fb7ff692 | [
"MIT"
] | null | null | null | Tests/attribution_calculation/ShapleyExcess/iterate_drug.py | anonymous29387491/iclr2022 | 60c5727f8519e64610b632d074510587fb7ff692 | [
"MIT"
] | null | null | null | Tests/attribution_calculation/ShapleyExcess/iterate_drug.py | anonymous29387491/iclr2022 | 60c5727f8519e64610b632d074510587fb7ff692 | [
"MIT"
] | null | null | null | from torchvision import datasets, transforms
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from argparse import ArgumentParser
from tqdm import tqdm
import time
import numpy as np
###########
# file imports / path issues
import os
import sys
from pathlib import Path
path = Path(os.path.abspath(__file__)).parents[3]
os.chdir(path)
sys.path.append('./BivariateShapley')
from utils_shapley import *
from shapley_kernel import Bivariate_KernelExplainer
import pickle
import os
import shap
############################################
# Define Test Parameters
############################################
parser = ArgumentParser(description='get phi plus matrices')
parser.add_argument('--dataset_min_index', type = int,default=0,
help='iterate over dataset starting from min_index')
parser.add_argument('--dataset_samples', type = int,default=500,
help='number of samples, starting from min_index')
parser.add_argument('--verbose', action='store_true', default=False,
help='boolean, use tqdm')
args = parser.parse_args()
min_index = args.dataset_min_index
max_index = min_index + args.dataset_samples
baseline = 'excess'
save_path = './Files/results_attribution/drug_%s' % (baseline)
make_dir(save_path)
model_path = './Files/trained_bb_models/model_drug.pkl'
data_path = './Files/Data/drug.h5'
from shapley_value_functions import *
# load model
import pickle
with open(model_path, 'rb') as fid:
model = pickle.load(fid)
model_eval = eval_RF_binary(model)
# Data Sample
from shapley_datasets import drug
dataset = drug(data_path = data_path, train = False)
dataloader = DataLoader(dataset, batch_size = 1, shuffle = False, num_workers = 0)
dataset_train = drug(data_path = data_path, train = True)
dataloader_train = DataLoader(dataset_train, batch_size = 10, shuffle = True, num_workers = 0)
data_iterator = iter(dataloader_train)
#######################
# Explainer
#######################
# initialize variables
x_list = []
label_list = []
unary_list = []
matrix_list = []
time_list = []
db_ind = {}
time1 = time.time()
if args.verbose:
batch_iterator = tqdm(enumerate(dataloader), total = max_index)
else:
batch_iterator = enumerate(dataloader)
for idx, (x, label) in batch_iterator:
# advance batch iterator
if idx < min_index:
continue
elif idx == max_index:
break
time_start = time.time()
label = label[0].item()
#######################################
# Calculate Shapley
#######################################
baseline_value = 0
########################################
x = tensor2numpy(x)
x_train = np.zeros_like(x)
n_feat = x.reshape(-1).shape[0]
matrix = np.zeros((n_feat, n_feat))
model_eval.init_baseline(x, baseline_value = baseline_value)
explainer = shap.KernelExplainer(model_eval, x_train)
shapley_values = explainer.shap_values(x, silent = True, l1_reg = False)
for i in range(n_feat):
for j in range(i+1, n_feat):
model_eval.init_baseline(x, j = j, i = i, baseline_value = baseline_value)
x_ = np_collapse(x, index = j) # remove column j from x
explainer = shap.KernelExplainer(model_eval, np.zeros_like(x_)+baseline_value)
shapley_coalition = explainer.shap_values(x_, silent = True, l1_reg = False)
shapley_coalition = np_insert(shapley_coalition, np.zeros((x.shape[0], 1)), index = j)
matrix[i, j] = 0.5 * (shapley_coalition[0,i] - shapley_values[0,i] - shapley_values[0,j])
matrix[j, i] = matrix[i,j]
#######################################
# save individual shapley
time_list.append(time.time() - time_start)
x_list.append(x)
label_list.append(label)
unary_list.append(shapley_values)
matrix_list.append(matrix)
if idx % 5 == 0:
if not args.verbose:
print('=====================')
print('samples:' + str(idx+1))
print('time per sample: ' + str(np.array(time_list).mean()))
'''
db_ind['x_list'] = x_list
db_ind['label_list'] = label_list
db_ind['unary_list'] = unary_list
db_ind['matrix_list'] = matrix_list
db_ind['time'] = time_list
save_dict(db_ind, os.path.join(save_path, '%s-%s_checkpoint.pkl' % (str(min_index), str(max_index-1))))
'''
db_ind['x_list'] = x_list
db_ind['label_list'] = label_list
db_ind['unary_list'] = unary_list
db_ind['matrix_list'] = matrix_list
db_ind['time_list'] = time_list
save_dict(db_ind, os.path.join(save_path, '%s-%s.pkl' % (str(min_index), str(max_index-1))))
#os.remove(os.path.join(save_path, '%s-%s_checkpoint.pkl' % (str(min_index), str(max_index-1))))
print('done!')
| 30.432927 | 112 | 0.61671 | from torchvision import datasets, transforms
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from argparse import ArgumentParser
from tqdm import tqdm
import time
import numpy as np
os.path.abspath(__file__)).parents[3]
os.chdir(path)
sys.path.append('./BivariateShapley')
from utils_shapley import *
from shapley_kernel import Bivariate_KernelExplainer
import pickle
import os
import shap
| true | true |
f72380ca6e9cedea194a5c13ba71ca069254a476 | 1,189 | py | Python | coursedashboards/migrations/0014_auto_20200911_2040.py | uw-it-aca/course-dashboards | 0f195f7233fc8e24e9ca0d2624ca288869e133ba | [
"Apache-2.0"
] | 1 | 2018-04-05T19:00:27.000Z | 2018-04-05T19:00:27.000Z | coursedashboards/migrations/0014_auto_20200911_2040.py | uw-it-aca/course-dashboards | 0f195f7233fc8e24e9ca0d2624ca288869e133ba | [
"Apache-2.0"
] | 188 | 2017-08-31T23:38:23.000Z | 2022-03-29T18:06:00.000Z | coursedashboards/migrations/0014_auto_20200911_2040.py | uw-it-aca/course-dashboards | 0f195f7233fc8e24e9ca0d2624ca288869e133ba | [
"Apache-2.0"
] | null | null | null | # Generated by Django 2.1.15 on 2020-09-11 20:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coursedashboards', '0013_auto_20190108_2238'),
]
operations = [
migrations.CreateModel(
name='CourseGradeAverage',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('curriculum', models.CharField(max_length=20)),
('course_number', models.PositiveSmallIntegerField()),
('grade', models.CharField(max_length=5, null=True)),
],
options={
'db_table': 'CourseGradeAverage',
},
),
migrations.AlterField(
model_name='course',
name='course_title',
field=models.CharField(default='', max_length=64),
),
migrations.AlterField(
model_name='term',
name='quarter',
field=models.CharField(choices=[('winter', 'Winter'), ('spring', 'Spring'), ('summer', 'Summer'), ('autumn', 'Autumn')], max_length=6),
),
]
| 33.027778 | 147 | 0.557611 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coursedashboards', '0013_auto_20190108_2238'),
]
operations = [
migrations.CreateModel(
name='CourseGradeAverage',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('curriculum', models.CharField(max_length=20)),
('course_number', models.PositiveSmallIntegerField()),
('grade', models.CharField(max_length=5, null=True)),
],
options={
'db_table': 'CourseGradeAverage',
},
),
migrations.AlterField(
model_name='course',
name='course_title',
field=models.CharField(default='', max_length=64),
),
migrations.AlterField(
model_name='term',
name='quarter',
field=models.CharField(choices=[('winter', 'Winter'), ('spring', 'Spring'), ('summer', 'Summer'), ('autumn', 'Autumn')], max_length=6),
),
]
| true | true |
f72380da1dd16cb6803819798678cc304b8a688a | 247 | py | Python | utils/download.py | yagajj/Tensorflow-video-Recognition-HTML-interface | b4980f31f92b97d2669135f55a15fc4c91e1824e | [
"MIT"
] | 67 | 2018-02-21T06:12:53.000Z | 2022-01-18T10:21:58.000Z | utils/download.py | yagajj/Tensorflow-video-Recognition-HTML-interface | b4980f31f92b97d2669135f55a15fc4c91e1824e | [
"MIT"
] | 6 | 2018-03-05T00:51:10.000Z | 2021-07-02T08:43:15.000Z | utils/download.py | yagajj/Tensorflow-video-Recognition-HTML-interface | b4980f31f92b97d2669135f55a15fc4c91e1824e | [
"MIT"
] | 22 | 2018-03-13T08:39:12.000Z | 2021-12-25T08:52:42.000Z | from google_drive_downloader import GoogleDriveDownloader as gdd
gdd.download_file_from_google_drive(file_id='16Gi1oZr3mEGMEUCsOQ3whFfDlv8IAyzG',
dest_path='./',
unzip=True)
| 41.166667 | 80 | 0.611336 | from google_drive_downloader import GoogleDriveDownloader as gdd
gdd.download_file_from_google_drive(file_id='16Gi1oZr3mEGMEUCsOQ3whFfDlv8IAyzG',
dest_path='./',
unzip=True)
| true | true |
f72380f565cdc8bef9d0b26561d67e2968bf236a | 119 | py | Python | shiyanlou_cs596-1805f3c438/design2.py | tongxindao/shiyanlou | 1d002ea342deb69066c287db9935f77f49f0a09e | [
"Apache-2.0"
] | null | null | null | shiyanlou_cs596-1805f3c438/design2.py | tongxindao/shiyanlou | 1d002ea342deb69066c287db9935f77f49f0a09e | [
"Apache-2.0"
] | null | null | null | shiyanlou_cs596-1805f3c438/design2.py | tongxindao/shiyanlou | 1d002ea342deb69066c287db9935f77f49f0a09e | [
"Apache-2.0"
] | null | null | null | #! /usr/bin/env python3
n = int(input("Enter the number of rows: "))
i = 1
while i <= n:
print("*" * i)
i += 1
| 17 | 44 | 0.521008 |
n = int(input("Enter the number of rows: "))
i = 1
while i <= n:
print("*" * i)
i += 1
| true | true |
f7238161eaf068d3b5854017d9c4ea5711b90f31 | 11,244 | py | Python | r2r_src_update/train.py | zhangyuejoslin/Recurrent-VLN-BERT | f9bc81c297d6ad04b6b846b4d702a8f7bb4544ab | [
"MIT"
] | null | null | null | r2r_src_update/train.py | zhangyuejoslin/Recurrent-VLN-BERT | f9bc81c297d6ad04b6b846b4d702a8f7bb4544ab | [
"MIT"
] | null | null | null | r2r_src_update/train.py | zhangyuejoslin/Recurrent-VLN-BERT | f9bc81c297d6ad04b6b846b4d702a8f7bb4544ab | [
"MIT"
] | null | null | null | import torch
import os
import time
import json
import random
import numpy as np
from collections import defaultdict
from utils import read_vocab, write_vocab, build_vocab, padding_idx, timeSince, read_img_features, print_progress, roi_img_features
import utils
from env import R2RBatch
from agent import Seq2SeqAgent
from eval import Evaluation
from param import args
import warnings
warnings.filterwarnings("ignore")
from tensorboardX import SummaryWriter
from vlnbert.vlnbert_init import get_tokenizer
log_dir = '/home/joslin/Recurrent-VLN-BERT/snap/%s' % args.name
if not os.path.exists(log_dir):
os.makedirs(log_dir)
IMAGENET_FEATURES = 'img_features/ResNet-152-imagenet.tsv'
PLACE365_FEATURES = '/home/hlr/shared/data/joslin/img_features/ResNet-152-places365.tsv'
#PLACE365_FEATURES = '/home/hlr/shared/data/joslin/img_features/CLIP-ViT-B-32-views.tsv'
result_path = "/home/joslin/Recurrent-VLN-BERT/result/"
experiment_time = time.strftime("%Y%m%d-%H%M%S", time.gmtime())
if args.features == 'imagenet':
features = IMAGENET_FEATURES
elif args.features == 'places365':
features = PLACE365_FEATURES
feedback_method = args.feedback # teacher or sample
print(args); print('')
''' train the listener '''
def train(train_env, tok, n_iters, log_every=2000, val_envs={}, aug_env=None):
writer = SummaryWriter(log_dir=log_dir)
listner = Seq2SeqAgent(train_env, "", tok, args.maxAction)
record_file = open('./logs/' + args.name + '.txt', 'a')
record_file.write(str(args) + '\n\n')
record_file.close()
start_iter = 0
if args.load is not None:
if args.aug is None:
start_iter = listner.load(os.path.join(args.load))
print("\nLOAD the model from {}, iteration ".format(args.load, start_iter))
else:
load_iter = listner.load(os.path.join(args.load))
print("\nLOAD the model from {}, iteration ".format(args.load, load_iter))
start = time.time()
print('\nListener training starts, start iteration: %s' % str(start_iter))
best_val = {'val_unseen': {"spl": 0., "sr": 0., "state":"", 'update':False}}
for idx in range(start_iter, start_iter+n_iters, log_every):
listner.logs = defaultdict(list)
interval = min(log_every, n_iters-idx)
iter = idx + interval
# Train for log_every interval
if aug_env is None:
listner.env = train_env
listner.train(interval, feedback=feedback_method) # Train interval iters
else:
jdx_length = len(range(interval // 2))
for jdx in range(interval // 2):
# Train with GT data
listner.env = train_env
args.ml_weight = 0.2
listner.train(1, feedback=feedback_method)
# Train with Augmented data
listner.env = aug_env
args.ml_weight = 0.2
listner.train(1, feedback=feedback_method)
print_progress(jdx, jdx_length, prefix='Progress:', suffix='Complete', bar_length=50)
# Log the training stats to tensorboard
total = max(sum(listner.logs['total']), 1)
length = max(len(listner.logs['critic_loss']), 1)
critic_loss = sum(listner.logs['critic_loss']) / total
RL_loss = sum(listner.logs['RL_loss']) / max(len(listner.logs['RL_loss']), 1)
IL_loss = sum(listner.logs['IL_loss']) / max(len(listner.logs['IL_loss']), 1)
entropy = sum(listner.logs['entropy']) / total
writer.add_scalar("loss/critic", critic_loss, idx)
writer.add_scalar("policy_entropy", entropy, idx)
writer.add_scalar("loss/RL_loss", RL_loss, idx)
writer.add_scalar("loss/IL_loss", IL_loss, idx)
writer.add_scalar("total_actions", total, idx)
writer.add_scalar("max_length", length, idx)
# print("total_actions", total, ", max_length", length)
# Run validation
loss_str = "iter {}".format(iter)
for env_name, (env, evaluator) in val_envs.items():
listner.env = env
# Get validation distance from goal under test evaluation conditions
listner.test(use_dropout=False, feedback='argmax', iters=None)
result = listner.get_results()
score_summary, _ = evaluator.score(result)
loss_str += ", %s " % env_name
for metric, val in score_summary.items():
if metric in ['spl']:
writer.add_scalar("spl/%s" % env_name, val, idx)
if env_name in best_val:
if val > best_val[env_name]['spl']:
best_val[env_name]['spl'] = val
best_val[env_name]['update'] = True
elif (val == best_val[env_name]['spl']) and (score_summary['success_rate'] > best_val[env_name]['sr']):
best_val[env_name]['spl'] = val
best_val[env_name]['update'] = True
loss_str += ', %s: %.4f' % (metric, val)
record_file = open('./logs/' + args.name + '.txt', 'a')
record_file.write(loss_str + '\n')
record_file.close()
for env_name in best_val:
if best_val[env_name]['update']:
best_val[env_name]['state'] = 'Iter %d %s' % (iter, loss_str)
best_val[env_name]['update'] = False
listner.save(idx, os.path.join("snap", args.name, "state_dict", "best_%s" % (env_name)))
else:
listner.save(idx, os.path.join("snap", args.name, "state_dict", "latest_dict"))
print(('%s (%d %d%%) %s' % (timeSince(start, float(iter)/n_iters),
iter, float(iter)/n_iters*100, loss_str)))
with open(result_path+str(experiment_time)+".txt", "a") as f_result:
f_result.write(('%s (%d %d%%) %s' % (timeSince(start, float(iter)/n_iters),
iter, float(iter)/n_iters*100, loss_str)))
f_result.write('\n')
if iter % 1000 == 0:
print("BEST RESULT TILL NOW")
for env_name in best_val:
print(env_name, best_val[env_name]['state'])
record_file = open('./logs/' + args.name + '.txt', 'a')
record_file.write('BEST RESULT TILL NOW: ' + env_name + ' | ' + best_val[env_name]['state'] + '\n')
record_file.close()
listner.save(idx, os.path.join("snap", args.name, "state_dict", "LAST_iter%d" % (idx)))
def valid(train_env, tok, val_envs={}):
agent = Seq2SeqAgent(train_env, "", tok, args.maxAction)
print("Loaded the listener model at iter %d from %s" % (agent.load(args.load), args.load))
for env_name, (env, evaluator) in val_envs.items():
agent.logs = defaultdict(list)
agent.env = env
iters = None
agent.test(use_dropout=False, feedback='argmax', iters=iters)
result = agent.get_results()
if env_name != '':
score_summary, _ = evaluator.score(result)
loss_str = "Env name: %s" % env_name
for metric,val in score_summary.items():
loss_str += ', %s: %.4f' % (metric, val)
print(loss_str)
# if args.submit:
json.dump(
result,
open(os.path.join(log_dir, "submit_%s.json" % env_name), 'w'),
sort_keys=True, indent=4, separators=(',', ': ')
)
# YZ: print the sorrted tokens
'''
json.dump(
agent.sort_tokens,
open(os.path.join(log_dir, "instr_%s.json" % env_name), 'w'),
sort_keys=True, indent=4, separators=(',', ': ')
)
'''
# YZ: output the heatmap of transformer attention
#np.save("/VL/space/zhan1624/Recurrent-VLN-BERT/attent_heatmap/mean/third_steps.npy", agent.atten_heat, allow_pickle=True)
# if env_name == "val_seen":
# np.save("/VL/space/zhan1624/Recurrent-VLN-BERT/attent_heatmap/all/first_step_original.npy", agent.obj_token_attn, allow_pickle=True)
def setup():
torch.manual_seed(1)
torch.cuda.manual_seed(1)
random.seed(0)
np.random.seed(0)
def train_val(test_only=False):
''' Train on the training set, and validate on seen and unseen splits. '''
setup()
tok = get_tokenizer(args)
feat_dict = read_img_features(features, test_only=test_only)
if args.using_obj:
obj_dict = np.load(args.obj_img_feat_path, allow_pickle=True).item()
else:
obj_dict = None
if test_only:
featurized_scans = None
val_env_names = ['val_train_seen']
else:
featurized_scans = set([key.split("_")[0] for key in list(feat_dict.keys())])
#val_env_names = ['val_train_seen', 'val_seen', 'val_unseen']
val_env_names = ['val_seen', 'val_unseen']
train_env = R2RBatch(feat_dict, batch_size=args.batchSize, splits=['train'], tokenizer=tok, obj_store=obj_dict)
from collections import OrderedDict
if args.submit:
val_env_names.append('test')
else:
pass
val_envs = OrderedDict(
((split,
(R2RBatch(feat_dict, batch_size=args.batchSize, splits=[split], tokenizer=tok, obj_store=obj_dict),
Evaluation([split], featurized_scans, tok))
)
for split in val_env_names
)
)
if args.train == 'listener':
train(train_env, tok, args.iters, val_envs=val_envs)
elif args.train == 'validlistener':
valid(train_env, tok, val_envs=val_envs)
else:
assert False
def train_val_augment(test_only=False):
"""
Train the listener with the augmented data
"""
setup()
# Create a batch training environment that will also preprocess text
tok_bert = get_tokenizer(args)
# Load the env img features
feat_dict = read_img_features(features, test_only=test_only)
#feat_dict = roi_img_features(features)
if test_only:
featurized_scans = None
val_env_names = ['val_train_seen']
else:
featurized_scans = set([key.split("_")[0] for key in list(feat_dict.keys())])
val_env_names = ['val_seen', 'val_unseen']
# Load the augmentation data
aug_path = args.aug
# Create the training environment
train_env = R2RBatch(feat_dict, batch_size=args.batchSize, splits=['train'], tokenizer=tok_bert)
aug_env = R2RBatch(feat_dict, batch_size=args.batchSize, splits=[aug_path], tokenizer=tok_bert, name='aug')
# Setup the validation data
val_envs = {split: (R2RBatch(feat_dict, batch_size=args.batchSize, splits=[split], tokenizer=tok_bert),
Evaluation([split], featurized_scans, tok_bert))
for split in val_env_names}
# Start training
train(train_env, tok_bert, args.iters, val_envs=val_envs, aug_env=aug_env)
if __name__ == "__main__":
if args.train in ['listener', 'validlistener']:
train_val(test_only=args.test_only)
elif args.train == 'auglistener':
train_val_augment(test_only=args.test_only)
else:
assert False
| 38.639175 | 146 | 0.609747 | import torch
import os
import time
import json
import random
import numpy as np
from collections import defaultdict
from utils import read_vocab, write_vocab, build_vocab, padding_idx, timeSince, read_img_features, print_progress, roi_img_features
import utils
from env import R2RBatch
from agent import Seq2SeqAgent
from eval import Evaluation
from param import args
import warnings
warnings.filterwarnings("ignore")
from tensorboardX import SummaryWriter
from vlnbert.vlnbert_init import get_tokenizer
log_dir = '/home/joslin/Recurrent-VLN-BERT/snap/%s' % args.name
if not os.path.exists(log_dir):
os.makedirs(log_dir)
IMAGENET_FEATURES = 'img_features/ResNet-152-imagenet.tsv'
PLACE365_FEATURES = '/home/hlr/shared/data/joslin/img_features/ResNet-152-places365.tsv'
result_path = "/home/joslin/Recurrent-VLN-BERT/result/"
experiment_time = time.strftime("%Y%m%d-%H%M%S", time.gmtime())
if args.features == 'imagenet':
features = IMAGENET_FEATURES
elif args.features == 'places365':
features = PLACE365_FEATURES
feedback_method = args.feedback
print(args); print('')
def train(train_env, tok, n_iters, log_every=2000, val_envs={}, aug_env=None):
writer = SummaryWriter(log_dir=log_dir)
listner = Seq2SeqAgent(train_env, "", tok, args.maxAction)
record_file = open('./logs/' + args.name + '.txt', 'a')
record_file.write(str(args) + '\n\n')
record_file.close()
start_iter = 0
if args.load is not None:
if args.aug is None:
start_iter = listner.load(os.path.join(args.load))
print("\nLOAD the model from {}, iteration ".format(args.load, start_iter))
else:
load_iter = listner.load(os.path.join(args.load))
print("\nLOAD the model from {}, iteration ".format(args.load, load_iter))
start = time.time()
print('\nListener training starts, start iteration: %s' % str(start_iter))
best_val = {'val_unseen': {"spl": 0., "sr": 0., "state":"", 'update':False}}
for idx in range(start_iter, start_iter+n_iters, log_every):
listner.logs = defaultdict(list)
interval = min(log_every, n_iters-idx)
iter = idx + interval
if aug_env is None:
listner.env = train_env
listner.train(interval, feedback=feedback_method)
else:
jdx_length = len(range(interval // 2))
for jdx in range(interval // 2):
listner.env = train_env
args.ml_weight = 0.2
listner.train(1, feedback=feedback_method)
listner.env = aug_env
args.ml_weight = 0.2
listner.train(1, feedback=feedback_method)
print_progress(jdx, jdx_length, prefix='Progress:', suffix='Complete', bar_length=50)
total = max(sum(listner.logs['total']), 1)
length = max(len(listner.logs['critic_loss']), 1)
critic_loss = sum(listner.logs['critic_loss']) / total
RL_loss = sum(listner.logs['RL_loss']) / max(len(listner.logs['RL_loss']), 1)
IL_loss = sum(listner.logs['IL_loss']) / max(len(listner.logs['IL_loss']), 1)
entropy = sum(listner.logs['entropy']) / total
writer.add_scalar("loss/critic", critic_loss, idx)
writer.add_scalar("policy_entropy", entropy, idx)
writer.add_scalar("loss/RL_loss", RL_loss, idx)
writer.add_scalar("loss/IL_loss", IL_loss, idx)
writer.add_scalar("total_actions", total, idx)
writer.add_scalar("max_length", length, idx)
loss_str = "iter {}".format(iter)
for env_name, (env, evaluator) in val_envs.items():
listner.env = env
listner.test(use_dropout=False, feedback='argmax', iters=None)
result = listner.get_results()
score_summary, _ = evaluator.score(result)
loss_str += ", %s " % env_name
for metric, val in score_summary.items():
if metric in ['spl']:
writer.add_scalar("spl/%s" % env_name, val, idx)
if env_name in best_val:
if val > best_val[env_name]['spl']:
best_val[env_name]['spl'] = val
best_val[env_name]['update'] = True
elif (val == best_val[env_name]['spl']) and (score_summary['success_rate'] > best_val[env_name]['sr']):
best_val[env_name]['spl'] = val
best_val[env_name]['update'] = True
loss_str += ', %s: %.4f' % (metric, val)
record_file = open('./logs/' + args.name + '.txt', 'a')
record_file.write(loss_str + '\n')
record_file.close()
for env_name in best_val:
if best_val[env_name]['update']:
best_val[env_name]['state'] = 'Iter %d %s' % (iter, loss_str)
best_val[env_name]['update'] = False
listner.save(idx, os.path.join("snap", args.name, "state_dict", "best_%s" % (env_name)))
else:
listner.save(idx, os.path.join("snap", args.name, "state_dict", "latest_dict"))
print(('%s (%d %d%%) %s' % (timeSince(start, float(iter)/n_iters),
iter, float(iter)/n_iters*100, loss_str)))
with open(result_path+str(experiment_time)+".txt", "a") as f_result:
f_result.write(('%s (%d %d%%) %s' % (timeSince(start, float(iter)/n_iters),
iter, float(iter)/n_iters*100, loss_str)))
f_result.write('\n')
if iter % 1000 == 0:
print("BEST RESULT TILL NOW")
for env_name in best_val:
print(env_name, best_val[env_name]['state'])
record_file = open('./logs/' + args.name + '.txt', 'a')
record_file.write('BEST RESULT TILL NOW: ' + env_name + ' | ' + best_val[env_name]['state'] + '\n')
record_file.close()
listner.save(idx, os.path.join("snap", args.name, "state_dict", "LAST_iter%d" % (idx)))
def valid(train_env, tok, val_envs={}):
agent = Seq2SeqAgent(train_env, "", tok, args.maxAction)
print("Loaded the listener model at iter %d from %s" % (agent.load(args.load), args.load))
for env_name, (env, evaluator) in val_envs.items():
agent.logs = defaultdict(list)
agent.env = env
iters = None
agent.test(use_dropout=False, feedback='argmax', iters=iters)
result = agent.get_results()
if env_name != '':
score_summary, _ = evaluator.score(result)
loss_str = "Env name: %s" % env_name
for metric,val in score_summary.items():
loss_str += ', %s: %.4f' % (metric, val)
print(loss_str)
json.dump(
result,
open(os.path.join(log_dir, "submit_%s.json" % env_name), 'w'),
sort_keys=True, indent=4, separators=(',', ': ')
)
def setup():
torch.manual_seed(1)
torch.cuda.manual_seed(1)
random.seed(0)
np.random.seed(0)
def train_val(test_only=False):
setup()
tok = get_tokenizer(args)
feat_dict = read_img_features(features, test_only=test_only)
if args.using_obj:
obj_dict = np.load(args.obj_img_feat_path, allow_pickle=True).item()
else:
obj_dict = None
if test_only:
featurized_scans = None
val_env_names = ['val_train_seen']
else:
featurized_scans = set([key.split("_")[0] for key in list(feat_dict.keys())])
val_env_names = ['val_seen', 'val_unseen']
train_env = R2RBatch(feat_dict, batch_size=args.batchSize, splits=['train'], tokenizer=tok, obj_store=obj_dict)
from collections import OrderedDict
if args.submit:
val_env_names.append('test')
else:
pass
val_envs = OrderedDict(
((split,
(R2RBatch(feat_dict, batch_size=args.batchSize, splits=[split], tokenizer=tok, obj_store=obj_dict),
Evaluation([split], featurized_scans, tok))
)
for split in val_env_names
)
)
if args.train == 'listener':
train(train_env, tok, args.iters, val_envs=val_envs)
elif args.train == 'validlistener':
valid(train_env, tok, val_envs=val_envs)
else:
assert False
def train_val_augment(test_only=False):
setup()
tok_bert = get_tokenizer(args)
feat_dict = read_img_features(features, test_only=test_only)
if test_only:
featurized_scans = None
val_env_names = ['val_train_seen']
else:
featurized_scans = set([key.split("_")[0] for key in list(feat_dict.keys())])
val_env_names = ['val_seen', 'val_unseen']
aug_path = args.aug
train_env = R2RBatch(feat_dict, batch_size=args.batchSize, splits=['train'], tokenizer=tok_bert)
aug_env = R2RBatch(feat_dict, batch_size=args.batchSize, splits=[aug_path], tokenizer=tok_bert, name='aug')
val_envs = {split: (R2RBatch(feat_dict, batch_size=args.batchSize, splits=[split], tokenizer=tok_bert),
Evaluation([split], featurized_scans, tok_bert))
for split in val_env_names}
train(train_env, tok_bert, args.iters, val_envs=val_envs, aug_env=aug_env)
if __name__ == "__main__":
if args.train in ['listener', 'validlistener']:
train_val(test_only=args.test_only)
elif args.train == 'auglistener':
train_val_augment(test_only=args.test_only)
else:
assert False
| true | true |
f72382a7360a9fea109a9136b65d1c2e4416f908 | 2,176 | py | Python | setup.py | berndca/xmodels | 8265522229a1ce482a2866cdbd1938293a74bb67 | [
"BSD-3-Clause"
] | 1 | 2016-05-05T08:33:41.000Z | 2016-05-05T08:33:41.000Z | setup.py | berndca/xmodels | 8265522229a1ce482a2866cdbd1938293a74bb67 | [
"BSD-3-Clause"
] | 1 | 2016-03-29T20:16:41.000Z | 2016-03-29T20:16:41.000Z | setup.py | berndca/xmodels | 8265522229a1ce482a2866cdbd1938293a74bb67 | [
"BSD-3-Clause"
] | null | null | null | from setuptools import setup
from setuptools.command.test import test as TestCommand
import os
import sys
import io
import re
rel_file = lambda *args: os.path.join(os.path.dirname(os.path.abspath(__file__)), *args)
def read(*filenames, **kwargs):
encoding = kwargs.get('encoding', 'utf-8')
sep = kwargs.get('sep', '\n')
buf = []
for filename in filenames:
with io.open(filename, encoding=encoding) as f:
buf.append(f.read())
return sep.join(buf)
def get_version():
data = read(rel_file('xmodels', '__init__.py'))
return re.search(r"__version__ = '([^']+)'", data).group(1)
readme = read('README.rst')
history = read('HISTORY.rst').replace('.. :changelog:', '')
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errcode = pytest.main(self.test_args)
sys.exit(errcode)
requirements = ['six']
try:
from collections import OrderedDict
except ImportError:
requirements.append('ordereddict')
test_requirements = [
'pytest'
]
setup(
name='xmodels',
version=get_version(),
description='Python models for creation, parsing and validation of XML documents.',
long_description=readme + '\n\n' + history,
author='Bernd Meyer',
author_email='berndca@gmail.com',
url='https://github.com/berndca/xmodels',
packages=['xmodels'],
include_package_data=True,
install_requires=requirements,
license="BSD",
zip_safe=False,
keywords='xmodels',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
test_suite='tests',
tests_require=test_requirements
) | 27.544304 | 88 | 0.642463 | from setuptools import setup
from setuptools.command.test import test as TestCommand
import os
import sys
import io
import re
rel_file = lambda *args: os.path.join(os.path.dirname(os.path.abspath(__file__)), *args)
def read(*filenames, **kwargs):
encoding = kwargs.get('encoding', 'utf-8')
sep = kwargs.get('sep', '\n')
buf = []
for filename in filenames:
with io.open(filename, encoding=encoding) as f:
buf.append(f.read())
return sep.join(buf)
def get_version():
data = read(rel_file('xmodels', '__init__.py'))
return re.search(r"__version__ = '([^']+)'", data).group(1)
readme = read('README.rst')
history = read('HISTORY.rst').replace('.. :changelog:', '')
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errcode = pytest.main(self.test_args)
sys.exit(errcode)
requirements = ['six']
try:
from collections import OrderedDict
except ImportError:
requirements.append('ordereddict')
test_requirements = [
'pytest'
]
setup(
name='xmodels',
version=get_version(),
description='Python models for creation, parsing and validation of XML documents.',
long_description=readme + '\n\n' + history,
author='Bernd Meyer',
author_email='berndca@gmail.com',
url='https://github.com/berndca/xmodels',
packages=['xmodels'],
include_package_data=True,
install_requires=requirements,
license="BSD",
zip_safe=False,
keywords='xmodels',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
test_suite='tests',
tests_require=test_requirements
) | true | true |
f723832938a425b075fb1d945232b872b512f67a | 119,909 | py | Python | tests/components/alexa/test_smart_home.py | GeorgeSG/homeassistant-core | d4615fd432f0c3c66eb0cf682c3da9a4accd7e6c | [
"Apache-2.0"
] | 1 | 2020-03-29T00:56:35.000Z | 2020-03-29T00:56:35.000Z | tests/components/alexa/test_smart_home.py | GeorgeSG/homeassistant-core | d4615fd432f0c3c66eb0cf682c3da9a4accd7e6c | [
"Apache-2.0"
] | null | null | null | tests/components/alexa/test_smart_home.py | GeorgeSG/homeassistant-core | d4615fd432f0c3c66eb0cf682c3da9a4accd7e6c | [
"Apache-2.0"
] | null | null | null | """Test for smart home alexa support."""
import pytest
from homeassistant.components.alexa import messages, smart_home
from homeassistant.components.media_player.const import (
SUPPORT_NEXT_TRACK,
SUPPORT_PAUSE,
SUPPORT_PLAY,
SUPPORT_PLAY_MEDIA,
SUPPORT_PREVIOUS_TRACK,
SUPPORT_SEEK,
SUPPORT_SELECT_SOUND_MODE,
SUPPORT_SELECT_SOURCE,
SUPPORT_STOP,
SUPPORT_TURN_OFF,
SUPPORT_TURN_ON,
SUPPORT_VOLUME_MUTE,
SUPPORT_VOLUME_SET,
SUPPORT_VOLUME_STEP,
)
import homeassistant.components.vacuum as vacuum
from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT
from homeassistant.core import Context, callback
from homeassistant.helpers import entityfilter
from . import (
DEFAULT_CONFIG,
MockConfig,
ReportedProperties,
assert_power_controller_works,
assert_request_calls_service,
assert_request_fails,
assert_scene_controller_works,
get_new_request,
reported_properties,
)
from tests.common import async_mock_service
@pytest.fixture
def events(hass):
"""Fixture that catches alexa events."""
events = []
hass.bus.async_listen(
smart_home.EVENT_ALEXA_SMART_HOME, callback(lambda e: events.append(e))
)
yield events
def test_create_api_message_defaults(hass):
"""Create a API message response of a request with defaults."""
request = get_new_request("Alexa.PowerController", "TurnOn", "switch#xy")
directive_header = request["directive"]["header"]
directive = messages.AlexaDirective(request)
msg = directive.response(payload={"test": 3})._response
assert "event" in msg
msg = msg["event"]
assert msg["header"]["messageId"] is not None
assert msg["header"]["messageId"] != directive_header["messageId"]
assert msg["header"]["correlationToken"] == directive_header["correlationToken"]
assert msg["header"]["name"] == "Response"
assert msg["header"]["namespace"] == "Alexa"
assert msg["header"]["payloadVersion"] == "3"
assert "test" in msg["payload"]
assert msg["payload"]["test"] == 3
assert msg["endpoint"] == request["directive"]["endpoint"]
assert msg["endpoint"] is not request["directive"]["endpoint"]
def test_create_api_message_special():
"""Create a API message response of a request with non defaults."""
request = get_new_request("Alexa.PowerController", "TurnOn")
directive_header = request["directive"]["header"]
directive_header.pop("correlationToken")
directive = messages.AlexaDirective(request)
msg = directive.response("testName", "testNameSpace")._response
assert "event" in msg
msg = msg["event"]
assert msg["header"]["messageId"] is not None
assert msg["header"]["messageId"] != directive_header["messageId"]
assert "correlationToken" not in msg["header"]
assert msg["header"]["name"] == "testName"
assert msg["header"]["namespace"] == "testNameSpace"
assert msg["header"]["payloadVersion"] == "3"
assert msg["payload"] == {}
assert "endpoint" not in msg
async def test_wrong_version(hass):
"""Test with wrong version."""
msg = get_new_request("Alexa.PowerController", "TurnOn")
msg["directive"]["header"]["payloadVersion"] = "2"
with pytest.raises(AssertionError):
await smart_home.async_handle_message(hass, DEFAULT_CONFIG, msg)
async def discovery_test(device, hass, expected_endpoints=1):
"""Test alexa discovery request."""
request = get_new_request("Alexa.Discovery", "Discover")
# setup test devices
hass.states.async_set(*device)
msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request)
assert "event" in msg
msg = msg["event"]
assert msg["header"]["name"] == "Discover.Response"
assert msg["header"]["namespace"] == "Alexa.Discovery"
endpoints = msg["payload"]["endpoints"]
assert len(endpoints) == expected_endpoints
if expected_endpoints == 1:
return endpoints[0]
if expected_endpoints > 1:
return endpoints
return None
def get_capability(capabilities, capability_name, instance=None):
"""Search a set of capabilities for a specific one."""
for capability in capabilities:
if instance and capability.get("instance") == instance:
return capability
if not instance and capability["interface"] == capability_name:
return capability
return None
def assert_endpoint_capabilities(endpoint, *interfaces):
"""Assert the endpoint supports the given interfaces.
Returns a set of capabilities, in case you want to assert more things about
them.
"""
capabilities = endpoint["capabilities"]
supported = set(feature["interface"] for feature in capabilities)
assert supported == set(interfaces)
return capabilities
async def test_switch(hass, events):
"""Test switch discovery."""
device = ("switch.test", "on", {"friendly_name": "Test switch"})
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "switch#test"
assert appliance["displayCategories"][0] == "SWITCH"
assert appliance["friendlyName"] == "Test switch"
assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa"
)
await assert_power_controller_works(
"switch#test", "switch.turn_on", "switch.turn_off", hass
)
properties = await reported_properties(hass, "switch#test")
properties.assert_equal("Alexa.PowerController", "powerState", "ON")
async def test_outlet(hass, events):
"""Test switch with device class outlet discovery."""
device = (
"switch.test",
"on",
{"friendly_name": "Test switch", "device_class": "outlet"},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "switch#test"
assert appliance["displayCategories"][0] == "SMARTPLUG"
assert appliance["friendlyName"] == "Test switch"
assert_endpoint_capabilities(
appliance, "Alexa", "Alexa.PowerController", "Alexa.EndpointHealth"
)
async def test_light(hass):
"""Test light discovery."""
device = ("light.test_1", "on", {"friendly_name": "Test light 1"})
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "light#test_1"
assert appliance["displayCategories"][0] == "LIGHT"
assert appliance["friendlyName"] == "Test light 1"
assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa"
)
await assert_power_controller_works(
"light#test_1", "light.turn_on", "light.turn_off", hass
)
async def test_dimmable_light(hass):
"""Test dimmable light discovery."""
device = (
"light.test_2",
"on",
{"brightness": 128, "friendly_name": "Test light 2", "supported_features": 1},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "light#test_2"
assert appliance["displayCategories"][0] == "LIGHT"
assert appliance["friendlyName"] == "Test light 2"
assert_endpoint_capabilities(
appliance,
"Alexa.BrightnessController",
"Alexa.PowerController",
"Alexa.EndpointHealth",
"Alexa",
)
properties = await reported_properties(hass, "light#test_2")
properties.assert_equal("Alexa.PowerController", "powerState", "ON")
properties.assert_equal("Alexa.BrightnessController", "brightness", 50)
call, _ = await assert_request_calls_service(
"Alexa.BrightnessController",
"SetBrightness",
"light#test_2",
"light.turn_on",
hass,
payload={"brightness": "50"},
)
assert call.data["brightness_pct"] == 50
async def test_color_light(hass):
"""Test color light discovery."""
device = (
"light.test_3",
"on",
{
"friendly_name": "Test light 3",
"supported_features": 19,
"min_mireds": 142,
"color_temp": "333",
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "light#test_3"
assert appliance["displayCategories"][0] == "LIGHT"
assert appliance["friendlyName"] == "Test light 3"
assert_endpoint_capabilities(
appliance,
"Alexa.BrightnessController",
"Alexa.PowerController",
"Alexa.ColorController",
"Alexa.ColorTemperatureController",
"Alexa.EndpointHealth",
"Alexa",
)
# IncreaseColorTemperature and DecreaseColorTemperature have their own
# tests
async def test_script(hass):
"""Test script discovery."""
device = ("script.test", "off", {"friendly_name": "Test script"})
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "script#test"
assert appliance["displayCategories"][0] == "ACTIVITY_TRIGGER"
assert appliance["friendlyName"] == "Test script"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.SceneController", "Alexa"
)
scene_capability = get_capability(capabilities, "Alexa.SceneController")
assert not scene_capability["supportsDeactivation"]
await assert_scene_controller_works("script#test", "script.turn_on", None, hass)
async def test_cancelable_script(hass):
"""Test cancalable script discovery."""
device = (
"script.test_2",
"off",
{"friendly_name": "Test script 2", "can_cancel": True},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "script#test_2"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.SceneController", "Alexa"
)
scene_capability = get_capability(capabilities, "Alexa.SceneController")
assert scene_capability["supportsDeactivation"]
await assert_scene_controller_works(
"script#test_2", "script.turn_on", "script.turn_off", hass
)
async def test_input_boolean(hass):
"""Test input boolean discovery."""
device = ("input_boolean.test", "off", {"friendly_name": "Test input boolean"})
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "input_boolean#test"
assert appliance["displayCategories"][0] == "OTHER"
assert appliance["friendlyName"] == "Test input boolean"
assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa"
)
await assert_power_controller_works(
"input_boolean#test", "input_boolean.turn_on", "input_boolean.turn_off", hass
)
async def test_scene(hass):
"""Test scene discovery."""
device = ("scene.test", "off", {"friendly_name": "Test scene"})
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "scene#test"
assert appliance["displayCategories"][0] == "SCENE_TRIGGER"
assert appliance["friendlyName"] == "Test scene"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.SceneController", "Alexa"
)
scene_capability = get_capability(capabilities, "Alexa.SceneController")
assert not scene_capability["supportsDeactivation"]
await assert_scene_controller_works("scene#test", "scene.turn_on", None, hass)
async def test_fan(hass):
"""Test fan discovery."""
device = ("fan.test_1", "off", {"friendly_name": "Test fan 1"})
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "fan#test_1"
assert appliance["displayCategories"][0] == "FAN"
assert appliance["friendlyName"] == "Test fan 1"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa"
)
power_capability = get_capability(capabilities, "Alexa.PowerController")
assert "capabilityResources" not in power_capability
assert "configuration" not in power_capability
async def test_variable_fan(hass):
"""Test fan discovery.
This one has variable speed.
"""
device = (
"fan.test_2",
"off",
{
"friendly_name": "Test fan 2",
"supported_features": 1,
"speed_list": ["low", "medium", "high"],
"speed": "high",
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "fan#test_2"
assert appliance["displayCategories"][0] == "FAN"
assert appliance["friendlyName"] == "Test fan 2"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PercentageController",
"Alexa.PowerController",
"Alexa.PowerLevelController",
"Alexa.RangeController",
"Alexa.EndpointHealth",
"Alexa",
)
range_capability = get_capability(capabilities, "Alexa.RangeController")
assert range_capability is not None
assert range_capability["instance"] == "fan.speed"
properties = range_capability["properties"]
assert properties["nonControllable"] is False
assert {"name": "rangeValue"} in properties["supported"]
capability_resources = range_capability["capabilityResources"]
assert capability_resources is not None
assert {
"@type": "asset",
"value": {"assetId": "Alexa.Setting.FanSpeed"},
} in capability_resources["friendlyNames"]
configuration = range_capability["configuration"]
assert configuration is not None
call, _ = await assert_request_calls_service(
"Alexa.PercentageController",
"SetPercentage",
"fan#test_2",
"fan.set_speed",
hass,
payload={"percentage": "50"},
)
assert call.data["speed"] == "medium"
call, _ = await assert_request_calls_service(
"Alexa.PercentageController",
"SetPercentage",
"fan#test_2",
"fan.set_speed",
hass,
payload={"percentage": "33"},
)
assert call.data["speed"] == "low"
call, _ = await assert_request_calls_service(
"Alexa.PercentageController",
"SetPercentage",
"fan#test_2",
"fan.set_speed",
hass,
payload={"percentage": "100"},
)
assert call.data["speed"] == "high"
await assert_percentage_changes(
hass,
[("high", "-5"), ("off", "5"), ("low", "-80"), ("medium", "-34")],
"Alexa.PercentageController",
"AdjustPercentage",
"fan#test_2",
"percentageDelta",
"fan.set_speed",
"speed",
)
call, _ = await assert_request_calls_service(
"Alexa.PowerLevelController",
"SetPowerLevel",
"fan#test_2",
"fan.set_speed",
hass,
payload={"powerLevel": "20"},
)
assert call.data["speed"] == "low"
call, _ = await assert_request_calls_service(
"Alexa.PowerLevelController",
"SetPowerLevel",
"fan#test_2",
"fan.set_speed",
hass,
payload={"powerLevel": "50"},
)
assert call.data["speed"] == "medium"
call, _ = await assert_request_calls_service(
"Alexa.PowerLevelController",
"SetPowerLevel",
"fan#test_2",
"fan.set_speed",
hass,
payload={"powerLevel": "99"},
)
assert call.data["speed"] == "high"
await assert_percentage_changes(
hass,
[("high", "-5"), ("medium", "-50"), ("low", "-80")],
"Alexa.PowerLevelController",
"AdjustPowerLevel",
"fan#test_2",
"powerLevelDelta",
"fan.set_speed",
"speed",
)
async def test_oscillating_fan(hass):
"""Test oscillating fan with ToggleController."""
device = (
"fan.test_3",
"off",
{"friendly_name": "Test fan 3", "supported_features": 2},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "fan#test_3"
assert appliance["displayCategories"][0] == "FAN"
assert appliance["friendlyName"] == "Test fan 3"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PowerController",
"Alexa.ToggleController",
"Alexa.EndpointHealth",
"Alexa",
)
toggle_capability = get_capability(capabilities, "Alexa.ToggleController")
assert toggle_capability is not None
assert toggle_capability["instance"] == "fan.oscillating"
properties = toggle_capability["properties"]
assert properties["nonControllable"] is False
assert {"name": "toggleState"} in properties["supported"]
capability_resources = toggle_capability["capabilityResources"]
assert capability_resources is not None
assert {
"@type": "asset",
"value": {"assetId": "Alexa.Setting.Oscillate"},
} in capability_resources["friendlyNames"]
call, _ = await assert_request_calls_service(
"Alexa.ToggleController",
"TurnOn",
"fan#test_3",
"fan.oscillate",
hass,
payload={},
instance="fan.oscillating",
)
assert call.data["oscillating"]
call, _ = await assert_request_calls_service(
"Alexa.ToggleController",
"TurnOff",
"fan#test_3",
"fan.oscillate",
hass,
payload={},
instance="fan.oscillating",
)
assert not call.data["oscillating"]
async def test_direction_fan(hass):
"""Test fan direction with modeController."""
device = (
"fan.test_4",
"on",
{
"friendly_name": "Test fan 4",
"supported_features": 4,
"direction": "forward",
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "fan#test_4"
assert appliance["displayCategories"][0] == "FAN"
assert appliance["friendlyName"] == "Test fan 4"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PowerController",
"Alexa.ModeController",
"Alexa.EndpointHealth",
"Alexa",
)
mode_capability = get_capability(capabilities, "Alexa.ModeController")
assert mode_capability is not None
assert mode_capability["instance"] == "fan.direction"
properties = mode_capability["properties"]
assert properties["nonControllable"] is False
assert {"name": "mode"} in properties["supported"]
capability_resources = mode_capability["capabilityResources"]
assert capability_resources is not None
assert {
"@type": "asset",
"value": {"assetId": "Alexa.Setting.Direction"},
} in capability_resources["friendlyNames"]
configuration = mode_capability["configuration"]
assert configuration is not None
assert configuration["ordered"] is False
supported_modes = configuration["supportedModes"]
assert supported_modes is not None
assert {
"value": "direction.forward",
"modeResources": {
"friendlyNames": [
{"@type": "text", "value": {"text": "forward", "locale": "en-US"}}
]
},
} in supported_modes
assert {
"value": "direction.reverse",
"modeResources": {
"friendlyNames": [
{"@type": "text", "value": {"text": "reverse", "locale": "en-US"}}
]
},
} in supported_modes
call, msg = await assert_request_calls_service(
"Alexa.ModeController",
"SetMode",
"fan#test_4",
"fan.set_direction",
hass,
payload={"mode": "direction.reverse"},
instance="fan.direction",
)
assert call.data["direction"] == "reverse"
properties = msg["context"]["properties"][0]
assert properties["name"] == "mode"
assert properties["namespace"] == "Alexa.ModeController"
assert properties["value"] == "direction.reverse"
call, msg = await assert_request_calls_service(
"Alexa.ModeController",
"SetMode",
"fan#test_4",
"fan.set_direction",
hass,
payload={"mode": "direction.forward"},
instance="fan.direction",
)
assert call.data["direction"] == "forward"
properties = msg["context"]["properties"][0]
assert properties["name"] == "mode"
assert properties["namespace"] == "Alexa.ModeController"
assert properties["value"] == "direction.forward"
# Test for AdjustMode instance=None Error coverage
with pytest.raises(AssertionError):
call, _ = await assert_request_calls_service(
"Alexa.ModeController",
"AdjustMode",
"fan#test_4",
"fan.set_direction",
hass,
payload={},
instance=None,
)
assert call.data
async def test_fan_range(hass):
"""Test fan speed with rangeController."""
device = (
"fan.test_5",
"off",
{
"friendly_name": "Test fan 5",
"supported_features": 1,
"speed_list": ["off", "low", "medium", "high", "turbo", 5, "warp_speed"],
"speed": "medium",
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "fan#test_5"
assert appliance["displayCategories"][0] == "FAN"
assert appliance["friendlyName"] == "Test fan 5"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PercentageController",
"Alexa.PowerController",
"Alexa.PowerLevelController",
"Alexa.RangeController",
"Alexa.EndpointHealth",
"Alexa",
)
range_capability = get_capability(capabilities, "Alexa.RangeController")
assert range_capability is not None
assert range_capability["instance"] == "fan.speed"
capability_resources = range_capability["capabilityResources"]
assert capability_resources is not None
assert {
"@type": "asset",
"value": {"assetId": "Alexa.Setting.FanSpeed"},
} in capability_resources["friendlyNames"]
configuration = range_capability["configuration"]
assert configuration is not None
supported_range = configuration["supportedRange"]
assert supported_range["minimumValue"] == 0
assert supported_range["maximumValue"] == 6
assert supported_range["precision"] == 1
presets = configuration["presets"]
assert {
"rangeValue": 0,
"presetResources": {
"friendlyNames": [
{"@type": "text", "value": {"text": "off", "locale": "en-US"}}
]
},
} in presets
assert {
"rangeValue": 1,
"presetResources": {
"friendlyNames": [
{"@type": "text", "value": {"text": "low", "locale": "en-US"}},
{"@type": "asset", "value": {"assetId": "Alexa.Value.Minimum"}},
]
},
} in presets
assert {
"rangeValue": 2,
"presetResources": {
"friendlyNames": [
{"@type": "text", "value": {"text": "medium", "locale": "en-US"}}
]
},
} in presets
assert {"rangeValue": 5} not in presets
assert {
"rangeValue": 6,
"presetResources": {
"friendlyNames": [
{"@type": "text", "value": {"text": "warp speed", "locale": "en-US"}},
{"@type": "asset", "value": {"assetId": "Alexa.Value.Maximum"}},
]
},
} in presets
call, _ = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"fan#test_5",
"fan.set_speed",
hass,
payload={"rangeValue": 1},
instance="fan.speed",
)
assert call.data["speed"] == "low"
call, _ = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"fan#test_5",
"fan.set_speed",
hass,
payload={"rangeValue": 5},
instance="fan.speed",
)
assert call.data["speed"] == 5
call, _ = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"fan#test_5",
"fan.set_speed",
hass,
payload={"rangeValue": 6},
instance="fan.speed",
)
assert call.data["speed"] == "warp_speed"
await assert_range_changes(
hass,
[
("low", -1, False),
("high", 1, False),
("medium", 0, False),
("warp_speed", 99, False),
],
"Alexa.RangeController",
"AdjustRangeValue",
"fan#test_5",
"fan.set_speed",
"speed",
instance="fan.speed",
)
async def test_fan_range_off(hass):
"""Test fan range controller 0 turns_off fan."""
device = (
"fan.test_6",
"off",
{
"friendly_name": "Test fan 6",
"supported_features": 1,
"speed_list": ["off", "low", "medium", "high"],
"speed": "high",
},
)
await discovery_test(device, hass)
call, _ = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"fan#test_6",
"fan.turn_off",
hass,
payload={"rangeValue": 0},
instance="fan.speed",
)
assert call.data["speed"] == "off"
await assert_range_changes(
hass,
[("off", -3, False), ("off", -99, False)],
"Alexa.RangeController",
"AdjustRangeValue",
"fan#test_6",
"fan.turn_off",
"speed",
instance="fan.speed",
)
async def test_lock(hass):
"""Test lock discovery."""
device = ("lock.test", "off", {"friendly_name": "Test lock"})
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "lock#test"
assert appliance["displayCategories"][0] == "SMARTLOCK"
assert appliance["friendlyName"] == "Test lock"
assert_endpoint_capabilities(
appliance, "Alexa.LockController", "Alexa.EndpointHealth", "Alexa"
)
_, msg = await assert_request_calls_service(
"Alexa.LockController", "Lock", "lock#test", "lock.lock", hass
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "lockState"
assert properties["namespace"] == "Alexa.LockController"
assert properties["value"] == "LOCKED"
_, msg = await assert_request_calls_service(
"Alexa.LockController", "Unlock", "lock#test", "lock.unlock", hass
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "lockState"
assert properties["namespace"] == "Alexa.LockController"
assert properties["value"] == "UNLOCKED"
async def test_media_player(hass):
"""Test media player discovery."""
device = (
"media_player.test",
"off",
{
"friendly_name": "Test media player",
"supported_features": SUPPORT_NEXT_TRACK
| SUPPORT_PAUSE
| SUPPORT_PLAY
| SUPPORT_PLAY_MEDIA
| SUPPORT_PREVIOUS_TRACK
| SUPPORT_SELECT_SOURCE
| SUPPORT_STOP
| SUPPORT_TURN_OFF
| SUPPORT_TURN_ON
| SUPPORT_VOLUME_MUTE
| SUPPORT_VOLUME_SET,
"volume_level": 0.75,
"source_list": ["hdmi", "tv"],
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "media_player#test"
assert appliance["displayCategories"][0] == "TV"
assert appliance["friendlyName"] == "Test media player"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa",
"Alexa.ChannelController",
"Alexa.EndpointHealth",
"Alexa.InputController",
"Alexa.PlaybackController",
"Alexa.PlaybackStateReporter",
"Alexa.PowerController",
"Alexa.Speaker",
)
playback_capability = get_capability(capabilities, "Alexa.PlaybackController")
assert playback_capability is not None
supported_operations = playback_capability["supportedOperations"]
operations = ["Play", "Pause", "Stop", "Next", "Previous"]
for operation in operations:
assert operation in supported_operations
await assert_power_controller_works(
"media_player#test", "media_player.turn_on", "media_player.turn_off", hass
)
await assert_request_calls_service(
"Alexa.PlaybackController",
"Play",
"media_player#test",
"media_player.media_play",
hass,
)
await assert_request_calls_service(
"Alexa.PlaybackController",
"Pause",
"media_player#test",
"media_player.media_pause",
hass,
)
await assert_request_calls_service(
"Alexa.PlaybackController",
"Stop",
"media_player#test",
"media_player.media_stop",
hass,
)
await assert_request_calls_service(
"Alexa.PlaybackController",
"Next",
"media_player#test",
"media_player.media_next_track",
hass,
)
await assert_request_calls_service(
"Alexa.PlaybackController",
"Previous",
"media_player#test",
"media_player.media_previous_track",
hass,
)
call, _ = await assert_request_calls_service(
"Alexa.ChannelController",
"ChangeChannel",
"media_player#test",
"media_player.play_media",
hass,
payload={"channel": {"number": "24"}, "channelMetadata": {"name": ""}},
)
call, _ = await assert_request_calls_service(
"Alexa.ChannelController",
"ChangeChannel",
"media_player#test",
"media_player.play_media",
hass,
payload={"channel": {"callSign": "ABC"}, "channelMetadata": {"name": ""}},
)
call, _ = await assert_request_calls_service(
"Alexa.ChannelController",
"ChangeChannel",
"media_player#test",
"media_player.play_media",
hass,
payload={"channel": {"number": ""}, "channelMetadata": {"name": "ABC"}},
)
call, _ = await assert_request_calls_service(
"Alexa.ChannelController",
"ChangeChannel",
"media_player#test",
"media_player.play_media",
hass,
payload={
"channel": {"affiliateCallSign": "ABC"},
"channelMetadata": {"name": ""},
},
)
call, _ = await assert_request_calls_service(
"Alexa.ChannelController",
"ChangeChannel",
"media_player#test",
"media_player.play_media",
hass,
payload={"channel": {"uri": "ABC"}, "channelMetadata": {"name": ""}},
)
call, _ = await assert_request_calls_service(
"Alexa.ChannelController",
"SkipChannels",
"media_player#test",
"media_player.media_next_track",
hass,
payload={"channelCount": 1},
)
call, _ = await assert_request_calls_service(
"Alexa.ChannelController",
"SkipChannels",
"media_player#test",
"media_player.media_previous_track",
hass,
payload={"channelCount": -1},
)
async def test_media_player_power(hass):
"""Test media player discovery with mapped on/off."""
device = (
"media_player.test",
"off",
{
"friendly_name": "Test media player",
"supported_features": 0xFA3F,
"volume_level": 0.75,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "media_player#test"
assert appliance["displayCategories"][0] == "TV"
assert appliance["friendlyName"] == "Test media player"
assert_endpoint_capabilities(
appliance,
"Alexa",
"Alexa.ChannelController",
"Alexa.EndpointHealth",
"Alexa.PlaybackController",
"Alexa.PlaybackStateReporter",
"Alexa.PowerController",
"Alexa.SeekController",
"Alexa.Speaker",
)
await assert_request_calls_service(
"Alexa.PowerController",
"TurnOn",
"media_player#test",
"media_player.media_play",
hass,
)
await assert_request_calls_service(
"Alexa.PowerController",
"TurnOff",
"media_player#test",
"media_player.media_stop",
hass,
)
async def test_media_player_inputs(hass):
"""Test media player discovery with source list inputs."""
device = (
"media_player.test",
"on",
{
"friendly_name": "Test media player",
"supported_features": SUPPORT_SELECT_SOURCE,
"volume_level": 0.75,
"source_list": [
"foo",
"foo_2",
"hdmi",
"hdmi_2",
"hdmi-3",
"hdmi4",
"hdmi 5",
"HDMI 6",
"hdmi_arc",
"aux",
"input 1",
"tv",
],
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "media_player#test"
assert appliance["displayCategories"][0] == "TV"
assert appliance["friendlyName"] == "Test media player"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa",
"Alexa.InputController",
"Alexa.PowerController",
"Alexa.EndpointHealth",
)
input_capability = get_capability(capabilities, "Alexa.InputController")
assert input_capability is not None
assert {"name": "AUX"} not in input_capability["inputs"]
assert {"name": "AUX 1"} in input_capability["inputs"]
assert {"name": "HDMI 1"} in input_capability["inputs"]
assert {"name": "HDMI 2"} in input_capability["inputs"]
assert {"name": "HDMI 3"} in input_capability["inputs"]
assert {"name": "HDMI 4"} in input_capability["inputs"]
assert {"name": "HDMI 5"} in input_capability["inputs"]
assert {"name": "HDMI 6"} in input_capability["inputs"]
assert {"name": "HDMI ARC"} in input_capability["inputs"]
assert {"name": "FOO 1"} not in input_capability["inputs"]
assert {"name": "TV"} in input_capability["inputs"]
call, _ = await assert_request_calls_service(
"Alexa.InputController",
"SelectInput",
"media_player#test",
"media_player.select_source",
hass,
payload={"input": "HDMI 1"},
)
assert call.data["source"] == "hdmi"
call, _ = await assert_request_calls_service(
"Alexa.InputController",
"SelectInput",
"media_player#test",
"media_player.select_source",
hass,
payload={"input": "HDMI 2"},
)
assert call.data["source"] == "hdmi_2"
call, _ = await assert_request_calls_service(
"Alexa.InputController",
"SelectInput",
"media_player#test",
"media_player.select_source",
hass,
payload={"input": "HDMI 5"},
)
assert call.data["source"] == "hdmi 5"
call, _ = await assert_request_calls_service(
"Alexa.InputController",
"SelectInput",
"media_player#test",
"media_player.select_source",
hass,
payload={"input": "HDMI 6"},
)
assert call.data["source"] == "HDMI 6"
call, _ = await assert_request_calls_service(
"Alexa.InputController",
"SelectInput",
"media_player#test",
"media_player.select_source",
hass,
payload={"input": "TV"},
)
assert call.data["source"] == "tv"
async def test_media_player_no_supported_inputs(hass):
"""Test media player discovery with no supported inputs."""
device = (
"media_player.test_no_inputs",
"off",
{
"friendly_name": "Test media player",
"supported_features": SUPPORT_SELECT_SOURCE,
"volume_level": 0.75,
"source_list": [
"foo",
"foo_2",
"vcr",
"betamax",
"record_player",
"f.m.",
"a.m.",
"tape_deck",
"laser_disc",
"hd_dvd",
],
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "media_player#test_no_inputs"
assert appliance["displayCategories"][0] == "TV"
assert appliance["friendlyName"] == "Test media player"
# Assert Alexa.InputController is not in capabilities list.
assert_endpoint_capabilities(
appliance, "Alexa", "Alexa.EndpointHealth", "Alexa.PowerController"
)
async def test_media_player_speaker(hass):
"""Test media player with speaker interface."""
device = (
"media_player.test_speaker",
"off",
{
"friendly_name": "Test media player speaker",
"supported_features": SUPPORT_VOLUME_MUTE | SUPPORT_VOLUME_SET,
"volume_level": 0.75,
"device_class": "speaker",
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "media_player#test_speaker"
assert appliance["displayCategories"][0] == "SPEAKER"
assert appliance["friendlyName"] == "Test media player speaker"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa",
"Alexa.EndpointHealth",
"Alexa.PowerController",
"Alexa.Speaker",
)
speaker_capability = get_capability(capabilities, "Alexa.Speaker")
properties = speaker_capability["properties"]
assert {"name": "volume"} in properties["supported"]
assert {"name": "muted"} in properties["supported"]
call, _ = await assert_request_calls_service(
"Alexa.Speaker",
"SetVolume",
"media_player#test_speaker",
"media_player.volume_set",
hass,
payload={"volume": 50},
)
assert call.data["volume_level"] == 0.5
call, _ = await assert_request_calls_service(
"Alexa.Speaker",
"SetMute",
"media_player#test_speaker",
"media_player.volume_mute",
hass,
payload={"mute": True},
)
assert call.data["is_volume_muted"]
call, _, = await assert_request_calls_service(
"Alexa.Speaker",
"SetMute",
"media_player#test_speaker",
"media_player.volume_mute",
hass,
payload={"mute": False},
)
assert not call.data["is_volume_muted"]
await assert_percentage_changes(
hass,
[(0.7, "-5"), (0.8, "5"), (0, "-80")],
"Alexa.Speaker",
"AdjustVolume",
"media_player#test_speaker",
"volume",
"media_player.volume_set",
"volume_level",
)
async def test_media_player_step_speaker(hass):
"""Test media player with step speaker interface."""
device = (
"media_player.test_step_speaker",
"off",
{
"friendly_name": "Test media player step speaker",
"supported_features": SUPPORT_VOLUME_MUTE | SUPPORT_VOLUME_STEP,
"device_class": "speaker",
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "media_player#test_step_speaker"
assert appliance["displayCategories"][0] == "SPEAKER"
assert appliance["friendlyName"] == "Test media player step speaker"
call, _ = await assert_request_calls_service(
"Alexa.StepSpeaker",
"SetMute",
"media_player#test_step_speaker",
"media_player.volume_mute",
hass,
payload={"mute": True},
)
assert call.data["is_volume_muted"]
call, _, = await assert_request_calls_service(
"Alexa.StepSpeaker",
"SetMute",
"media_player#test_step_speaker",
"media_player.volume_mute",
hass,
payload={"mute": False},
)
assert not call.data["is_volume_muted"]
call, _ = await assert_request_calls_service(
"Alexa.StepSpeaker",
"AdjustVolume",
"media_player#test_step_speaker",
"media_player.volume_up",
hass,
payload={"volumeSteps": 1, "volumeStepsDefault": False},
)
call, _ = await assert_request_calls_service(
"Alexa.StepSpeaker",
"AdjustVolume",
"media_player#test_step_speaker",
"media_player.volume_down",
hass,
payload={"volumeSteps": -1, "volumeStepsDefault": False},
)
call, _ = await assert_request_calls_service(
"Alexa.StepSpeaker",
"AdjustVolume",
"media_player#test_step_speaker",
"media_player.volume_up",
hass,
payload={"volumeSteps": 10, "volumeStepsDefault": True},
)
async def test_media_player_seek(hass):
"""Test media player seek capability."""
device = (
"media_player.test_seek",
"playing",
{
"friendly_name": "Test media player seek",
"supported_features": SUPPORT_SEEK,
"media_position": 300, # 5min
"media_duration": 600, # 10min
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "media_player#test_seek"
assert appliance["displayCategories"][0] == "TV"
assert appliance["friendlyName"] == "Test media player seek"
assert_endpoint_capabilities(
appliance,
"Alexa",
"Alexa.EndpointHealth",
"Alexa.PowerController",
"Alexa.SeekController",
)
# Test seek forward 30 seconds.
call, msg = await assert_request_calls_service(
"Alexa.SeekController",
"AdjustSeekPosition",
"media_player#test_seek",
"media_player.media_seek",
hass,
response_type="StateReport",
payload={"deltaPositionMilliseconds": 30000},
)
assert call.data["seek_position"] == 330
assert "properties" in msg["event"]["payload"]
properties = msg["event"]["payload"]["properties"]
assert {"name": "positionMilliseconds", "value": 330000} in properties
# Test seek reverse 30 seconds.
call, msg = await assert_request_calls_service(
"Alexa.SeekController",
"AdjustSeekPosition",
"media_player#test_seek",
"media_player.media_seek",
hass,
response_type="StateReport",
payload={"deltaPositionMilliseconds": -30000},
)
assert call.data["seek_position"] == 270
assert "properties" in msg["event"]["payload"]
properties = msg["event"]["payload"]["properties"]
assert {"name": "positionMilliseconds", "value": 270000} in properties
# Test seek backwards more than current position (5 min.) result = 0.
call, msg = await assert_request_calls_service(
"Alexa.SeekController",
"AdjustSeekPosition",
"media_player#test_seek",
"media_player.media_seek",
hass,
response_type="StateReport",
payload={"deltaPositionMilliseconds": -500000},
)
assert call.data["seek_position"] == 0
assert "properties" in msg["event"]["payload"]
properties = msg["event"]["payload"]["properties"]
assert {"name": "positionMilliseconds", "value": 0} in properties
# Test seek forward more than current duration (10 min.) result = 600 sec.
call, msg = await assert_request_calls_service(
"Alexa.SeekController",
"AdjustSeekPosition",
"media_player#test_seek",
"media_player.media_seek",
hass,
response_type="StateReport",
payload={"deltaPositionMilliseconds": 800000},
)
assert call.data["seek_position"] == 600
assert "properties" in msg["event"]["payload"]
properties = msg["event"]["payload"]["properties"]
assert {"name": "positionMilliseconds", "value": 600000} in properties
async def test_media_player_seek_error(hass):
"""Test media player seek capability for media_position Error."""
device = (
"media_player.test_seek",
"playing",
{"friendly_name": "Test media player seek", "supported_features": SUPPORT_SEEK},
)
await discovery_test(device, hass)
# Test for media_position error.
with pytest.raises(AssertionError):
call, msg = await assert_request_calls_service(
"Alexa.SeekController",
"AdjustSeekPosition",
"media_player#test_seek",
"media_player.media_seek",
hass,
response_type="StateReport",
payload={"deltaPositionMilliseconds": 30000},
)
assert "event" in msg
msg = msg["event"]
assert msg["header"]["name"] == "ErrorResponse"
assert msg["header"]["namespace"] == "Alexa.Video"
assert msg["payload"]["type"] == "ACTION_NOT_PERMITTED_FOR_CONTENT"
async def test_alert(hass):
"""Test alert discovery."""
device = ("alert.test", "off", {"friendly_name": "Test alert"})
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "alert#test"
assert appliance["displayCategories"][0] == "OTHER"
assert appliance["friendlyName"] == "Test alert"
assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa"
)
await assert_power_controller_works(
"alert#test", "alert.turn_on", "alert.turn_off", hass
)
async def test_automation(hass):
"""Test automation discovery."""
device = ("automation.test", "off", {"friendly_name": "Test automation"})
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "automation#test"
assert appliance["displayCategories"][0] == "OTHER"
assert appliance["friendlyName"] == "Test automation"
assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa"
)
await assert_power_controller_works(
"automation#test", "automation.turn_on", "automation.turn_off", hass
)
async def test_group(hass):
"""Test group discovery."""
device = ("group.test", "off", {"friendly_name": "Test group"})
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "group#test"
assert appliance["displayCategories"][0] == "OTHER"
assert appliance["friendlyName"] == "Test group"
assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa"
)
await assert_power_controller_works(
"group#test", "homeassistant.turn_on", "homeassistant.turn_off", hass
)
async def test_cover_position_range(hass):
"""Test cover discovery and position using rangeController."""
device = (
"cover.test_range",
"open",
{
"friendly_name": "Test cover range",
"device_class": "blind",
"supported_features": 7,
"position": 30,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "cover#test_range"
assert appliance["displayCategories"][0] == "INTERIOR_BLIND"
assert appliance["friendlyName"] == "Test cover range"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PowerController",
"Alexa.RangeController",
"Alexa.EndpointHealth",
"Alexa",
)
range_capability = get_capability(capabilities, "Alexa.RangeController")
assert range_capability is not None
assert range_capability["instance"] == "cover.position"
properties = range_capability["properties"]
assert properties["nonControllable"] is False
assert {"name": "rangeValue"} in properties["supported"]
capability_resources = range_capability["capabilityResources"]
assert capability_resources is not None
assert {
"@type": "text",
"value": {"text": "Position", "locale": "en-US"},
} in capability_resources["friendlyNames"]
assert {
"@type": "asset",
"value": {"assetId": "Alexa.Setting.Opening"},
} in capability_resources["friendlyNames"]
configuration = range_capability["configuration"]
assert configuration is not None
assert configuration["unitOfMeasure"] == "Alexa.Unit.Percent"
supported_range = configuration["supportedRange"]
assert supported_range["minimumValue"] == 0
assert supported_range["maximumValue"] == 100
assert supported_range["precision"] == 1
# Assert for Position Semantics
position_semantics = range_capability["semantics"]
assert position_semantics is not None
position_action_mappings = position_semantics["actionMappings"]
assert position_action_mappings is not None
assert {
"@type": "ActionsToDirective",
"actions": ["Alexa.Actions.Lower", "Alexa.Actions.Close"],
"directive": {"name": "SetRangeValue", "payload": {"rangeValue": 0}},
} in position_action_mappings
assert {
"@type": "ActionsToDirective",
"actions": ["Alexa.Actions.Raise", "Alexa.Actions.Open"],
"directive": {"name": "SetRangeValue", "payload": {"rangeValue": 100}},
} in position_action_mappings
position_state_mappings = position_semantics["stateMappings"]
assert position_state_mappings is not None
assert {
"@type": "StatesToValue",
"states": ["Alexa.States.Closed"],
"value": 0,
} in position_state_mappings
assert {
"@type": "StatesToRange",
"states": ["Alexa.States.Open"],
"range": {"minimumValue": 1, "maximumValue": 100},
} in position_state_mappings
call, _ = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"cover#test_range",
"cover.set_cover_position",
hass,
payload={"rangeValue": 50},
instance="cover.position",
)
assert call.data["position"] == 50
call, msg = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"cover#test_range",
"cover.close_cover",
hass,
payload={"rangeValue": 0},
instance="cover.position",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "rangeValue"
assert properties["namespace"] == "Alexa.RangeController"
assert properties["value"] == 0
call, msg = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"cover#test_range",
"cover.open_cover",
hass,
payload={"rangeValue": 100},
instance="cover.position",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "rangeValue"
assert properties["namespace"] == "Alexa.RangeController"
assert properties["value"] == 100
call, msg = await assert_request_calls_service(
"Alexa.RangeController",
"AdjustRangeValue",
"cover#test_range",
"cover.open_cover",
hass,
payload={"rangeValueDelta": 99, "rangeValueDeltaDefault": False},
instance="cover.position",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "rangeValue"
assert properties["namespace"] == "Alexa.RangeController"
assert properties["value"] == 100
call, msg = await assert_request_calls_service(
"Alexa.RangeController",
"AdjustRangeValue",
"cover#test_range",
"cover.close_cover",
hass,
payload={"rangeValueDelta": -99, "rangeValueDeltaDefault": False},
instance="cover.position",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "rangeValue"
assert properties["namespace"] == "Alexa.RangeController"
assert properties["value"] == 0
await assert_range_changes(
hass,
[(25, -5, False), (35, 5, False), (50, 1, True), (10, -1, True)],
"Alexa.RangeController",
"AdjustRangeValue",
"cover#test_range",
"cover.set_cover_position",
"position",
instance="cover.position",
)
async def assert_percentage_changes(
hass, adjustments, namespace, name, endpoint, parameter, service, changed_parameter
):
"""Assert an API request making percentage changes works.
AdjustPercentage, AdjustBrightness, etc. are examples of such requests.
"""
for result_volume, adjustment in adjustments:
if parameter:
payload = {parameter: adjustment}
else:
payload = {}
call, _ = await assert_request_calls_service(
namespace, name, endpoint, service, hass, payload=payload
)
assert call.data[changed_parameter] == result_volume
async def assert_range_changes(
hass, adjustments, namespace, name, endpoint, service, changed_parameter, instance
):
"""Assert an API request making range changes works.
AdjustRangeValue are examples of such requests.
"""
for result_range, adjustment, delta_default in adjustments:
payload = {
"rangeValueDelta": adjustment,
"rangeValueDeltaDefault": delta_default,
}
call, _ = await assert_request_calls_service(
namespace, name, endpoint, service, hass, payload=payload, instance=instance
)
assert call.data[changed_parameter] == result_range
async def test_temp_sensor(hass):
"""Test temperature sensor discovery."""
device = (
"sensor.test_temp",
"42",
{"friendly_name": "Test Temp Sensor", "unit_of_measurement": TEMP_FAHRENHEIT},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "sensor#test_temp"
assert appliance["displayCategories"][0] == "TEMPERATURE_SENSOR"
assert appliance["friendlyName"] == "Test Temp Sensor"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.TemperatureSensor", "Alexa.EndpointHealth", "Alexa"
)
temp_sensor_capability = get_capability(capabilities, "Alexa.TemperatureSensor")
assert temp_sensor_capability is not None
properties = temp_sensor_capability["properties"]
assert properties["retrievable"] is True
assert {"name": "temperature"} in properties["supported"]
properties = await reported_properties(hass, "sensor#test_temp")
properties.assert_equal(
"Alexa.TemperatureSensor", "temperature", {"value": 42.0, "scale": "FAHRENHEIT"}
)
async def test_contact_sensor(hass):
"""Test contact sensor discovery."""
device = (
"binary_sensor.test_contact",
"on",
{"friendly_name": "Test Contact Sensor", "device_class": "door"},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "binary_sensor#test_contact"
assert appliance["displayCategories"][0] == "CONTACT_SENSOR"
assert appliance["friendlyName"] == "Test Contact Sensor"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.ContactSensor", "Alexa.EndpointHealth", "Alexa"
)
contact_sensor_capability = get_capability(capabilities, "Alexa.ContactSensor")
assert contact_sensor_capability is not None
properties = contact_sensor_capability["properties"]
assert properties["retrievable"] is True
assert {"name": "detectionState"} in properties["supported"]
properties = await reported_properties(hass, "binary_sensor#test_contact")
properties.assert_equal("Alexa.ContactSensor", "detectionState", "DETECTED")
properties.assert_equal("Alexa.EndpointHealth", "connectivity", {"value": "OK"})
async def test_forced_contact_sensor(hass):
"""Test contact sensor discovery with specified display_category."""
device = (
"binary_sensor.test_contact_forced",
"on",
{"friendly_name": "Test Contact Sensor With DisplayCategory"},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "binary_sensor#test_contact_forced"
assert appliance["displayCategories"][0] == "CONTACT_SENSOR"
assert appliance["friendlyName"] == "Test Contact Sensor With DisplayCategory"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.ContactSensor", "Alexa.EndpointHealth", "Alexa"
)
contact_sensor_capability = get_capability(capabilities, "Alexa.ContactSensor")
assert contact_sensor_capability is not None
properties = contact_sensor_capability["properties"]
assert properties["retrievable"] is True
assert {"name": "detectionState"} in properties["supported"]
properties = await reported_properties(hass, "binary_sensor#test_contact_forced")
properties.assert_equal("Alexa.ContactSensor", "detectionState", "DETECTED")
properties.assert_equal("Alexa.EndpointHealth", "connectivity", {"value": "OK"})
async def test_motion_sensor(hass):
"""Test motion sensor discovery."""
device = (
"binary_sensor.test_motion",
"on",
{"friendly_name": "Test Motion Sensor", "device_class": "motion"},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "binary_sensor#test_motion"
assert appliance["displayCategories"][0] == "MOTION_SENSOR"
assert appliance["friendlyName"] == "Test Motion Sensor"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.MotionSensor", "Alexa.EndpointHealth", "Alexa"
)
motion_sensor_capability = get_capability(capabilities, "Alexa.MotionSensor")
assert motion_sensor_capability is not None
properties = motion_sensor_capability["properties"]
assert properties["retrievable"] is True
assert {"name": "detectionState"} in properties["supported"]
properties = await reported_properties(hass, "binary_sensor#test_motion")
properties.assert_equal("Alexa.MotionSensor", "detectionState", "DETECTED")
async def test_forced_motion_sensor(hass):
"""Test motion sensor discovery with specified display_category."""
device = (
"binary_sensor.test_motion_forced",
"on",
{"friendly_name": "Test Motion Sensor With DisplayCategory"},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "binary_sensor#test_motion_forced"
assert appliance["displayCategories"][0] == "MOTION_SENSOR"
assert appliance["friendlyName"] == "Test Motion Sensor With DisplayCategory"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.MotionSensor", "Alexa.EndpointHealth", "Alexa"
)
motion_sensor_capability = get_capability(capabilities, "Alexa.MotionSensor")
assert motion_sensor_capability is not None
properties = motion_sensor_capability["properties"]
assert properties["retrievable"] is True
assert {"name": "detectionState"} in properties["supported"]
properties = await reported_properties(hass, "binary_sensor#test_motion_forced")
properties.assert_equal("Alexa.MotionSensor", "detectionState", "DETECTED")
properties.assert_equal("Alexa.EndpointHealth", "connectivity", {"value": "OK"})
async def test_doorbell_sensor(hass):
"""Test doorbell sensor discovery."""
device = (
"binary_sensor.test_doorbell",
"off",
{"friendly_name": "Test Doorbell Sensor", "device_class": "occupancy"},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "binary_sensor#test_doorbell"
assert appliance["displayCategories"][0] == "DOORBELL"
assert appliance["friendlyName"] == "Test Doorbell Sensor"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.DoorbellEventSource", "Alexa.EndpointHealth", "Alexa"
)
doorbell_capability = get_capability(capabilities, "Alexa.DoorbellEventSource")
assert doorbell_capability is not None
assert doorbell_capability["proactivelyReported"] is True
async def test_unknown_sensor(hass):
"""Test sensors of unknown quantities are not discovered."""
device = (
"sensor.test_sickness",
"0.1",
{"friendly_name": "Test Space Sickness Sensor", "unit_of_measurement": "garn"},
)
await discovery_test(device, hass, expected_endpoints=0)
async def test_thermostat(hass):
"""Test thermostat discovery."""
hass.config.units.temperature_unit = TEMP_FAHRENHEIT
device = (
"climate.test_thermostat",
"cool",
{
"temperature": 70.0,
"target_temp_high": 80.0,
"target_temp_low": 60.0,
"current_temperature": 75.0,
"friendly_name": "Test Thermostat",
"supported_features": 1 | 2 | 4 | 128,
"hvac_modes": ["off", "heat", "cool", "auto", "dry"],
"preset_mode": None,
"preset_modes": ["eco"],
"min_temp": 50,
"max_temp": 90,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "climate#test_thermostat"
assert appliance["displayCategories"][0] == "THERMOSTAT"
assert appliance["friendlyName"] == "Test Thermostat"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PowerController",
"Alexa.ThermostatController",
"Alexa.TemperatureSensor",
"Alexa.EndpointHealth",
"Alexa",
)
properties = await reported_properties(hass, "climate#test_thermostat")
properties.assert_equal("Alexa.ThermostatController", "thermostatMode", "COOL")
properties.assert_equal(
"Alexa.ThermostatController",
"targetSetpoint",
{"value": 70.0, "scale": "FAHRENHEIT"},
)
properties.assert_equal(
"Alexa.TemperatureSensor", "temperature", {"value": 75.0, "scale": "FAHRENHEIT"}
)
thermostat_capability = get_capability(capabilities, "Alexa.ThermostatController")
assert thermostat_capability is not None
configuration = thermostat_capability["configuration"]
assert configuration["supportsScheduling"] is False
supported_modes = ["OFF", "HEAT", "COOL", "AUTO", "ECO", "CUSTOM"]
for mode in supported_modes:
assert mode in configuration["supportedModes"]
call, msg = await assert_request_calls_service(
"Alexa.ThermostatController",
"SetTargetTemperature",
"climate#test_thermostat",
"climate.set_temperature",
hass,
payload={"targetSetpoint": {"value": 69.0, "scale": "FAHRENHEIT"}},
)
assert call.data["temperature"] == 69.0
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal(
"Alexa.ThermostatController",
"targetSetpoint",
{"value": 69.0, "scale": "FAHRENHEIT"},
)
msg = await assert_request_fails(
"Alexa.ThermostatController",
"SetTargetTemperature",
"climate#test_thermostat",
"climate.set_temperature",
hass,
payload={"targetSetpoint": {"value": 0.0, "scale": "CELSIUS"}},
)
assert msg["event"]["payload"]["type"] == "TEMPERATURE_VALUE_OUT_OF_RANGE"
call, msg = await assert_request_calls_service(
"Alexa.ThermostatController",
"SetTargetTemperature",
"climate#test_thermostat",
"climate.set_temperature",
hass,
payload={
"targetSetpoint": {"value": 70.0, "scale": "FAHRENHEIT"},
"lowerSetpoint": {"value": 293.15, "scale": "KELVIN"},
"upperSetpoint": {"value": 30.0, "scale": "CELSIUS"},
},
)
assert call.data["temperature"] == 70.0
assert call.data["target_temp_low"] == 68.0
assert call.data["target_temp_high"] == 86.0
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal(
"Alexa.ThermostatController",
"targetSetpoint",
{"value": 70.0, "scale": "FAHRENHEIT"},
)
properties.assert_equal(
"Alexa.ThermostatController",
"lowerSetpoint",
{"value": 68.0, "scale": "FAHRENHEIT"},
)
properties.assert_equal(
"Alexa.ThermostatController",
"upperSetpoint",
{"value": 86.0, "scale": "FAHRENHEIT"},
)
msg = await assert_request_fails(
"Alexa.ThermostatController",
"SetTargetTemperature",
"climate#test_thermostat",
"climate.set_temperature",
hass,
payload={
"lowerSetpoint": {"value": 273.15, "scale": "KELVIN"},
"upperSetpoint": {"value": 75.0, "scale": "FAHRENHEIT"},
},
)
assert msg["event"]["payload"]["type"] == "TEMPERATURE_VALUE_OUT_OF_RANGE"
msg = await assert_request_fails(
"Alexa.ThermostatController",
"SetTargetTemperature",
"climate#test_thermostat",
"climate.set_temperature",
hass,
payload={
"lowerSetpoint": {"value": 293.15, "scale": "FAHRENHEIT"},
"upperSetpoint": {"value": 75.0, "scale": "CELSIUS"},
},
)
assert msg["event"]["payload"]["type"] == "TEMPERATURE_VALUE_OUT_OF_RANGE"
call, msg = await assert_request_calls_service(
"Alexa.ThermostatController",
"AdjustTargetTemperature",
"climate#test_thermostat",
"climate.set_temperature",
hass,
payload={"targetSetpointDelta": {"value": -10.0, "scale": "KELVIN"}},
)
assert call.data["temperature"] == 52.0
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal(
"Alexa.ThermostatController",
"targetSetpoint",
{"value": 52.0, "scale": "FAHRENHEIT"},
)
msg = await assert_request_fails(
"Alexa.ThermostatController",
"AdjustTargetTemperature",
"climate#test_thermostat",
"climate.set_temperature",
hass,
payload={"targetSetpointDelta": {"value": 20.0, "scale": "CELSIUS"}},
)
assert msg["event"]["payload"]["type"] == "TEMPERATURE_VALUE_OUT_OF_RANGE"
# Setting mode, the payload can be an object with a value attribute...
call, msg = await assert_request_calls_service(
"Alexa.ThermostatController",
"SetThermostatMode",
"climate#test_thermostat",
"climate.set_hvac_mode",
hass,
payload={"thermostatMode": {"value": "HEAT"}},
)
assert call.data["hvac_mode"] == "heat"
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal("Alexa.ThermostatController", "thermostatMode", "HEAT")
call, msg = await assert_request_calls_service(
"Alexa.ThermostatController",
"SetThermostatMode",
"climate#test_thermostat",
"climate.set_hvac_mode",
hass,
payload={"thermostatMode": {"value": "COOL"}},
)
assert call.data["hvac_mode"] == "cool"
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal("Alexa.ThermostatController", "thermostatMode", "COOL")
# ...it can also be just the mode.
call, msg = await assert_request_calls_service(
"Alexa.ThermostatController",
"SetThermostatMode",
"climate#test_thermostat",
"climate.set_hvac_mode",
hass,
payload={"thermostatMode": "HEAT"},
)
assert call.data["hvac_mode"] == "heat"
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal("Alexa.ThermostatController", "thermostatMode", "HEAT")
# Assert we can call custom modes
call, msg = await assert_request_calls_service(
"Alexa.ThermostatController",
"SetThermostatMode",
"climate#test_thermostat",
"climate.set_hvac_mode",
hass,
payload={"thermostatMode": {"value": "CUSTOM", "customName": "DEHUMIDIFY"}},
)
assert call.data["hvac_mode"] == "dry"
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal("Alexa.ThermostatController", "thermostatMode", "CUSTOM")
# assert unsupported custom mode
msg = await assert_request_fails(
"Alexa.ThermostatController",
"SetThermostatMode",
"climate#test_thermostat",
"climate.set_hvac_mode",
hass,
payload={"thermostatMode": {"value": "CUSTOM", "customName": "INVALID"}},
)
assert msg["event"]["payload"]["type"] == "UNSUPPORTED_THERMOSTAT_MODE"
msg = await assert_request_fails(
"Alexa.ThermostatController",
"SetThermostatMode",
"climate#test_thermostat",
"climate.set_hvac_mode",
hass,
payload={"thermostatMode": {"value": "INVALID"}},
)
assert msg["event"]["payload"]["type"] == "UNSUPPORTED_THERMOSTAT_MODE"
call, _ = await assert_request_calls_service(
"Alexa.ThermostatController",
"SetThermostatMode",
"climate#test_thermostat",
"climate.set_hvac_mode",
hass,
payload={"thermostatMode": "OFF"},
)
assert call.data["hvac_mode"] == "off"
# Assert we can call presets
call, msg = await assert_request_calls_service(
"Alexa.ThermostatController",
"SetThermostatMode",
"climate#test_thermostat",
"climate.set_preset_mode",
hass,
payload={"thermostatMode": "ECO"},
)
assert call.data["preset_mode"] == "eco"
# Reset config temperature_unit back to CELSIUS, required for additional tests outside this component.
hass.config.units.temperature_unit = TEMP_CELSIUS
async def test_exclude_filters(hass):
"""Test exclusion filters."""
request = get_new_request("Alexa.Discovery", "Discover")
# setup test devices
hass.states.async_set("switch.test", "on", {"friendly_name": "Test switch"})
hass.states.async_set("script.deny", "off", {"friendly_name": "Blocked script"})
hass.states.async_set("cover.deny", "off", {"friendly_name": "Blocked cover"})
alexa_config = MockConfig(hass)
alexa_config.should_expose = entityfilter.generate_filter(
include_domains=[],
include_entities=[],
exclude_domains=["script"],
exclude_entities=["cover.deny"],
)
msg = await smart_home.async_handle_message(hass, alexa_config, request)
await hass.async_block_till_done()
msg = msg["event"]
assert len(msg["payload"]["endpoints"]) == 1
async def test_include_filters(hass):
"""Test inclusion filters."""
request = get_new_request("Alexa.Discovery", "Discover")
# setup test devices
hass.states.async_set("switch.deny", "on", {"friendly_name": "Blocked switch"})
hass.states.async_set("script.deny", "off", {"friendly_name": "Blocked script"})
hass.states.async_set(
"automation.allow", "off", {"friendly_name": "Allowed automation"}
)
hass.states.async_set("group.allow", "off", {"friendly_name": "Allowed group"})
alexa_config = MockConfig(hass)
alexa_config.should_expose = entityfilter.generate_filter(
include_domains=["automation", "group"],
include_entities=["script.deny"],
exclude_domains=[],
exclude_entities=[],
)
msg = await smart_home.async_handle_message(hass, alexa_config, request)
await hass.async_block_till_done()
msg = msg["event"]
assert len(msg["payload"]["endpoints"]) == 3
async def test_never_exposed_entities(hass):
"""Test never exposed locks do not get discovered."""
request = get_new_request("Alexa.Discovery", "Discover")
# setup test devices
hass.states.async_set("group.all_locks", "on", {"friendly_name": "Blocked locks"})
hass.states.async_set("group.allow", "off", {"friendly_name": "Allowed group"})
alexa_config = MockConfig(hass)
alexa_config.should_expose = entityfilter.generate_filter(
include_domains=["group"],
include_entities=[],
exclude_domains=[],
exclude_entities=[],
)
msg = await smart_home.async_handle_message(hass, alexa_config, request)
await hass.async_block_till_done()
msg = msg["event"]
assert len(msg["payload"]["endpoints"]) == 1
async def test_api_entity_not_exists(hass):
"""Test api turn on process without entity."""
request = get_new_request("Alexa.PowerController", "TurnOn", "switch#test")
call_switch = async_mock_service(hass, "switch", "turn_on")
msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request)
await hass.async_block_till_done()
assert "event" in msg
msg = msg["event"]
assert not call_switch
assert msg["header"]["name"] == "ErrorResponse"
assert msg["header"]["namespace"] == "Alexa"
assert msg["payload"]["type"] == "NO_SUCH_ENDPOINT"
async def test_api_function_not_implemented(hass):
"""Test api call that is not implemented to us."""
request = get_new_request("Alexa.HAHAAH", "Sweet")
msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request)
assert "event" in msg
msg = msg["event"]
assert msg["header"]["name"] == "ErrorResponse"
assert msg["header"]["namespace"] == "Alexa"
assert msg["payload"]["type"] == "INTERNAL_ERROR"
async def test_api_accept_grant(hass):
"""Test api AcceptGrant process."""
request = get_new_request("Alexa.Authorization", "AcceptGrant")
# add payload
request["directive"]["payload"] = {
"grant": {
"type": "OAuth2.AuthorizationCode",
"code": "VGhpcyBpcyBhbiBhdXRob3JpemF0aW9uIGNvZGUuIDotKQ==",
},
"grantee": {"type": "BearerToken", "token": "access-token-from-skill"},
}
# setup test devices
msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request)
await hass.async_block_till_done()
assert "event" in msg
msg = msg["event"]
assert msg["header"]["name"] == "AcceptGrant.Response"
async def test_entity_config(hass):
"""Test that we can configure things via entity config."""
request = get_new_request("Alexa.Discovery", "Discover")
hass.states.async_set("light.test_1", "on", {"friendly_name": "Test light 1"})
hass.states.async_set("scene.test_1", "scening", {"friendly_name": "Test 1"})
alexa_config = MockConfig(hass)
alexa_config.entity_config = {
"light.test_1": {
"name": "Config *name*",
"display_categories": "SWITCH",
"description": "Config >!<description",
},
"scene.test_1": {"description": "Config description"},
}
msg = await smart_home.async_handle_message(hass, alexa_config, request)
assert "event" in msg
msg = msg["event"]
assert len(msg["payload"]["endpoints"]) == 2
appliance = msg["payload"]["endpoints"][0]
assert appliance["endpointId"] == "light#test_1"
assert appliance["displayCategories"][0] == "SWITCH"
assert appliance["friendlyName"] == "Config name"
assert appliance["description"] == "Config description via Home Assistant"
assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa"
)
scene = msg["payload"]["endpoints"][1]
assert scene["endpointId"] == "scene#test_1"
assert scene["displayCategories"][0] == "SCENE_TRIGGER"
assert scene["friendlyName"] == "Test 1"
assert scene["description"] == "Config description via Home Assistant (Scene)"
async def test_logging_request(hass, events):
"""Test that we log requests."""
context = Context()
request = get_new_request("Alexa.Discovery", "Discover")
await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request, context)
# To trigger event listener
await hass.async_block_till_done()
assert len(events) == 1
event = events[0]
assert event.data["request"] == {"namespace": "Alexa.Discovery", "name": "Discover"}
assert event.data["response"] == {
"namespace": "Alexa.Discovery",
"name": "Discover.Response",
}
assert event.context == context
async def test_logging_request_with_entity(hass, events):
"""Test that we log requests."""
context = Context()
request = get_new_request("Alexa.PowerController", "TurnOn", "switch#xy")
await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request, context)
# To trigger event listener
await hass.async_block_till_done()
assert len(events) == 1
event = events[0]
assert event.data["request"] == {
"namespace": "Alexa.PowerController",
"name": "TurnOn",
"entity_id": "switch.xy",
}
# Entity doesn't exist
assert event.data["response"] == {"namespace": "Alexa", "name": "ErrorResponse"}
assert event.context == context
async def test_disabled(hass):
"""When enabled=False, everything fails."""
hass.states.async_set("switch.test", "on", {"friendly_name": "Test switch"})
request = get_new_request("Alexa.PowerController", "TurnOn", "switch#test")
call_switch = async_mock_service(hass, "switch", "turn_on")
msg = await smart_home.async_handle_message(
hass, DEFAULT_CONFIG, request, enabled=False
)
await hass.async_block_till_done()
assert "event" in msg
msg = msg["event"]
assert not call_switch
assert msg["header"]["name"] == "ErrorResponse"
assert msg["header"]["namespace"] == "Alexa"
assert msg["payload"]["type"] == "BRIDGE_UNREACHABLE"
async def test_endpoint_good_health(hass):
"""Test endpoint health reporting."""
device = (
"binary_sensor.test_contact",
"on",
{"friendly_name": "Test Contact Sensor", "device_class": "door"},
)
await discovery_test(device, hass)
properties = await reported_properties(hass, "binary_sensor#test_contact")
properties.assert_equal("Alexa.EndpointHealth", "connectivity", {"value": "OK"})
async def test_endpoint_bad_health(hass):
"""Test endpoint health reporting."""
device = (
"binary_sensor.test_contact",
"unavailable",
{"friendly_name": "Test Contact Sensor", "device_class": "door"},
)
await discovery_test(device, hass)
properties = await reported_properties(hass, "binary_sensor#test_contact")
properties.assert_equal(
"Alexa.EndpointHealth", "connectivity", {"value": "UNREACHABLE"}
)
async def test_alarm_control_panel_disarmed(hass):
"""Test alarm_control_panel discovery."""
device = (
"alarm_control_panel.test_1",
"disarmed",
{
"friendly_name": "Test Alarm Control Panel 1",
"code_arm_required": False,
"code_format": "number",
"code": "1234",
"supported_features": 31,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "alarm_control_panel#test_1"
assert appliance["displayCategories"][0] == "SECURITY_PANEL"
assert appliance["friendlyName"] == "Test Alarm Control Panel 1"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.SecurityPanelController", "Alexa.EndpointHealth", "Alexa"
)
security_panel_capability = get_capability(
capabilities, "Alexa.SecurityPanelController"
)
assert security_panel_capability is not None
configuration = security_panel_capability["configuration"]
assert {"type": "FOUR_DIGIT_PIN"} in configuration["supportedAuthorizationTypes"]
assert {"value": "DISARMED"} in configuration["supportedArmStates"]
assert {"value": "ARMED_STAY"} in configuration["supportedArmStates"]
assert {"value": "ARMED_AWAY"} in configuration["supportedArmStates"]
assert {"value": "ARMED_NIGHT"} in configuration["supportedArmStates"]
properties = await reported_properties(hass, "alarm_control_panel#test_1")
properties.assert_equal("Alexa.SecurityPanelController", "armState", "DISARMED")
call, msg = await assert_request_calls_service(
"Alexa.SecurityPanelController",
"Arm",
"alarm_control_panel#test_1",
"alarm_control_panel.alarm_arm_home",
hass,
response_type="Arm.Response",
payload={"armState": "ARMED_STAY"},
)
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal("Alexa.SecurityPanelController", "armState", "ARMED_STAY")
call, msg = await assert_request_calls_service(
"Alexa.SecurityPanelController",
"Arm",
"alarm_control_panel#test_1",
"alarm_control_panel.alarm_arm_away",
hass,
response_type="Arm.Response",
payload={"armState": "ARMED_AWAY"},
)
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal("Alexa.SecurityPanelController", "armState", "ARMED_AWAY")
call, msg = await assert_request_calls_service(
"Alexa.SecurityPanelController",
"Arm",
"alarm_control_panel#test_1",
"alarm_control_panel.alarm_arm_night",
hass,
response_type="Arm.Response",
payload={"armState": "ARMED_NIGHT"},
)
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal("Alexa.SecurityPanelController", "armState", "ARMED_NIGHT")
async def test_alarm_control_panel_armed(hass):
"""Test alarm_control_panel discovery."""
device = (
"alarm_control_panel.test_2",
"armed_away",
{
"friendly_name": "Test Alarm Control Panel 2",
"code_arm_required": False,
"code_format": "FORMAT_NUMBER",
"code": "1234",
"supported_features": 3,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "alarm_control_panel#test_2"
assert appliance["displayCategories"][0] == "SECURITY_PANEL"
assert appliance["friendlyName"] == "Test Alarm Control Panel 2"
assert_endpoint_capabilities(
appliance, "Alexa.SecurityPanelController", "Alexa.EndpointHealth", "Alexa"
)
properties = await reported_properties(hass, "alarm_control_panel#test_2")
properties.assert_equal("Alexa.SecurityPanelController", "armState", "ARMED_AWAY")
call, msg = await assert_request_calls_service(
"Alexa.SecurityPanelController",
"Disarm",
"alarm_control_panel#test_2",
"alarm_control_panel.alarm_disarm",
hass,
payload={"authorization": {"type": "FOUR_DIGIT_PIN", "value": "1234"}},
)
assert call.data["code"] == "1234"
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal("Alexa.SecurityPanelController", "armState", "DISARMED")
msg = await assert_request_fails(
"Alexa.SecurityPanelController",
"Arm",
"alarm_control_panel#test_2",
"alarm_control_panel.alarm_arm_home",
hass,
payload={"armState": "ARMED_STAY"},
)
assert msg["event"]["payload"]["type"] == "AUTHORIZATION_REQUIRED"
async def test_alarm_control_panel_code_arm_required(hass):
"""Test alarm_control_panel with code_arm_required not in discovery."""
device = (
"alarm_control_panel.test_3",
"disarmed",
{
"friendly_name": "Test Alarm Control Panel 3",
"code_arm_required": True,
"supported_features": 3,
},
)
await discovery_test(device, hass, expected_endpoints=0)
async def test_range_unsupported_domain(hass):
"""Test rangeController with unsupported domain."""
device = ("switch.test", "on", {"friendly_name": "Test switch"})
await discovery_test(device, hass)
context = Context()
request = get_new_request("Alexa.RangeController", "SetRangeValue", "switch#test")
request["directive"]["payload"] = {"rangeValue": 1}
request["directive"]["header"]["instance"] = "switch.speed"
msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request, context)
assert "event" in msg
msg = msg["event"]
assert msg["header"]["name"] == "ErrorResponse"
assert msg["header"]["namespace"] == "Alexa"
assert msg["payload"]["type"] == "INVALID_DIRECTIVE"
async def test_mode_unsupported_domain(hass):
"""Test modeController with unsupported domain."""
device = ("switch.test", "on", {"friendly_name": "Test switch"})
await discovery_test(device, hass)
context = Context()
request = get_new_request("Alexa.ModeController", "SetMode", "switch#test")
request["directive"]["payload"] = {"mode": "testMode"}
request["directive"]["header"]["instance"] = "switch.direction"
msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request, context)
assert "event" in msg
msg = msg["event"]
assert msg["header"]["name"] == "ErrorResponse"
assert msg["header"]["namespace"] == "Alexa"
assert msg["payload"]["type"] == "INVALID_DIRECTIVE"
async def test_cover_garage_door(hass):
"""Test garage door cover discovery."""
device = (
"cover.test_garage_door",
"off",
{
"friendly_name": "Test cover garage door",
"supported_features": 3,
"device_class": "garage",
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "cover#test_garage_door"
assert appliance["displayCategories"][0] == "GARAGE_DOOR"
assert appliance["friendlyName"] == "Test cover garage door"
assert_endpoint_capabilities(
appliance, "Alexa.ModeController", "Alexa.EndpointHealth", "Alexa"
)
async def test_cover_position_mode(hass):
"""Test cover discovery and position using modeController."""
device = (
"cover.test_mode",
"open",
{
"friendly_name": "Test cover mode",
"device_class": "blind",
"supported_features": 3,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "cover#test_mode"
assert appliance["displayCategories"][0] == "INTERIOR_BLIND"
assert appliance["friendlyName"] == "Test cover mode"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PowerController",
"Alexa.ModeController",
"Alexa.EndpointHealth",
"Alexa",
)
mode_capability = get_capability(capabilities, "Alexa.ModeController")
assert mode_capability is not None
assert mode_capability["instance"] == "cover.position"
properties = mode_capability["properties"]
assert properties["nonControllable"] is False
assert {"name": "mode"} in properties["supported"]
capability_resources = mode_capability["capabilityResources"]
assert capability_resources is not None
assert {
"@type": "text",
"value": {"text": "Position", "locale": "en-US"},
} in capability_resources["friendlyNames"]
assert {
"@type": "asset",
"value": {"assetId": "Alexa.Setting.Opening"},
} in capability_resources["friendlyNames"]
configuration = mode_capability["configuration"]
assert configuration is not None
assert configuration["ordered"] is False
supported_modes = configuration["supportedModes"]
assert supported_modes is not None
assert {
"value": "position.open",
"modeResources": {
"friendlyNames": [
{"@type": "asset", "value": {"assetId": "Alexa.Value.Open"}}
]
},
} in supported_modes
assert {
"value": "position.closed",
"modeResources": {
"friendlyNames": [
{"@type": "asset", "value": {"assetId": "Alexa.Value.Close"}}
]
},
} in supported_modes
# Assert for Position Semantics
position_semantics = mode_capability["semantics"]
assert position_semantics is not None
position_action_mappings = position_semantics["actionMappings"]
assert position_action_mappings is not None
assert {
"@type": "ActionsToDirective",
"actions": ["Alexa.Actions.Lower", "Alexa.Actions.Close"],
"directive": {"name": "SetMode", "payload": {"mode": "position.closed"}},
} in position_action_mappings
assert {
"@type": "ActionsToDirective",
"actions": ["Alexa.Actions.Raise", "Alexa.Actions.Open"],
"directive": {"name": "SetMode", "payload": {"mode": "position.open"}},
} in position_action_mappings
position_state_mappings = position_semantics["stateMappings"]
assert position_state_mappings is not None
assert {
"@type": "StatesToValue",
"states": ["Alexa.States.Closed"],
"value": "position.closed",
} in position_state_mappings
assert {
"@type": "StatesToValue",
"states": ["Alexa.States.Open"],
"value": "position.open",
} in position_state_mappings
_, msg = await assert_request_calls_service(
"Alexa.ModeController",
"SetMode",
"cover#test_mode",
"cover.close_cover",
hass,
payload={"mode": "position.closed"},
instance="cover.position",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "mode"
assert properties["namespace"] == "Alexa.ModeController"
assert properties["value"] == "position.closed"
_, msg = await assert_request_calls_service(
"Alexa.ModeController",
"SetMode",
"cover#test_mode",
"cover.open_cover",
hass,
payload={"mode": "position.open"},
instance="cover.position",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "mode"
assert properties["namespace"] == "Alexa.ModeController"
assert properties["value"] == "position.open"
_, msg = await assert_request_calls_service(
"Alexa.ModeController",
"SetMode",
"cover#test_mode",
"cover.stop_cover",
hass,
payload={"mode": "position.custom"},
instance="cover.position",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "mode"
assert properties["namespace"] == "Alexa.ModeController"
assert properties["value"] == "position.custom"
async def test_image_processing(hass):
"""Test image_processing discovery as event detection."""
device = (
"image_processing.test_face",
0,
{
"friendly_name": "Test face",
"device_class": "face",
"faces": [],
"total_faces": 0,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "image_processing#test_face"
assert appliance["displayCategories"][0] == "CAMERA"
assert appliance["friendlyName"] == "Test face"
assert_endpoint_capabilities(
appliance, "Alexa.EventDetectionSensor", "Alexa.EndpointHealth", "Alexa"
)
async def test_motion_sensor_event_detection(hass):
"""Test motion sensor with EventDetectionSensor discovery."""
device = (
"binary_sensor.test_motion_camera_event",
"off",
{"friendly_name": "Test motion camera event", "device_class": "motion"},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "binary_sensor#test_motion_camera_event"
assert appliance["displayCategories"][0] == "CAMERA"
assert appliance["friendlyName"] == "Test motion camera event"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa",
"Alexa.MotionSensor",
"Alexa.EventDetectionSensor",
"Alexa.EndpointHealth",
)
event_detection_capability = get_capability(
capabilities, "Alexa.EventDetectionSensor"
)
assert event_detection_capability is not None
properties = event_detection_capability["properties"]
assert properties["proactivelyReported"] is True
assert not properties["retrievable"]
assert {"name": "humanPresenceDetectionState"} in properties["supported"]
async def test_presence_sensor(hass):
"""Test presence sensor."""
device = (
"binary_sensor.test_presence_sensor",
"off",
{"friendly_name": "Test presence sensor", "device_class": "presence"},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "binary_sensor#test_presence_sensor"
assert appliance["displayCategories"][0] == "CAMERA"
assert appliance["friendlyName"] == "Test presence sensor"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa", "Alexa.EventDetectionSensor", "Alexa.EndpointHealth"
)
event_detection_capability = get_capability(
capabilities, "Alexa.EventDetectionSensor"
)
assert event_detection_capability is not None
properties = event_detection_capability["properties"]
assert properties["proactivelyReported"] is True
assert not properties["retrievable"]
assert {"name": "humanPresenceDetectionState"} in properties["supported"]
async def test_cover_tilt_position_range(hass):
"""Test cover discovery and tilt position using rangeController."""
device = (
"cover.test_tilt_range",
"open",
{
"friendly_name": "Test cover tilt range",
"device_class": "blind",
"supported_features": 240,
"tilt_position": 30,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "cover#test_tilt_range"
assert appliance["displayCategories"][0] == "INTERIOR_BLIND"
assert appliance["friendlyName"] == "Test cover tilt range"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PowerController",
"Alexa.RangeController",
"Alexa.EndpointHealth",
"Alexa",
)
range_capability = get_capability(capabilities, "Alexa.RangeController")
assert range_capability is not None
assert range_capability["instance"] == "cover.tilt"
semantics = range_capability["semantics"]
assert semantics is not None
action_mappings = semantics["actionMappings"]
assert action_mappings is not None
state_mappings = semantics["stateMappings"]
assert state_mappings is not None
call, _ = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"cover#test_tilt_range",
"cover.set_cover_tilt_position",
hass,
payload={"rangeValue": 50},
instance="cover.tilt",
)
assert call.data["tilt_position"] == 50
call, msg = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"cover#test_tilt_range",
"cover.close_cover_tilt",
hass,
payload={"rangeValue": 0},
instance="cover.tilt",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "rangeValue"
assert properties["namespace"] == "Alexa.RangeController"
assert properties["value"] == 0
call, msg = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"cover#test_tilt_range",
"cover.open_cover_tilt",
hass,
payload={"rangeValue": 100},
instance="cover.tilt",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "rangeValue"
assert properties["namespace"] == "Alexa.RangeController"
assert properties["value"] == 100
call, msg = await assert_request_calls_service(
"Alexa.RangeController",
"AdjustRangeValue",
"cover#test_tilt_range",
"cover.open_cover_tilt",
hass,
payload={"rangeValueDelta": 99, "rangeValueDeltaDefault": False},
instance="cover.tilt",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "rangeValue"
assert properties["namespace"] == "Alexa.RangeController"
assert properties["value"] == 100
call, msg = await assert_request_calls_service(
"Alexa.RangeController",
"AdjustRangeValue",
"cover#test_tilt_range",
"cover.close_cover_tilt",
hass,
payload={"rangeValueDelta": -99, "rangeValueDeltaDefault": False},
instance="cover.tilt",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "rangeValue"
assert properties["namespace"] == "Alexa.RangeController"
assert properties["value"] == 0
await assert_range_changes(
hass,
[(25, -5, False), (35, 5, False), (50, 1, True), (10, -1, True)],
"Alexa.RangeController",
"AdjustRangeValue",
"cover#test_tilt_range",
"cover.set_cover_tilt_position",
"tilt_position",
instance="cover.tilt",
)
async def test_cover_semantics_position_and_tilt(hass):
"""Test cover discovery and semantics with position and tilt support."""
device = (
"cover.test_semantics",
"open",
{
"friendly_name": "Test cover semantics",
"device_class": "blind",
"supported_features": 255,
"position": 30,
"tilt_position": 30,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "cover#test_semantics"
assert appliance["displayCategories"][0] == "INTERIOR_BLIND"
assert appliance["friendlyName"] == "Test cover semantics"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PowerController",
"Alexa.RangeController",
"Alexa.EndpointHealth",
"Alexa",
)
# Assert for Position Semantics
position_capability = get_capability(
capabilities, "Alexa.RangeController", "cover.position"
)
position_semantics = position_capability["semantics"]
assert position_semantics is not None
position_action_mappings = position_semantics["actionMappings"]
assert position_action_mappings is not None
assert {
"@type": "ActionsToDirective",
"actions": ["Alexa.Actions.Lower"],
"directive": {"name": "SetRangeValue", "payload": {"rangeValue": 0}},
} in position_action_mappings
assert {
"@type": "ActionsToDirective",
"actions": ["Alexa.Actions.Raise"],
"directive": {"name": "SetRangeValue", "payload": {"rangeValue": 100}},
} in position_action_mappings
# Assert for Tilt Semantics
tilt_capability = get_capability(
capabilities, "Alexa.RangeController", "cover.tilt"
)
tilt_semantics = tilt_capability["semantics"]
assert tilt_semantics is not None
tilt_action_mappings = tilt_semantics["actionMappings"]
assert tilt_action_mappings is not None
assert {
"@type": "ActionsToDirective",
"actions": ["Alexa.Actions.Close"],
"directive": {"name": "SetRangeValue", "payload": {"rangeValue": 0}},
} in tilt_action_mappings
assert {
"@type": "ActionsToDirective",
"actions": ["Alexa.Actions.Open"],
"directive": {"name": "SetRangeValue", "payload": {"rangeValue": 100}},
} in tilt_action_mappings
tilt_state_mappings = tilt_semantics["stateMappings"]
assert tilt_state_mappings is not None
assert {
"@type": "StatesToValue",
"states": ["Alexa.States.Closed"],
"value": 0,
} in tilt_state_mappings
assert {
"@type": "StatesToRange",
"states": ["Alexa.States.Open"],
"range": {"minimumValue": 1, "maximumValue": 100},
} in tilt_state_mappings
async def test_input_number(hass):
"""Test input_number discovery."""
device = (
"input_number.test_slider",
30,
{
"initial": 30,
"min": -20,
"max": 35,
"step": 1,
"mode": "slider",
"friendly_name": "Test Slider",
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "input_number#test_slider"
assert appliance["displayCategories"][0] == "OTHER"
assert appliance["friendlyName"] == "Test Slider"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.RangeController", "Alexa.EndpointHealth", "Alexa"
)
range_capability = get_capability(
capabilities, "Alexa.RangeController", "input_number.value"
)
capability_resources = range_capability["capabilityResources"]
assert capability_resources is not None
assert {
"@type": "text",
"value": {"text": "Value", "locale": "en-US"},
} in capability_resources["friendlyNames"]
configuration = range_capability["configuration"]
assert configuration is not None
supported_range = configuration["supportedRange"]
assert supported_range["minimumValue"] == -20
assert supported_range["maximumValue"] == 35
assert supported_range["precision"] == 1
presets = configuration["presets"]
assert {
"rangeValue": 35,
"presetResources": {
"friendlyNames": [
{"@type": "asset", "value": {"assetId": "Alexa.Value.Maximum"}}
]
},
} in presets
assert {
"rangeValue": -20,
"presetResources": {
"friendlyNames": [
{"@type": "asset", "value": {"assetId": "Alexa.Value.Minimum"}}
]
},
} in presets
call, _ = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"input_number#test_slider",
"input_number.set_value",
hass,
payload={"rangeValue": 10},
instance="input_number.value",
)
assert call.data["value"] == 10
await assert_range_changes(
hass,
[(25, -5, False), (35, 5, False), (-20, -100, False), (35, 100, False)],
"Alexa.RangeController",
"AdjustRangeValue",
"input_number#test_slider",
"input_number.set_value",
"value",
instance="input_number.value",
)
async def test_input_number_float(hass):
"""Test input_number discovery."""
device = (
"input_number.test_slider_float",
0.5,
{
"initial": 0.5,
"min": 0,
"max": 1,
"step": 0.01,
"mode": "slider",
"friendly_name": "Test Slider Float",
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "input_number#test_slider_float"
assert appliance["displayCategories"][0] == "OTHER"
assert appliance["friendlyName"] == "Test Slider Float"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.RangeController", "Alexa.EndpointHealth", "Alexa"
)
range_capability = get_capability(
capabilities, "Alexa.RangeController", "input_number.value"
)
capability_resources = range_capability["capabilityResources"]
assert capability_resources is not None
assert {
"@type": "text",
"value": {"text": "Value", "locale": "en-US"},
} in capability_resources["friendlyNames"]
configuration = range_capability["configuration"]
assert configuration is not None
supported_range = configuration["supportedRange"]
assert supported_range["minimumValue"] == 0
assert supported_range["maximumValue"] == 1
assert supported_range["precision"] == 0.01
presets = configuration["presets"]
assert {
"rangeValue": 1,
"presetResources": {
"friendlyNames": [
{"@type": "asset", "value": {"assetId": "Alexa.Value.Maximum"}}
]
},
} in presets
assert {
"rangeValue": 0,
"presetResources": {
"friendlyNames": [
{"@type": "asset", "value": {"assetId": "Alexa.Value.Minimum"}}
]
},
} in presets
call, _ = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"input_number#test_slider_float",
"input_number.set_value",
hass,
payload={"rangeValue": 0.333},
instance="input_number.value",
)
assert call.data["value"] == 0.333
await assert_range_changes(
hass,
[
(0.4, -0.1, False),
(0.6, 0.1, False),
(0, -100, False),
(1, 100, False),
(0.51, 0.01, False),
],
"Alexa.RangeController",
"AdjustRangeValue",
"input_number#test_slider_float",
"input_number.set_value",
"value",
instance="input_number.value",
)
async def test_media_player_eq_modes(hass):
"""Test media player discovery with sound mode list."""
device = (
"media_player.test",
"on",
{
"friendly_name": "Test media player",
"supported_features": SUPPORT_SELECT_SOUND_MODE,
"sound_mode": "tv",
"sound_mode_list": ["movie", "music", "night", "sport", "tv", "rocknroll"],
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "media_player#test"
assert appliance["friendlyName"] == "Test media player"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa",
"Alexa.EqualizerController",
"Alexa.PowerController",
"Alexa.EndpointHealth",
)
eq_capability = get_capability(capabilities, "Alexa.EqualizerController")
assert eq_capability is not None
assert "modes" in eq_capability["configurations"]
eq_modes = eq_capability["configurations"]["modes"]
assert {"name": "rocknroll"} not in eq_modes["supported"]
assert {"name": "ROCKNROLL"} not in eq_modes["supported"]
for mode in ("MOVIE", "MUSIC", "NIGHT", "SPORT", "TV"):
assert {"name": mode} in eq_modes["supported"]
call, _ = await assert_request_calls_service(
"Alexa.EqualizerController",
"SetMode",
"media_player#test",
"media_player.select_sound_mode",
hass,
payload={"mode": mode},
)
assert call.data["sound_mode"] == mode.lower()
async def test_media_player_sound_mode_list_none(hass):
"""Test EqualizerController bands directive not supported."""
device = (
"media_player.test",
"on",
{
"friendly_name": "Test media player",
"supported_features": SUPPORT_SELECT_SOUND_MODE,
"sound_mode": "unknown",
"sound_mode_list": None,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "media_player#test"
assert appliance["friendlyName"] == "Test media player"
async def test_media_player_eq_bands_not_supported(hass):
"""Test EqualizerController bands directive not supported."""
device = (
"media_player.test_bands",
"on",
{
"friendly_name": "Test media player",
"supported_features": SUPPORT_SELECT_SOUND_MODE,
"sound_mode": "tv",
"sound_mode_list": ["movie", "music", "night", "sport", "tv", "rocknroll"],
},
)
await discovery_test(device, hass)
context = Context()
# Test for SetBands Error
request = get_new_request(
"Alexa.EqualizerController", "SetBands", "media_player#test_bands"
)
request["directive"]["payload"] = {"bands": [{"name": "BASS", "value": -2}]}
msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request, context)
assert "event" in msg
msg = msg["event"]
assert msg["header"]["name"] == "ErrorResponse"
assert msg["header"]["namespace"] == "Alexa"
assert msg["payload"]["type"] == "INVALID_DIRECTIVE"
# Test for AdjustBands Error
request = get_new_request(
"Alexa.EqualizerController", "AdjustBands", "media_player#test_bands"
)
request["directive"]["payload"] = {
"bands": [{"name": "BASS", "levelDelta": 3, "levelDirection": "UP"}]
}
msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request, context)
assert "event" in msg
msg = msg["event"]
assert msg["header"]["name"] == "ErrorResponse"
assert msg["header"]["namespace"] == "Alexa"
assert msg["payload"]["type"] == "INVALID_DIRECTIVE"
# Test for ResetBands Error
request = get_new_request(
"Alexa.EqualizerController", "ResetBands", "media_player#test_bands"
)
request["directive"]["payload"] = {
"bands": [{"name": "BASS", "levelDelta": 3, "levelDirection": "UP"}]
}
msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request, context)
assert "event" in msg
msg = msg["event"]
assert msg["header"]["name"] == "ErrorResponse"
assert msg["header"]["namespace"] == "Alexa"
assert msg["payload"]["type"] == "INVALID_DIRECTIVE"
async def test_timer_hold(hass):
"""Test timer hold."""
device = (
"timer.laundry",
"active",
{"friendly_name": "Laundry", "duration": "00:01:00", "remaining": "00:50:00"},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "timer#laundry"
assert appliance["displayCategories"][0] == "OTHER"
assert appliance["friendlyName"] == "Laundry"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa", "Alexa.TimeHoldController"
)
time_hold_capability = get_capability(capabilities, "Alexa.TimeHoldController")
assert time_hold_capability is not None
configuration = time_hold_capability["configuration"]
assert configuration["allowRemoteResume"] is True
await assert_request_calls_service(
"Alexa.TimeHoldController", "Hold", "timer#laundry", "timer.pause", hass
)
async def test_timer_resume(hass):
"""Test timer resume."""
device = (
"timer.laundry",
"paused",
{"friendly_name": "Laundry", "duration": "00:01:00", "remaining": "00:50:00"},
)
await discovery_test(device, hass)
await assert_request_calls_service(
"Alexa.TimeHoldController", "Resume", "timer#laundry", "timer.start", hass
)
async def test_vacuum_discovery(hass):
"""Test vacuum discovery."""
device = (
"vacuum.test_1",
"docked",
{
"friendly_name": "Test vacuum 1",
"supported_features": vacuum.SUPPORT_TURN_ON
| vacuum.SUPPORT_TURN_OFF
| vacuum.SUPPORT_START
| vacuum.SUPPORT_STOP
| vacuum.SUPPORT_RETURN_HOME
| vacuum.SUPPORT_PAUSE,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "vacuum#test_1"
assert appliance["displayCategories"][0] == "OTHER"
assert appliance["friendlyName"] == "Test vacuum 1"
assert_endpoint_capabilities(
appliance,
"Alexa.PowerController",
"Alexa.TimeHoldController",
"Alexa.EndpointHealth",
"Alexa",
)
properties = await reported_properties(hass, "vacuum#test_1")
properties.assert_equal("Alexa.PowerController", "powerState", "OFF")
await assert_request_calls_service(
"Alexa.PowerController", "TurnOn", "vacuum#test_1", "vacuum.turn_on", hass,
)
await assert_request_calls_service(
"Alexa.PowerController", "TurnOff", "vacuum#test_1", "vacuum.turn_off", hass,
)
async def test_vacuum_fan_speed(hass):
"""Test vacuum fan speed with rangeController."""
device = (
"vacuum.test_2",
"cleaning",
{
"friendly_name": "Test vacuum 2",
"supported_features": vacuum.SUPPORT_TURN_ON
| vacuum.SUPPORT_TURN_OFF
| vacuum.SUPPORT_START
| vacuum.SUPPORT_STOP
| vacuum.SUPPORT_PAUSE
| vacuum.SUPPORT_FAN_SPEED,
"fan_speed_list": ["off", "low", "medium", "high", "turbo", "super_sucker"],
"fan_speed": "medium",
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "vacuum#test_2"
assert appliance["displayCategories"][0] == "OTHER"
assert appliance["friendlyName"] == "Test vacuum 2"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PowerController",
"Alexa.RangeController",
"Alexa.TimeHoldController",
"Alexa.EndpointHealth",
"Alexa",
)
range_capability = get_capability(capabilities, "Alexa.RangeController")
assert range_capability is not None
assert range_capability["instance"] == "vacuum.fan_speed"
capability_resources = range_capability["capabilityResources"]
assert capability_resources is not None
assert {
"@type": "asset",
"value": {"assetId": "Alexa.Setting.FanSpeed"},
} in capability_resources["friendlyNames"]
configuration = range_capability["configuration"]
assert configuration is not None
supported_range = configuration["supportedRange"]
assert supported_range["minimumValue"] == 0
assert supported_range["maximumValue"] == 5
assert supported_range["precision"] == 1
presets = configuration["presets"]
assert {
"rangeValue": 0,
"presetResources": {
"friendlyNames": [
{"@type": "text", "value": {"text": "off", "locale": "en-US"}}
]
},
} in presets
assert {
"rangeValue": 1,
"presetResources": {
"friendlyNames": [
{"@type": "text", "value": {"text": "low", "locale": "en-US"}},
{"@type": "asset", "value": {"assetId": "Alexa.Value.Minimum"}},
]
},
} in presets
assert {
"rangeValue": 2,
"presetResources": {
"friendlyNames": [
{"@type": "text", "value": {"text": "medium", "locale": "en-US"}}
]
},
} in presets
assert {
"rangeValue": 5,
"presetResources": {
"friendlyNames": [
{"@type": "text", "value": {"text": "super sucker", "locale": "en-US"}},
{"@type": "asset", "value": {"assetId": "Alexa.Value.Maximum"}},
]
},
} in presets
call, _ = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"vacuum#test_2",
"vacuum.set_fan_speed",
hass,
payload={"rangeValue": 1},
instance="vacuum.fan_speed",
)
assert call.data["fan_speed"] == "low"
call, _ = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"vacuum#test_2",
"vacuum.set_fan_speed",
hass,
payload={"rangeValue": 5},
instance="vacuum.fan_speed",
)
assert call.data["fan_speed"] == "super_sucker"
await assert_range_changes(
hass,
[
("low", -1, False),
("high", 1, False),
("medium", 0, False),
("super_sucker", 99, False),
],
"Alexa.RangeController",
"AdjustRangeValue",
"vacuum#test_2",
"vacuum.set_fan_speed",
"fan_speed",
instance="vacuum.fan_speed",
)
async def test_vacuum_pause(hass):
"""Test vacuum pause with TimeHoldController."""
device = (
"vacuum.test_3",
"cleaning",
{
"friendly_name": "Test vacuum 3",
"supported_features": vacuum.SUPPORT_TURN_ON
| vacuum.SUPPORT_TURN_OFF
| vacuum.SUPPORT_START
| vacuum.SUPPORT_STOP
| vacuum.SUPPORT_PAUSE
| vacuum.SUPPORT_FAN_SPEED,
"fan_speed_list": ["off", "low", "medium", "high", "turbo", "super_sucker"],
"fan_speed": "medium",
},
)
appliance = await discovery_test(device, hass)
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PowerController",
"Alexa.RangeController",
"Alexa.TimeHoldController",
"Alexa.EndpointHealth",
"Alexa",
)
time_hold_capability = get_capability(capabilities, "Alexa.TimeHoldController")
assert time_hold_capability is not None
configuration = time_hold_capability["configuration"]
assert configuration["allowRemoteResume"] is True
await assert_request_calls_service(
"Alexa.TimeHoldController", "Hold", "vacuum#test_3", "vacuum.start_pause", hass
)
async def test_vacuum_resume(hass):
"""Test vacuum resume with TimeHoldController."""
device = (
"vacuum.test_4",
"docked",
{
"friendly_name": "Test vacuum 4",
"supported_features": vacuum.SUPPORT_TURN_ON
| vacuum.SUPPORT_TURN_OFF
| vacuum.SUPPORT_START
| vacuum.SUPPORT_STOP
| vacuum.SUPPORT_PAUSE
| vacuum.SUPPORT_FAN_SPEED,
"fan_speed_list": ["off", "low", "medium", "high", "turbo", "super_sucker"],
"fan_speed": "medium",
},
)
await discovery_test(device, hass)
await assert_request_calls_service(
"Alexa.TimeHoldController",
"Resume",
"vacuum#test_4",
"vacuum.start_pause",
hass,
)
async def test_vacuum_discovery_no_turn_on(hass):
"""Test vacuum discovery for vacuums without turn_on."""
device = (
"vacuum.test_5",
"cleaning",
{
"friendly_name": "Test vacuum 5",
"supported_features": vacuum.SUPPORT_TURN_OFF
| vacuum.SUPPORT_START
| vacuum.SUPPORT_RETURN_HOME,
},
)
appliance = await discovery_test(device, hass)
assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa",
)
properties = await reported_properties(hass, "vacuum#test_5")
properties.assert_equal("Alexa.PowerController", "powerState", "ON")
await assert_request_calls_service(
"Alexa.PowerController", "TurnOn", "vacuum#test_5", "vacuum.start", hass,
)
await assert_request_calls_service(
"Alexa.PowerController", "TurnOff", "vacuum#test_5", "vacuum.turn_off", hass,
)
async def test_vacuum_discovery_no_turn_off(hass):
"""Test vacuum discovery for vacuums without turn_off."""
device = (
"vacuum.test_6",
"cleaning",
{
"friendly_name": "Test vacuum 6",
"supported_features": vacuum.SUPPORT_TURN_ON
| vacuum.SUPPORT_START
| vacuum.SUPPORT_RETURN_HOME,
},
)
appliance = await discovery_test(device, hass)
assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa",
)
await assert_request_calls_service(
"Alexa.PowerController", "TurnOn", "vacuum#test_6", "vacuum.turn_on", hass,
)
await assert_request_calls_service(
"Alexa.PowerController",
"TurnOff",
"vacuum#test_6",
"vacuum.return_to_base",
hass,
)
async def test_vacuum_discovery_no_turn_on_or_off(hass):
"""Test vacuum discovery vacuums without on or off."""
device = (
"vacuum.test_7",
"cleaning",
{
"friendly_name": "Test vacuum 7",
"supported_features": vacuum.SUPPORT_START | vacuum.SUPPORT_RETURN_HOME,
},
)
appliance = await discovery_test(device, hass)
assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa",
)
await assert_request_calls_service(
"Alexa.PowerController", "TurnOn", "vacuum#test_7", "vacuum.start", hass,
)
await assert_request_calls_service(
"Alexa.PowerController",
"TurnOff",
"vacuum#test_7",
"vacuum.return_to_base",
hass,
)
| 32.39033 | 106 | 0.62891 | import pytest
from homeassistant.components.alexa import messages, smart_home
from homeassistant.components.media_player.const import (
SUPPORT_NEXT_TRACK,
SUPPORT_PAUSE,
SUPPORT_PLAY,
SUPPORT_PLAY_MEDIA,
SUPPORT_PREVIOUS_TRACK,
SUPPORT_SEEK,
SUPPORT_SELECT_SOUND_MODE,
SUPPORT_SELECT_SOURCE,
SUPPORT_STOP,
SUPPORT_TURN_OFF,
SUPPORT_TURN_ON,
SUPPORT_VOLUME_MUTE,
SUPPORT_VOLUME_SET,
SUPPORT_VOLUME_STEP,
)
import homeassistant.components.vacuum as vacuum
from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT
from homeassistant.core import Context, callback
from homeassistant.helpers import entityfilter
from . import (
DEFAULT_CONFIG,
MockConfig,
ReportedProperties,
assert_power_controller_works,
assert_request_calls_service,
assert_request_fails,
assert_scene_controller_works,
get_new_request,
reported_properties,
)
from tests.common import async_mock_service
@pytest.fixture
def events(hass):
events = []
hass.bus.async_listen(
smart_home.EVENT_ALEXA_SMART_HOME, callback(lambda e: events.append(e))
)
yield events
def test_create_api_message_defaults(hass):
request = get_new_request("Alexa.PowerController", "TurnOn", "switch#xy")
directive_header = request["directive"]["header"]
directive = messages.AlexaDirective(request)
msg = directive.response(payload={"test": 3})._response
assert "event" in msg
msg = msg["event"]
assert msg["header"]["messageId"] is not None
assert msg["header"]["messageId"] != directive_header["messageId"]
assert msg["header"]["correlationToken"] == directive_header["correlationToken"]
assert msg["header"]["name"] == "Response"
assert msg["header"]["namespace"] == "Alexa"
assert msg["header"]["payloadVersion"] == "3"
assert "test" in msg["payload"]
assert msg["payload"]["test"] == 3
assert msg["endpoint"] == request["directive"]["endpoint"]
assert msg["endpoint"] is not request["directive"]["endpoint"]
def test_create_api_message_special():
request = get_new_request("Alexa.PowerController", "TurnOn")
directive_header = request["directive"]["header"]
directive_header.pop("correlationToken")
directive = messages.AlexaDirective(request)
msg = directive.response("testName", "testNameSpace")._response
assert "event" in msg
msg = msg["event"]
assert msg["header"]["messageId"] is not None
assert msg["header"]["messageId"] != directive_header["messageId"]
assert "correlationToken" not in msg["header"]
assert msg["header"]["name"] == "testName"
assert msg["header"]["namespace"] == "testNameSpace"
assert msg["header"]["payloadVersion"] == "3"
assert msg["payload"] == {}
assert "endpoint" not in msg
async def test_wrong_version(hass):
msg = get_new_request("Alexa.PowerController", "TurnOn")
msg["directive"]["header"]["payloadVersion"] = "2"
with pytest.raises(AssertionError):
await smart_home.async_handle_message(hass, DEFAULT_CONFIG, msg)
async def discovery_test(device, hass, expected_endpoints=1):
request = get_new_request("Alexa.Discovery", "Discover")
hass.states.async_set(*device)
msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request)
assert "event" in msg
msg = msg["event"]
assert msg["header"]["name"] == "Discover.Response"
assert msg["header"]["namespace"] == "Alexa.Discovery"
endpoints = msg["payload"]["endpoints"]
assert len(endpoints) == expected_endpoints
if expected_endpoints == 1:
return endpoints[0]
if expected_endpoints > 1:
return endpoints
return None
def get_capability(capabilities, capability_name, instance=None):
for capability in capabilities:
if instance and capability.get("instance") == instance:
return capability
if not instance and capability["interface"] == capability_name:
return capability
return None
def assert_endpoint_capabilities(endpoint, *interfaces):
capabilities = endpoint["capabilities"]
supported = set(feature["interface"] for feature in capabilities)
assert supported == set(interfaces)
return capabilities
async def test_switch(hass, events):
device = ("switch.test", "on", {"friendly_name": "Test switch"})
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "switch#test"
assert appliance["displayCategories"][0] == "SWITCH"
assert appliance["friendlyName"] == "Test switch"
assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa"
)
await assert_power_controller_works(
"switch#test", "switch.turn_on", "switch.turn_off", hass
)
properties = await reported_properties(hass, "switch#test")
properties.assert_equal("Alexa.PowerController", "powerState", "ON")
async def test_outlet(hass, events):
device = (
"switch.test",
"on",
{"friendly_name": "Test switch", "device_class": "outlet"},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "switch#test"
assert appliance["displayCategories"][0] == "SMARTPLUG"
assert appliance["friendlyName"] == "Test switch"
assert_endpoint_capabilities(
appliance, "Alexa", "Alexa.PowerController", "Alexa.EndpointHealth"
)
async def test_light(hass):
device = ("light.test_1", "on", {"friendly_name": "Test light 1"})
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "light#test_1"
assert appliance["displayCategories"][0] == "LIGHT"
assert appliance["friendlyName"] == "Test light 1"
assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa"
)
await assert_power_controller_works(
"light#test_1", "light.turn_on", "light.turn_off", hass
)
async def test_dimmable_light(hass):
device = (
"light.test_2",
"on",
{"brightness": 128, "friendly_name": "Test light 2", "supported_features": 1},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "light#test_2"
assert appliance["displayCategories"][0] == "LIGHT"
assert appliance["friendlyName"] == "Test light 2"
assert_endpoint_capabilities(
appliance,
"Alexa.BrightnessController",
"Alexa.PowerController",
"Alexa.EndpointHealth",
"Alexa",
)
properties = await reported_properties(hass, "light#test_2")
properties.assert_equal("Alexa.PowerController", "powerState", "ON")
properties.assert_equal("Alexa.BrightnessController", "brightness", 50)
call, _ = await assert_request_calls_service(
"Alexa.BrightnessController",
"SetBrightness",
"light#test_2",
"light.turn_on",
hass,
payload={"brightness": "50"},
)
assert call.data["brightness_pct"] == 50
async def test_color_light(hass):
device = (
"light.test_3",
"on",
{
"friendly_name": "Test light 3",
"supported_features": 19,
"min_mireds": 142,
"color_temp": "333",
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "light#test_3"
assert appliance["displayCategories"][0] == "LIGHT"
assert appliance["friendlyName"] == "Test light 3"
assert_endpoint_capabilities(
appliance,
"Alexa.BrightnessController",
"Alexa.PowerController",
"Alexa.ColorController",
"Alexa.ColorTemperatureController",
"Alexa.EndpointHealth",
"Alexa",
)
async def test_script(hass):
device = ("script.test", "off", {"friendly_name": "Test script"})
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "script#test"
assert appliance["displayCategories"][0] == "ACTIVITY_TRIGGER"
assert appliance["friendlyName"] == "Test script"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.SceneController", "Alexa"
)
scene_capability = get_capability(capabilities, "Alexa.SceneController")
assert not scene_capability["supportsDeactivation"]
await assert_scene_controller_works("script#test", "script.turn_on", None, hass)
async def test_cancelable_script(hass):
device = (
"script.test_2",
"off",
{"friendly_name": "Test script 2", "can_cancel": True},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "script#test_2"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.SceneController", "Alexa"
)
scene_capability = get_capability(capabilities, "Alexa.SceneController")
assert scene_capability["supportsDeactivation"]
await assert_scene_controller_works(
"script#test_2", "script.turn_on", "script.turn_off", hass
)
async def test_input_boolean(hass):
device = ("input_boolean.test", "off", {"friendly_name": "Test input boolean"})
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "input_boolean#test"
assert appliance["displayCategories"][0] == "OTHER"
assert appliance["friendlyName"] == "Test input boolean"
assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa"
)
await assert_power_controller_works(
"input_boolean#test", "input_boolean.turn_on", "input_boolean.turn_off", hass
)
async def test_scene(hass):
device = ("scene.test", "off", {"friendly_name": "Test scene"})
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "scene#test"
assert appliance["displayCategories"][0] == "SCENE_TRIGGER"
assert appliance["friendlyName"] == "Test scene"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.SceneController", "Alexa"
)
scene_capability = get_capability(capabilities, "Alexa.SceneController")
assert not scene_capability["supportsDeactivation"]
await assert_scene_controller_works("scene#test", "scene.turn_on", None, hass)
async def test_fan(hass):
device = ("fan.test_1", "off", {"friendly_name": "Test fan 1"})
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "fan#test_1"
assert appliance["displayCategories"][0] == "FAN"
assert appliance["friendlyName"] == "Test fan 1"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa"
)
power_capability = get_capability(capabilities, "Alexa.PowerController")
assert "capabilityResources" not in power_capability
assert "configuration" not in power_capability
async def test_variable_fan(hass):
device = (
"fan.test_2",
"off",
{
"friendly_name": "Test fan 2",
"supported_features": 1,
"speed_list": ["low", "medium", "high"],
"speed": "high",
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "fan#test_2"
assert appliance["displayCategories"][0] == "FAN"
assert appliance["friendlyName"] == "Test fan 2"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PercentageController",
"Alexa.PowerController",
"Alexa.PowerLevelController",
"Alexa.RangeController",
"Alexa.EndpointHealth",
"Alexa",
)
range_capability = get_capability(capabilities, "Alexa.RangeController")
assert range_capability is not None
assert range_capability["instance"] == "fan.speed"
properties = range_capability["properties"]
assert properties["nonControllable"] is False
assert {"name": "rangeValue"} in properties["supported"]
capability_resources = range_capability["capabilityResources"]
assert capability_resources is not None
assert {
"@type": "asset",
"value": {"assetId": "Alexa.Setting.FanSpeed"},
} in capability_resources["friendlyNames"]
configuration = range_capability["configuration"]
assert configuration is not None
call, _ = await assert_request_calls_service(
"Alexa.PercentageController",
"SetPercentage",
"fan#test_2",
"fan.set_speed",
hass,
payload={"percentage": "50"},
)
assert call.data["speed"] == "medium"
call, _ = await assert_request_calls_service(
"Alexa.PercentageController",
"SetPercentage",
"fan#test_2",
"fan.set_speed",
hass,
payload={"percentage": "33"},
)
assert call.data["speed"] == "low"
call, _ = await assert_request_calls_service(
"Alexa.PercentageController",
"SetPercentage",
"fan#test_2",
"fan.set_speed",
hass,
payload={"percentage": "100"},
)
assert call.data["speed"] == "high"
await assert_percentage_changes(
hass,
[("high", "-5"), ("off", "5"), ("low", "-80"), ("medium", "-34")],
"Alexa.PercentageController",
"AdjustPercentage",
"fan#test_2",
"percentageDelta",
"fan.set_speed",
"speed",
)
call, _ = await assert_request_calls_service(
"Alexa.PowerLevelController",
"SetPowerLevel",
"fan#test_2",
"fan.set_speed",
hass,
payload={"powerLevel": "20"},
)
assert call.data["speed"] == "low"
call, _ = await assert_request_calls_service(
"Alexa.PowerLevelController",
"SetPowerLevel",
"fan#test_2",
"fan.set_speed",
hass,
payload={"powerLevel": "50"},
)
assert call.data["speed"] == "medium"
call, _ = await assert_request_calls_service(
"Alexa.PowerLevelController",
"SetPowerLevel",
"fan#test_2",
"fan.set_speed",
hass,
payload={"powerLevel": "99"},
)
assert call.data["speed"] == "high"
await assert_percentage_changes(
hass,
[("high", "-5"), ("medium", "-50"), ("low", "-80")],
"Alexa.PowerLevelController",
"AdjustPowerLevel",
"fan#test_2",
"powerLevelDelta",
"fan.set_speed",
"speed",
)
async def test_oscillating_fan(hass):
device = (
"fan.test_3",
"off",
{"friendly_name": "Test fan 3", "supported_features": 2},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "fan#test_3"
assert appliance["displayCategories"][0] == "FAN"
assert appliance["friendlyName"] == "Test fan 3"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PowerController",
"Alexa.ToggleController",
"Alexa.EndpointHealth",
"Alexa",
)
toggle_capability = get_capability(capabilities, "Alexa.ToggleController")
assert toggle_capability is not None
assert toggle_capability["instance"] == "fan.oscillating"
properties = toggle_capability["properties"]
assert properties["nonControllable"] is False
assert {"name": "toggleState"} in properties["supported"]
capability_resources = toggle_capability["capabilityResources"]
assert capability_resources is not None
assert {
"@type": "asset",
"value": {"assetId": "Alexa.Setting.Oscillate"},
} in capability_resources["friendlyNames"]
call, _ = await assert_request_calls_service(
"Alexa.ToggleController",
"TurnOn",
"fan#test_3",
"fan.oscillate",
hass,
payload={},
instance="fan.oscillating",
)
assert call.data["oscillating"]
call, _ = await assert_request_calls_service(
"Alexa.ToggleController",
"TurnOff",
"fan#test_3",
"fan.oscillate",
hass,
payload={},
instance="fan.oscillating",
)
assert not call.data["oscillating"]
async def test_direction_fan(hass):
device = (
"fan.test_4",
"on",
{
"friendly_name": "Test fan 4",
"supported_features": 4,
"direction": "forward",
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "fan#test_4"
assert appliance["displayCategories"][0] == "FAN"
assert appliance["friendlyName"] == "Test fan 4"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PowerController",
"Alexa.ModeController",
"Alexa.EndpointHealth",
"Alexa",
)
mode_capability = get_capability(capabilities, "Alexa.ModeController")
assert mode_capability is not None
assert mode_capability["instance"] == "fan.direction"
properties = mode_capability["properties"]
assert properties["nonControllable"] is False
assert {"name": "mode"} in properties["supported"]
capability_resources = mode_capability["capabilityResources"]
assert capability_resources is not None
assert {
"@type": "asset",
"value": {"assetId": "Alexa.Setting.Direction"},
} in capability_resources["friendlyNames"]
configuration = mode_capability["configuration"]
assert configuration is not None
assert configuration["ordered"] is False
supported_modes = configuration["supportedModes"]
assert supported_modes is not None
assert {
"value": "direction.forward",
"modeResources": {
"friendlyNames": [
{"@type": "text", "value": {"text": "forward", "locale": "en-US"}}
]
},
} in supported_modes
assert {
"value": "direction.reverse",
"modeResources": {
"friendlyNames": [
{"@type": "text", "value": {"text": "reverse", "locale": "en-US"}}
]
},
} in supported_modes
call, msg = await assert_request_calls_service(
"Alexa.ModeController",
"SetMode",
"fan#test_4",
"fan.set_direction",
hass,
payload={"mode": "direction.reverse"},
instance="fan.direction",
)
assert call.data["direction"] == "reverse"
properties = msg["context"]["properties"][0]
assert properties["name"] == "mode"
assert properties["namespace"] == "Alexa.ModeController"
assert properties["value"] == "direction.reverse"
call, msg = await assert_request_calls_service(
"Alexa.ModeController",
"SetMode",
"fan#test_4",
"fan.set_direction",
hass,
payload={"mode": "direction.forward"},
instance="fan.direction",
)
assert call.data["direction"] == "forward"
properties = msg["context"]["properties"][0]
assert properties["name"] == "mode"
assert properties["namespace"] == "Alexa.ModeController"
assert properties["value"] == "direction.forward"
with pytest.raises(AssertionError):
call, _ = await assert_request_calls_service(
"Alexa.ModeController",
"AdjustMode",
"fan#test_4",
"fan.set_direction",
hass,
payload={},
instance=None,
)
assert call.data
async def test_fan_range(hass):
device = (
"fan.test_5",
"off",
{
"friendly_name": "Test fan 5",
"supported_features": 1,
"speed_list": ["off", "low", "medium", "high", "turbo", 5, "warp_speed"],
"speed": "medium",
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "fan#test_5"
assert appliance["displayCategories"][0] == "FAN"
assert appliance["friendlyName"] == "Test fan 5"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PercentageController",
"Alexa.PowerController",
"Alexa.PowerLevelController",
"Alexa.RangeController",
"Alexa.EndpointHealth",
"Alexa",
)
range_capability = get_capability(capabilities, "Alexa.RangeController")
assert range_capability is not None
assert range_capability["instance"] == "fan.speed"
capability_resources = range_capability["capabilityResources"]
assert capability_resources is not None
assert {
"@type": "asset",
"value": {"assetId": "Alexa.Setting.FanSpeed"},
} in capability_resources["friendlyNames"]
configuration = range_capability["configuration"]
assert configuration is not None
supported_range = configuration["supportedRange"]
assert supported_range["minimumValue"] == 0
assert supported_range["maximumValue"] == 6
assert supported_range["precision"] == 1
presets = configuration["presets"]
assert {
"rangeValue": 0,
"presetResources": {
"friendlyNames": [
{"@type": "text", "value": {"text": "off", "locale": "en-US"}}
]
},
} in presets
assert {
"rangeValue": 1,
"presetResources": {
"friendlyNames": [
{"@type": "text", "value": {"text": "low", "locale": "en-US"}},
{"@type": "asset", "value": {"assetId": "Alexa.Value.Minimum"}},
]
},
} in presets
assert {
"rangeValue": 2,
"presetResources": {
"friendlyNames": [
{"@type": "text", "value": {"text": "medium", "locale": "en-US"}}
]
},
} in presets
assert {"rangeValue": 5} not in presets
assert {
"rangeValue": 6,
"presetResources": {
"friendlyNames": [
{"@type": "text", "value": {"text": "warp speed", "locale": "en-US"}},
{"@type": "asset", "value": {"assetId": "Alexa.Value.Maximum"}},
]
},
} in presets
call, _ = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"fan#test_5",
"fan.set_speed",
hass,
payload={"rangeValue": 1},
instance="fan.speed",
)
assert call.data["speed"] == "low"
call, _ = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"fan#test_5",
"fan.set_speed",
hass,
payload={"rangeValue": 5},
instance="fan.speed",
)
assert call.data["speed"] == 5
call, _ = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"fan#test_5",
"fan.set_speed",
hass,
payload={"rangeValue": 6},
instance="fan.speed",
)
assert call.data["speed"] == "warp_speed"
await assert_range_changes(
hass,
[
("low", -1, False),
("high", 1, False),
("medium", 0, False),
("warp_speed", 99, False),
],
"Alexa.RangeController",
"AdjustRangeValue",
"fan#test_5",
"fan.set_speed",
"speed",
instance="fan.speed",
)
async def test_fan_range_off(hass):
device = (
"fan.test_6",
"off",
{
"friendly_name": "Test fan 6",
"supported_features": 1,
"speed_list": ["off", "low", "medium", "high"],
"speed": "high",
},
)
await discovery_test(device, hass)
call, _ = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"fan#test_6",
"fan.turn_off",
hass,
payload={"rangeValue": 0},
instance="fan.speed",
)
assert call.data["speed"] == "off"
await assert_range_changes(
hass,
[("off", -3, False), ("off", -99, False)],
"Alexa.RangeController",
"AdjustRangeValue",
"fan#test_6",
"fan.turn_off",
"speed",
instance="fan.speed",
)
async def test_lock(hass):
device = ("lock.test", "off", {"friendly_name": "Test lock"})
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "lock#test"
assert appliance["displayCategories"][0] == "SMARTLOCK"
assert appliance["friendlyName"] == "Test lock"
assert_endpoint_capabilities(
appliance, "Alexa.LockController", "Alexa.EndpointHealth", "Alexa"
)
_, msg = await assert_request_calls_service(
"Alexa.LockController", "Lock", "lock#test", "lock.lock", hass
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "lockState"
assert properties["namespace"] == "Alexa.LockController"
assert properties["value"] == "LOCKED"
_, msg = await assert_request_calls_service(
"Alexa.LockController", "Unlock", "lock#test", "lock.unlock", hass
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "lockState"
assert properties["namespace"] == "Alexa.LockController"
assert properties["value"] == "UNLOCKED"
async def test_media_player(hass):
device = (
"media_player.test",
"off",
{
"friendly_name": "Test media player",
"supported_features": SUPPORT_NEXT_TRACK
| SUPPORT_PAUSE
| SUPPORT_PLAY
| SUPPORT_PLAY_MEDIA
| SUPPORT_PREVIOUS_TRACK
| SUPPORT_SELECT_SOURCE
| SUPPORT_STOP
| SUPPORT_TURN_OFF
| SUPPORT_TURN_ON
| SUPPORT_VOLUME_MUTE
| SUPPORT_VOLUME_SET,
"volume_level": 0.75,
"source_list": ["hdmi", "tv"],
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "media_player#test"
assert appliance["displayCategories"][0] == "TV"
assert appliance["friendlyName"] == "Test media player"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa",
"Alexa.ChannelController",
"Alexa.EndpointHealth",
"Alexa.InputController",
"Alexa.PlaybackController",
"Alexa.PlaybackStateReporter",
"Alexa.PowerController",
"Alexa.Speaker",
)
playback_capability = get_capability(capabilities, "Alexa.PlaybackController")
assert playback_capability is not None
supported_operations = playback_capability["supportedOperations"]
operations = ["Play", "Pause", "Stop", "Next", "Previous"]
for operation in operations:
assert operation in supported_operations
await assert_power_controller_works(
"media_player#test", "media_player.turn_on", "media_player.turn_off", hass
)
await assert_request_calls_service(
"Alexa.PlaybackController",
"Play",
"media_player#test",
"media_player.media_play",
hass,
)
await assert_request_calls_service(
"Alexa.PlaybackController",
"Pause",
"media_player#test",
"media_player.media_pause",
hass,
)
await assert_request_calls_service(
"Alexa.PlaybackController",
"Stop",
"media_player#test",
"media_player.media_stop",
hass,
)
await assert_request_calls_service(
"Alexa.PlaybackController",
"Next",
"media_player#test",
"media_player.media_next_track",
hass,
)
await assert_request_calls_service(
"Alexa.PlaybackController",
"Previous",
"media_player#test",
"media_player.media_previous_track",
hass,
)
call, _ = await assert_request_calls_service(
"Alexa.ChannelController",
"ChangeChannel",
"media_player#test",
"media_player.play_media",
hass,
payload={"channel": {"number": "24"}, "channelMetadata": {"name": ""}},
)
call, _ = await assert_request_calls_service(
"Alexa.ChannelController",
"ChangeChannel",
"media_player#test",
"media_player.play_media",
hass,
payload={"channel": {"callSign": "ABC"}, "channelMetadata": {"name": ""}},
)
call, _ = await assert_request_calls_service(
"Alexa.ChannelController",
"ChangeChannel",
"media_player#test",
"media_player.play_media",
hass,
payload={"channel": {"number": ""}, "channelMetadata": {"name": "ABC"}},
)
call, _ = await assert_request_calls_service(
"Alexa.ChannelController",
"ChangeChannel",
"media_player#test",
"media_player.play_media",
hass,
payload={
"channel": {"affiliateCallSign": "ABC"},
"channelMetadata": {"name": ""},
},
)
call, _ = await assert_request_calls_service(
"Alexa.ChannelController",
"ChangeChannel",
"media_player#test",
"media_player.play_media",
hass,
payload={"channel": {"uri": "ABC"}, "channelMetadata": {"name": ""}},
)
call, _ = await assert_request_calls_service(
"Alexa.ChannelController",
"SkipChannels",
"media_player#test",
"media_player.media_next_track",
hass,
payload={"channelCount": 1},
)
call, _ = await assert_request_calls_service(
"Alexa.ChannelController",
"SkipChannels",
"media_player#test",
"media_player.media_previous_track",
hass,
payload={"channelCount": -1},
)
async def test_media_player_power(hass):
device = (
"media_player.test",
"off",
{
"friendly_name": "Test media player",
"supported_features": 0xFA3F,
"volume_level": 0.75,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "media_player#test"
assert appliance["displayCategories"][0] == "TV"
assert appliance["friendlyName"] == "Test media player"
assert_endpoint_capabilities(
appliance,
"Alexa",
"Alexa.ChannelController",
"Alexa.EndpointHealth",
"Alexa.PlaybackController",
"Alexa.PlaybackStateReporter",
"Alexa.PowerController",
"Alexa.SeekController",
"Alexa.Speaker",
)
await assert_request_calls_service(
"Alexa.PowerController",
"TurnOn",
"media_player#test",
"media_player.media_play",
hass,
)
await assert_request_calls_service(
"Alexa.PowerController",
"TurnOff",
"media_player#test",
"media_player.media_stop",
hass,
)
async def test_media_player_inputs(hass):
device = (
"media_player.test",
"on",
{
"friendly_name": "Test media player",
"supported_features": SUPPORT_SELECT_SOURCE,
"volume_level": 0.75,
"source_list": [
"foo",
"foo_2",
"hdmi",
"hdmi_2",
"hdmi-3",
"hdmi4",
"hdmi 5",
"HDMI 6",
"hdmi_arc",
"aux",
"input 1",
"tv",
],
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "media_player#test"
assert appliance["displayCategories"][0] == "TV"
assert appliance["friendlyName"] == "Test media player"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa",
"Alexa.InputController",
"Alexa.PowerController",
"Alexa.EndpointHealth",
)
input_capability = get_capability(capabilities, "Alexa.InputController")
assert input_capability is not None
assert {"name": "AUX"} not in input_capability["inputs"]
assert {"name": "AUX 1"} in input_capability["inputs"]
assert {"name": "HDMI 1"} in input_capability["inputs"]
assert {"name": "HDMI 2"} in input_capability["inputs"]
assert {"name": "HDMI 3"} in input_capability["inputs"]
assert {"name": "HDMI 4"} in input_capability["inputs"]
assert {"name": "HDMI 5"} in input_capability["inputs"]
assert {"name": "HDMI 6"} in input_capability["inputs"]
assert {"name": "HDMI ARC"} in input_capability["inputs"]
assert {"name": "FOO 1"} not in input_capability["inputs"]
assert {"name": "TV"} in input_capability["inputs"]
call, _ = await assert_request_calls_service(
"Alexa.InputController",
"SelectInput",
"media_player#test",
"media_player.select_source",
hass,
payload={"input": "HDMI 1"},
)
assert call.data["source"] == "hdmi"
call, _ = await assert_request_calls_service(
"Alexa.InputController",
"SelectInput",
"media_player#test",
"media_player.select_source",
hass,
payload={"input": "HDMI 2"},
)
assert call.data["source"] == "hdmi_2"
call, _ = await assert_request_calls_service(
"Alexa.InputController",
"SelectInput",
"media_player#test",
"media_player.select_source",
hass,
payload={"input": "HDMI 5"},
)
assert call.data["source"] == "hdmi 5"
call, _ = await assert_request_calls_service(
"Alexa.InputController",
"SelectInput",
"media_player#test",
"media_player.select_source",
hass,
payload={"input": "HDMI 6"},
)
assert call.data["source"] == "HDMI 6"
call, _ = await assert_request_calls_service(
"Alexa.InputController",
"SelectInput",
"media_player#test",
"media_player.select_source",
hass,
payload={"input": "TV"},
)
assert call.data["source"] == "tv"
async def test_media_player_no_supported_inputs(hass):
device = (
"media_player.test_no_inputs",
"off",
{
"friendly_name": "Test media player",
"supported_features": SUPPORT_SELECT_SOURCE,
"volume_level": 0.75,
"source_list": [
"foo",
"foo_2",
"vcr",
"betamax",
"record_player",
"f.m.",
"a.m.",
"tape_deck",
"laser_disc",
"hd_dvd",
],
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "media_player#test_no_inputs"
assert appliance["displayCategories"][0] == "TV"
assert appliance["friendlyName"] == "Test media player"
assert_endpoint_capabilities(
appliance, "Alexa", "Alexa.EndpointHealth", "Alexa.PowerController"
)
async def test_media_player_speaker(hass):
device = (
"media_player.test_speaker",
"off",
{
"friendly_name": "Test media player speaker",
"supported_features": SUPPORT_VOLUME_MUTE | SUPPORT_VOLUME_SET,
"volume_level": 0.75,
"device_class": "speaker",
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "media_player#test_speaker"
assert appliance["displayCategories"][0] == "SPEAKER"
assert appliance["friendlyName"] == "Test media player speaker"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa",
"Alexa.EndpointHealth",
"Alexa.PowerController",
"Alexa.Speaker",
)
speaker_capability = get_capability(capabilities, "Alexa.Speaker")
properties = speaker_capability["properties"]
assert {"name": "volume"} in properties["supported"]
assert {"name": "muted"} in properties["supported"]
call, _ = await assert_request_calls_service(
"Alexa.Speaker",
"SetVolume",
"media_player#test_speaker",
"media_player.volume_set",
hass,
payload={"volume": 50},
)
assert call.data["volume_level"] == 0.5
call, _ = await assert_request_calls_service(
"Alexa.Speaker",
"SetMute",
"media_player#test_speaker",
"media_player.volume_mute",
hass,
payload={"mute": True},
)
assert call.data["is_volume_muted"]
call, _, = await assert_request_calls_service(
"Alexa.Speaker",
"SetMute",
"media_player#test_speaker",
"media_player.volume_mute",
hass,
payload={"mute": False},
)
assert not call.data["is_volume_muted"]
await assert_percentage_changes(
hass,
[(0.7, "-5"), (0.8, "5"), (0, "-80")],
"Alexa.Speaker",
"AdjustVolume",
"media_player#test_speaker",
"volume",
"media_player.volume_set",
"volume_level",
)
async def test_media_player_step_speaker(hass):
device = (
"media_player.test_step_speaker",
"off",
{
"friendly_name": "Test media player step speaker",
"supported_features": SUPPORT_VOLUME_MUTE | SUPPORT_VOLUME_STEP,
"device_class": "speaker",
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "media_player#test_step_speaker"
assert appliance["displayCategories"][0] == "SPEAKER"
assert appliance["friendlyName"] == "Test media player step speaker"
call, _ = await assert_request_calls_service(
"Alexa.StepSpeaker",
"SetMute",
"media_player#test_step_speaker",
"media_player.volume_mute",
hass,
payload={"mute": True},
)
assert call.data["is_volume_muted"]
call, _, = await assert_request_calls_service(
"Alexa.StepSpeaker",
"SetMute",
"media_player#test_step_speaker",
"media_player.volume_mute",
hass,
payload={"mute": False},
)
assert not call.data["is_volume_muted"]
call, _ = await assert_request_calls_service(
"Alexa.StepSpeaker",
"AdjustVolume",
"media_player#test_step_speaker",
"media_player.volume_up",
hass,
payload={"volumeSteps": 1, "volumeStepsDefault": False},
)
call, _ = await assert_request_calls_service(
"Alexa.StepSpeaker",
"AdjustVolume",
"media_player#test_step_speaker",
"media_player.volume_down",
hass,
payload={"volumeSteps": -1, "volumeStepsDefault": False},
)
call, _ = await assert_request_calls_service(
"Alexa.StepSpeaker",
"AdjustVolume",
"media_player#test_step_speaker",
"media_player.volume_up",
hass,
payload={"volumeSteps": 10, "volumeStepsDefault": True},
)
async def test_media_player_seek(hass):
device = (
"media_player.test_seek",
"playing",
{
"friendly_name": "Test media player seek",
"supported_features": SUPPORT_SEEK,
"media_position": 300,
"media_duration": 600,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "media_player#test_seek"
assert appliance["displayCategories"][0] == "TV"
assert appliance["friendlyName"] == "Test media player seek"
assert_endpoint_capabilities(
appliance,
"Alexa",
"Alexa.EndpointHealth",
"Alexa.PowerController",
"Alexa.SeekController",
)
call, msg = await assert_request_calls_service(
"Alexa.SeekController",
"AdjustSeekPosition",
"media_player#test_seek",
"media_player.media_seek",
hass,
response_type="StateReport",
payload={"deltaPositionMilliseconds": 30000},
)
assert call.data["seek_position"] == 330
assert "properties" in msg["event"]["payload"]
properties = msg["event"]["payload"]["properties"]
assert {"name": "positionMilliseconds", "value": 330000} in properties
call, msg = await assert_request_calls_service(
"Alexa.SeekController",
"AdjustSeekPosition",
"media_player#test_seek",
"media_player.media_seek",
hass,
response_type="StateReport",
payload={"deltaPositionMilliseconds": -30000},
)
assert call.data["seek_position"] == 270
assert "properties" in msg["event"]["payload"]
properties = msg["event"]["payload"]["properties"]
assert {"name": "positionMilliseconds", "value": 270000} in properties
call, msg = await assert_request_calls_service(
"Alexa.SeekController",
"AdjustSeekPosition",
"media_player#test_seek",
"media_player.media_seek",
hass,
response_type="StateReport",
payload={"deltaPositionMilliseconds": -500000},
)
assert call.data["seek_position"] == 0
assert "properties" in msg["event"]["payload"]
properties = msg["event"]["payload"]["properties"]
assert {"name": "positionMilliseconds", "value": 0} in properties
call, msg = await assert_request_calls_service(
"Alexa.SeekController",
"AdjustSeekPosition",
"media_player#test_seek",
"media_player.media_seek",
hass,
response_type="StateReport",
payload={"deltaPositionMilliseconds": 800000},
)
assert call.data["seek_position"] == 600
assert "properties" in msg["event"]["payload"]
properties = msg["event"]["payload"]["properties"]
assert {"name": "positionMilliseconds", "value": 600000} in properties
async def test_media_player_seek_error(hass):
device = (
"media_player.test_seek",
"playing",
{"friendly_name": "Test media player seek", "supported_features": SUPPORT_SEEK},
)
await discovery_test(device, hass)
with pytest.raises(AssertionError):
call, msg = await assert_request_calls_service(
"Alexa.SeekController",
"AdjustSeekPosition",
"media_player#test_seek",
"media_player.media_seek",
hass,
response_type="StateReport",
payload={"deltaPositionMilliseconds": 30000},
)
assert "event" in msg
msg = msg["event"]
assert msg["header"]["name"] == "ErrorResponse"
assert msg["header"]["namespace"] == "Alexa.Video"
assert msg["payload"]["type"] == "ACTION_NOT_PERMITTED_FOR_CONTENT"
async def test_alert(hass):
device = ("alert.test", "off", {"friendly_name": "Test alert"})
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "alert#test"
assert appliance["displayCategories"][0] == "OTHER"
assert appliance["friendlyName"] == "Test alert"
assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa"
)
await assert_power_controller_works(
"alert#test", "alert.turn_on", "alert.turn_off", hass
)
async def test_automation(hass):
device = ("automation.test", "off", {"friendly_name": "Test automation"})
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "automation#test"
assert appliance["displayCategories"][0] == "OTHER"
assert appliance["friendlyName"] == "Test automation"
assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa"
)
await assert_power_controller_works(
"automation#test", "automation.turn_on", "automation.turn_off", hass
)
async def test_group(hass):
device = ("group.test", "off", {"friendly_name": "Test group"})
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "group#test"
assert appliance["displayCategories"][0] == "OTHER"
assert appliance["friendlyName"] == "Test group"
assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa"
)
await assert_power_controller_works(
"group#test", "homeassistant.turn_on", "homeassistant.turn_off", hass
)
async def test_cover_position_range(hass):
device = (
"cover.test_range",
"open",
{
"friendly_name": "Test cover range",
"device_class": "blind",
"supported_features": 7,
"position": 30,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "cover#test_range"
assert appliance["displayCategories"][0] == "INTERIOR_BLIND"
assert appliance["friendlyName"] == "Test cover range"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PowerController",
"Alexa.RangeController",
"Alexa.EndpointHealth",
"Alexa",
)
range_capability = get_capability(capabilities, "Alexa.RangeController")
assert range_capability is not None
assert range_capability["instance"] == "cover.position"
properties = range_capability["properties"]
assert properties["nonControllable"] is False
assert {"name": "rangeValue"} in properties["supported"]
capability_resources = range_capability["capabilityResources"]
assert capability_resources is not None
assert {
"@type": "text",
"value": {"text": "Position", "locale": "en-US"},
} in capability_resources["friendlyNames"]
assert {
"@type": "asset",
"value": {"assetId": "Alexa.Setting.Opening"},
} in capability_resources["friendlyNames"]
configuration = range_capability["configuration"]
assert configuration is not None
assert configuration["unitOfMeasure"] == "Alexa.Unit.Percent"
supported_range = configuration["supportedRange"]
assert supported_range["minimumValue"] == 0
assert supported_range["maximumValue"] == 100
assert supported_range["precision"] == 1
position_semantics = range_capability["semantics"]
assert position_semantics is not None
position_action_mappings = position_semantics["actionMappings"]
assert position_action_mappings is not None
assert {
"@type": "ActionsToDirective",
"actions": ["Alexa.Actions.Lower", "Alexa.Actions.Close"],
"directive": {"name": "SetRangeValue", "payload": {"rangeValue": 0}},
} in position_action_mappings
assert {
"@type": "ActionsToDirective",
"actions": ["Alexa.Actions.Raise", "Alexa.Actions.Open"],
"directive": {"name": "SetRangeValue", "payload": {"rangeValue": 100}},
} in position_action_mappings
position_state_mappings = position_semantics["stateMappings"]
assert position_state_mappings is not None
assert {
"@type": "StatesToValue",
"states": ["Alexa.States.Closed"],
"value": 0,
} in position_state_mappings
assert {
"@type": "StatesToRange",
"states": ["Alexa.States.Open"],
"range": {"minimumValue": 1, "maximumValue": 100},
} in position_state_mappings
call, _ = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"cover#test_range",
"cover.set_cover_position",
hass,
payload={"rangeValue": 50},
instance="cover.position",
)
assert call.data["position"] == 50
call, msg = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"cover#test_range",
"cover.close_cover",
hass,
payload={"rangeValue": 0},
instance="cover.position",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "rangeValue"
assert properties["namespace"] == "Alexa.RangeController"
assert properties["value"] == 0
call, msg = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"cover#test_range",
"cover.open_cover",
hass,
payload={"rangeValue": 100},
instance="cover.position",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "rangeValue"
assert properties["namespace"] == "Alexa.RangeController"
assert properties["value"] == 100
call, msg = await assert_request_calls_service(
"Alexa.RangeController",
"AdjustRangeValue",
"cover#test_range",
"cover.open_cover",
hass,
payload={"rangeValueDelta": 99, "rangeValueDeltaDefault": False},
instance="cover.position",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "rangeValue"
assert properties["namespace"] == "Alexa.RangeController"
assert properties["value"] == 100
call, msg = await assert_request_calls_service(
"Alexa.RangeController",
"AdjustRangeValue",
"cover#test_range",
"cover.close_cover",
hass,
payload={"rangeValueDelta": -99, "rangeValueDeltaDefault": False},
instance="cover.position",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "rangeValue"
assert properties["namespace"] == "Alexa.RangeController"
assert properties["value"] == 0
await assert_range_changes(
hass,
[(25, -5, False), (35, 5, False), (50, 1, True), (10, -1, True)],
"Alexa.RangeController",
"AdjustRangeValue",
"cover#test_range",
"cover.set_cover_position",
"position",
instance="cover.position",
)
async def assert_percentage_changes(
hass, adjustments, namespace, name, endpoint, parameter, service, changed_parameter
):
for result_volume, adjustment in adjustments:
if parameter:
payload = {parameter: adjustment}
else:
payload = {}
call, _ = await assert_request_calls_service(
namespace, name, endpoint, service, hass, payload=payload
)
assert call.data[changed_parameter] == result_volume
async def assert_range_changes(
hass, adjustments, namespace, name, endpoint, service, changed_parameter, instance
):
for result_range, adjustment, delta_default in adjustments:
payload = {
"rangeValueDelta": adjustment,
"rangeValueDeltaDefault": delta_default,
}
call, _ = await assert_request_calls_service(
namespace, name, endpoint, service, hass, payload=payload, instance=instance
)
assert call.data[changed_parameter] == result_range
async def test_temp_sensor(hass):
device = (
"sensor.test_temp",
"42",
{"friendly_name": "Test Temp Sensor", "unit_of_measurement": TEMP_FAHRENHEIT},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "sensor#test_temp"
assert appliance["displayCategories"][0] == "TEMPERATURE_SENSOR"
assert appliance["friendlyName"] == "Test Temp Sensor"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.TemperatureSensor", "Alexa.EndpointHealth", "Alexa"
)
temp_sensor_capability = get_capability(capabilities, "Alexa.TemperatureSensor")
assert temp_sensor_capability is not None
properties = temp_sensor_capability["properties"]
assert properties["retrievable"] is True
assert {"name": "temperature"} in properties["supported"]
properties = await reported_properties(hass, "sensor#test_temp")
properties.assert_equal(
"Alexa.TemperatureSensor", "temperature", {"value": 42.0, "scale": "FAHRENHEIT"}
)
async def test_contact_sensor(hass):
device = (
"binary_sensor.test_contact",
"on",
{"friendly_name": "Test Contact Sensor", "device_class": "door"},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "binary_sensor#test_contact"
assert appliance["displayCategories"][0] == "CONTACT_SENSOR"
assert appliance["friendlyName"] == "Test Contact Sensor"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.ContactSensor", "Alexa.EndpointHealth", "Alexa"
)
contact_sensor_capability = get_capability(capabilities, "Alexa.ContactSensor")
assert contact_sensor_capability is not None
properties = contact_sensor_capability["properties"]
assert properties["retrievable"] is True
assert {"name": "detectionState"} in properties["supported"]
properties = await reported_properties(hass, "binary_sensor#test_contact")
properties.assert_equal("Alexa.ContactSensor", "detectionState", "DETECTED")
properties.assert_equal("Alexa.EndpointHealth", "connectivity", {"value": "OK"})
async def test_forced_contact_sensor(hass):
device = (
"binary_sensor.test_contact_forced",
"on",
{"friendly_name": "Test Contact Sensor With DisplayCategory"},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "binary_sensor#test_contact_forced"
assert appliance["displayCategories"][0] == "CONTACT_SENSOR"
assert appliance["friendlyName"] == "Test Contact Sensor With DisplayCategory"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.ContactSensor", "Alexa.EndpointHealth", "Alexa"
)
contact_sensor_capability = get_capability(capabilities, "Alexa.ContactSensor")
assert contact_sensor_capability is not None
properties = contact_sensor_capability["properties"]
assert properties["retrievable"] is True
assert {"name": "detectionState"} in properties["supported"]
properties = await reported_properties(hass, "binary_sensor#test_contact_forced")
properties.assert_equal("Alexa.ContactSensor", "detectionState", "DETECTED")
properties.assert_equal("Alexa.EndpointHealth", "connectivity", {"value": "OK"})
async def test_motion_sensor(hass):
device = (
"binary_sensor.test_motion",
"on",
{"friendly_name": "Test Motion Sensor", "device_class": "motion"},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "binary_sensor#test_motion"
assert appliance["displayCategories"][0] == "MOTION_SENSOR"
assert appliance["friendlyName"] == "Test Motion Sensor"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.MotionSensor", "Alexa.EndpointHealth", "Alexa"
)
motion_sensor_capability = get_capability(capabilities, "Alexa.MotionSensor")
assert motion_sensor_capability is not None
properties = motion_sensor_capability["properties"]
assert properties["retrievable"] is True
assert {"name": "detectionState"} in properties["supported"]
properties = await reported_properties(hass, "binary_sensor#test_motion")
properties.assert_equal("Alexa.MotionSensor", "detectionState", "DETECTED")
async def test_forced_motion_sensor(hass):
device = (
"binary_sensor.test_motion_forced",
"on",
{"friendly_name": "Test Motion Sensor With DisplayCategory"},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "binary_sensor#test_motion_forced"
assert appliance["displayCategories"][0] == "MOTION_SENSOR"
assert appliance["friendlyName"] == "Test Motion Sensor With DisplayCategory"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.MotionSensor", "Alexa.EndpointHealth", "Alexa"
)
motion_sensor_capability = get_capability(capabilities, "Alexa.MotionSensor")
assert motion_sensor_capability is not None
properties = motion_sensor_capability["properties"]
assert properties["retrievable"] is True
assert {"name": "detectionState"} in properties["supported"]
properties = await reported_properties(hass, "binary_sensor#test_motion_forced")
properties.assert_equal("Alexa.MotionSensor", "detectionState", "DETECTED")
properties.assert_equal("Alexa.EndpointHealth", "connectivity", {"value": "OK"})
async def test_doorbell_sensor(hass):
device = (
"binary_sensor.test_doorbell",
"off",
{"friendly_name": "Test Doorbell Sensor", "device_class": "occupancy"},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "binary_sensor#test_doorbell"
assert appliance["displayCategories"][0] == "DOORBELL"
assert appliance["friendlyName"] == "Test Doorbell Sensor"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.DoorbellEventSource", "Alexa.EndpointHealth", "Alexa"
)
doorbell_capability = get_capability(capabilities, "Alexa.DoorbellEventSource")
assert doorbell_capability is not None
assert doorbell_capability["proactivelyReported"] is True
async def test_unknown_sensor(hass):
device = (
"sensor.test_sickness",
"0.1",
{"friendly_name": "Test Space Sickness Sensor", "unit_of_measurement": "garn"},
)
await discovery_test(device, hass, expected_endpoints=0)
async def test_thermostat(hass):
hass.config.units.temperature_unit = TEMP_FAHRENHEIT
device = (
"climate.test_thermostat",
"cool",
{
"temperature": 70.0,
"target_temp_high": 80.0,
"target_temp_low": 60.0,
"current_temperature": 75.0,
"friendly_name": "Test Thermostat",
"supported_features": 1 | 2 | 4 | 128,
"hvac_modes": ["off", "heat", "cool", "auto", "dry"],
"preset_mode": None,
"preset_modes": ["eco"],
"min_temp": 50,
"max_temp": 90,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "climate#test_thermostat"
assert appliance["displayCategories"][0] == "THERMOSTAT"
assert appliance["friendlyName"] == "Test Thermostat"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PowerController",
"Alexa.ThermostatController",
"Alexa.TemperatureSensor",
"Alexa.EndpointHealth",
"Alexa",
)
properties = await reported_properties(hass, "climate#test_thermostat")
properties.assert_equal("Alexa.ThermostatController", "thermostatMode", "COOL")
properties.assert_equal(
"Alexa.ThermostatController",
"targetSetpoint",
{"value": 70.0, "scale": "FAHRENHEIT"},
)
properties.assert_equal(
"Alexa.TemperatureSensor", "temperature", {"value": 75.0, "scale": "FAHRENHEIT"}
)
thermostat_capability = get_capability(capabilities, "Alexa.ThermostatController")
assert thermostat_capability is not None
configuration = thermostat_capability["configuration"]
assert configuration["supportsScheduling"] is False
supported_modes = ["OFF", "HEAT", "COOL", "AUTO", "ECO", "CUSTOM"]
for mode in supported_modes:
assert mode in configuration["supportedModes"]
call, msg = await assert_request_calls_service(
"Alexa.ThermostatController",
"SetTargetTemperature",
"climate#test_thermostat",
"climate.set_temperature",
hass,
payload={"targetSetpoint": {"value": 69.0, "scale": "FAHRENHEIT"}},
)
assert call.data["temperature"] == 69.0
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal(
"Alexa.ThermostatController",
"targetSetpoint",
{"value": 69.0, "scale": "FAHRENHEIT"},
)
msg = await assert_request_fails(
"Alexa.ThermostatController",
"SetTargetTemperature",
"climate#test_thermostat",
"climate.set_temperature",
hass,
payload={"targetSetpoint": {"value": 0.0, "scale": "CELSIUS"}},
)
assert msg["event"]["payload"]["type"] == "TEMPERATURE_VALUE_OUT_OF_RANGE"
call, msg = await assert_request_calls_service(
"Alexa.ThermostatController",
"SetTargetTemperature",
"climate#test_thermostat",
"climate.set_temperature",
hass,
payload={
"targetSetpoint": {"value": 70.0, "scale": "FAHRENHEIT"},
"lowerSetpoint": {"value": 293.15, "scale": "KELVIN"},
"upperSetpoint": {"value": 30.0, "scale": "CELSIUS"},
},
)
assert call.data["temperature"] == 70.0
assert call.data["target_temp_low"] == 68.0
assert call.data["target_temp_high"] == 86.0
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal(
"Alexa.ThermostatController",
"targetSetpoint",
{"value": 70.0, "scale": "FAHRENHEIT"},
)
properties.assert_equal(
"Alexa.ThermostatController",
"lowerSetpoint",
{"value": 68.0, "scale": "FAHRENHEIT"},
)
properties.assert_equal(
"Alexa.ThermostatController",
"upperSetpoint",
{"value": 86.0, "scale": "FAHRENHEIT"},
)
msg = await assert_request_fails(
"Alexa.ThermostatController",
"SetTargetTemperature",
"climate#test_thermostat",
"climate.set_temperature",
hass,
payload={
"lowerSetpoint": {"value": 273.15, "scale": "KELVIN"},
"upperSetpoint": {"value": 75.0, "scale": "FAHRENHEIT"},
},
)
assert msg["event"]["payload"]["type"] == "TEMPERATURE_VALUE_OUT_OF_RANGE"
msg = await assert_request_fails(
"Alexa.ThermostatController",
"SetTargetTemperature",
"climate#test_thermostat",
"climate.set_temperature",
hass,
payload={
"lowerSetpoint": {"value": 293.15, "scale": "FAHRENHEIT"},
"upperSetpoint": {"value": 75.0, "scale": "CELSIUS"},
},
)
assert msg["event"]["payload"]["type"] == "TEMPERATURE_VALUE_OUT_OF_RANGE"
call, msg = await assert_request_calls_service(
"Alexa.ThermostatController",
"AdjustTargetTemperature",
"climate#test_thermostat",
"climate.set_temperature",
hass,
payload={"targetSetpointDelta": {"value": -10.0, "scale": "KELVIN"}},
)
assert call.data["temperature"] == 52.0
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal(
"Alexa.ThermostatController",
"targetSetpoint",
{"value": 52.0, "scale": "FAHRENHEIT"},
)
msg = await assert_request_fails(
"Alexa.ThermostatController",
"AdjustTargetTemperature",
"climate#test_thermostat",
"climate.set_temperature",
hass,
payload={"targetSetpointDelta": {"value": 20.0, "scale": "CELSIUS"}},
)
assert msg["event"]["payload"]["type"] == "TEMPERATURE_VALUE_OUT_OF_RANGE"
call, msg = await assert_request_calls_service(
"Alexa.ThermostatController",
"SetThermostatMode",
"climate#test_thermostat",
"climate.set_hvac_mode",
hass,
payload={"thermostatMode": {"value": "HEAT"}},
)
assert call.data["hvac_mode"] == "heat"
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal("Alexa.ThermostatController", "thermostatMode", "HEAT")
call, msg = await assert_request_calls_service(
"Alexa.ThermostatController",
"SetThermostatMode",
"climate#test_thermostat",
"climate.set_hvac_mode",
hass,
payload={"thermostatMode": {"value": "COOL"}},
)
assert call.data["hvac_mode"] == "cool"
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal("Alexa.ThermostatController", "thermostatMode", "COOL")
call, msg = await assert_request_calls_service(
"Alexa.ThermostatController",
"SetThermostatMode",
"climate#test_thermostat",
"climate.set_hvac_mode",
hass,
payload={"thermostatMode": "HEAT"},
)
assert call.data["hvac_mode"] == "heat"
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal("Alexa.ThermostatController", "thermostatMode", "HEAT")
call, msg = await assert_request_calls_service(
"Alexa.ThermostatController",
"SetThermostatMode",
"climate#test_thermostat",
"climate.set_hvac_mode",
hass,
payload={"thermostatMode": {"value": "CUSTOM", "customName": "DEHUMIDIFY"}},
)
assert call.data["hvac_mode"] == "dry"
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal("Alexa.ThermostatController", "thermostatMode", "CUSTOM")
msg = await assert_request_fails(
"Alexa.ThermostatController",
"SetThermostatMode",
"climate#test_thermostat",
"climate.set_hvac_mode",
hass,
payload={"thermostatMode": {"value": "CUSTOM", "customName": "INVALID"}},
)
assert msg["event"]["payload"]["type"] == "UNSUPPORTED_THERMOSTAT_MODE"
msg = await assert_request_fails(
"Alexa.ThermostatController",
"SetThermostatMode",
"climate#test_thermostat",
"climate.set_hvac_mode",
hass,
payload={"thermostatMode": {"value": "INVALID"}},
)
assert msg["event"]["payload"]["type"] == "UNSUPPORTED_THERMOSTAT_MODE"
call, _ = await assert_request_calls_service(
"Alexa.ThermostatController",
"SetThermostatMode",
"climate#test_thermostat",
"climate.set_hvac_mode",
hass,
payload={"thermostatMode": "OFF"},
)
assert call.data["hvac_mode"] == "off"
call, msg = await assert_request_calls_service(
"Alexa.ThermostatController",
"SetThermostatMode",
"climate#test_thermostat",
"climate.set_preset_mode",
hass,
payload={"thermostatMode": "ECO"},
)
assert call.data["preset_mode"] == "eco"
hass.config.units.temperature_unit = TEMP_CELSIUS
async def test_exclude_filters(hass):
request = get_new_request("Alexa.Discovery", "Discover")
hass.states.async_set("switch.test", "on", {"friendly_name": "Test switch"})
hass.states.async_set("script.deny", "off", {"friendly_name": "Blocked script"})
hass.states.async_set("cover.deny", "off", {"friendly_name": "Blocked cover"})
alexa_config = MockConfig(hass)
alexa_config.should_expose = entityfilter.generate_filter(
include_domains=[],
include_entities=[],
exclude_domains=["script"],
exclude_entities=["cover.deny"],
)
msg = await smart_home.async_handle_message(hass, alexa_config, request)
await hass.async_block_till_done()
msg = msg["event"]
assert len(msg["payload"]["endpoints"]) == 1
async def test_include_filters(hass):
request = get_new_request("Alexa.Discovery", "Discover")
hass.states.async_set("switch.deny", "on", {"friendly_name": "Blocked switch"})
hass.states.async_set("script.deny", "off", {"friendly_name": "Blocked script"})
hass.states.async_set(
"automation.allow", "off", {"friendly_name": "Allowed automation"}
)
hass.states.async_set("group.allow", "off", {"friendly_name": "Allowed group"})
alexa_config = MockConfig(hass)
alexa_config.should_expose = entityfilter.generate_filter(
include_domains=["automation", "group"],
include_entities=["script.deny"],
exclude_domains=[],
exclude_entities=[],
)
msg = await smart_home.async_handle_message(hass, alexa_config, request)
await hass.async_block_till_done()
msg = msg["event"]
assert len(msg["payload"]["endpoints"]) == 3
async def test_never_exposed_entities(hass):
request = get_new_request("Alexa.Discovery", "Discover")
hass.states.async_set("group.all_locks", "on", {"friendly_name": "Blocked locks"})
hass.states.async_set("group.allow", "off", {"friendly_name": "Allowed group"})
alexa_config = MockConfig(hass)
alexa_config.should_expose = entityfilter.generate_filter(
include_domains=["group"],
include_entities=[],
exclude_domains=[],
exclude_entities=[],
)
msg = await smart_home.async_handle_message(hass, alexa_config, request)
await hass.async_block_till_done()
msg = msg["event"]
assert len(msg["payload"]["endpoints"]) == 1
async def test_api_entity_not_exists(hass):
request = get_new_request("Alexa.PowerController", "TurnOn", "switch#test")
call_switch = async_mock_service(hass, "switch", "turn_on")
msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request)
await hass.async_block_till_done()
assert "event" in msg
msg = msg["event"]
assert not call_switch
assert msg["header"]["name"] == "ErrorResponse"
assert msg["header"]["namespace"] == "Alexa"
assert msg["payload"]["type"] == "NO_SUCH_ENDPOINT"
async def test_api_function_not_implemented(hass):
request = get_new_request("Alexa.HAHAAH", "Sweet")
msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request)
assert "event" in msg
msg = msg["event"]
assert msg["header"]["name"] == "ErrorResponse"
assert msg["header"]["namespace"] == "Alexa"
assert msg["payload"]["type"] == "INTERNAL_ERROR"
async def test_api_accept_grant(hass):
request = get_new_request("Alexa.Authorization", "AcceptGrant")
request["directive"]["payload"] = {
"grant": {
"type": "OAuth2.AuthorizationCode",
"code": "VGhpcyBpcyBhbiBhdXRob3JpemF0aW9uIGNvZGUuIDotKQ==",
},
"grantee": {"type": "BearerToken", "token": "access-token-from-skill"},
}
msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request)
await hass.async_block_till_done()
assert "event" in msg
msg = msg["event"]
assert msg["header"]["name"] == "AcceptGrant.Response"
async def test_entity_config(hass):
request = get_new_request("Alexa.Discovery", "Discover")
hass.states.async_set("light.test_1", "on", {"friendly_name": "Test light 1"})
hass.states.async_set("scene.test_1", "scening", {"friendly_name": "Test 1"})
alexa_config = MockConfig(hass)
alexa_config.entity_config = {
"light.test_1": {
"name": "Config *name*",
"display_categories": "SWITCH",
"description": "Config >!<description",
},
"scene.test_1": {"description": "Config description"},
}
msg = await smart_home.async_handle_message(hass, alexa_config, request)
assert "event" in msg
msg = msg["event"]
assert len(msg["payload"]["endpoints"]) == 2
appliance = msg["payload"]["endpoints"][0]
assert appliance["endpointId"] == "light#test_1"
assert appliance["displayCategories"][0] == "SWITCH"
assert appliance["friendlyName"] == "Config name"
assert appliance["description"] == "Config description via Home Assistant"
assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa"
)
scene = msg["payload"]["endpoints"][1]
assert scene["endpointId"] == "scene#test_1"
assert scene["displayCategories"][0] == "SCENE_TRIGGER"
assert scene["friendlyName"] == "Test 1"
assert scene["description"] == "Config description via Home Assistant (Scene)"
async def test_logging_request(hass, events):
context = Context()
request = get_new_request("Alexa.Discovery", "Discover")
await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request, context)
await hass.async_block_till_done()
assert len(events) == 1
event = events[0]
assert event.data["request"] == {"namespace": "Alexa.Discovery", "name": "Discover"}
assert event.data["response"] == {
"namespace": "Alexa.Discovery",
"name": "Discover.Response",
}
assert event.context == context
async def test_logging_request_with_entity(hass, events):
context = Context()
request = get_new_request("Alexa.PowerController", "TurnOn", "switch#xy")
await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request, context)
await hass.async_block_till_done()
assert len(events) == 1
event = events[0]
assert event.data["request"] == {
"namespace": "Alexa.PowerController",
"name": "TurnOn",
"entity_id": "switch.xy",
}
assert event.data["response"] == {"namespace": "Alexa", "name": "ErrorResponse"}
assert event.context == context
async def test_disabled(hass):
hass.states.async_set("switch.test", "on", {"friendly_name": "Test switch"})
request = get_new_request("Alexa.PowerController", "TurnOn", "switch#test")
call_switch = async_mock_service(hass, "switch", "turn_on")
msg = await smart_home.async_handle_message(
hass, DEFAULT_CONFIG, request, enabled=False
)
await hass.async_block_till_done()
assert "event" in msg
msg = msg["event"]
assert not call_switch
assert msg["header"]["name"] == "ErrorResponse"
assert msg["header"]["namespace"] == "Alexa"
assert msg["payload"]["type"] == "BRIDGE_UNREACHABLE"
async def test_endpoint_good_health(hass):
device = (
"binary_sensor.test_contact",
"on",
{"friendly_name": "Test Contact Sensor", "device_class": "door"},
)
await discovery_test(device, hass)
properties = await reported_properties(hass, "binary_sensor#test_contact")
properties.assert_equal("Alexa.EndpointHealth", "connectivity", {"value": "OK"})
async def test_endpoint_bad_health(hass):
device = (
"binary_sensor.test_contact",
"unavailable",
{"friendly_name": "Test Contact Sensor", "device_class": "door"},
)
await discovery_test(device, hass)
properties = await reported_properties(hass, "binary_sensor#test_contact")
properties.assert_equal(
"Alexa.EndpointHealth", "connectivity", {"value": "UNREACHABLE"}
)
async def test_alarm_control_panel_disarmed(hass):
device = (
"alarm_control_panel.test_1",
"disarmed",
{
"friendly_name": "Test Alarm Control Panel 1",
"code_arm_required": False,
"code_format": "number",
"code": "1234",
"supported_features": 31,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "alarm_control_panel#test_1"
assert appliance["displayCategories"][0] == "SECURITY_PANEL"
assert appliance["friendlyName"] == "Test Alarm Control Panel 1"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.SecurityPanelController", "Alexa.EndpointHealth", "Alexa"
)
security_panel_capability = get_capability(
capabilities, "Alexa.SecurityPanelController"
)
assert security_panel_capability is not None
configuration = security_panel_capability["configuration"]
assert {"type": "FOUR_DIGIT_PIN"} in configuration["supportedAuthorizationTypes"]
assert {"value": "DISARMED"} in configuration["supportedArmStates"]
assert {"value": "ARMED_STAY"} in configuration["supportedArmStates"]
assert {"value": "ARMED_AWAY"} in configuration["supportedArmStates"]
assert {"value": "ARMED_NIGHT"} in configuration["supportedArmStates"]
properties = await reported_properties(hass, "alarm_control_panel#test_1")
properties.assert_equal("Alexa.SecurityPanelController", "armState", "DISARMED")
call, msg = await assert_request_calls_service(
"Alexa.SecurityPanelController",
"Arm",
"alarm_control_panel#test_1",
"alarm_control_panel.alarm_arm_home",
hass,
response_type="Arm.Response",
payload={"armState": "ARMED_STAY"},
)
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal("Alexa.SecurityPanelController", "armState", "ARMED_STAY")
call, msg = await assert_request_calls_service(
"Alexa.SecurityPanelController",
"Arm",
"alarm_control_panel#test_1",
"alarm_control_panel.alarm_arm_away",
hass,
response_type="Arm.Response",
payload={"armState": "ARMED_AWAY"},
)
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal("Alexa.SecurityPanelController", "armState", "ARMED_AWAY")
call, msg = await assert_request_calls_service(
"Alexa.SecurityPanelController",
"Arm",
"alarm_control_panel#test_1",
"alarm_control_panel.alarm_arm_night",
hass,
response_type="Arm.Response",
payload={"armState": "ARMED_NIGHT"},
)
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal("Alexa.SecurityPanelController", "armState", "ARMED_NIGHT")
async def test_alarm_control_panel_armed(hass):
device = (
"alarm_control_panel.test_2",
"armed_away",
{
"friendly_name": "Test Alarm Control Panel 2",
"code_arm_required": False,
"code_format": "FORMAT_NUMBER",
"code": "1234",
"supported_features": 3,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "alarm_control_panel#test_2"
assert appliance["displayCategories"][0] == "SECURITY_PANEL"
assert appliance["friendlyName"] == "Test Alarm Control Panel 2"
assert_endpoint_capabilities(
appliance, "Alexa.SecurityPanelController", "Alexa.EndpointHealth", "Alexa"
)
properties = await reported_properties(hass, "alarm_control_panel#test_2")
properties.assert_equal("Alexa.SecurityPanelController", "armState", "ARMED_AWAY")
call, msg = await assert_request_calls_service(
"Alexa.SecurityPanelController",
"Disarm",
"alarm_control_panel#test_2",
"alarm_control_panel.alarm_disarm",
hass,
payload={"authorization": {"type": "FOUR_DIGIT_PIN", "value": "1234"}},
)
assert call.data["code"] == "1234"
properties = ReportedProperties(msg["context"]["properties"])
properties.assert_equal("Alexa.SecurityPanelController", "armState", "DISARMED")
msg = await assert_request_fails(
"Alexa.SecurityPanelController",
"Arm",
"alarm_control_panel#test_2",
"alarm_control_panel.alarm_arm_home",
hass,
payload={"armState": "ARMED_STAY"},
)
assert msg["event"]["payload"]["type"] == "AUTHORIZATION_REQUIRED"
async def test_alarm_control_panel_code_arm_required(hass):
device = (
"alarm_control_panel.test_3",
"disarmed",
{
"friendly_name": "Test Alarm Control Panel 3",
"code_arm_required": True,
"supported_features": 3,
},
)
await discovery_test(device, hass, expected_endpoints=0)
async def test_range_unsupported_domain(hass):
device = ("switch.test", "on", {"friendly_name": "Test switch"})
await discovery_test(device, hass)
context = Context()
request = get_new_request("Alexa.RangeController", "SetRangeValue", "switch#test")
request["directive"]["payload"] = {"rangeValue": 1}
request["directive"]["header"]["instance"] = "switch.speed"
msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request, context)
assert "event" in msg
msg = msg["event"]
assert msg["header"]["name"] == "ErrorResponse"
assert msg["header"]["namespace"] == "Alexa"
assert msg["payload"]["type"] == "INVALID_DIRECTIVE"
async def test_mode_unsupported_domain(hass):
device = ("switch.test", "on", {"friendly_name": "Test switch"})
await discovery_test(device, hass)
context = Context()
request = get_new_request("Alexa.ModeController", "SetMode", "switch#test")
request["directive"]["payload"] = {"mode": "testMode"}
request["directive"]["header"]["instance"] = "switch.direction"
msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request, context)
assert "event" in msg
msg = msg["event"]
assert msg["header"]["name"] == "ErrorResponse"
assert msg["header"]["namespace"] == "Alexa"
assert msg["payload"]["type"] == "INVALID_DIRECTIVE"
async def test_cover_garage_door(hass):
device = (
"cover.test_garage_door",
"off",
{
"friendly_name": "Test cover garage door",
"supported_features": 3,
"device_class": "garage",
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "cover#test_garage_door"
assert appliance["displayCategories"][0] == "GARAGE_DOOR"
assert appliance["friendlyName"] == "Test cover garage door"
assert_endpoint_capabilities(
appliance, "Alexa.ModeController", "Alexa.EndpointHealth", "Alexa"
)
async def test_cover_position_mode(hass):
device = (
"cover.test_mode",
"open",
{
"friendly_name": "Test cover mode",
"device_class": "blind",
"supported_features": 3,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "cover#test_mode"
assert appliance["displayCategories"][0] == "INTERIOR_BLIND"
assert appliance["friendlyName"] == "Test cover mode"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PowerController",
"Alexa.ModeController",
"Alexa.EndpointHealth",
"Alexa",
)
mode_capability = get_capability(capabilities, "Alexa.ModeController")
assert mode_capability is not None
assert mode_capability["instance"] == "cover.position"
properties = mode_capability["properties"]
assert properties["nonControllable"] is False
assert {"name": "mode"} in properties["supported"]
capability_resources = mode_capability["capabilityResources"]
assert capability_resources is not None
assert {
"@type": "text",
"value": {"text": "Position", "locale": "en-US"},
} in capability_resources["friendlyNames"]
assert {
"@type": "asset",
"value": {"assetId": "Alexa.Setting.Opening"},
} in capability_resources["friendlyNames"]
configuration = mode_capability["configuration"]
assert configuration is not None
assert configuration["ordered"] is False
supported_modes = configuration["supportedModes"]
assert supported_modes is not None
assert {
"value": "position.open",
"modeResources": {
"friendlyNames": [
{"@type": "asset", "value": {"assetId": "Alexa.Value.Open"}}
]
},
} in supported_modes
assert {
"value": "position.closed",
"modeResources": {
"friendlyNames": [
{"@type": "asset", "value": {"assetId": "Alexa.Value.Close"}}
]
},
} in supported_modes
# Assert for Position Semantics
position_semantics = mode_capability["semantics"]
assert position_semantics is not None
position_action_mappings = position_semantics["actionMappings"]
assert position_action_mappings is not None
assert {
"@type": "ActionsToDirective",
"actions": ["Alexa.Actions.Lower", "Alexa.Actions.Close"],
"directive": {"name": "SetMode", "payload": {"mode": "position.closed"}},
} in position_action_mappings
assert {
"@type": "ActionsToDirective",
"actions": ["Alexa.Actions.Raise", "Alexa.Actions.Open"],
"directive": {"name": "SetMode", "payload": {"mode": "position.open"}},
} in position_action_mappings
position_state_mappings = position_semantics["stateMappings"]
assert position_state_mappings is not None
assert {
"@type": "StatesToValue",
"states": ["Alexa.States.Closed"],
"value": "position.closed",
} in position_state_mappings
assert {
"@type": "StatesToValue",
"states": ["Alexa.States.Open"],
"value": "position.open",
} in position_state_mappings
_, msg = await assert_request_calls_service(
"Alexa.ModeController",
"SetMode",
"cover#test_mode",
"cover.close_cover",
hass,
payload={"mode": "position.closed"},
instance="cover.position",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "mode"
assert properties["namespace"] == "Alexa.ModeController"
assert properties["value"] == "position.closed"
_, msg = await assert_request_calls_service(
"Alexa.ModeController",
"SetMode",
"cover#test_mode",
"cover.open_cover",
hass,
payload={"mode": "position.open"},
instance="cover.position",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "mode"
assert properties["namespace"] == "Alexa.ModeController"
assert properties["value"] == "position.open"
_, msg = await assert_request_calls_service(
"Alexa.ModeController",
"SetMode",
"cover#test_mode",
"cover.stop_cover",
hass,
payload={"mode": "position.custom"},
instance="cover.position",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "mode"
assert properties["namespace"] == "Alexa.ModeController"
assert properties["value"] == "position.custom"
async def test_image_processing(hass):
device = (
"image_processing.test_face",
0,
{
"friendly_name": "Test face",
"device_class": "face",
"faces": [],
"total_faces": 0,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "image_processing#test_face"
assert appliance["displayCategories"][0] == "CAMERA"
assert appliance["friendlyName"] == "Test face"
assert_endpoint_capabilities(
appliance, "Alexa.EventDetectionSensor", "Alexa.EndpointHealth", "Alexa"
)
async def test_motion_sensor_event_detection(hass):
device = (
"binary_sensor.test_motion_camera_event",
"off",
{"friendly_name": "Test motion camera event", "device_class": "motion"},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "binary_sensor#test_motion_camera_event"
assert appliance["displayCategories"][0] == "CAMERA"
assert appliance["friendlyName"] == "Test motion camera event"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa",
"Alexa.MotionSensor",
"Alexa.EventDetectionSensor",
"Alexa.EndpointHealth",
)
event_detection_capability = get_capability(
capabilities, "Alexa.EventDetectionSensor"
)
assert event_detection_capability is not None
properties = event_detection_capability["properties"]
assert properties["proactivelyReported"] is True
assert not properties["retrievable"]
assert {"name": "humanPresenceDetectionState"} in properties["supported"]
async def test_presence_sensor(hass):
device = (
"binary_sensor.test_presence_sensor",
"off",
{"friendly_name": "Test presence sensor", "device_class": "presence"},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "binary_sensor#test_presence_sensor"
assert appliance["displayCategories"][0] == "CAMERA"
assert appliance["friendlyName"] == "Test presence sensor"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa", "Alexa.EventDetectionSensor", "Alexa.EndpointHealth"
)
event_detection_capability = get_capability(
capabilities, "Alexa.EventDetectionSensor"
)
assert event_detection_capability is not None
properties = event_detection_capability["properties"]
assert properties["proactivelyReported"] is True
assert not properties["retrievable"]
assert {"name": "humanPresenceDetectionState"} in properties["supported"]
async def test_cover_tilt_position_range(hass):
device = (
"cover.test_tilt_range",
"open",
{
"friendly_name": "Test cover tilt range",
"device_class": "blind",
"supported_features": 240,
"tilt_position": 30,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "cover#test_tilt_range"
assert appliance["displayCategories"][0] == "INTERIOR_BLIND"
assert appliance["friendlyName"] == "Test cover tilt range"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PowerController",
"Alexa.RangeController",
"Alexa.EndpointHealth",
"Alexa",
)
range_capability = get_capability(capabilities, "Alexa.RangeController")
assert range_capability is not None
assert range_capability["instance"] == "cover.tilt"
semantics = range_capability["semantics"]
assert semantics is not None
action_mappings = semantics["actionMappings"]
assert action_mappings is not None
state_mappings = semantics["stateMappings"]
assert state_mappings is not None
call, _ = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"cover#test_tilt_range",
"cover.set_cover_tilt_position",
hass,
payload={"rangeValue": 50},
instance="cover.tilt",
)
assert call.data["tilt_position"] == 50
call, msg = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"cover#test_tilt_range",
"cover.close_cover_tilt",
hass,
payload={"rangeValue": 0},
instance="cover.tilt",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "rangeValue"
assert properties["namespace"] == "Alexa.RangeController"
assert properties["value"] == 0
call, msg = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"cover#test_tilt_range",
"cover.open_cover_tilt",
hass,
payload={"rangeValue": 100},
instance="cover.tilt",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "rangeValue"
assert properties["namespace"] == "Alexa.RangeController"
assert properties["value"] == 100
call, msg = await assert_request_calls_service(
"Alexa.RangeController",
"AdjustRangeValue",
"cover#test_tilt_range",
"cover.open_cover_tilt",
hass,
payload={"rangeValueDelta": 99, "rangeValueDeltaDefault": False},
instance="cover.tilt",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "rangeValue"
assert properties["namespace"] == "Alexa.RangeController"
assert properties["value"] == 100
call, msg = await assert_request_calls_service(
"Alexa.RangeController",
"AdjustRangeValue",
"cover#test_tilt_range",
"cover.close_cover_tilt",
hass,
payload={"rangeValueDelta": -99, "rangeValueDeltaDefault": False},
instance="cover.tilt",
)
properties = msg["context"]["properties"][0]
assert properties["name"] == "rangeValue"
assert properties["namespace"] == "Alexa.RangeController"
assert properties["value"] == 0
await assert_range_changes(
hass,
[(25, -5, False), (35, 5, False), (50, 1, True), (10, -1, True)],
"Alexa.RangeController",
"AdjustRangeValue",
"cover#test_tilt_range",
"cover.set_cover_tilt_position",
"tilt_position",
instance="cover.tilt",
)
async def test_cover_semantics_position_and_tilt(hass):
device = (
"cover.test_semantics",
"open",
{
"friendly_name": "Test cover semantics",
"device_class": "blind",
"supported_features": 255,
"position": 30,
"tilt_position": 30,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "cover#test_semantics"
assert appliance["displayCategories"][0] == "INTERIOR_BLIND"
assert appliance["friendlyName"] == "Test cover semantics"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PowerController",
"Alexa.RangeController",
"Alexa.EndpointHealth",
"Alexa",
)
# Assert for Position Semantics
position_capability = get_capability(
capabilities, "Alexa.RangeController", "cover.position"
)
position_semantics = position_capability["semantics"]
assert position_semantics is not None
position_action_mappings = position_semantics["actionMappings"]
assert position_action_mappings is not None
assert {
"@type": "ActionsToDirective",
"actions": ["Alexa.Actions.Lower"],
"directive": {"name": "SetRangeValue", "payload": {"rangeValue": 0}},
} in position_action_mappings
assert {
"@type": "ActionsToDirective",
"actions": ["Alexa.Actions.Raise"],
"directive": {"name": "SetRangeValue", "payload": {"rangeValue": 100}},
} in position_action_mappings
# Assert for Tilt Semantics
tilt_capability = get_capability(
capabilities, "Alexa.RangeController", "cover.tilt"
)
tilt_semantics = tilt_capability["semantics"]
assert tilt_semantics is not None
tilt_action_mappings = tilt_semantics["actionMappings"]
assert tilt_action_mappings is not None
assert {
"@type": "ActionsToDirective",
"actions": ["Alexa.Actions.Close"],
"directive": {"name": "SetRangeValue", "payload": {"rangeValue": 0}},
} in tilt_action_mappings
assert {
"@type": "ActionsToDirective",
"actions": ["Alexa.Actions.Open"],
"directive": {"name": "SetRangeValue", "payload": {"rangeValue": 100}},
} in tilt_action_mappings
tilt_state_mappings = tilt_semantics["stateMappings"]
assert tilt_state_mappings is not None
assert {
"@type": "StatesToValue",
"states": ["Alexa.States.Closed"],
"value": 0,
} in tilt_state_mappings
assert {
"@type": "StatesToRange",
"states": ["Alexa.States.Open"],
"range": {"minimumValue": 1, "maximumValue": 100},
} in tilt_state_mappings
async def test_input_number(hass):
device = (
"input_number.test_slider",
30,
{
"initial": 30,
"min": -20,
"max": 35,
"step": 1,
"mode": "slider",
"friendly_name": "Test Slider",
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "input_number#test_slider"
assert appliance["displayCategories"][0] == "OTHER"
assert appliance["friendlyName"] == "Test Slider"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.RangeController", "Alexa.EndpointHealth", "Alexa"
)
range_capability = get_capability(
capabilities, "Alexa.RangeController", "input_number.value"
)
capability_resources = range_capability["capabilityResources"]
assert capability_resources is not None
assert {
"@type": "text",
"value": {"text": "Value", "locale": "en-US"},
} in capability_resources["friendlyNames"]
configuration = range_capability["configuration"]
assert configuration is not None
supported_range = configuration["supportedRange"]
assert supported_range["minimumValue"] == -20
assert supported_range["maximumValue"] == 35
assert supported_range["precision"] == 1
presets = configuration["presets"]
assert {
"rangeValue": 35,
"presetResources": {
"friendlyNames": [
{"@type": "asset", "value": {"assetId": "Alexa.Value.Maximum"}}
]
},
} in presets
assert {
"rangeValue": -20,
"presetResources": {
"friendlyNames": [
{"@type": "asset", "value": {"assetId": "Alexa.Value.Minimum"}}
]
},
} in presets
call, _ = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"input_number#test_slider",
"input_number.set_value",
hass,
payload={"rangeValue": 10},
instance="input_number.value",
)
assert call.data["value"] == 10
await assert_range_changes(
hass,
[(25, -5, False), (35, 5, False), (-20, -100, False), (35, 100, False)],
"Alexa.RangeController",
"AdjustRangeValue",
"input_number#test_slider",
"input_number.set_value",
"value",
instance="input_number.value",
)
async def test_input_number_float(hass):
device = (
"input_number.test_slider_float",
0.5,
{
"initial": 0.5,
"min": 0,
"max": 1,
"step": 0.01,
"mode": "slider",
"friendly_name": "Test Slider Float",
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "input_number#test_slider_float"
assert appliance["displayCategories"][0] == "OTHER"
assert appliance["friendlyName"] == "Test Slider Float"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa.RangeController", "Alexa.EndpointHealth", "Alexa"
)
range_capability = get_capability(
capabilities, "Alexa.RangeController", "input_number.value"
)
capability_resources = range_capability["capabilityResources"]
assert capability_resources is not None
assert {
"@type": "text",
"value": {"text": "Value", "locale": "en-US"},
} in capability_resources["friendlyNames"]
configuration = range_capability["configuration"]
assert configuration is not None
supported_range = configuration["supportedRange"]
assert supported_range["minimumValue"] == 0
assert supported_range["maximumValue"] == 1
assert supported_range["precision"] == 0.01
presets = configuration["presets"]
assert {
"rangeValue": 1,
"presetResources": {
"friendlyNames": [
{"@type": "asset", "value": {"assetId": "Alexa.Value.Maximum"}}
]
},
} in presets
assert {
"rangeValue": 0,
"presetResources": {
"friendlyNames": [
{"@type": "asset", "value": {"assetId": "Alexa.Value.Minimum"}}
]
},
} in presets
call, _ = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"input_number#test_slider_float",
"input_number.set_value",
hass,
payload={"rangeValue": 0.333},
instance="input_number.value",
)
assert call.data["value"] == 0.333
await assert_range_changes(
hass,
[
(0.4, -0.1, False),
(0.6, 0.1, False),
(0, -100, False),
(1, 100, False),
(0.51, 0.01, False),
],
"Alexa.RangeController",
"AdjustRangeValue",
"input_number#test_slider_float",
"input_number.set_value",
"value",
instance="input_number.value",
)
async def test_media_player_eq_modes(hass):
device = (
"media_player.test",
"on",
{
"friendly_name": "Test media player",
"supported_features": SUPPORT_SELECT_SOUND_MODE,
"sound_mode": "tv",
"sound_mode_list": ["movie", "music", "night", "sport", "tv", "rocknroll"],
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "media_player#test"
assert appliance["friendlyName"] == "Test media player"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa",
"Alexa.EqualizerController",
"Alexa.PowerController",
"Alexa.EndpointHealth",
)
eq_capability = get_capability(capabilities, "Alexa.EqualizerController")
assert eq_capability is not None
assert "modes" in eq_capability["configurations"]
eq_modes = eq_capability["configurations"]["modes"]
assert {"name": "rocknroll"} not in eq_modes["supported"]
assert {"name": "ROCKNROLL"} not in eq_modes["supported"]
for mode in ("MOVIE", "MUSIC", "NIGHT", "SPORT", "TV"):
assert {"name": mode} in eq_modes["supported"]
call, _ = await assert_request_calls_service(
"Alexa.EqualizerController",
"SetMode",
"media_player#test",
"media_player.select_sound_mode",
hass,
payload={"mode": mode},
)
assert call.data["sound_mode"] == mode.lower()
async def test_media_player_sound_mode_list_none(hass):
device = (
"media_player.test",
"on",
{
"friendly_name": "Test media player",
"supported_features": SUPPORT_SELECT_SOUND_MODE,
"sound_mode": "unknown",
"sound_mode_list": None,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "media_player#test"
assert appliance["friendlyName"] == "Test media player"
async def test_media_player_eq_bands_not_supported(hass):
device = (
"media_player.test_bands",
"on",
{
"friendly_name": "Test media player",
"supported_features": SUPPORT_SELECT_SOUND_MODE,
"sound_mode": "tv",
"sound_mode_list": ["movie", "music", "night", "sport", "tv", "rocknroll"],
},
)
await discovery_test(device, hass)
context = Context()
# Test for SetBands Error
request = get_new_request(
"Alexa.EqualizerController", "SetBands", "media_player#test_bands"
)
request["directive"]["payload"] = {"bands": [{"name": "BASS", "value": -2}]}
msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request, context)
assert "event" in msg
msg = msg["event"]
assert msg["header"]["name"] == "ErrorResponse"
assert msg["header"]["namespace"] == "Alexa"
assert msg["payload"]["type"] == "INVALID_DIRECTIVE"
# Test for AdjustBands Error
request = get_new_request(
"Alexa.EqualizerController", "AdjustBands", "media_player#test_bands"
)
request["directive"]["payload"] = {
"bands": [{"name": "BASS", "levelDelta": 3, "levelDirection": "UP"}]
}
msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request, context)
assert "event" in msg
msg = msg["event"]
assert msg["header"]["name"] == "ErrorResponse"
assert msg["header"]["namespace"] == "Alexa"
assert msg["payload"]["type"] == "INVALID_DIRECTIVE"
# Test for ResetBands Error
request = get_new_request(
"Alexa.EqualizerController", "ResetBands", "media_player#test_bands"
)
request["directive"]["payload"] = {
"bands": [{"name": "BASS", "levelDelta": 3, "levelDirection": "UP"}]
}
msg = await smart_home.async_handle_message(hass, DEFAULT_CONFIG, request, context)
assert "event" in msg
msg = msg["event"]
assert msg["header"]["name"] == "ErrorResponse"
assert msg["header"]["namespace"] == "Alexa"
assert msg["payload"]["type"] == "INVALID_DIRECTIVE"
async def test_timer_hold(hass):
device = (
"timer.laundry",
"active",
{"friendly_name": "Laundry", "duration": "00:01:00", "remaining": "00:50:00"},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "timer#laundry"
assert appliance["displayCategories"][0] == "OTHER"
assert appliance["friendlyName"] == "Laundry"
capabilities = assert_endpoint_capabilities(
appliance, "Alexa", "Alexa.TimeHoldController"
)
time_hold_capability = get_capability(capabilities, "Alexa.TimeHoldController")
assert time_hold_capability is not None
configuration = time_hold_capability["configuration"]
assert configuration["allowRemoteResume"] is True
await assert_request_calls_service(
"Alexa.TimeHoldController", "Hold", "timer#laundry", "timer.pause", hass
)
async def test_timer_resume(hass):
device = (
"timer.laundry",
"paused",
{"friendly_name": "Laundry", "duration": "00:01:00", "remaining": "00:50:00"},
)
await discovery_test(device, hass)
await assert_request_calls_service(
"Alexa.TimeHoldController", "Resume", "timer#laundry", "timer.start", hass
)
async def test_vacuum_discovery(hass):
device = (
"vacuum.test_1",
"docked",
{
"friendly_name": "Test vacuum 1",
"supported_features": vacuum.SUPPORT_TURN_ON
| vacuum.SUPPORT_TURN_OFF
| vacuum.SUPPORT_START
| vacuum.SUPPORT_STOP
| vacuum.SUPPORT_RETURN_HOME
| vacuum.SUPPORT_PAUSE,
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "vacuum#test_1"
assert appliance["displayCategories"][0] == "OTHER"
assert appliance["friendlyName"] == "Test vacuum 1"
assert_endpoint_capabilities(
appliance,
"Alexa.PowerController",
"Alexa.TimeHoldController",
"Alexa.EndpointHealth",
"Alexa",
)
properties = await reported_properties(hass, "vacuum#test_1")
properties.assert_equal("Alexa.PowerController", "powerState", "OFF")
await assert_request_calls_service(
"Alexa.PowerController", "TurnOn", "vacuum#test_1", "vacuum.turn_on", hass,
)
await assert_request_calls_service(
"Alexa.PowerController", "TurnOff", "vacuum#test_1", "vacuum.turn_off", hass,
)
async def test_vacuum_fan_speed(hass):
device = (
"vacuum.test_2",
"cleaning",
{
"friendly_name": "Test vacuum 2",
"supported_features": vacuum.SUPPORT_TURN_ON
| vacuum.SUPPORT_TURN_OFF
| vacuum.SUPPORT_START
| vacuum.SUPPORT_STOP
| vacuum.SUPPORT_PAUSE
| vacuum.SUPPORT_FAN_SPEED,
"fan_speed_list": ["off", "low", "medium", "high", "turbo", "super_sucker"],
"fan_speed": "medium",
},
)
appliance = await discovery_test(device, hass)
assert appliance["endpointId"] == "vacuum#test_2"
assert appliance["displayCategories"][0] == "OTHER"
assert appliance["friendlyName"] == "Test vacuum 2"
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PowerController",
"Alexa.RangeController",
"Alexa.TimeHoldController",
"Alexa.EndpointHealth",
"Alexa",
)
range_capability = get_capability(capabilities, "Alexa.RangeController")
assert range_capability is not None
assert range_capability["instance"] == "vacuum.fan_speed"
capability_resources = range_capability["capabilityResources"]
assert capability_resources is not None
assert {
"@type": "asset",
"value": {"assetId": "Alexa.Setting.FanSpeed"},
} in capability_resources["friendlyNames"]
configuration = range_capability["configuration"]
assert configuration is not None
supported_range = configuration["supportedRange"]
assert supported_range["minimumValue"] == 0
assert supported_range["maximumValue"] == 5
assert supported_range["precision"] == 1
presets = configuration["presets"]
assert {
"rangeValue": 0,
"presetResources": {
"friendlyNames": [
{"@type": "text", "value": {"text": "off", "locale": "en-US"}}
]
},
} in presets
assert {
"rangeValue": 1,
"presetResources": {
"friendlyNames": [
{"@type": "text", "value": {"text": "low", "locale": "en-US"}},
{"@type": "asset", "value": {"assetId": "Alexa.Value.Minimum"}},
]
},
} in presets
assert {
"rangeValue": 2,
"presetResources": {
"friendlyNames": [
{"@type": "text", "value": {"text": "medium", "locale": "en-US"}}
]
},
} in presets
assert {
"rangeValue": 5,
"presetResources": {
"friendlyNames": [
{"@type": "text", "value": {"text": "super sucker", "locale": "en-US"}},
{"@type": "asset", "value": {"assetId": "Alexa.Value.Maximum"}},
]
},
} in presets
call, _ = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"vacuum#test_2",
"vacuum.set_fan_speed",
hass,
payload={"rangeValue": 1},
instance="vacuum.fan_speed",
)
assert call.data["fan_speed"] == "low"
call, _ = await assert_request_calls_service(
"Alexa.RangeController",
"SetRangeValue",
"vacuum#test_2",
"vacuum.set_fan_speed",
hass,
payload={"rangeValue": 5},
instance="vacuum.fan_speed",
)
assert call.data["fan_speed"] == "super_sucker"
await assert_range_changes(
hass,
[
("low", -1, False),
("high", 1, False),
("medium", 0, False),
("super_sucker", 99, False),
],
"Alexa.RangeController",
"AdjustRangeValue",
"vacuum#test_2",
"vacuum.set_fan_speed",
"fan_speed",
instance="vacuum.fan_speed",
)
async def test_vacuum_pause(hass):
device = (
"vacuum.test_3",
"cleaning",
{
"friendly_name": "Test vacuum 3",
"supported_features": vacuum.SUPPORT_TURN_ON
| vacuum.SUPPORT_TURN_OFF
| vacuum.SUPPORT_START
| vacuum.SUPPORT_STOP
| vacuum.SUPPORT_PAUSE
| vacuum.SUPPORT_FAN_SPEED,
"fan_speed_list": ["off", "low", "medium", "high", "turbo", "super_sucker"],
"fan_speed": "medium",
},
)
appliance = await discovery_test(device, hass)
capabilities = assert_endpoint_capabilities(
appliance,
"Alexa.PowerController",
"Alexa.RangeController",
"Alexa.TimeHoldController",
"Alexa.EndpointHealth",
"Alexa",
)
time_hold_capability = get_capability(capabilities, "Alexa.TimeHoldController")
assert time_hold_capability is not None
configuration = time_hold_capability["configuration"]
assert configuration["allowRemoteResume"] is True
await assert_request_calls_service(
"Alexa.TimeHoldController", "Hold", "vacuum#test_3", "vacuum.start_pause", hass
)
async def test_vacuum_resume(hass):
device = (
"vacuum.test_4",
"docked",
{
"friendly_name": "Test vacuum 4",
"supported_features": vacuum.SUPPORT_TURN_ON
| vacuum.SUPPORT_TURN_OFF
| vacuum.SUPPORT_START
| vacuum.SUPPORT_STOP
| vacuum.SUPPORT_PAUSE
| vacuum.SUPPORT_FAN_SPEED,
"fan_speed_list": ["off", "low", "medium", "high", "turbo", "super_sucker"],
"fan_speed": "medium",
},
)
await discovery_test(device, hass)
await assert_request_calls_service(
"Alexa.TimeHoldController",
"Resume",
"vacuum#test_4",
"vacuum.start_pause",
hass,
)
async def test_vacuum_discovery_no_turn_on(hass):
device = (
"vacuum.test_5",
"cleaning",
{
"friendly_name": "Test vacuum 5",
"supported_features": vacuum.SUPPORT_TURN_OFF
| vacuum.SUPPORT_START
| vacuum.SUPPORT_RETURN_HOME,
},
)
appliance = await discovery_test(device, hass)
assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa",
)
properties = await reported_properties(hass, "vacuum#test_5")
properties.assert_equal("Alexa.PowerController", "powerState", "ON")
await assert_request_calls_service(
"Alexa.PowerController", "TurnOn", "vacuum#test_5", "vacuum.start", hass,
)
await assert_request_calls_service(
"Alexa.PowerController", "TurnOff", "vacuum#test_5", "vacuum.turn_off", hass,
)
async def test_vacuum_discovery_no_turn_off(hass):
device = (
"vacuum.test_6",
"cleaning",
{
"friendly_name": "Test vacuum 6",
"supported_features": vacuum.SUPPORT_TURN_ON
| vacuum.SUPPORT_START
| vacuum.SUPPORT_RETURN_HOME,
},
)
appliance = await discovery_test(device, hass)
assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa",
)
await assert_request_calls_service(
"Alexa.PowerController", "TurnOn", "vacuum#test_6", "vacuum.turn_on", hass,
)
await assert_request_calls_service(
"Alexa.PowerController",
"TurnOff",
"vacuum#test_6",
"vacuum.return_to_base",
hass,
)
async def test_vacuum_discovery_no_turn_on_or_off(hass):
device = (
"vacuum.test_7",
"cleaning",
{
"friendly_name": "Test vacuum 7",
"supported_features": vacuum.SUPPORT_START | vacuum.SUPPORT_RETURN_HOME,
},
)
appliance = await discovery_test(device, hass)
assert_endpoint_capabilities(
appliance, "Alexa.PowerController", "Alexa.EndpointHealth", "Alexa",
)
await assert_request_calls_service(
"Alexa.PowerController", "TurnOn", "vacuum#test_7", "vacuum.start", hass,
)
await assert_request_calls_service(
"Alexa.PowerController",
"TurnOff",
"vacuum#test_7",
"vacuum.return_to_base",
hass,
)
| true | true |
f7238338295de431651ec0169448982206e86681 | 81 | py | Python | tests/periodicities/Week/Cycle_Week_25_W_60.py | shaido987/pyaf | b9afd089557bed6b90b246d3712c481ae26a1957 | [
"BSD-3-Clause"
] | 377 | 2016-10-13T20:52:44.000Z | 2022-03-29T18:04:14.000Z | tests/periodicities/Week/Cycle_Week_25_W_60.py | ysdede/pyaf | b5541b8249d5a1cfdc01f27fdfd99b6580ed680b | [
"BSD-3-Clause"
] | 160 | 2016-10-13T16:11:53.000Z | 2022-03-28T04:21:34.000Z | tests/periodicities/Week/Cycle_Week_25_W_60.py | ysdede/pyaf | b5541b8249d5a1cfdc01f27fdfd99b6580ed680b | [
"BSD-3-Clause"
] | 63 | 2017-03-09T14:51:18.000Z | 2022-03-27T20:52:57.000Z | import tests.periodicities.period_test as per
per.buildModel((60 , 'W' , 25));
| 16.2 | 45 | 0.716049 | import tests.periodicities.period_test as per
per.buildModel((60 , 'W' , 25));
| true | true |
f72383e343f175fae08802e8401da5dec36ca055 | 8,628 | py | Python | GeneratorInterface/Core/test/Pythia8ConcurrentGeneratorFilter_WZ_TuneCP5_13TeV-pythia8_cfg.py | AndrissP/cmssw | b03578d2a2573923af5db50d0508baf3bd6a208e | [
"Apache-2.0"
] | null | null | null | GeneratorInterface/Core/test/Pythia8ConcurrentGeneratorFilter_WZ_TuneCP5_13TeV-pythia8_cfg.py | AndrissP/cmssw | b03578d2a2573923af5db50d0508baf3bd6a208e | [
"Apache-2.0"
] | null | null | null | GeneratorInterface/Core/test/Pythia8ConcurrentGeneratorFilter_WZ_TuneCP5_13TeV-pythia8_cfg.py | AndrissP/cmssw | b03578d2a2573923af5db50d0508baf3bd6a208e | [
"Apache-2.0"
] | null | null | null | # Auto generated configuration file
# using:
# Revision: 1.19
# Source: /local/reps/CMSSW/CMSSW/Configuration/Applications/python/ConfigBuilder.py,v
# with command line options: Configuration/GenProduction/python/BTV-RunIISummer20UL17GEN-00002-fragment.py --python_filename BTV-RunIISummer20UL17GEN-00002_1_cfg.py --eventcontent RAWSIM --customise Configuration/DataProcessing/Utils.addMonitoring --datatier GEN --fileout file:BTV-RunIISummer20UL17GEN-00002.root --conditions 106X_mc2017_realistic_v6 --beamspot Realistic25ns13TeVEarly2017Collision --customise_commands process.source.numberEventsInLuminosityBlock=cms.untracked.uint32(100) --step GEN --geometry DB:Extended --era Run2_2017 --no_exec --mc -n 100 --nThreads 4 --nConcurrentLumis 0
import FWCore.ParameterSet.Config as cms
from Configuration.Eras.Era_Run2_2017_cff import Run2_2017
process = cms.Process('GEN',Run2_2017)
# import of standard configurations
process.load('Configuration.StandardSequences.Services_cff')
process.load('SimGeneral.HepPDTESSource.pythiapdt_cfi')
process.load('FWCore.MessageService.MessageLogger_cfi')
process.load('Configuration.EventContent.EventContent_cff')
process.load('SimGeneral.MixingModule.mixNoPU_cfi')
process.load('Configuration.StandardSequences.GeometryRecoDB_cff')
process.load('Configuration.StandardSequences.MagneticField_cff')
process.load('Configuration.StandardSequences.Generator_cff')
process.load('IOMC.EventVertexGenerators.VtxSmearedRealistic25ns13TeVEarly2017Collision_cfi')
process.load('GeneratorInterface.Core.genFilterSummary_cff')
process.load('Configuration.StandardSequences.EndOfProcess_cff')
process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(100)
)
# Input source
process.source = cms.Source("EmptySource")
process.options = cms.untracked.PSet(
)
# Production Info
process.configurationMetadata = cms.untracked.PSet(
annotation = cms.untracked.string('WZ, 13 TeV, TuneCP5'),
name = cms.untracked.string('\\$Source$'),
version = cms.untracked.string('\\$Revision$')
)
# Output definition
process.RAWSIMoutput = cms.OutputModule("PoolOutputModule",
SelectEvents = cms.untracked.PSet(
SelectEvents = cms.vstring('generation_step')
),
compressionAlgorithm = cms.untracked.string('LZMA'),
compressionLevel = cms.untracked.int32(1),
dataset = cms.untracked.PSet(
dataTier = cms.untracked.string('GEN'),
filterName = cms.untracked.string('')
),
eventAutoFlushCompressedSize = cms.untracked.int32(20971520),
fileName = cms.untracked.string('file:BTV-RunIISummer20UL17GEN-00002.root'),
outputCommands = process.RAWSIMEventContent.outputCommands,
splitLevel = cms.untracked.int32(0)
)
# Additional output definition
# Other statements
process.genstepfilter.triggerConditions=cms.vstring("generation_step")
from Configuration.AlCa.GlobalTag import GlobalTag
process.GlobalTag = GlobalTag(process.GlobalTag, '106X_mc2017_realistic_v6', '')
process.generator = cms.EDFilter("Pythia8ConcurrentGeneratorFilter",
PythiaParameters = cms.PSet(
parameterSets = cms.vstring(
'pythia8CommonSettings',
'pythia8CP5Settings',
'pythia8PSweightsSettings',
'processParameters'
),
processParameters = cms.vstring('WeakDoubleBoson:ffbar2ZW = on'),
pythia8CP5Settings = cms.vstring(
'Tune:pp 14',
'Tune:ee 7',
'MultipartonInteractions:ecmPow=0.03344',
'MultipartonInteractions:bProfile=2',
'MultipartonInteractions:pT0Ref=1.41',
'MultipartonInteractions:coreRadius=0.7634',
'MultipartonInteractions:coreFraction=0.63',
'ColourReconnection:range=5.176',
'SigmaTotal:zeroAXB=off',
'SpaceShower:alphaSorder=2',
'SpaceShower:alphaSvalue=0.118',
'SigmaProcess:alphaSvalue=0.118',
'SigmaProcess:alphaSorder=2',
'MultipartonInteractions:alphaSvalue=0.118',
'MultipartonInteractions:alphaSorder=2',
'TimeShower:alphaSorder=2',
'TimeShower:alphaSvalue=0.118',
'SigmaTotal:mode = 0',
'SigmaTotal:sigmaEl = 21.89',
'SigmaTotal:sigmaTot = 100.309',
'PDF:pSet=LHAPDF6:NNPDF31_nnlo_as_0118'
),
pythia8CommonSettings = cms.vstring(
'Tune:preferLHAPDF = 2',
'Main:timesAllowErrors = 10000',
'Check:epTolErr = 0.01',
'Beams:setProductionScalesFromLHEF = off',
'SLHA:keepSM = on',
'SLHA:minMassSM = 1000.',
'ParticleDecays:limitTau0 = on',
'ParticleDecays:tau0Max = 10',
'ParticleDecays:allowPhotonRadiation = on'
),
pythia8PSweightsSettings = cms.vstring(
'UncertaintyBands:doVariations = on',
'UncertaintyBands:List = {isrRedHi isr:muRfac=0.707,fsrRedHi fsr:muRfac=0.707,isrRedLo isr:muRfac=1.414,fsrRedLo fsr:muRfac=1.414,isrDefHi isr:muRfac=0.5,fsrDefHi fsr:muRfac=0.5,isrDefLo isr:muRfac=2.0,fsrDefLo fsr:muRfac=2.0,isrConHi isr:muRfac=0.25,fsrConHi fsr:muRfac=0.25,isrConLo isr:muRfac=4.0,fsrConLo fsr:muRfac=4.0,fsr_G2GG_muR_dn fsr:G2GG:muRfac=0.5,fsr_G2GG_muR_up fsr:G2GG:muRfac=2.0,fsr_G2QQ_muR_dn fsr:G2QQ:muRfac=0.5,fsr_G2QQ_muR_up fsr:G2QQ:muRfac=2.0,fsr_Q2QG_muR_dn fsr:Q2QG:muRfac=0.5,fsr_Q2QG_muR_up fsr:Q2QG:muRfac=2.0,fsr_X2XG_muR_dn fsr:X2XG:muRfac=0.5,fsr_X2XG_muR_up fsr:X2XG:muRfac=2.0,fsr_G2GG_cNS_dn fsr:G2GG:cNS=-2.0,fsr_G2GG_cNS_up fsr:G2GG:cNS=2.0,fsr_G2QQ_cNS_dn fsr:G2QQ:cNS=-2.0,fsr_G2QQ_cNS_up fsr:G2QQ:cNS=2.0,fsr_Q2QG_cNS_dn fsr:Q2QG:cNS=-2.0,fsr_Q2QG_cNS_up fsr:Q2QG:cNS=2.0,fsr_X2XG_cNS_dn fsr:X2XG:cNS=-2.0,fsr_X2XG_cNS_up fsr:X2XG:cNS=2.0,isr_G2GG_muR_dn isr:G2GG:muRfac=0.5,isr_G2GG_muR_up isr:G2GG:muRfac=2.0,isr_G2QQ_muR_dn isr:G2QQ:muRfac=0.5,isr_G2QQ_muR_up isr:G2QQ:muRfac=2.0,isr_Q2QG_muR_dn isr:Q2QG:muRfac=0.5,isr_Q2QG_muR_up isr:Q2QG:muRfac=2.0,isr_X2XG_muR_dn isr:X2XG:muRfac=0.5,isr_X2XG_muR_up isr:X2XG:muRfac=2.0,isr_G2GG_cNS_dn isr:G2GG:cNS=-2.0,isr_G2GG_cNS_up isr:G2GG:cNS=2.0,isr_G2QQ_cNS_dn isr:G2QQ:cNS=-2.0,isr_G2QQ_cNS_up isr:G2QQ:cNS=2.0,isr_Q2QG_cNS_dn isr:Q2QG:cNS=-2.0,isr_Q2QG_cNS_up isr:Q2QG:cNS=2.0,isr_X2XG_cNS_dn isr:X2XG:cNS=-2.0,isr_X2XG_cNS_up isr:X2XG:cNS=2.0}',
'UncertaintyBands:nFlavQ = 4',
'UncertaintyBands:MPIshowers = on',
'UncertaintyBands:overSampleFSR = 10.0',
'UncertaintyBands:overSampleISR = 10.0',
'UncertaintyBands:FSRpTmin2Fac = 20',
'UncertaintyBands:ISRpTmin2Fac = 1'
)
),
comEnergy = cms.double(13000.0),
crossSection = cms.untracked.double(27.6),
filterEfficiency = cms.untracked.double(1.0),
maxEventsToPrint = cms.untracked.int32(1),
pythiaHepMCVerbosity = cms.untracked.bool(False),
pythiaPylistVerbosity = cms.untracked.int32(1)
)
# Path and EndPath definitions
process.generation_step = cms.Path(process.pgen)
process.genfiltersummary_step = cms.EndPath(process.genFilterSummary)
process.endjob_step = cms.EndPath(process.endOfProcess)
process.RAWSIMoutput_step = cms.EndPath(process.RAWSIMoutput)
# Schedule definition
process.schedule = cms.Schedule(process.generation_step,process.genfiltersummary_step,process.endjob_step,process.RAWSIMoutput_step)
from PhysicsTools.PatAlgos.tools.helpers import associatePatAlgosToolsTask
associatePatAlgosToolsTask(process)
#Setup FWK for multithreaded
process.options.numberOfThreads=cms.untracked.uint32(4)
process.options.numberOfStreams=cms.untracked.uint32(0)
process.options.numberOfConcurrentLuminosityBlocks=cms.untracked.uint32(0)
# filter all path with the production filter sequence
for path in process.paths:
getattr(process,path).insert(0, process.generator)
# customisation of the process.
# Automatic addition of the customisation function from Configuration.DataProcessing.Utils
from Configuration.DataProcessing.Utils import addMonitoring
#call to customisation function addMonitoring imported from Configuration.DataProcessing.Utils
process = addMonitoring(process)
# End of customisation functions
# Customisation from command line
process.source.numberEventsInLuminosityBlock=cms.untracked.uint32(100)
# Add early deletion of temporary data products to reduce peak memory need
from Configuration.StandardSequences.earlyDeleteSettings_cff import customiseEarlyDelete
process = customiseEarlyDelete(process)
# End adding early deletion
| 51.357143 | 1,451 | 0.74803 |
import FWCore.ParameterSet.Config as cms
from Configuration.Eras.Era_Run2_2017_cff import Run2_2017
process = cms.Process('GEN',Run2_2017)
process.load('Configuration.StandardSequences.Services_cff')
process.load('SimGeneral.HepPDTESSource.pythiapdt_cfi')
process.load('FWCore.MessageService.MessageLogger_cfi')
process.load('Configuration.EventContent.EventContent_cff')
process.load('SimGeneral.MixingModule.mixNoPU_cfi')
process.load('Configuration.StandardSequences.GeometryRecoDB_cff')
process.load('Configuration.StandardSequences.MagneticField_cff')
process.load('Configuration.StandardSequences.Generator_cff')
process.load('IOMC.EventVertexGenerators.VtxSmearedRealistic25ns13TeVEarly2017Collision_cfi')
process.load('GeneratorInterface.Core.genFilterSummary_cff')
process.load('Configuration.StandardSequences.EndOfProcess_cff')
process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(100)
)
process.source = cms.Source("EmptySource")
process.options = cms.untracked.PSet(
)
process.configurationMetadata = cms.untracked.PSet(
annotation = cms.untracked.string('WZ, 13 TeV, TuneCP5'),
name = cms.untracked.string('\\$Source$'),
version = cms.untracked.string('\\$Revision$')
)
process.RAWSIMoutput = cms.OutputModule("PoolOutputModule",
SelectEvents = cms.untracked.PSet(
SelectEvents = cms.vstring('generation_step')
),
compressionAlgorithm = cms.untracked.string('LZMA'),
compressionLevel = cms.untracked.int32(1),
dataset = cms.untracked.PSet(
dataTier = cms.untracked.string('GEN'),
filterName = cms.untracked.string('')
),
eventAutoFlushCompressedSize = cms.untracked.int32(20971520),
fileName = cms.untracked.string('file:BTV-RunIISummer20UL17GEN-00002.root'),
outputCommands = process.RAWSIMEventContent.outputCommands,
splitLevel = cms.untracked.int32(0)
)
process.genstepfilter.triggerConditions=cms.vstring("generation_step")
from Configuration.AlCa.GlobalTag import GlobalTag
process.GlobalTag = GlobalTag(process.GlobalTag, '106X_mc2017_realistic_v6', '')
process.generator = cms.EDFilter("Pythia8ConcurrentGeneratorFilter",
PythiaParameters = cms.PSet(
parameterSets = cms.vstring(
'pythia8CommonSettings',
'pythia8CP5Settings',
'pythia8PSweightsSettings',
'processParameters'
),
processParameters = cms.vstring('WeakDoubleBoson:ffbar2ZW = on'),
pythia8CP5Settings = cms.vstring(
'Tune:pp 14',
'Tune:ee 7',
'MultipartonInteractions:ecmPow=0.03344',
'MultipartonInteractions:bProfile=2',
'MultipartonInteractions:pT0Ref=1.41',
'MultipartonInteractions:coreRadius=0.7634',
'MultipartonInteractions:coreFraction=0.63',
'ColourReconnection:range=5.176',
'SigmaTotal:zeroAXB=off',
'SpaceShower:alphaSorder=2',
'SpaceShower:alphaSvalue=0.118',
'SigmaProcess:alphaSvalue=0.118',
'SigmaProcess:alphaSorder=2',
'MultipartonInteractions:alphaSvalue=0.118',
'MultipartonInteractions:alphaSorder=2',
'TimeShower:alphaSorder=2',
'TimeShower:alphaSvalue=0.118',
'SigmaTotal:mode = 0',
'SigmaTotal:sigmaEl = 21.89',
'SigmaTotal:sigmaTot = 100.309',
'PDF:pSet=LHAPDF6:NNPDF31_nnlo_as_0118'
),
pythia8CommonSettings = cms.vstring(
'Tune:preferLHAPDF = 2',
'Main:timesAllowErrors = 10000',
'Check:epTolErr = 0.01',
'Beams:setProductionScalesFromLHEF = off',
'SLHA:keepSM = on',
'SLHA:minMassSM = 1000.',
'ParticleDecays:limitTau0 = on',
'ParticleDecays:tau0Max = 10',
'ParticleDecays:allowPhotonRadiation = on'
),
pythia8PSweightsSettings = cms.vstring(
'UncertaintyBands:doVariations = on',
'UncertaintyBands:List = {isrRedHi isr:muRfac=0.707,fsrRedHi fsr:muRfac=0.707,isrRedLo isr:muRfac=1.414,fsrRedLo fsr:muRfac=1.414,isrDefHi isr:muRfac=0.5,fsrDefHi fsr:muRfac=0.5,isrDefLo isr:muRfac=2.0,fsrDefLo fsr:muRfac=2.0,isrConHi isr:muRfac=0.25,fsrConHi fsr:muRfac=0.25,isrConLo isr:muRfac=4.0,fsrConLo fsr:muRfac=4.0,fsr_G2GG_muR_dn fsr:G2GG:muRfac=0.5,fsr_G2GG_muR_up fsr:G2GG:muRfac=2.0,fsr_G2QQ_muR_dn fsr:G2QQ:muRfac=0.5,fsr_G2QQ_muR_up fsr:G2QQ:muRfac=2.0,fsr_Q2QG_muR_dn fsr:Q2QG:muRfac=0.5,fsr_Q2QG_muR_up fsr:Q2QG:muRfac=2.0,fsr_X2XG_muR_dn fsr:X2XG:muRfac=0.5,fsr_X2XG_muR_up fsr:X2XG:muRfac=2.0,fsr_G2GG_cNS_dn fsr:G2GG:cNS=-2.0,fsr_G2GG_cNS_up fsr:G2GG:cNS=2.0,fsr_G2QQ_cNS_dn fsr:G2QQ:cNS=-2.0,fsr_G2QQ_cNS_up fsr:G2QQ:cNS=2.0,fsr_Q2QG_cNS_dn fsr:Q2QG:cNS=-2.0,fsr_Q2QG_cNS_up fsr:Q2QG:cNS=2.0,fsr_X2XG_cNS_dn fsr:X2XG:cNS=-2.0,fsr_X2XG_cNS_up fsr:X2XG:cNS=2.0,isr_G2GG_muR_dn isr:G2GG:muRfac=0.5,isr_G2GG_muR_up isr:G2GG:muRfac=2.0,isr_G2QQ_muR_dn isr:G2QQ:muRfac=0.5,isr_G2QQ_muR_up isr:G2QQ:muRfac=2.0,isr_Q2QG_muR_dn isr:Q2QG:muRfac=0.5,isr_Q2QG_muR_up isr:Q2QG:muRfac=2.0,isr_X2XG_muR_dn isr:X2XG:muRfac=0.5,isr_X2XG_muR_up isr:X2XG:muRfac=2.0,isr_G2GG_cNS_dn isr:G2GG:cNS=-2.0,isr_G2GG_cNS_up isr:G2GG:cNS=2.0,isr_G2QQ_cNS_dn isr:G2QQ:cNS=-2.0,isr_G2QQ_cNS_up isr:G2QQ:cNS=2.0,isr_Q2QG_cNS_dn isr:Q2QG:cNS=-2.0,isr_Q2QG_cNS_up isr:Q2QG:cNS=2.0,isr_X2XG_cNS_dn isr:X2XG:cNS=-2.0,isr_X2XG_cNS_up isr:X2XG:cNS=2.0}',
'UncertaintyBands:nFlavQ = 4',
'UncertaintyBands:MPIshowers = on',
'UncertaintyBands:overSampleFSR = 10.0',
'UncertaintyBands:overSampleISR = 10.0',
'UncertaintyBands:FSRpTmin2Fac = 20',
'UncertaintyBands:ISRpTmin2Fac = 1'
)
),
comEnergy = cms.double(13000.0),
crossSection = cms.untracked.double(27.6),
filterEfficiency = cms.untracked.double(1.0),
maxEventsToPrint = cms.untracked.int32(1),
pythiaHepMCVerbosity = cms.untracked.bool(False),
pythiaPylistVerbosity = cms.untracked.int32(1)
)
process.generation_step = cms.Path(process.pgen)
process.genfiltersummary_step = cms.EndPath(process.genFilterSummary)
process.endjob_step = cms.EndPath(process.endOfProcess)
process.RAWSIMoutput_step = cms.EndPath(process.RAWSIMoutput)
process.schedule = cms.Schedule(process.generation_step,process.genfiltersummary_step,process.endjob_step,process.RAWSIMoutput_step)
from PhysicsTools.PatAlgos.tools.helpers import associatePatAlgosToolsTask
associatePatAlgosToolsTask(process)
process.options.numberOfThreads=cms.untracked.uint32(4)
process.options.numberOfStreams=cms.untracked.uint32(0)
process.options.numberOfConcurrentLuminosityBlocks=cms.untracked.uint32(0)
for path in process.paths:
getattr(process,path).insert(0, process.generator)
from Configuration.DataProcessing.Utils import addMonitoring
process = addMonitoring(process)
process.source.numberEventsInLuminosityBlock=cms.untracked.uint32(100)
from Configuration.StandardSequences.earlyDeleteSettings_cff import customiseEarlyDelete
process = customiseEarlyDelete(process)
| true | true |
f723840200cf6e8ca14e042f3945330caf70bbb8 | 265 | py | Python | test/test_lcs.py | currentsapi/dragnet | 7ad5ff25b1e5596c5ed1c5090f1aad7205804ea1 | [
"MIT"
] | 40 | 2021-01-05T09:40:35.000Z | 2022-03-22T12:18:12.000Z | test/test_lcs.py | currentsapi/dragnet | 7ad5ff25b1e5596c5ed1c5090f1aad7205804ea1 | [
"MIT"
] | 3 | 2022-01-18T22:53:45.000Z | 2022-03-13T16:17:00.000Z | test/test_lcs.py | currentsapi/dragnet | 7ad5ff25b1e5596c5ed1c5090f1aad7205804ea1 | [
"MIT"
] | 10 | 2021-03-08T16:10:43.000Z | 2022-03-22T12:17:54.000Z | from extractnet.lcs import check_inclusion
def test_check_inclusion():
inc = check_inclusion(
["some", "words", "here", "the", "football"],
["he", "said", "words", "kick", "the", "football"])
assert inc == [False, True, False, True, True]
| 29.444444 | 59 | 0.603774 | from extractnet.lcs import check_inclusion
def test_check_inclusion():
inc = check_inclusion(
["some", "words", "here", "the", "football"],
["he", "said", "words", "kick", "the", "football"])
assert inc == [False, True, False, True, True]
| true | true |
f723849aef25a63a26e2db80a574c1ce7e44a552 | 18,576 | py | Python | neo/Network/syncmanager.py | volekerb/neo-python | 5bdded2c339219355cf1d31ae58653b0f94c6e51 | [
"MIT"
] | 387 | 2017-07-17T18:25:54.000Z | 2021-11-18T06:19:47.000Z | neo/Network/syncmanager.py | volekerb/neo-python | 5bdded2c339219355cf1d31ae58653b0f94c6e51 | [
"MIT"
] | 967 | 2017-08-19T15:48:03.000Z | 2021-06-01T21:42:39.000Z | neo/Network/syncmanager.py | volekerb/neo-python | 5bdded2c339219355cf1d31ae58653b0f94c6e51 | [
"MIT"
] | 286 | 2017-07-17T03:44:36.000Z | 2021-11-18T06:19:32.000Z | import asyncio
import traceback
from datetime import datetime
from neo.Network.core.header import Header
from typing import TYPE_CHECKING, List
from neo.Network.flightinfo import FlightInfo
from neo.Network.requestinfo import RequestInfo
from neo.Network.payloads.inventory import InventoryType
from neo.Network.common import msgrouter
from neo.Network.common.singleton import Singleton
from contextlib import suppress
from neo.Network.core.uint256 import UInt256
from neo.logging import log_manager
logger = log_manager.getLogger('syncmanager')
# log_manager.config_stdio([('syncmanager', 10)])
if TYPE_CHECKING:
from neo.Network.nodemanager import NodeManager
from neo.Network.payloads import Block
class SyncManager(Singleton):
HEADER_MAX_LOOK_AHEAD = 6000
HEADER_REQUEST_TIMEOUT = 5
BLOCK_MAX_CACHE_SIZE = 500
BLOCK_NETWORK_REQ_LIMIT = 500
BLOCK_REQUEST_TIMEOUT = 5
def init(self, nodemgr: 'NodeManager'):
self.nodemgr = nodemgr
self.controller = None
self.block_requests = dict() # header_hash:RequestInfo
self.header_request = None # type: RequestInfo
self.ledger = None
self.block_cache = []
self.header_cache = []
self.raw_block_cache = []
self.is_persisting_blocks = False
self.is_persisting_headers = False
self.keep_running = True
self.service_task = None
self.persist_task = None
self.health_task = None
msgrouter.on_headers += self.on_headers_received
msgrouter.on_block += self.on_block_received
async def start(self) -> None:
while not self.nodemgr.running:
await asyncio.sleep(0.1)
self.service_task = asyncio.create_task(self.run_service())
self.health_task = asyncio.create_task(self.block_health())
async def shutdown(self):
print("Shutting down sync manager...", end='')
self.keep_running = False
self.block_cache = []
shutdown_tasks = []
# start up errors can cause the tasks to not have been assigned,
# so we must validate their presence before feeding them to `gather`
if self.service_task:
shutdown_tasks.append(self.service_task)
if self.health_task:
shutdown_tasks.append(self.health_task)
if self.persist_task:
shutdown_tasks.append(self.persist_task)
await asyncio.gather(*shutdown_tasks, return_exceptions=True)
print("DONE")
async def block_health(self):
# TODO: move this to nodemanager, once the network in general supports ping/pong
# we can then make smarter choices by looking at individual nodes advancing or not and dropping just those
error_counter = 0
last_height = await self.ledger.cur_block_height()
while self.keep_running:
await asyncio.sleep(15)
cur_height = await self.ledger.cur_block_height()
if cur_height == last_height:
error_counter += 1
if error_counter == 3:
to_disconnect = list(map(lambda n: n, self.nodemgr.nodes))
logger.debug(f"Block height not advancing. Replacing nodes: {to_disconnect}")
for n in to_disconnect:
await self.nodemgr.replace_node(n)
else:
error_counter = 0
last_height = cur_height
async def run_service(self):
while self.keep_running:
await self.check_timeout()
await self.sync()
await asyncio.sleep(1)
async def sync(self) -> None:
await self.sync_header()
await self.sync_block()
await self.persist_headers()
if not self.is_persisting_blocks:
self.persist_task = asyncio.create_task(self.persist_blocks())
async def sync_header(self) -> None:
if self.header_request:
return
cur_header_height = await self.ledger.cur_header_height()
cur_block_height = await self.ledger.cur_block_height()
if cur_header_height - cur_block_height >= self.HEADER_MAX_LOOK_AHEAD:
return
node = self.nodemgr.get_next_node(cur_header_height + 1)
if not node:
# No connected nodes or no nodes with our height. We'll wait for node manager to resolve this
# or for the nodes to increase their height on the next produced block
return
self.header_request = RequestInfo(cur_header_height + 1)
self.header_request.add_new_flight(FlightInfo(node.nodeid, cur_header_height + 1))
cur_header_hash = await self.ledger.header_hash_by_height(cur_header_height)
await node.get_headers(hash_start=cur_header_hash)
logger.debug(f"Requested headers starting at {cur_header_height + 1} from node {node.nodeid_human}")
node.nodeweight.append_new_request_time()
async def persist_headers(self):
self.is_persisting_headers = True
if len(self.header_cache) > 0:
while self.keep_running:
try:
headers = self.header_cache.pop(0)
try:
await self.ledger.add_headers(headers)
except Exception as e:
print(traceback.format_exc())
await asyncio.sleep(0)
except IndexError:
# cache empty
break
# reset header_request such that the a new header sync task can be added
self.header_request = None
logger.debug("Finished processing headers")
self.is_persisting_headers = False
async def sync_block(self) -> None:
# to simplify syncing, don't ask for more data if we still have requests in flight
if len(self.block_requests) > 0:
return
# the block cache might not have been fully processed, so we want to avoid asking for data we actually already have
best_block_height = await self.get_best_stored_block_height()
cur_header_height = await self.ledger.cur_header_height()
blocks_to_fetch = cur_header_height - best_block_height
if blocks_to_fetch <= 0:
return
block_cache_space = self.BLOCK_MAX_CACHE_SIZE - len(self.block_cache)
if block_cache_space <= 0:
return
if blocks_to_fetch > block_cache_space or blocks_to_fetch > self.BLOCK_NETWORK_REQ_LIMIT:
blocks_to_fetch = min(block_cache_space, self.BLOCK_NETWORK_REQ_LIMIT)
try:
best_node_height = max(map(lambda node: node.best_height, self.nodemgr.nodes))
except ValueError:
# if the node list is empty max() fails on an empty list
return
node = self.nodemgr.get_next_node(best_node_height)
if not node:
# no nodes with our desired height. We'll wait for node manager to resolve this
# or for the nodes to increase their height on the next produced block
return
hashes = []
endheight = None
for i in range(1, blocks_to_fetch + 1):
next_block_height = best_block_height + i
if self.is_in_blockcache(next_block_height):
continue
if next_block_height > best_node_height:
break
next_header_hash = await self.ledger.header_hash_by_height(next_block_height)
if next_header_hash == UInt256.zero():
# we do not have enough headers to fill the block cache. That's fine, just return
break
endheight = next_block_height
hashes.append(next_header_hash)
self.add_block_flight_info(node.nodeid, next_block_height, next_header_hash)
if len(hashes) > 0:
logger.debug(f"Asking for blocks {best_block_height + 1} - {endheight} from {node.nodeid_human}")
await node.get_data(InventoryType.block, hashes)
node.nodeweight.append_new_request_time()
async def persist_blocks(self) -> None:
self.is_persisting_blocks = True
while self.keep_running:
try:
b = self.block_cache.pop(0)
raw_b = self.raw_block_cache.pop(0)
await self.ledger.add_block(raw_b)
await asyncio.sleep(0.001)
except IndexError:
# cache empty
break
self.is_persisting_blocks = False
async def check_timeout(self) -> None:
task1 = asyncio.create_task(self.check_header_timeout())
task2 = asyncio.create_task(self.check_block_timeout())
try:
await asyncio.gather(task1, task2)
except Exception:
logger.debug(traceback.format_exc())
async def check_header_timeout(self) -> None:
if not self.header_request:
# no data requests outstanding
return
last_flight_info = self.header_request.most_recent_flight()
now = datetime.utcnow().timestamp()
delta = now - last_flight_info.start_time
if delta < self.HEADER_REQUEST_TIMEOUT:
# we're still good on time
return
node = self.nodemgr.get_node_by_nodeid(last_flight_info.node_id)
if node:
logger.debug(f"Header timeout limit exceeded by {delta - self.HEADER_REQUEST_TIMEOUT:.2f}s for node {node.nodeid_human}")
cur_header_height = await self.ledger.cur_header_height()
if last_flight_info.height <= cur_header_height:
# it has already come in in the mean time
# reset so sync_header will request new headers
self.header_request = None
return
# punish node that is causing header_timeout and retry using another node
self.header_request.mark_failed_node(last_flight_info.node_id)
await self.nodemgr.add_node_timeout_count(last_flight_info.node_id)
# retry with a new node
node = self.nodemgr.get_node_with_min_failed_time(self.header_request)
if node is None:
# only happens if there are no nodes that have data matching our needed height
self.header_request = None
return
hash = await self.ledger.header_hash_by_height(last_flight_info.height - 1)
logger.debug(f"Retry requesting headers starting at {last_flight_info.height} from new node {node.nodeid_human}")
await node.get_headers(hash_start=hash)
# restart start_time of flight info or else we'll timeout too fast for the next node
self.header_request.add_new_flight(FlightInfo(node.nodeid, last_flight_info.height))
node.nodeweight.append_new_request_time()
async def check_block_timeout(self) -> None:
if len(self.block_requests) == 0:
# no data requests outstanding
return
now = datetime.utcnow().timestamp()
block_timeout_flights = dict()
# test for timeout
for block_hash, request_info in self.block_requests.items(): # type: _, RequestInfo
flight_info = request_info.most_recent_flight()
if now - flight_info.start_time > self.BLOCK_REQUEST_TIMEOUT:
block_timeout_flights[block_hash] = flight_info
if len(block_timeout_flights) == 0:
# no timeouts
return
# 1) we first filter out invalid requests as some might have come in by now
# 2) for each block_sync cycle we requested blocks in batches of max 500 per node, now when resending we try to
# create another batch
# 3) Blocks arrive one by one in 'inv' messages. In the block_sync cycle we created a FlightInfo object per
# requested block such that we can determine speed among others. If one block in a request times out all
# others for the same request will of course do as well (as they arrive in a linear fashion from the same node).
# As such we only want to tag the individual node once (per request) for being slower than our timeout threshold not 500 times.
remaining_requests = []
nodes_to_tag_for_timeout = set()
nodes_to_mark_failed = dict()
best_stored_block_height = await self.get_best_stored_block_height()
for block_hash, fi in block_timeout_flights.items(): # type: _, FlightInfo
nodes_to_tag_for_timeout.add(fi.node_id)
try:
request_info = self.block_requests[block_hash]
except KeyError:
# means on_block_received popped it of the list
# we don't have to retry for data anymore
continue
if fi.height <= best_stored_block_height:
with suppress(KeyError):
self.block_requests.pop(block_hash)
continue
nodes_to_mark_failed[request_info] = fi.node_id
remaining_requests.append((block_hash, fi.height, request_info))
for nodeid in nodes_to_tag_for_timeout:
await self.nodemgr.add_node_timeout_count(nodeid)
for request_info, node_id in nodes_to_mark_failed.items():
request_info.mark_failed_node(node_id)
# for the remaining requests that need to be queued again, we create new FlightInfo objects that use a new node
# and ask them in a single batch from that new node.
hashes = []
if len(remaining_requests) > 0:
# retry the batch with a new node
ri_first = remaining_requests[0][2]
ri_last = remaining_requests[-1][2]
# using `ri_last` because this has the highest block height and we want a node that supports that
node = self.nodemgr.get_node_with_min_failed_time(ri_last)
if not node:
return
for block_hash, height, ri in remaining_requests: # type: _, int, RequestInfo
ri.add_new_flight(FlightInfo(node.nodeid, height))
hashes.append(block_hash)
if len(hashes) > 0:
logger.debug(f"Block time out for blocks {ri_first.height} - {ri_last.height}. Trying again using new node {node.nodeid_human} {hashes[0]}")
await node.get_data(InventoryType.block, hashes)
node.nodeweight.append_new_request_time()
async def on_headers_received(self, from_nodeid, headers: List[Header]) -> int:
if len(headers) == 0:
return -1
if self.header_request is None:
return -2
height = headers[0].index
if height != self.header_request.height:
# received headers we did not ask for
return -3
logger.debug(f"Headers received {headers[0].index} - {headers[-1].index}")
if headers in self.header_cache:
return -4
cur_header_height = await self.ledger.cur_header_height()
if height <= cur_header_height:
return -5
self.header_cache.append(headers)
return 1
async def on_block_received(self, from_nodeid, block: 'Block', raw_block) -> None:
# TODO: take out raw_block and raw_block_cache once we can serialize a full block
# print(f"{block.index} {block.hash} received")
next_header_height = await self.ledger.cur_header_height() + 1
if block.index > next_header_height:
return
cur_block_height = await self.ledger.cur_block_height()
if block.index <= cur_block_height:
return
try:
ri = self.block_requests.pop(block.hash) # type: RequestInfo
fi = ri.flights.pop(from_nodeid) # type: FlightInfo
now = datetime.utcnow().timestamp()
delta_time = now - fi.start_time
speed = (block._size / 1024) / delta_time # KB/s
node = self.nodemgr.get_node_by_nodeid(fi.node_id)
if node:
node.nodeweight.append_new_speed(speed)
except KeyError:
# it's a block we did not ask for
# this can either be caused by rogue actors sending bad blocks
# or as a reply to our `get_data` on a broadcasted `inv` message by the node.
# (neo-cli nodes broadcast `inv` messages with their latest hash, we currently need to do a `get_data`
# and receive the full block to know what their best height is as we have no other mechanism (yet))
# TODO: remove once the network all start using neo-cli 2.10.1 or above which support ping/pong for height
sync_distance = block.index - cur_block_height
if sync_distance != 1:
return
# but if the distance is 1 we're in sync so we add the block anyway
# to avoid having the `sync_block` task request the same data again
# this is also necessary for neo-cli nodes because they maintain a TaskSession and refuse to send recently requested data
if not self.is_in_blockcache(block.index) and self.keep_running:
self.block_cache.append(block)
self.raw_block_cache.append(raw_block)
async def get_best_stored_block_height(self) -> int:
"""
Helper to return the highest block in our possession (either in ledger or in block_cache)
"""
best_block_cache_height = 0
if len(self.block_cache) > 0:
best_block_cache_height = self.block_cache[-1].index
ledger_height = await self.ledger.cur_block_height()
return max(ledger_height, best_block_cache_height)
def is_in_blockcache(self, block_height: int) -> bool:
for b in self.block_cache:
if b.index == block_height:
return True
else:
return False
def add_block_flight_info(self, nodeid, height, header_hash) -> None:
request_info = self.block_requests.get(header_hash, None) # type: RequestInfo
if request_info is None:
# no outstanding requests for this particular hash, so we create it
req = RequestInfo(height)
req.add_new_flight(FlightInfo(nodeid, height))
self.block_requests[header_hash] = req
else:
request_info.flights.update({nodeid: FlightInfo(nodeid, height)})
def reset(self) -> None:
self.header_request = None
self.block_requests = dict()
self.block_cache = []
self.raw_block_cache = []
| 41.18847 | 156 | 0.643411 | import asyncio
import traceback
from datetime import datetime
from neo.Network.core.header import Header
from typing import TYPE_CHECKING, List
from neo.Network.flightinfo import FlightInfo
from neo.Network.requestinfo import RequestInfo
from neo.Network.payloads.inventory import InventoryType
from neo.Network.common import msgrouter
from neo.Network.common.singleton import Singleton
from contextlib import suppress
from neo.Network.core.uint256 import UInt256
from neo.logging import log_manager
logger = log_manager.getLogger('syncmanager')
if TYPE_CHECKING:
from neo.Network.nodemanager import NodeManager
from neo.Network.payloads import Block
class SyncManager(Singleton):
HEADER_MAX_LOOK_AHEAD = 6000
HEADER_REQUEST_TIMEOUT = 5
BLOCK_MAX_CACHE_SIZE = 500
BLOCK_NETWORK_REQ_LIMIT = 500
BLOCK_REQUEST_TIMEOUT = 5
def init(self, nodemgr: 'NodeManager'):
self.nodemgr = nodemgr
self.controller = None
self.block_requests = dict()
self.header_request = None
self.ledger = None
self.block_cache = []
self.header_cache = []
self.raw_block_cache = []
self.is_persisting_blocks = False
self.is_persisting_headers = False
self.keep_running = True
self.service_task = None
self.persist_task = None
self.health_task = None
msgrouter.on_headers += self.on_headers_received
msgrouter.on_block += self.on_block_received
async def start(self) -> None:
while not self.nodemgr.running:
await asyncio.sleep(0.1)
self.service_task = asyncio.create_task(self.run_service())
self.health_task = asyncio.create_task(self.block_health())
async def shutdown(self):
print("Shutting down sync manager...", end='')
self.keep_running = False
self.block_cache = []
shutdown_tasks = []
if self.service_task:
shutdown_tasks.append(self.service_task)
if self.health_task:
shutdown_tasks.append(self.health_task)
if self.persist_task:
shutdown_tasks.append(self.persist_task)
await asyncio.gather(*shutdown_tasks, return_exceptions=True)
print("DONE")
async def block_health(self):
error_counter = 0
last_height = await self.ledger.cur_block_height()
while self.keep_running:
await asyncio.sleep(15)
cur_height = await self.ledger.cur_block_height()
if cur_height == last_height:
error_counter += 1
if error_counter == 3:
to_disconnect = list(map(lambda n: n, self.nodemgr.nodes))
logger.debug(f"Block height not advancing. Replacing nodes: {to_disconnect}")
for n in to_disconnect:
await self.nodemgr.replace_node(n)
else:
error_counter = 0
last_height = cur_height
async def run_service(self):
while self.keep_running:
await self.check_timeout()
await self.sync()
await asyncio.sleep(1)
async def sync(self) -> None:
await self.sync_header()
await self.sync_block()
await self.persist_headers()
if not self.is_persisting_blocks:
self.persist_task = asyncio.create_task(self.persist_blocks())
async def sync_header(self) -> None:
if self.header_request:
return
cur_header_height = await self.ledger.cur_header_height()
cur_block_height = await self.ledger.cur_block_height()
if cur_header_height - cur_block_height >= self.HEADER_MAX_LOOK_AHEAD:
return
node = self.nodemgr.get_next_node(cur_header_height + 1)
if not node:
# or for the nodes to increase their height on the next produced block
return
self.header_request = RequestInfo(cur_header_height + 1)
self.header_request.add_new_flight(FlightInfo(node.nodeid, cur_header_height + 1))
cur_header_hash = await self.ledger.header_hash_by_height(cur_header_height)
await node.get_headers(hash_start=cur_header_hash)
logger.debug(f"Requested headers starting at {cur_header_height + 1} from node {node.nodeid_human}")
node.nodeweight.append_new_request_time()
async def persist_headers(self):
self.is_persisting_headers = True
if len(self.header_cache) > 0:
while self.keep_running:
try:
headers = self.header_cache.pop(0)
try:
await self.ledger.add_headers(headers)
except Exception as e:
print(traceback.format_exc())
await asyncio.sleep(0)
except IndexError:
# cache empty
break
# reset header_request such that the a new header sync task can be added
self.header_request = None
logger.debug("Finished processing headers")
self.is_persisting_headers = False
async def sync_block(self) -> None:
# to simplify syncing, don't ask for more data if we still have requests in flight
if len(self.block_requests) > 0:
return
best_block_height = await self.get_best_stored_block_height()
cur_header_height = await self.ledger.cur_header_height()
blocks_to_fetch = cur_header_height - best_block_height
if blocks_to_fetch <= 0:
return
block_cache_space = self.BLOCK_MAX_CACHE_SIZE - len(self.block_cache)
if block_cache_space <= 0:
return
if blocks_to_fetch > block_cache_space or blocks_to_fetch > self.BLOCK_NETWORK_REQ_LIMIT:
blocks_to_fetch = min(block_cache_space, self.BLOCK_NETWORK_REQ_LIMIT)
try:
best_node_height = max(map(lambda node: node.best_height, self.nodemgr.nodes))
except ValueError:
return
node = self.nodemgr.get_next_node(best_node_height)
if not node:
# or for the nodes to increase their height on the next produced block
return
hashes = []
endheight = None
for i in range(1, blocks_to_fetch + 1):
next_block_height = best_block_height + i
if self.is_in_blockcache(next_block_height):
continue
if next_block_height > best_node_height:
break
next_header_hash = await self.ledger.header_hash_by_height(next_block_height)
if next_header_hash == UInt256.zero():
# we do not have enough headers to fill the block cache. That's fine, just return
break
endheight = next_block_height
hashes.append(next_header_hash)
self.add_block_flight_info(node.nodeid, next_block_height, next_header_hash)
if len(hashes) > 0:
logger.debug(f"Asking for blocks {best_block_height + 1} - {endheight} from {node.nodeid_human}")
await node.get_data(InventoryType.block, hashes)
node.nodeweight.append_new_request_time()
async def persist_blocks(self) -> None:
self.is_persisting_blocks = True
while self.keep_running:
try:
b = self.block_cache.pop(0)
raw_b = self.raw_block_cache.pop(0)
await self.ledger.add_block(raw_b)
await asyncio.sleep(0.001)
except IndexError:
break
self.is_persisting_blocks = False
async def check_timeout(self) -> None:
task1 = asyncio.create_task(self.check_header_timeout())
task2 = asyncio.create_task(self.check_block_timeout())
try:
await asyncio.gather(task1, task2)
except Exception:
logger.debug(traceback.format_exc())
async def check_header_timeout(self) -> None:
if not self.header_request:
return
last_flight_info = self.header_request.most_recent_flight()
now = datetime.utcnow().timestamp()
delta = now - last_flight_info.start_time
if delta < self.HEADER_REQUEST_TIMEOUT:
return
node = self.nodemgr.get_node_by_nodeid(last_flight_info.node_id)
if node:
logger.debug(f"Header timeout limit exceeded by {delta - self.HEADER_REQUEST_TIMEOUT:.2f}s for node {node.nodeid_human}")
cur_header_height = await self.ledger.cur_header_height()
if last_flight_info.height <= cur_header_height:
# it has already come in in the mean time
# reset so sync_header will request new headers
self.header_request = None
return
# punish node that is causing header_timeout and retry using another node
self.header_request.mark_failed_node(last_flight_info.node_id)
await self.nodemgr.add_node_timeout_count(last_flight_info.node_id)
# retry with a new node
node = self.nodemgr.get_node_with_min_failed_time(self.header_request)
if node is None:
# only happens if there are no nodes that have data matching our needed height
self.header_request = None
return
hash = await self.ledger.header_hash_by_height(last_flight_info.height - 1)
logger.debug(f"Retry requesting headers starting at {last_flight_info.height} from new node {node.nodeid_human}")
await node.get_headers(hash_start=hash)
# restart start_time of flight info or else we'll timeout too fast for the next node
self.header_request.add_new_flight(FlightInfo(node.nodeid, last_flight_info.height))
node.nodeweight.append_new_request_time()
async def check_block_timeout(self) -> None:
if len(self.block_requests) == 0:
return
now = datetime.utcnow().timestamp()
block_timeout_flights = dict()
for block_hash, request_info in self.block_requests.items():
flight_info = request_info.most_recent_flight()
if now - flight_info.start_time > self.BLOCK_REQUEST_TIMEOUT:
block_timeout_flights[block_hash] = flight_info
if len(block_timeout_flights) == 0:
return
remaining_requests = []
nodes_to_tag_for_timeout = set()
nodes_to_mark_failed = dict()
best_stored_block_height = await self.get_best_stored_block_height()
for block_hash, fi in block_timeout_flights.items():
nodes_to_tag_for_timeout.add(fi.node_id)
try:
request_info = self.block_requests[block_hash]
except KeyError:
continue
if fi.height <= best_stored_block_height:
with suppress(KeyError):
self.block_requests.pop(block_hash)
continue
nodes_to_mark_failed[request_info] = fi.node_id
remaining_requests.append((block_hash, fi.height, request_info))
for nodeid in nodes_to_tag_for_timeout:
await self.nodemgr.add_node_timeout_count(nodeid)
for request_info, node_id in nodes_to_mark_failed.items():
request_info.mark_failed_node(node_id)
# for the remaining requests that need to be queued again, we create new FlightInfo objects that use a new node
# and ask them in a single batch from that new node.
hashes = []
if len(remaining_requests) > 0:
# retry the batch with a new node
ri_first = remaining_requests[0][2]
ri_last = remaining_requests[-1][2]
# using `ri_last` because this has the highest block height and we want a node that supports that
node = self.nodemgr.get_node_with_min_failed_time(ri_last)
if not node:
return
for block_hash, height, ri in remaining_requests: # type: _, int, RequestInfo
ri.add_new_flight(FlightInfo(node.nodeid, height))
hashes.append(block_hash)
if len(hashes) > 0:
logger.debug(f"Block time out for blocks {ri_first.height} - {ri_last.height}. Trying again using new node {node.nodeid_human} {hashes[0]}")
await node.get_data(InventoryType.block, hashes)
node.nodeweight.append_new_request_time()
async def on_headers_received(self, from_nodeid, headers: List[Header]) -> int:
if len(headers) == 0:
return -1
if self.header_request is None:
return -2
height = headers[0].index
if height != self.header_request.height:
# received headers we did not ask for
return -3
logger.debug(f"Headers received {headers[0].index} - {headers[-1].index}")
if headers in self.header_cache:
return -4
cur_header_height = await self.ledger.cur_header_height()
if height <= cur_header_height:
return -5
self.header_cache.append(headers)
return 1
async def on_block_received(self, from_nodeid, block: 'Block', raw_block) -> None:
# TODO: take out raw_block and raw_block_cache once we can serialize a full block
# print(f"{block.index} {block.hash} received")
next_header_height = await self.ledger.cur_header_height() + 1
if block.index > next_header_height:
return
cur_block_height = await self.ledger.cur_block_height()
if block.index <= cur_block_height:
return
try:
ri = self.block_requests.pop(block.hash) # type: RequestInfo
fi = ri.flights.pop(from_nodeid) # type: FlightInfo
now = datetime.utcnow().timestamp()
delta_time = now - fi.start_time
speed = (block._size / 1024) / delta_time # KB/s
node = self.nodemgr.get_node_by_nodeid(fi.node_id)
if node:
node.nodeweight.append_new_speed(speed)
except KeyError:
# it's a block we did not ask for
sync_distance = block.index - cur_block_height
if sync_distance != 1:
return
# to avoid having the `sync_block` task request the same data again
# this is also necessary for neo-cli nodes because they maintain a TaskSession and refuse to send recently requested data
if not self.is_in_blockcache(block.index) and self.keep_running:
self.block_cache.append(block)
self.raw_block_cache.append(raw_block)
async def get_best_stored_block_height(self) -> int:
best_block_cache_height = 0
if len(self.block_cache) > 0:
best_block_cache_height = self.block_cache[-1].index
ledger_height = await self.ledger.cur_block_height()
return max(ledger_height, best_block_cache_height)
def is_in_blockcache(self, block_height: int) -> bool:
for b in self.block_cache:
if b.index == block_height:
return True
else:
return False
def add_block_flight_info(self, nodeid, height, header_hash) -> None:
request_info = self.block_requests.get(header_hash, None) # type: RequestInfo
if request_info is None:
# no outstanding requests for this particular hash, so we create it
req = RequestInfo(height)
req.add_new_flight(FlightInfo(nodeid, height))
self.block_requests[header_hash] = req
else:
request_info.flights.update({nodeid: FlightInfo(nodeid, height)})
def reset(self) -> None:
self.header_request = None
self.block_requests = dict()
self.block_cache = []
self.raw_block_cache = []
| true | true |
f723864acb53fed407c35dcf3a1fd70e71ad72f3 | 6,431 | py | Python | taln2016/icsisumm-primary-sys34_v1/nltk/nltk-0.9.2/nltk_contrib/classifier/commandline.py | hectormartinez/rougexstem | 32da9eab253cb88fc1882e59026e8b5b40900a25 | [
"Apache-2.0"
] | null | null | null | taln2016/icsisumm-primary-sys34_v1/nltk/nltk-0.9.2/nltk_contrib/classifier/commandline.py | hectormartinez/rougexstem | 32da9eab253cb88fc1882e59026e8b5b40900a25 | [
"Apache-2.0"
] | null | null | null | taln2016/icsisumm-primary-sys34_v1/nltk/nltk-0.9.2/nltk_contrib/classifier/commandline.py | hectormartinez/rougexstem | 32da9eab253cb88fc1882e59026e8b5b40900a25 | [
"Apache-2.0"
] | null | null | null | # Natural Language Toolkit CommandLine
# understands the command line interaction
# Author: Sumukh Ghodke <sumukh dot ghodke at gmail dot com>
#
# URL: <http://nltk.sf.net>
# This software is distributed under GPL, for license information see LICENSE.TXT
from optparse import OptionParser
from nltk_contrib.classifier.exceptions import filenotfounderror as fnf, invaliddataerror as inv
from nltk_contrib.classifier import format
import time
D_help = "Used to specify the data format. " \
+ "Options: C45 for C4.5 format. " \
+ "Default: C45. "
l_help = "Used to specify the log file. "
ALGORITHM = 'algorithm'
FILES = 'files'
TRAINING = 'training'
TEST = 'test'
GOLD = 'gold'
DATA_FORMAT = 'data_format'
LOG_FILE = 'log_file'
OPTIONS = 'options'
C45_FORMAT = 'c45'
DATA_FORMAT_MAPPINGS = {C45_FORMAT: format.c45}
class CommandLineInterface(OptionParser):
def __init__(self, alg_choices, alg_default, a_help, f_help, t_help, T_help, g_help, o_help):
OptionParser.__init__(self)
self.add_option("-a", "--algorithm", dest=ALGORITHM, type="choice", \
choices=alg_choices, default=alg_default, help= a_help)
self.add_option("-f", "--files", dest=FILES, type="string", help=f_help)
self.add_option("-t", "--training-file", dest=TRAINING, type="string", help=t_help)
self.add_option("-T", "--test-file", dest=TEST, type="string", help=T_help)
self.add_option("-g", "--gold-file", dest=GOLD, type="string", help=g_help)
self.add_option("-D", "--data-format", dest=DATA_FORMAT, type="choice", choices=DATA_FORMAT_MAPPINGS.keys(), \
default=C45_FORMAT, help=D_help)
self.add_option("-l", "--log-file", dest=LOG_FILE, type="string", help=l_help)
self.add_option("-o", "--options", dest=OPTIONS, type="string", help=o_help)
def get_value(self, name):
return self.values.ensure_value(name, None)
def parse(self, args):
"""
method to aid testing
"""
self.parse_args(args, None)
def execute(self):
"""
Stores values from arguments which are common to all command line interfaces
"""
self.algorithm = self.get_value(ALGORITHM)
self.files = self.get_value(FILES)
self.training_path = self.get_value(TRAINING)
self.test_path = self.get_value(TEST)
self.gold_path = self.get_value(GOLD)
self.options = self.get_value(OPTIONS)
self.data_format = DATA_FORMAT_MAPPINGS[self.get_value(DATA_FORMAT)]
log_file = self.get_value(LOG_FILE)
self.log = None
if log_file is not None:
self.log = open(log_file, 'a')
print >>self.log, '-' * 40
print >>self.log, 'DateTime: ' + time.strftime('%c', time.localtime())
def run(self, args):
"""
Main method which delegates all the work
"""
self.parse(args)
self.execute()
if self.log is not None: self.log.close()
def validate_basic_arguments_are_present(self):
if self.algorithm is None or self.files is None and self.training_path is None :
self.required_arguments_not_present_error()
def validate_files_arg_is_exclusive(self):
if self.files is not None and (self.training_path is not None or self.test_path is not None or self.gold_path is not None):
self.error("Invalid arguments. The files argument cannot exist with training, test or gold arguments.")
def get_instances(self, training_path, test_path, gold_path, ignore_missing = False):
test = gold = None
training = self.data_format.training(training_path)
attributes, klass = self.data_format.metadata(training_path)
test = self.__get_instance(self.data_format.test, test_path, ignore_missing)
gold = self.__get_instance(self.data_format.gold, gold_path, ignore_missing)
return (training, attributes, klass, test, gold)
def __get_instance(self, method, path, ignore_if_missing):
if path is not None:
if ignore_if_missing:
try:
return method(path)
except fnf.FileNotFoundError:
return None
return method(path)
return None
def required_arguments_not_present_error(self):
self.error("Invalid arguments. One or more required arguments are not present.")
def write_to_file(self, suffix, training, attributes, klass, test, gold, include_classification = True):
files_written = []
files_written.append(self.data_format.write_training(training, self.training_path + suffix))
if test is not None: files_written.append(self.data_format.write_test(test, self.test_path + suffix, include_classification))
if gold is not None: files_written.append(self.data_format.write_gold(gold, self.gold_path + suffix, include_classification))
files_written.append(self.data_format.write_metadata(attributes, klass, self.training_path + suffix))
return files_written
def log_common_params(self, name):
if self.log is not None:
print >>self.log, 'Operation: ' + name
print >>self.log, '\nAlgorithm: ' + str(self.algorithm) + '\nTraining: ' + str(self.training_path) + \
'\nTest: ' + str(self.test_path) + '\nGold: ' + str(self.gold_path) + '\nOptions: ' + str(self.options)
def log_created_files(self, files_names, message):
if self.log is None:
print message
else:
print >>self.log, "NumberOfFilesCreated: " + str(len(files_names))
count = 0
for file_name in files_names:
if self.log is None:
print file_name
else:
print >>self.log, "CreatedFile" + str(count) + ": " + file_name
count += 1
def as_integers(name, com_str):
indices = []
if com_str is not None:
for element in com_str.split(','):
try:
indices.append(int(element.strip()))
except ValueError:
raise inv.InvalidDataError('Invalid Data. ' + name + ' should contain integers.')
return indices
| 43.161074 | 133 | 0.628985 |
from optparse import OptionParser
from nltk_contrib.classifier.exceptions import filenotfounderror as fnf, invaliddataerror as inv
from nltk_contrib.classifier import format
import time
D_help = "Used to specify the data format. " \
+ "Options: C45 for C4.5 format. " \
+ "Default: C45. "
l_help = "Used to specify the log file. "
ALGORITHM = 'algorithm'
FILES = 'files'
TRAINING = 'training'
TEST = 'test'
GOLD = 'gold'
DATA_FORMAT = 'data_format'
LOG_FILE = 'log_file'
OPTIONS = 'options'
C45_FORMAT = 'c45'
DATA_FORMAT_MAPPINGS = {C45_FORMAT: format.c45}
class CommandLineInterface(OptionParser):
def __init__(self, alg_choices, alg_default, a_help, f_help, t_help, T_help, g_help, o_help):
OptionParser.__init__(self)
self.add_option("-a", "--algorithm", dest=ALGORITHM, type="choice", \
choices=alg_choices, default=alg_default, help= a_help)
self.add_option("-f", "--files", dest=FILES, type="string", help=f_help)
self.add_option("-t", "--training-file", dest=TRAINING, type="string", help=t_help)
self.add_option("-T", "--test-file", dest=TEST, type="string", help=T_help)
self.add_option("-g", "--gold-file", dest=GOLD, type="string", help=g_help)
self.add_option("-D", "--data-format", dest=DATA_FORMAT, type="choice", choices=DATA_FORMAT_MAPPINGS.keys(), \
default=C45_FORMAT, help=D_help)
self.add_option("-l", "--log-file", dest=LOG_FILE, type="string", help=l_help)
self.add_option("-o", "--options", dest=OPTIONS, type="string", help=o_help)
def get_value(self, name):
return self.values.ensure_value(name, None)
def parse(self, args):
"""
method to aid testing
"""
self.parse_args(args, None)
def execute(self):
"""
Stores values from arguments which are common to all command line interfaces
"""
self.algorithm = self.get_value(ALGORITHM)
self.files = self.get_value(FILES)
self.training_path = self.get_value(TRAINING)
self.test_path = self.get_value(TEST)
self.gold_path = self.get_value(GOLD)
self.options = self.get_value(OPTIONS)
self.data_format = DATA_FORMAT_MAPPINGS[self.get_value(DATA_FORMAT)]
log_file = self.get_value(LOG_FILE)
self.log = None
if log_file is not None:
self.log = open(log_file, 'a')
print >>self.log, '-' * 40
print >>self.log, 'DateTime: ' + time.strftime('%c', time.localtime())
def run(self, args):
"""
Main method which delegates all the work
"""
self.parse(args)
self.execute()
if self.log is not None: self.log.close()
def validate_basic_arguments_are_present(self):
if self.algorithm is None or self.files is None and self.training_path is None :
self.required_arguments_not_present_error()
def validate_files_arg_is_exclusive(self):
if self.files is not None and (self.training_path is not None or self.test_path is not None or self.gold_path is not None):
self.error("Invalid arguments. The files argument cannot exist with training, test or gold arguments.")
def get_instances(self, training_path, test_path, gold_path, ignore_missing = False):
test = gold = None
training = self.data_format.training(training_path)
attributes, klass = self.data_format.metadata(training_path)
test = self.__get_instance(self.data_format.test, test_path, ignore_missing)
gold = self.__get_instance(self.data_format.gold, gold_path, ignore_missing)
return (training, attributes, klass, test, gold)
def __get_instance(self, method, path, ignore_if_missing):
if path is not None:
if ignore_if_missing:
try:
return method(path)
except fnf.FileNotFoundError:
return None
return method(path)
return None
def required_arguments_not_present_error(self):
self.error("Invalid arguments. One or more required arguments are not present.")
def write_to_file(self, suffix, training, attributes, klass, test, gold, include_classification = True):
files_written = []
files_written.append(self.data_format.write_training(training, self.training_path + suffix))
if test is not None: files_written.append(self.data_format.write_test(test, self.test_path + suffix, include_classification))
if gold is not None: files_written.append(self.data_format.write_gold(gold, self.gold_path + suffix, include_classification))
files_written.append(self.data_format.write_metadata(attributes, klass, self.training_path + suffix))
return files_written
def log_common_params(self, name):
if self.log is not None:
print >>self.log, 'Operation: ' + name
print >>self.log, '\nAlgorithm: ' + str(self.algorithm) + '\nTraining: ' + str(self.training_path) + \
'\nTest: ' + str(self.test_path) + '\nGold: ' + str(self.gold_path) + '\nOptions: ' + str(self.options)
def log_created_files(self, files_names, message):
if self.log is None:
print message
else:
print >>self.log, "NumberOfFilesCreated: " + str(len(files_names))
count = 0
for file_name in files_names:
if self.log is None:
print file_name
else:
print >>self.log, "CreatedFile" + str(count) + ": " + file_name
count += 1
def as_integers(name, com_str):
indices = []
if com_str is not None:
for element in com_str.split(','):
try:
indices.append(int(element.strip()))
except ValueError:
raise inv.InvalidDataError('Invalid Data. ' + name + ' should contain integers.')
return indices
| false | true |
f7238671141edde716244b94339cf5f49fe0ddb8 | 3,020 | py | Python | dynamic-ingest/python/di-example-source-file-upload.py | AdiCheo/dynamic-ingest-code-samples | e36fd847744099da29c6aa214a58d4c4ba4600cc | [
"MIT"
] | 4 | 2017-01-16T08:12:48.000Z | 2020-07-29T07:50:25.000Z | dynamic-ingest/python/di-example-source-file-upload.py | AdiCheo/dynamic-ingest-code-samples | e36fd847744099da29c6aa214a58d4c4ba4600cc | [
"MIT"
] | 2 | 2016-10-04T11:54:09.000Z | 2021-01-21T00:17:20.000Z | dynamic-ingest/python/di-example-source-file-upload.py | AdiCheo/dynamic-ingest-code-samples | e36fd847744099da29c6aa214a58d4c4ba4600cc | [
"MIT"
] | 10 | 2016-10-04T10:49:06.000Z | 2019-11-28T23:18:56.000Z | #!/usr/bin/env python
import sys
import requests
import json
import argparse
pub_id = "***ACCOUNT ID HERE****"
client_id = "***CLIENT ID HERE****"
client_secret = "***CLIENT SECRET HERE****"
source_filename = "*** LOCAL VIDEO FILE HERE***"
access_token_url = "https://oauth.brightcove.com/v3/access_token"
profiles_base_url = "http://ingestion.api.brightcove.com/v1/accounts/{pubid}/profiles"
# Making requests with the Brightcove CMS API requires the use of OAuth
# get_authorization_headers is a convenience method that obtains an OAuth access token
# and embeds it appropriately in a map suitable for use with the requests HTTP library
def get_authorization_headers():
access_token = None
r = requests.post(access_token_url, params="grant_type=client_credentials", auth=(client_id, client_secret), verify=False)
if r.status_code == 200:
access_token = r.json().get('access_token')
print(access_token)
return { 'Authorization': 'Bearer ' + access_token, "Content-Type": "application/json" }
# create_video makes the CMS API call to create a video in the VideoCloud catalog
# This example demonstrates setting only the 'name' attribute on the created title
def create_video():
url = ("https://cms.api.brightcove.com/v1/accounts/{pubid}/videos/").format(pubid=pub_id)
data = '{"name": "***VIDEO TITLE HERE***"}'
r = requests.post(url, headers=get_authorization_headers(), data=data)
return r.json()
# get_upload_location_and_upload_file first performs an authenticated request to discover
# a Brightcove-provided location to securely upload a source file
def get_upload_location_and_upload_file(account_id, video_id, source_filename):
# Perform an authorized request to obtain a file upload location
url = ("https://cms.api.brightcove.com/v1/accounts/{pubid}/videos/{videoid}/upload-urls/{sourcefilename}").format(pubid=pub_id, videoid=video_id, sourcefilename=source_filename)
r = requests.get(url, headers=get_authorization_headers())
upload_urls_response = r.json()
# Upload the contents of our local file to the location provided via HTTP PUT
# This is not recommended for large files
with open(filepath) as fh:
s = requests.put(upload_urls_response['signed_url'], data=fh.read())
return upload_urls_response
# di_request makes the Ingest API call to populate a video with transcoded renditions
# from the source file that was uploaded in the previous step
def di_request(video_id, upload_urls_response):
url = ("https://ingest.api.brightcove.com/v1/accounts/{pubid}/videos/{videoid}/ingest-requests").format(pubid=pub_id, videoid=video_id)
data = '''{"master": { "url": "''' + upload_urls_response['api_request_url'] + '''" }}'''
r = requests.post(url, headers=get_authorization_headers(), data=data)
return r.json()
if __name__ == '__main__':
v = create_video()
upload_urls = get_upload_location_and_upload_file(pub_id, v['id'], source_filename)
print di_request(v['id'], upload_urls) | 49.508197 | 181 | 0.740397 |
import sys
import requests
import json
import argparse
pub_id = "***ACCOUNT ID HERE****"
client_id = "***CLIENT ID HERE****"
client_secret = "***CLIENT SECRET HERE****"
source_filename = "*** LOCAL VIDEO FILE HERE***"
access_token_url = "https://oauth.brightcove.com/v3/access_token"
profiles_base_url = "http://ingestion.api.brightcove.com/v1/accounts/{pubid}/profiles"
def get_authorization_headers():
access_token = None
r = requests.post(access_token_url, params="grant_type=client_credentials", auth=(client_id, client_secret), verify=False)
if r.status_code == 200:
access_token = r.json().get('access_token')
print(access_token)
return { 'Authorization': 'Bearer ' + access_token, "Content-Type": "application/json" }
def create_video():
url = ("https://cms.api.brightcove.com/v1/accounts/{pubid}/videos/").format(pubid=pub_id)
data = '{"name": "***VIDEO TITLE HERE***"}'
r = requests.post(url, headers=get_authorization_headers(), data=data)
return r.json()
def get_upload_location_and_upload_file(account_id, video_id, source_filename):
url = ("https://cms.api.brightcove.com/v1/accounts/{pubid}/videos/{videoid}/upload-urls/{sourcefilename}").format(pubid=pub_id, videoid=video_id, sourcefilename=source_filename)
r = requests.get(url, headers=get_authorization_headers())
upload_urls_response = r.json()
with open(filepath) as fh:
s = requests.put(upload_urls_response['signed_url'], data=fh.read())
return upload_urls_response
def di_request(video_id, upload_urls_response):
url = ("https://ingest.api.brightcove.com/v1/accounts/{pubid}/videos/{videoid}/ingest-requests").format(pubid=pub_id, videoid=video_id)
data = '''{"master": { "url": "''' + upload_urls_response['api_request_url'] + '''" }}'''
r = requests.post(url, headers=get_authorization_headers(), data=data)
return r.json()
if __name__ == '__main__':
v = create_video()
upload_urls = get_upload_location_and_upload_file(pub_id, v['id'], source_filename)
print di_request(v['id'], upload_urls) | false | true |
f72386a8a5199feebb6ae6ddf5ad300495566d00 | 7,304 | py | Python | src/genie/libs/parser/iosxe/tests/ShowIpRoute/cli/equal/golden_output92_expected.py | miwamoto0203/genieparser | d0595046f0f804aa4143c13e20a738b41a3a8c25 | [
"Apache-2.0"
] | null | null | null | src/genie/libs/parser/iosxe/tests/ShowIpRoute/cli/equal/golden_output92_expected.py | miwamoto0203/genieparser | d0595046f0f804aa4143c13e20a738b41a3a8c25 | [
"Apache-2.0"
] | null | null | null | src/genie/libs/parser/iosxe/tests/ShowIpRoute/cli/equal/golden_output92_expected.py | miwamoto0203/genieparser | d0595046f0f804aa4143c13e20a738b41a3a8c25 | [
"Apache-2.0"
] | null | null | null | expected_output = {
"vrf": {
"VRF1": {
"address_family": {
"ipv4": {
"routes": {
"10.0.0.0/24": {
"route": "10.0.0.0/24",
"active": True,
"route_preference": 110,
"metric": 1,
"source_protocol_codes": "O",
"source_protocol": "ospf",
"next_hop": {
"next_hop_list": {
1: {
"index": 1,
"next_hop": "10.81.1.2",
"updated": "01:02:20",
"outgoing_interface": "GigabitEthernet0/0/2.100",
}
}
},
},
"10.0.1.0/24": {
"route": "10.0.1.0/24",
"active": True,
"route_preference": 110,
"metric": 1,
"source_protocol_codes": "O",
"source_protocol": "ospf",
"next_hop": {
"next_hop_list": {
1: {
"index": 1,
"next_hop": "10.81.1.2",
"updated": "01:02:20",
"outgoing_interface": "GigabitEthernet0/0/2.100",
}
}
},
},
"10.0.2.0/24": {
"route": "10.0.2.0/24",
"active": True,
"route_preference": 110,
"metric": 1,
"source_protocol_codes": "O IA",
"source_protocol": "ospf",
"next_hop": {
"next_hop_list": {
1: {
"index": 1,
"next_hop": "10.81.1.2",
"updated": "01:02:20",
"outgoing_interface": "GigabitEthernet0/0/2.100",
}
}
},
},
"10.145.0.0/24": {
"route": "10.145.0.0/24",
"active": True,
"route_preference": 200,
"metric": 1,
"source_protocol_codes": "B",
"source_protocol": "bgp",
"next_hop": {
"next_hop_list": {
1: {
"index": 1,
"next_hop": "192.168.51.1",
"updated": "01:01:10",
}
}
},
},
"10.145.1.0/24": {
"route": "10.145.1.0/24",
"active": True,
"route_preference": 200,
"metric": 1,
"source_protocol_codes": "B",
"source_protocol": "bgp",
"next_hop": {
"next_hop_list": {
1: {
"index": 1,
"next_hop": "192.168.51.1",
"updated": "01:01:10",
}
}
},
},
"10.145.2.0/24": {
"route": "10.145.2.0/24",
"active": True,
"route_preference": 200,
"metric": 1,
"source_protocol_codes": "B",
"source_protocol": "bgp",
"next_hop": {
"next_hop_list": {
1: {
"index": 1,
"next_hop": "192.168.51.1",
"updated": "01:01:10",
}
}
},
},
"10.81.1.0/24": {
"route": "10.81.1.0/24",
"active": True,
"source_protocol_codes": "C",
"source_protocol": "connected",
"next_hop": {
"outgoing_interface": {
"GigabitEthernet0/0/2.100": {
"outgoing_interface": "GigabitEthernet0/0/2.100"
}
}
},
},
"10.81.1.1/32": {
"route": "10.81.1.1/32",
"active": True,
"source_protocol_codes": "L",
"source_protocol": "local",
"next_hop": {
"outgoing_interface": {
"GigabitEthernet0/0/2.100": {
"outgoing_interface": "GigabitEthernet0/0/2.100"
}
}
},
},
"192.168.4.0/24": {
"route": "192.168.4.0/24",
"active": True,
"route_preference": 200,
"metric": 0,
"source_protocol_codes": "B",
"source_protocol": "bgp",
"next_hop": {
"next_hop_list": {
1: {
"index": 1,
"next_hop": "192.168.51.1",
"updated": "01:01:10",
}
}
},
},
}
}
}
}
}
}
| 45.36646 | 89 | 0.214951 | expected_output = {
"vrf": {
"VRF1": {
"address_family": {
"ipv4": {
"routes": {
"10.0.0.0/24": {
"route": "10.0.0.0/24",
"active": True,
"route_preference": 110,
"metric": 1,
"source_protocol_codes": "O",
"source_protocol": "ospf",
"next_hop": {
"next_hop_list": {
1: {
"index": 1,
"next_hop": "10.81.1.2",
"updated": "01:02:20",
"outgoing_interface": "GigabitEthernet0/0/2.100",
}
}
},
},
"10.0.1.0/24": {
"route": "10.0.1.0/24",
"active": True,
"route_preference": 110,
"metric": 1,
"source_protocol_codes": "O",
"source_protocol": "ospf",
"next_hop": {
"next_hop_list": {
1: {
"index": 1,
"next_hop": "10.81.1.2",
"updated": "01:02:20",
"outgoing_interface": "GigabitEthernet0/0/2.100",
}
}
},
},
"10.0.2.0/24": {
"route": "10.0.2.0/24",
"active": True,
"route_preference": 110,
"metric": 1,
"source_protocol_codes": "O IA",
"source_protocol": "ospf",
"next_hop": {
"next_hop_list": {
1: {
"index": 1,
"next_hop": "10.81.1.2",
"updated": "01:02:20",
"outgoing_interface": "GigabitEthernet0/0/2.100",
}
}
},
},
"10.145.0.0/24": {
"route": "10.145.0.0/24",
"active": True,
"route_preference": 200,
"metric": 1,
"source_protocol_codes": "B",
"source_protocol": "bgp",
"next_hop": {
"next_hop_list": {
1: {
"index": 1,
"next_hop": "192.168.51.1",
"updated": "01:01:10",
}
}
},
},
"10.145.1.0/24": {
"route": "10.145.1.0/24",
"active": True,
"route_preference": 200,
"metric": 1,
"source_protocol_codes": "B",
"source_protocol": "bgp",
"next_hop": {
"next_hop_list": {
1: {
"index": 1,
"next_hop": "192.168.51.1",
"updated": "01:01:10",
}
}
},
},
"10.145.2.0/24": {
"route": "10.145.2.0/24",
"active": True,
"route_preference": 200,
"metric": 1,
"source_protocol_codes": "B",
"source_protocol": "bgp",
"next_hop": {
"next_hop_list": {
1: {
"index": 1,
"next_hop": "192.168.51.1",
"updated": "01:01:10",
}
}
},
},
"10.81.1.0/24": {
"route": "10.81.1.0/24",
"active": True,
"source_protocol_codes": "C",
"source_protocol": "connected",
"next_hop": {
"outgoing_interface": {
"GigabitEthernet0/0/2.100": {
"outgoing_interface": "GigabitEthernet0/0/2.100"
}
}
},
},
"10.81.1.1/32": {
"route": "10.81.1.1/32",
"active": True,
"source_protocol_codes": "L",
"source_protocol": "local",
"next_hop": {
"outgoing_interface": {
"GigabitEthernet0/0/2.100": {
"outgoing_interface": "GigabitEthernet0/0/2.100"
}
}
},
},
"192.168.4.0/24": {
"route": "192.168.4.0/24",
"active": True,
"route_preference": 200,
"metric": 0,
"source_protocol_codes": "B",
"source_protocol": "bgp",
"next_hop": {
"next_hop_list": {
1: {
"index": 1,
"next_hop": "192.168.51.1",
"updated": "01:01:10",
}
}
},
},
}
}
}
}
}
}
| true | true |
f72386b405bdb028c4ce4c2d9c8dba4a5bba70db | 8,755 | py | Python | vyper/utils.py | milancermak/vyper | f1c65b7fecc2dadb3ea761aed1b668227a44730a | [
"Apache-2.0"
] | 1 | 2020-06-28T11:48:41.000Z | 2020-06-28T11:48:41.000Z | vyper/utils.py | milancermak/vyper | f1c65b7fecc2dadb3ea761aed1b668227a44730a | [
"Apache-2.0"
] | 1 | 2020-11-28T11:54:29.000Z | 2020-11-28T11:54:29.000Z | vyper/utils.py | milancermak/vyper | f1c65b7fecc2dadb3ea761aed1b668227a44730a | [
"Apache-2.0"
] | null | null | null | import binascii
import functools
from typing import Dict, List, Union
from vyper.exceptions import InvalidLiteral
try:
from Crypto.Hash import keccak # type: ignore
keccak256 = lambda x: keccak.new(digest_bits=256, data=x).digest() # noqa: E731
except ImportError:
import sha3 as _sha3
keccak256 = lambda x: _sha3.sha3_256(x).digest() # noqa: E731
# Converts four bytes to an integer
def fourbytes_to_int(inp):
return (inp[0] << 24) + (inp[1] << 16) + (inp[2] << 8) + inp[3]
# Converts string to bytes
def string_to_bytes(str):
bytez = b""
for c in str:
if ord(c) >= 256:
raise InvalidLiteral(f"Cannot insert special character {c} into byte array")
bytez += bytes([ord(c)])
bytez_length = len(bytez)
return bytez, bytez_length
# Converts a provided hex string to an integer
def hex_to_int(inp):
if inp[:2] == "0x":
inp = inp[2:]
return bytes_to_int(binascii.unhexlify(inp))
# Converts bytes to an integer
def bytes_to_int(bytez):
o = 0
for b in bytez:
o = o * 256 + b
return o
# Encodes an address using ethereum's checksum scheme
def checksum_encode(addr): # Expects an input of the form 0x<40 hex chars>
assert addr[:2] == "0x" and len(addr) == 42
o = ""
v = bytes_to_int(keccak256(addr[2:].lower().encode("utf-8")))
for i, c in enumerate(addr[2:]):
if c in "0123456789":
o += c
else:
o += c.upper() if (v & (2 ** (255 - 4 * i))) else c.lower()
return "0x" + o
# Returns lowest multiple of 32 >= the input
def ceil32(x):
return x if x % 32 == 0 else x + 32 - (x % 32)
# Calculates amount of gas needed for memory expansion
def calc_mem_gas(memsize):
return (memsize // 32) * 3 + (memsize // 32) ** 2 // 512
# Specific gas usage
GAS_IDENTITY = 15
GAS_IDENTITYWORD = 3
# A decimal value can store multiples of 1/DECIMAL_DIVISOR
MAX_DECIMAL_PLACES = 10
DECIMAL_DIVISOR = 10 ** MAX_DECIMAL_PLACES
# Number of bytes in memory used for system purposes, not for variables
class MemoryPositions:
ADDRSIZE = 32
MAX_INT128 = 64
MIN_INT128 = 96
MAXDECIMAL = 128
MINDECIMAL = 160
FREE_VAR_SPACE = 192
FREE_VAR_SPACE2 = 224
BLANK_SPACE = 256
FREE_LOOP_INDEX = 288
RESERVED_MEMORY = 320
# Sizes of different data types. Used to clamp types.
class SizeLimits:
ADDRSIZE = 2 ** 160
MAX_INT128 = 2 ** 127 - 1
MIN_INT128 = -(2 ** 127)
MAX_INT256 = 2 ** 255 - 1
MIN_INT256 = -(2 ** 255)
MAXDECIMAL = (2 ** 127 - 1) * DECIMAL_DIVISOR
MINDECIMAL = (-(2 ** 127)) * DECIMAL_DIVISOR
MAX_UINT256 = 2 ** 256 - 1
@classmethod
def in_bounds(cls, type_str, value):
assert isinstance(type_str, str)
if type_str == "decimal":
return float(cls.MINDECIMAL) <= value <= float(cls.MAXDECIMAL)
if type_str == "uint256":
return 0 <= value <= cls.MAX_UINT256
elif type_str == "int128":
return cls.MIN_INT128 <= value <= cls.MAX_INT128
elif type_str == "int256":
return cls.MIN_INT256 <= value <= cls.MAX_INT256
else:
raise Exception(f'Unknown type "{type_str}" supplied.')
# Map representing all limits loaded into a contract as part of the initializer
# code.
LOADED_LIMITS: Dict[int, int] = {
MemoryPositions.ADDRSIZE: SizeLimits.ADDRSIZE,
MemoryPositions.MAX_INT128: SizeLimits.MAX_INT128,
MemoryPositions.MIN_INT128: SizeLimits.MIN_INT128,
MemoryPositions.MAXDECIMAL: SizeLimits.MAXDECIMAL,
MemoryPositions.MINDECIMAL: SizeLimits.MINDECIMAL,
}
# Otherwise reserved words that are whitelisted for function declarations
FUNCTION_WHITELIST = {
"send",
}
# List of valid LLL macros.
VALID_LLL_MACROS = {
"assert",
"break",
"ceil32",
"clamp",
"clamp",
"clamp_nonzero",
"clampge",
"clampgt",
"clample",
"clamplt",
"codeload",
"continue",
"debugger",
"ge",
"if",
"le",
"lll",
"ne",
"pass",
"repeat",
"seq",
"set",
"sge",
"sha3_32",
"sha3_64",
"sle",
"uclampge",
"uclampgt",
"uclample",
"uclamplt",
"with",
"~codelen",
"label",
"goto",
}
# Available base types
BASE_TYPES = {"int128", "int256", "decimal", "bytes32", "uint256", "bool", "address"}
def is_instances(instances, instance_type):
return all([isinstance(inst, instance_type) for inst in instances])
def iterable_cast(cast_type):
def yf(func):
@functools.wraps(func)
def f(*args, **kwargs):
return cast_type(func(*args, **kwargs))
return f
return yf
def indent(text: str, indent_chars: Union[str, List[str]] = " ", level: int = 1) -> str:
"""
Indent lines of text in the string ``text`` using the indentation
character(s) given in ``indent_chars`` ``level`` times.
:param text: A string containing the lines of text to be indented.
:param level: The number of times to indent lines in ``text``.
:param indent_chars: The characters to use for indentation. If a string,
uses repetitions of that string for indentation. If a list of strings,
uses repetitions of each string to indent each line.
:return: The indented text.
"""
text_lines = text.splitlines(keepends=True)
if isinstance(indent_chars, str):
indented_lines = [indent_chars * level + line for line in text_lines]
elif isinstance(indent_chars, list):
if len(indent_chars) != len(text_lines):
raise ValueError("Must provide indentation chars for each line")
indented_lines = [ind * level + line for ind, line in zip(indent_chars, text_lines)]
else:
raise ValueError("Unrecognized indentation characters value")
return "".join(indented_lines)
def annotate_source_code(
source_code: str,
lineno: int,
col_offset: int = None,
context_lines: int = 0,
line_numbers: bool = False,
) -> str:
"""
Annotate the location specified by ``lineno`` and ``col_offset`` in the
source code given by ``source_code`` with a location marker and optional
line numbers and context lines.
:param source_code: The source code containing the source location.
:param lineno: The 1-indexed line number of the source location.
:param col_offset: The 0-indexed column offset of the source location.
:param context_lines: The number of contextual lines to include above and
below the source location.
:param line_numbers: If true, line numbers are included in the location
representation.
:return: A string containing the annotated source code location.
"""
if lineno is None:
return ""
source_lines = source_code.splitlines(keepends=True)
if lineno < 1 or lineno > len(source_lines):
raise ValueError("Line number is out of range")
line_offset = lineno - 1
start_offset = max(0, line_offset - context_lines)
end_offset = min(len(source_lines), line_offset + context_lines + 1)
line_repr = source_lines[line_offset]
if "\n" not in line_repr[-2:]: # Handle certain edge cases
line_repr += "\n"
if col_offset is None:
mark_repr = ""
else:
mark_repr = "-" * col_offset + "^" + "\n"
before_lines = "".join(source_lines[start_offset:line_offset])
after_lines = "".join(source_lines[line_offset + 1 : end_offset]) # noqa: E203
location_repr = "".join((before_lines, line_repr, mark_repr, after_lines))
if line_numbers:
# Create line numbers
lineno_reprs = [f"{i} " for i in range(start_offset + 1, end_offset + 1)]
# Highlight line identified by `lineno`
local_line_off = line_offset - start_offset
lineno_reprs[local_line_off] = "---> " + lineno_reprs[local_line_off]
# Calculate width of widest line no
max_len = max(len(i) for i in lineno_reprs)
# Justify all line nos according to this width
justified_reprs = [i.rjust(max_len) for i in lineno_reprs]
if col_offset is not None:
justified_reprs.insert(local_line_off + 1, "-" * max_len)
location_repr = indent(location_repr, indent_chars=justified_reprs)
# Ensure no trailing whitespace and trailing blank lines are only included
# if they are part of the source code
if col_offset is None:
# Number of lines doesn't include column marker line
num_lines = end_offset - start_offset
else:
num_lines = end_offset - start_offset + 1
cleanup_lines = [line.rstrip() for line in location_repr.splitlines()]
cleanup_lines += [""] * (num_lines - len(cleanup_lines))
return "\n".join(cleanup_lines)
| 29.577703 | 92 | 0.647744 | import binascii
import functools
from typing import Dict, List, Union
from vyper.exceptions import InvalidLiteral
try:
from Crypto.Hash import keccak
keccak256 = lambda x: keccak.new(digest_bits=256, data=x).digest()
except ImportError:
import sha3 as _sha3
keccak256 = lambda x: _sha3.sha3_256(x).digest()
def fourbytes_to_int(inp):
return (inp[0] << 24) + (inp[1] << 16) + (inp[2] << 8) + inp[3]
def string_to_bytes(str):
bytez = b""
for c in str:
if ord(c) >= 256:
raise InvalidLiteral(f"Cannot insert special character {c} into byte array")
bytez += bytes([ord(c)])
bytez_length = len(bytez)
return bytez, bytez_length
def hex_to_int(inp):
if inp[:2] == "0x":
inp = inp[2:]
return bytes_to_int(binascii.unhexlify(inp))
def bytes_to_int(bytez):
o = 0
for b in bytez:
o = o * 256 + b
return o
def checksum_encode(addr): # Expects an input of the form 0x<40 hex chars>
assert addr[:2] == "0x" and len(addr) == 42
o = ""
v = bytes_to_int(keccak256(addr[2:].lower().encode("utf-8")))
for i, c in enumerate(addr[2:]):
if c in "0123456789":
o += c
else:
o += c.upper() if (v & (2 ** (255 - 4 * i))) else c.lower()
return "0x" + o
# Returns lowest multiple of 32 >= the input
def ceil32(x):
return x if x % 32 == 0 else x + 32 - (x % 32)
# Calculates amount of gas needed for memory expansion
def calc_mem_gas(memsize):
return (memsize // 32) * 3 + (memsize // 32) ** 2 // 512
# Specific gas usage
GAS_IDENTITY = 15
GAS_IDENTITYWORD = 3
# A decimal value can store multiples of 1/DECIMAL_DIVISOR
MAX_DECIMAL_PLACES = 10
DECIMAL_DIVISOR = 10 ** MAX_DECIMAL_PLACES
# Number of bytes in memory used for system purposes, not for variables
class MemoryPositions:
ADDRSIZE = 32
MAX_INT128 = 64
MIN_INT128 = 96
MAXDECIMAL = 128
MINDECIMAL = 160
FREE_VAR_SPACE = 192
FREE_VAR_SPACE2 = 224
BLANK_SPACE = 256
FREE_LOOP_INDEX = 288
RESERVED_MEMORY = 320
# Sizes of different data types. Used to clamp types.
class SizeLimits:
ADDRSIZE = 2 ** 160
MAX_INT128 = 2 ** 127 - 1
MIN_INT128 = -(2 ** 127)
MAX_INT256 = 2 ** 255 - 1
MIN_INT256 = -(2 ** 255)
MAXDECIMAL = (2 ** 127 - 1) * DECIMAL_DIVISOR
MINDECIMAL = (-(2 ** 127)) * DECIMAL_DIVISOR
MAX_UINT256 = 2 ** 256 - 1
@classmethod
def in_bounds(cls, type_str, value):
assert isinstance(type_str, str)
if type_str == "decimal":
return float(cls.MINDECIMAL) <= value <= float(cls.MAXDECIMAL)
if type_str == "uint256":
return 0 <= value <= cls.MAX_UINT256
elif type_str == "int128":
return cls.MIN_INT128 <= value <= cls.MAX_INT128
elif type_str == "int256":
return cls.MIN_INT256 <= value <= cls.MAX_INT256
else:
raise Exception(f'Unknown type "{type_str}" supplied.')
# Map representing all limits loaded into a contract as part of the initializer
# code.
LOADED_LIMITS: Dict[int, int] = {
MemoryPositions.ADDRSIZE: SizeLimits.ADDRSIZE,
MemoryPositions.MAX_INT128: SizeLimits.MAX_INT128,
MemoryPositions.MIN_INT128: SizeLimits.MIN_INT128,
MemoryPositions.MAXDECIMAL: SizeLimits.MAXDECIMAL,
MemoryPositions.MINDECIMAL: SizeLimits.MINDECIMAL,
}
# Otherwise reserved words that are whitelisted for function declarations
FUNCTION_WHITELIST = {
"send",
}
# List of valid LLL macros.
VALID_LLL_MACROS = {
"assert",
"break",
"ceil32",
"clamp",
"clamp",
"clamp_nonzero",
"clampge",
"clampgt",
"clample",
"clamplt",
"codeload",
"continue",
"debugger",
"ge",
"if",
"le",
"lll",
"ne",
"pass",
"repeat",
"seq",
"set",
"sge",
"sha3_32",
"sha3_64",
"sle",
"uclampge",
"uclampgt",
"uclample",
"uclamplt",
"with",
"~codelen",
"label",
"goto",
}
# Available base types
BASE_TYPES = {"int128", "int256", "decimal", "bytes32", "uint256", "bool", "address"}
def is_instances(instances, instance_type):
return all([isinstance(inst, instance_type) for inst in instances])
def iterable_cast(cast_type):
def yf(func):
@functools.wraps(func)
def f(*args, **kwargs):
return cast_type(func(*args, **kwargs))
return f
return yf
def indent(text: str, indent_chars: Union[str, List[str]] = " ", level: int = 1) -> str:
text_lines = text.splitlines(keepends=True)
if isinstance(indent_chars, str):
indented_lines = [indent_chars * level + line for line in text_lines]
elif isinstance(indent_chars, list):
if len(indent_chars) != len(text_lines):
raise ValueError("Must provide indentation chars for each line")
indented_lines = [ind * level + line for ind, line in zip(indent_chars, text_lines)]
else:
raise ValueError("Unrecognized indentation characters value")
return "".join(indented_lines)
def annotate_source_code(
source_code: str,
lineno: int,
col_offset: int = None,
context_lines: int = 0,
line_numbers: bool = False,
) -> str:
if lineno is None:
return ""
source_lines = source_code.splitlines(keepends=True)
if lineno < 1 or lineno > len(source_lines):
raise ValueError("Line number is out of range")
line_offset = lineno - 1
start_offset = max(0, line_offset - context_lines)
end_offset = min(len(source_lines), line_offset + context_lines + 1)
line_repr = source_lines[line_offset]
if "\n" not in line_repr[-2:]: # Handle certain edge cases
line_repr += "\n"
if col_offset is None:
mark_repr = ""
else:
mark_repr = "-" * col_offset + "^" + "\n"
before_lines = "".join(source_lines[start_offset:line_offset])
after_lines = "".join(source_lines[line_offset + 1 : end_offset]) # noqa: E203
location_repr = "".join((before_lines, line_repr, mark_repr, after_lines))
if line_numbers:
# Create line numbers
lineno_reprs = [f"{i} " for i in range(start_offset + 1, end_offset + 1)]
# Highlight line identified by `lineno`
local_line_off = line_offset - start_offset
lineno_reprs[local_line_off] = "---> " + lineno_reprs[local_line_off]
# Calculate width of widest line no
max_len = max(len(i) for i in lineno_reprs)
# Justify all line nos according to this width
justified_reprs = [i.rjust(max_len) for i in lineno_reprs]
if col_offset is not None:
justified_reprs.insert(local_line_off + 1, "-" * max_len)
location_repr = indent(location_repr, indent_chars=justified_reprs)
# Ensure no trailing whitespace and trailing blank lines are only included
# if they are part of the source code
if col_offset is None:
# Number of lines doesn't include column marker line
num_lines = end_offset - start_offset
else:
num_lines = end_offset - start_offset + 1
cleanup_lines = [line.rstrip() for line in location_repr.splitlines()]
cleanup_lines += [""] * (num_lines - len(cleanup_lines))
return "\n".join(cleanup_lines)
| true | true |
f72387c2dd643350d80025eeec9fc77fd14f40aa | 6,859 | py | Python | lib/src/klio/transforms/core.py | gaybro8777/klio | e14055fba73f275ebbe7b3b64cc43beaa4ac2f69 | [
"Apache-2.0"
] | null | null | null | lib/src/klio/transforms/core.py | gaybro8777/klio | e14055fba73f275ebbe7b3b64cc43beaa4ac2f69 | [
"Apache-2.0"
] | null | null | null | lib/src/klio/transforms/core.py | gaybro8777/klio | e14055fba73f275ebbe7b3b64cc43beaa4ac2f69 | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 Spotify AB
#
# 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 __main__
import glob
import logging
import os
import threading
import yaml
from klio_core import config
from klio_core.proto import klio_pb2
from klio.metrics import client as metrics_client
from klio.metrics import logger as metrics_logger
from klio.metrics import stackdriver
class RunConfig(object):
_thread_local = threading.local()
@classmethod
def _load_config_from_file(cls):
# [Klio v2] this may get expensive, to always be reading config
# from a file. Can this be replaced by something in memory
# that's also globally accessible?
klio_job_file = "/usr/src/config/.effective-klio-job.yaml"
# for backwards compatibility, and user is using setup.py and we
# have to find it somewhere...
if not os.path.exists(klio_job_file):
# use iterator so we don't waste time searching everywhere upfront
files = glob.iglob("/usr/**/klio-job.yaml", recursive=True)
for f in files:
klio_job_file = f
# only grab the first one
break
with open(klio_job_file, "r") as f:
all_config_data = yaml.safe_load(f)
return config.KlioConfig(all_config_data)
# NOTE: for now this approach is not being used (and may be removed in the
# future)
@classmethod
def _get_via_main_session(cls):
if hasattr(__main__, "run_config"):
return __main__.run_config
else:
raise Exception(
"Attempt to access RunConfig before it was set. This likely"
" means something was imported before RunConfig was set."
)
@classmethod
def _get_via_thread_local(cls):
klio_config = getattr(cls._thread_local, "klio_config", None)
if not klio_config:
cls._thread_local.klio_config = cls._load_config_from_file()
return cls._thread_local.klio_config
@classmethod
def get(cls):
return cls._get_via_thread_local()
@classmethod
def set(cls, config):
__main__.run_config = config
class KlioContext(object):
"""Context related to the currently running job.
Available to transforms via one of the :ref:`KlioContext decorators
<klio-context-decorators>`.
"""
_thread_local = threading.local()
def __init__(self):
self.__transform_name = None
def _create_klio_job_obj(self):
klio_job = klio_pb2.KlioJob()
klio_job.job_name = self.config.job_name
klio_job.gcp_project = self.config.pipeline_options.project
klio_job_str = klio_job.SerializeToString()
return klio_job_str
def _get_metrics_registry(self):
clients = []
use_logger, use_stackdriver = None, None
metrics_config = self.config.job_config.metrics
# use_logger and use_stackdriver could be False (turn off),
# None (use default config), or a dict of configured values
use_logger = metrics_config.get("logger")
use_stackdriver = metrics_config.get("stackdriver_logger")
# TODO: set runner in OS environment (via klio-exec), since
# the runner defined in config could be overwritten via
# `--direct-runner`.
# i.e.: runner = os.getenv("BEAM_RUNNER", "").lower()
runner = self.config.pipeline_options.runner
if "dataflow" in runner.lower():
# Must explicitly compare to `False` since `None` could be
# the user accepting default config.
# If explicitly false, then just disable logger underneath SD
if use_stackdriver is not False:
sd_client = stackdriver.StackdriverLogMetricsClient(
self.config
)
clients.append(sd_client)
else:
# if use_stackdriver is explicitly false, then make sure
# logger client is disabled since the stackdriver client
# inherits the logger client
use_logger = False
if not len(clients): # setup default client
disabled = False
# User might disable the logger, but we still need a relay
# client if all other relay clients are disabled. This allows
# folks to silence metrics but not need to remove code that
# interacts with `_klio.metrics`.
# Must explicitly compare to `False` since `None` could be
# the user accepting default config
if use_logger is False:
disabled = True
logger_client = metrics_logger.MetricsLoggerClient(
self.config, disabled=disabled
)
clients.append(logger_client)
return metrics_client.MetricsRegistry(
clients, transform_name=self._transform_name
)
@property
def config(self):
"""A ``KlioConfig`` instance representing the job's configuration."""
return RunConfig.get()
@property
def job(self):
"""An instance of :ref:`kliojob` of the current job."""
klio_job = getattr(self._thread_local, "klio_job", None)
if not klio_job:
self._thread_local.klio_job = self._create_klio_job_obj()
return self._thread_local.klio_job
@property
def logger(self):
"""A namespaced logger.
Equivalent to ``logging.getLogger("klio")``.
"""
klio_logger = getattr(self._thread_local, "klio_logger", None)
if not klio_logger:
self._thread_local.klio_logger = logging.getLogger("klio")
return self._thread_local.klio_logger
@property
def metrics(self):
"""A metrics registry instance.
See :ref:`metrics <metrics>` for more information."""
metrics_registry = getattr(self._thread_local, "klio_metrics", None)
if not metrics_registry:
self._thread_local.klio_metrics = self._get_metrics_registry()
return self._thread_local.klio_metrics
# <-- private/internal attributes -->
@property
def _transform_name(self):
return self.__transform_name
@_transform_name.setter
def _transform_name(self, name):
self.__transform_name = name
| 35.53886 | 78 | 0.648637 |
import __main__
import glob
import logging
import os
import threading
import yaml
from klio_core import config
from klio_core.proto import klio_pb2
from klio.metrics import client as metrics_client
from klio.metrics import logger as metrics_logger
from klio.metrics import stackdriver
class RunConfig(object):
_thread_local = threading.local()
@classmethod
def _load_config_from_file(cls):
klio_job_file = "/usr/src/config/.effective-klio-job.yaml"
# for backwards compatibility, and user is using setup.py and we
# have to find it somewhere...
if not os.path.exists(klio_job_file):
# use iterator so we don't waste time searching everywhere upfront
files = glob.iglob("/usr/**/klio-job.yaml", recursive=True)
for f in files:
klio_job_file = f
break
with open(klio_job_file, "r") as f:
all_config_data = yaml.safe_load(f)
return config.KlioConfig(all_config_data)
@classmethod
def _get_via_main_session(cls):
if hasattr(__main__, "run_config"):
return __main__.run_config
else:
raise Exception(
"Attempt to access RunConfig before it was set. This likely"
" means something was imported before RunConfig was set."
)
@classmethod
def _get_via_thread_local(cls):
klio_config = getattr(cls._thread_local, "klio_config", None)
if not klio_config:
cls._thread_local.klio_config = cls._load_config_from_file()
return cls._thread_local.klio_config
@classmethod
def get(cls):
return cls._get_via_thread_local()
@classmethod
def set(cls, config):
__main__.run_config = config
class KlioContext(object):
_thread_local = threading.local()
def __init__(self):
self.__transform_name = None
def _create_klio_job_obj(self):
klio_job = klio_pb2.KlioJob()
klio_job.job_name = self.config.job_name
klio_job.gcp_project = self.config.pipeline_options.project
klio_job_str = klio_job.SerializeToString()
return klio_job_str
def _get_metrics_registry(self):
clients = []
use_logger, use_stackdriver = None, None
metrics_config = self.config.job_config.metrics
use_logger = metrics_config.get("logger")
use_stackdriver = metrics_config.get("stackdriver_logger")
runner = self.config.pipeline_options.runner
if "dataflow" in runner.lower():
if use_stackdriver is not False:
sd_client = stackdriver.StackdriverLogMetricsClient(
self.config
)
clients.append(sd_client)
else:
use_logger = False
if not len(clients):
disabled = False
if use_logger is False:
disabled = True
logger_client = metrics_logger.MetricsLoggerClient(
self.config, disabled=disabled
)
clients.append(logger_client)
return metrics_client.MetricsRegistry(
clients, transform_name=self._transform_name
)
@property
def config(self):
return RunConfig.get()
@property
def job(self):
klio_job = getattr(self._thread_local, "klio_job", None)
if not klio_job:
self._thread_local.klio_job = self._create_klio_job_obj()
return self._thread_local.klio_job
@property
def logger(self):
klio_logger = getattr(self._thread_local, "klio_logger", None)
if not klio_logger:
self._thread_local.klio_logger = logging.getLogger("klio")
return self._thread_local.klio_logger
@property
def metrics(self):
metrics_registry = getattr(self._thread_local, "klio_metrics", None)
if not metrics_registry:
self._thread_local.klio_metrics = self._get_metrics_registry()
return self._thread_local.klio_metrics
@property
def _transform_name(self):
return self.__transform_name
@_transform_name.setter
def _transform_name(self, name):
self.__transform_name = name
| true | true |
f723892226135464b2c3c112e24e1665bfad3147 | 289 | py | Python | learn-to-code-with-python/08-Control-Flow/the-bool-function-truthiness-and-falsiness.py | MaciejZurek/python_practicing | 0a426f2aed151573e1f8678e0239ff596d92bbde | [
"MIT"
] | null | null | null | learn-to-code-with-python/08-Control-Flow/the-bool-function-truthiness-and-falsiness.py | MaciejZurek/python_practicing | 0a426f2aed151573e1f8678e0239ff596d92bbde | [
"MIT"
] | null | null | null | learn-to-code-with-python/08-Control-Flow/the-bool-function-truthiness-and-falsiness.py | MaciejZurek/python_practicing | 0a426f2aed151573e1f8678e0239ff596d92bbde | [
"MIT"
] | null | null | null | if 10 > 3:
print("Hello")
if 3:
print("Yes, it's 3")
if 0:
print("This won't execute")
if -1:
print("Will it print?")
if "hello":
print("interesting")
if "":
print("This will not print either")
if " ":
print("aaa")
print(bool(1)) # rzutowanie na boolean
| 12.565217 | 39 | 0.564014 | if 10 > 3:
print("Hello")
if 3:
print("Yes, it's 3")
if 0:
print("This won't execute")
if -1:
print("Will it print?")
if "hello":
print("interesting")
if "":
print("This will not print either")
if " ":
print("aaa")
print(bool(1))
| true | true |
f7238a0d2a2db0352b919fd8d9f2ced545ef73c3 | 8,990 | py | Python | src/eipcmd.py | CloudVelox/simple-cloud-shell | 48548b4c24d99a8fe3866f552e1b4e5be2924a62 | [
"Apache-2.0"
] | null | null | null | src/eipcmd.py | CloudVelox/simple-cloud-shell | 48548b4c24d99a8fe3866f552e1b4e5be2924a62 | [
"Apache-2.0"
] | null | null | null | src/eipcmd.py | CloudVelox/simple-cloud-shell | 48548b4c24d99a8fe3866f552e1b4e5be2924a62 | [
"Apache-2.0"
] | null | null | null | #
# Copyright 2014-2016 CloudVelox Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
#
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""This module contains the implementation of the 'eip' command
"""
import getopt
import common
from common import CommandError
from common import DisplayOptions
from common import CommandOutput
from common import ResourceSelector
from common import optional
class EIPCommand(common.BaseCommand):
"""Implements the 'eip' command
"""
@staticmethod
def __eip_display(address, disp, pg):
"""Display info about the specified address
"""
if disp.display == DisplayOptions.LONG:
pg.prt("%-16s %-10s %-12s %-16s %s",
address.public_ip,
address.domain,
optional(address.instance_id),
optional(address.private_ip_address),
optional(address.allocation_id)
)
elif disp.display == DisplayOptions.EXTENDED:
pg.prt("%s", address.public_ip)
pg.prt("%15s : %s", "Domain", address.domain)
if address.instance_id:
pg.prt("%15s : %s", "Instance", address.instance_id)
if address.allocation_id:
pg.prt("%15s : %s", "Allocation", address.allocation_id)
if address.association_id:
pg.prt("%15s : %s", "Association", address.association_id)
if address.network_interface_id:
pg.prt("%15s : %s", "Interface", address.network_interface_id)
if address.private_ip_address:
pg.prt("%15s : %s", "Private-IP", address.private_ip_address)
else:
pg.prt("%s", address.public_ip)
def __eip_list_cmd(self, region, selector, disp):
"""Implements the eip list functionality
"""
if not selector.has_selection():
return
ec2_conn = self.get_ec2_conn(region)
address_list = ec2_conn.get_all_addresses(
addresses=selector.resource_id_list)
with CommandOutput() as pg:
for address in address_list:
self.__eip_display(address, disp, pg)
def __eip_allocate(self, region, in_vpc, eip_list):
"""Implements the EIP allocation functionality
"""
if eip_list:
print "No arguments expected"
return
ec2_conn = self.get_ec2_conn(region)
domain = "vpc" if in_vpc else None
address = ec2_conn.allocate_address(domain)
if in_vpc:
print "%-16s %-12s" % (address.public_ip, address.allocation_id)
else:
print address.public_ip
@staticmethod
def __eip_release_one(ec2_conn, address):
"""Release the specified address
"""
if address.domain == 'vpc':
res = ec2_conn.release_address(allocation_id=address.allocation_id)
else:
res = ec2_conn.release_address(public_ip=address.public_ip)
if not res:
print "Failed to release %s" % (address.public_ip,)
def __eip_release(self, region, eip_list):
"""Implements the EIP release functionality
"""
ec2_conn = self.get_ec2_conn(region)
address_list = ec2_conn.get_all_addresses(addresses=eip_list)
for address in address_list:
self.__eip_release_one(ec2_conn, address)
def __eip_associate(self, region, move_address, arg_list):
"""Associate an IP address with an instance.
arg_list[0] is the EIP (aka public_ip).
"""
try:
eip_address = arg_list.pop(0)
except IndexError:
raise CommandError("Missing EIP")
instance_id = None
eni_id = None
private_ip = None
for arg in arg_list:
if arg.startswith("i-"):
instance_id = arg
elif arg.startswith("eni-"):
eni_id = arg
else:
private_ip = arg
if instance_id is None and eni_id is None:
raise CommandError(
"Either an instance-id or an interface id must be specified")
if instance_id is not None and eni_id is not None:
raise CommandError(
"Either an instance-id or an interface id "
"must be specified; not both")
ec2_conn = self.get_ec2_conn(region)
address_list = ec2_conn.get_all_addresses(addresses=[eip_address])
address = address_list[0]
if address.allocation_id:
print instance_id, private_ip, eni_id, move_address
ec2_conn.associate_address(instance_id=instance_id,
allocation_id=address.allocation_id,
private_ip_address=private_ip,
network_interface_id=eni_id,
allow_reassociation=move_address)
else:
ec2_conn.associate_address(instance_id=instance_id,
public_ip=address.public_ip,
private_ip_address=private_ip,
network_interface_id=eni_id,
allow_reassociation=move_address)
def __eip_disassociate(self, region, arg_list):
"""Associate an IP address with an instance
"""
ec2_conn = self.get_ec2_conn(region)
address_list = ec2_conn.get_all_addresses(addresses=arg_list)
for address in address_list:
if address.association_id:
ec2_conn.disassociate_address(
association_id=address.association_id)
else:
ec2_conn.disassociate_address(public_ip=address.public_ip)
def __eip_cmd(self, argv):
"""Implements the eip command
"""
in_vpc = False
cmd_allocate = False
cmd_release = False
cmd_associate = False
cmd_disassociate = False
move_address = False
disp = DisplayOptions()
selector = ResourceSelector()
region = None
opt_list, args = getopt.getopt(argv, "Aaf:lmRr:StXxV")
if opt_list:
for opt in opt_list:
if opt[0] == '-a':
selector.select_all = True
elif opt[0] == '-A':
cmd_allocate = True
elif opt[0] == '-f':
selector.add_filter_spec(opt[1])
elif opt[0] == '-l':
disp.display = DisplayOptions.LONG
elif opt[0] == '-m':
move_address = True
elif opt[0] == '-R':
cmd_release = True
elif opt[0] == '-r':
region = opt[1]
elif opt[0] == '-S':
cmd_associate = True
elif opt[0] == '-t':
disp.display_tags = True
elif opt[0] == '-X':
cmd_disassociate = True
elif opt[0] == '-x':
disp.display = DisplayOptions.EXTENDED
elif opt[0] == '-V':
in_vpc = True
if cmd_allocate:
self.__eip_allocate(region, in_vpc, args)
elif cmd_release:
self.__eip_release(region, args)
elif cmd_associate:
self.__eip_associate(region, move_address, args)
elif cmd_disassociate:
self.__eip_disassociate(region, args)
else:
selector.resource_id_list = args
self.__eip_list_cmd(region, selector, disp)
def do_eip(self, ln):
"""
eip [std-options] [list-options] [-A] [-m] [-v] [eip] ...
Options:
-A : allocate an elastic IP address
-R : release an elastic IP address
-S : associate an IP address with an instance
-X : disassociate an IP address from an instance
-m : move an EIP between the instance's interfaces
-v : allocate VPC-suitable address
The -S option expects an EIP address followed by either an instance-id or
a network-interface-id (eni-id), and optionally a private IP address of
the instance.
The -X option expects a list of EIP addresses (can be just one).
"""
self.dispatch(self.__eip_cmd, ln)
| 38.583691 | 79 | 0.568187 |
"""This module contains the implementation of the 'eip' command
"""
import getopt
import common
from common import CommandError
from common import DisplayOptions
from common import CommandOutput
from common import ResourceSelector
from common import optional
class EIPCommand(common.BaseCommand):
"""Implements the 'eip' command
"""
@staticmethod
def __eip_display(address, disp, pg):
"""Display info about the specified address
"""
if disp.display == DisplayOptions.LONG:
pg.prt("%-16s %-10s %-12s %-16s %s",
address.public_ip,
address.domain,
optional(address.instance_id),
optional(address.private_ip_address),
optional(address.allocation_id)
)
elif disp.display == DisplayOptions.EXTENDED:
pg.prt("%s", address.public_ip)
pg.prt("%15s : %s", "Domain", address.domain)
if address.instance_id:
pg.prt("%15s : %s", "Instance", address.instance_id)
if address.allocation_id:
pg.prt("%15s : %s", "Allocation", address.allocation_id)
if address.association_id:
pg.prt("%15s : %s", "Association", address.association_id)
if address.network_interface_id:
pg.prt("%15s : %s", "Interface", address.network_interface_id)
if address.private_ip_address:
pg.prt("%15s : %s", "Private-IP", address.private_ip_address)
else:
pg.prt("%s", address.public_ip)
def __eip_list_cmd(self, region, selector, disp):
"""Implements the eip list functionality
"""
if not selector.has_selection():
return
ec2_conn = self.get_ec2_conn(region)
address_list = ec2_conn.get_all_addresses(
addresses=selector.resource_id_list)
with CommandOutput() as pg:
for address in address_list:
self.__eip_display(address, disp, pg)
def __eip_allocate(self, region, in_vpc, eip_list):
"""Implements the EIP allocation functionality
"""
if eip_list:
print "No arguments expected"
return
ec2_conn = self.get_ec2_conn(region)
domain = "vpc" if in_vpc else None
address = ec2_conn.allocate_address(domain)
if in_vpc:
print "%-16s %-12s" % (address.public_ip, address.allocation_id)
else:
print address.public_ip
@staticmethod
def __eip_release_one(ec2_conn, address):
"""Release the specified address
"""
if address.domain == 'vpc':
res = ec2_conn.release_address(allocation_id=address.allocation_id)
else:
res = ec2_conn.release_address(public_ip=address.public_ip)
if not res:
print "Failed to release %s" % (address.public_ip,)
def __eip_release(self, region, eip_list):
"""Implements the EIP release functionality
"""
ec2_conn = self.get_ec2_conn(region)
address_list = ec2_conn.get_all_addresses(addresses=eip_list)
for address in address_list:
self.__eip_release_one(ec2_conn, address)
def __eip_associate(self, region, move_address, arg_list):
"""Associate an IP address with an instance.
arg_list[0] is the EIP (aka public_ip).
"""
try:
eip_address = arg_list.pop(0)
except IndexError:
raise CommandError("Missing EIP")
instance_id = None
eni_id = None
private_ip = None
for arg in arg_list:
if arg.startswith("i-"):
instance_id = arg
elif arg.startswith("eni-"):
eni_id = arg
else:
private_ip = arg
if instance_id is None and eni_id is None:
raise CommandError(
"Either an instance-id or an interface id must be specified")
if instance_id is not None and eni_id is not None:
raise CommandError(
"Either an instance-id or an interface id "
"must be specified; not both")
ec2_conn = self.get_ec2_conn(region)
address_list = ec2_conn.get_all_addresses(addresses=[eip_address])
address = address_list[0]
if address.allocation_id:
print instance_id, private_ip, eni_id, move_address
ec2_conn.associate_address(instance_id=instance_id,
allocation_id=address.allocation_id,
private_ip_address=private_ip,
network_interface_id=eni_id,
allow_reassociation=move_address)
else:
ec2_conn.associate_address(instance_id=instance_id,
public_ip=address.public_ip,
private_ip_address=private_ip,
network_interface_id=eni_id,
allow_reassociation=move_address)
def __eip_disassociate(self, region, arg_list):
"""Associate an IP address with an instance
"""
ec2_conn = self.get_ec2_conn(region)
address_list = ec2_conn.get_all_addresses(addresses=arg_list)
for address in address_list:
if address.association_id:
ec2_conn.disassociate_address(
association_id=address.association_id)
else:
ec2_conn.disassociate_address(public_ip=address.public_ip)
def __eip_cmd(self, argv):
"""Implements the eip command
"""
in_vpc = False
cmd_allocate = False
cmd_release = False
cmd_associate = False
cmd_disassociate = False
move_address = False
disp = DisplayOptions()
selector = ResourceSelector()
region = None
opt_list, args = getopt.getopt(argv, "Aaf:lmRr:StXxV")
if opt_list:
for opt in opt_list:
if opt[0] == '-a':
selector.select_all = True
elif opt[0] == '-A':
cmd_allocate = True
elif opt[0] == '-f':
selector.add_filter_spec(opt[1])
elif opt[0] == '-l':
disp.display = DisplayOptions.LONG
elif opt[0] == '-m':
move_address = True
elif opt[0] == '-R':
cmd_release = True
elif opt[0] == '-r':
region = opt[1]
elif opt[0] == '-S':
cmd_associate = True
elif opt[0] == '-t':
disp.display_tags = True
elif opt[0] == '-X':
cmd_disassociate = True
elif opt[0] == '-x':
disp.display = DisplayOptions.EXTENDED
elif opt[0] == '-V':
in_vpc = True
if cmd_allocate:
self.__eip_allocate(region, in_vpc, args)
elif cmd_release:
self.__eip_release(region, args)
elif cmd_associate:
self.__eip_associate(region, move_address, args)
elif cmd_disassociate:
self.__eip_disassociate(region, args)
else:
selector.resource_id_list = args
self.__eip_list_cmd(region, selector, disp)
def do_eip(self, ln):
"""
eip [std-options] [list-options] [-A] [-m] [-v] [eip] ...
Options:
-A : allocate an elastic IP address
-R : release an elastic IP address
-S : associate an IP address with an instance
-X : disassociate an IP address from an instance
-m : move an EIP between the instance's interfaces
-v : allocate VPC-suitable address
The -S option expects an EIP address followed by either an instance-id or
a network-interface-id (eni-id), and optionally a private IP address of
the instance.
The -X option expects a list of EIP addresses (can be just one).
"""
self.dispatch(self.__eip_cmd, ln)
| false | true |
f7238a6d4e5cd8d4b14e0a203fa2488a811e8cca | 1,702 | py | Python | fcntest.py | alexjercan/unsupervised-segmentation | 172273fef52df3771d8de7c167fb0910f4079733 | [
"MIT"
] | 1 | 2022-01-13T11:56:59.000Z | 2022-01-13T11:56:59.000Z | fcntest.py | alexjercan/unsupervised-segmentation | 172273fef52df3771d8de7c167fb0910f4079733 | [
"MIT"
] | null | null | null | fcntest.py | alexjercan/unsupervised-segmentation | 172273fef52df3771d8de7c167fb0910f4079733 | [
"MIT"
] | null | null | null | from metrics import MetricFunctionNYUv2, print_single_error
from model import SupervisedLossFunction
from torch.utils.data import DataLoader
from torchvision import transforms
from nyuv2 import NYUv2
from tqdm import tqdm
from general import generate_layers, load_checkpoint, tensors_to_device
import torch
from torchvision.models.segmentation.segmentation import fcn_resnet50
num_layers = 3
def runmodel(model, imgs, depths):
layers = generate_layers(imgs, depths, num_layers)
x = [model(x)['out'] for x in layers]
return torch.stack(x, dim=-1)
def run_test_nyuv2(model, dataloader, loss_fn, metric_fn):
loop = tqdm(dataloader, position=0, leave=True)
for i, tensors in enumerate(loop):
imgs, seg13, normals, depths = tensors_to_device(tensors, DEVICE)
with torch.no_grad():
predictions = runmodel(model, imgs, depths)
loss_fn(predictions, (normals, depths))
metric_fn.evaluate(predictions, (seg13, normals, depths))
loop.close()
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
model = fcn_resnet50(pretrained=False, num_classes=14)
model = model.to(DEVICE)
epoch_idx, model = load_checkpoint(model, "fcnmodel.pth", DEVICE)
t = transforms.Compose([transforms.Resize((256, 256)), transforms.ToTensor()])
test_dataset = NYUv2(root="../NYUv2", download=True, rgb_transform=t, seg_transform=t, sn_transform=t, depth_transform=t, train=False)
dataloader = DataLoader(test_dataset, batch_size=2, shuffle=True)
loss_fn = SupervisedLossFunction()
metric_fn = MetricFunctionNYUv2(2)
model.eval()
run_test_nyuv2(model, dataloader, loss_fn, metric_fn)
print_single_error(epoch_idx, loss_fn.show(), metric_fn.show()) | 35.458333 | 134 | 0.754994 | from metrics import MetricFunctionNYUv2, print_single_error
from model import SupervisedLossFunction
from torch.utils.data import DataLoader
from torchvision import transforms
from nyuv2 import NYUv2
from tqdm import tqdm
from general import generate_layers, load_checkpoint, tensors_to_device
import torch
from torchvision.models.segmentation.segmentation import fcn_resnet50
num_layers = 3
def runmodel(model, imgs, depths):
layers = generate_layers(imgs, depths, num_layers)
x = [model(x)['out'] for x in layers]
return torch.stack(x, dim=-1)
def run_test_nyuv2(model, dataloader, loss_fn, metric_fn):
loop = tqdm(dataloader, position=0, leave=True)
for i, tensors in enumerate(loop):
imgs, seg13, normals, depths = tensors_to_device(tensors, DEVICE)
with torch.no_grad():
predictions = runmodel(model, imgs, depths)
loss_fn(predictions, (normals, depths))
metric_fn.evaluate(predictions, (seg13, normals, depths))
loop.close()
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
model = fcn_resnet50(pretrained=False, num_classes=14)
model = model.to(DEVICE)
epoch_idx, model = load_checkpoint(model, "fcnmodel.pth", DEVICE)
t = transforms.Compose([transforms.Resize((256, 256)), transforms.ToTensor()])
test_dataset = NYUv2(root="../NYUv2", download=True, rgb_transform=t, seg_transform=t, sn_transform=t, depth_transform=t, train=False)
dataloader = DataLoader(test_dataset, batch_size=2, shuffle=True)
loss_fn = SupervisedLossFunction()
metric_fn = MetricFunctionNYUv2(2)
model.eval()
run_test_nyuv2(model, dataloader, loss_fn, metric_fn)
print_single_error(epoch_idx, loss_fn.show(), metric_fn.show()) | true | true |
f7238b5b5c564f9712d0f7d3d3703ab811f151d6 | 2,964 | py | Python | ndflow/util.py | dccastro/NDFlow | 1e46cf00e78068d3c78281b42aa8aaed310e53c9 | [
"MIT"
] | 6 | 2018-10-18T23:51:33.000Z | 2021-03-12T16:44:51.000Z | ndflow/util.py | dccastro/NDFlow | 1e46cf00e78068d3c78281b42aa8aaed310e53c9 | [
"MIT"
] | 1 | 2018-11-05T01:52:40.000Z | 2018-11-07T11:34:47.000Z | ndflow/util.py | dccastro/NDFlow | 1e46cf00e78068d3c78281b42aa8aaed310e53c9 | [
"MIT"
] | 1 | 2019-03-04T13:35:20.000Z | 2019-03-04T13:35:20.000Z | import os
import numpy as np
import ndflow
from ndflow.models.mixture import MixtureModel
def list_images(imgs_dir):
import SimpleITK as sitk
for filename in os.listdir(imgs_dir):
path = os.path.join(imgs_dir, filename)
reader = sitk.ImageFileReader()
reader.SetFileName(path)
try:
reader.ReadImageInformation()
yield filename
except RuntimeError:
continue # Probably not an image file, skip
def list_gmms(gmms_dir):
return (filename for filename in os.listdir(gmms_dir)
if filename.endswith(ndflow.GMM_FILENAME_SUFFIX))
def list_matches(matches_dir):
return (filename for filename in os.listdir(matches_dir)
if filename.endswith(ndflow.MATCH_FILENAME_SUFFIX))
def quantise(data, levels: int = None):
"""Quantise data into discrete values, similarly to a histogram.
Parameters
----------
data : array_like
Input data array.
levels : int or None, optional
Number of levels at which to quantise the data. If `None`, data will be cast to `int` and
integer values in the data range will be used.
Returns
-------
values : np.ndarray
Values to which `data` was quantised.
weights : np.ndarray
Array of counts of items collapsed into each of the `values`.
"""
data = np.asarray(data).flatten()
if levels is None:
data = data.astype(int)
data_min = data.min()
weights = np.bincount(data - data_min)
values = np.arange(len(weights), dtype=int) + data_min
else:
weights, bins = np.histogram(data, bins=levels, density=False)
values = .5 * (bins[:-1] + bins[1:]) # Bin centres
return values, weights
def plot_gmm(gmm: MixtureModel, x, values=None, weights=None, ax=None, **kwargs):
"""Plot a Gaussian mixture model (GMM) density.
Parameters
----------
gmm : ndflow.models.mixture.MixtureModel
x : array_like
Values at which to evaluate the GMM likelihood.
values, weights : np.ndarray, optional
Quantised data distribution as computed by `quantise()`. If given, will plot a histogram
alongside the GMM density.
ax : matplotlib.axes.Axes, optional
Axes onto which to draw. Defaults to the current axes.
kwargs
Keyword arguments passed through to the `plot()` call.
"""
import matplotlib.pyplot as plt
if ax is None:
ax = plt.gca()
if values is not None and weights is not None:
# Compute histogram bars' parameters in case values are not evenly spaced
widths = np.empty(values.shape[0])
widths[1:] = values[1:] - values[:-1]
widths[0] = widths[1]
edges = values - .5 * widths
heights = weights / (weights.sum() * widths)
ax.bar(edges, heights, widths, align='edge', linewidth=0, alpha=.5)
ax.plot(x, gmm.marginal_likelihood(x), **kwargs)
| 31.2 | 97 | 0.6417 | import os
import numpy as np
import ndflow
from ndflow.models.mixture import MixtureModel
def list_images(imgs_dir):
import SimpleITK as sitk
for filename in os.listdir(imgs_dir):
path = os.path.join(imgs_dir, filename)
reader = sitk.ImageFileReader()
reader.SetFileName(path)
try:
reader.ReadImageInformation()
yield filename
except RuntimeError:
continue
def list_gmms(gmms_dir):
return (filename for filename in os.listdir(gmms_dir)
if filename.endswith(ndflow.GMM_FILENAME_SUFFIX))
def list_matches(matches_dir):
return (filename for filename in os.listdir(matches_dir)
if filename.endswith(ndflow.MATCH_FILENAME_SUFFIX))
def quantise(data, levels: int = None):
data = np.asarray(data).flatten()
if levels is None:
data = data.astype(int)
data_min = data.min()
weights = np.bincount(data - data_min)
values = np.arange(len(weights), dtype=int) + data_min
else:
weights, bins = np.histogram(data, bins=levels, density=False)
values = .5 * (bins[:-1] + bins[1:])
return values, weights
def plot_gmm(gmm: MixtureModel, x, values=None, weights=None, ax=None, **kwargs):
import matplotlib.pyplot as plt
if ax is None:
ax = plt.gca()
if values is not None and weights is not None:
widths = np.empty(values.shape[0])
widths[1:] = values[1:] - values[:-1]
widths[0] = widths[1]
edges = values - .5 * widths
heights = weights / (weights.sum() * widths)
ax.bar(edges, heights, widths, align='edge', linewidth=0, alpha=.5)
ax.plot(x, gmm.marginal_likelihood(x), **kwargs)
| true | true |
f7238b7c15908087282d882259e37dedefe55ab5 | 506 | py | Python | python/token_generator/token_generator.py | trypolis464/random_scripts | 9832e2b793e49de0bd40c975faaea216eb1903e9 | [
"MIT"
] | null | null | null | python/token_generator/token_generator.py | trypolis464/random_scripts | 9832e2b793e49de0bd40c975faaea216eb1903e9 | [
"MIT"
] | null | null | null | python/token_generator/token_generator.py | trypolis464/random_scripts | 9832e2b793e49de0bd40c975faaea216eb1903e9 | [
"MIT"
] | null | null | null | # token_generator. Generate random strings.
#
# Copyright (C) 2021, Ty Gillespie. All rights reserved.
# MIT License.
import random
def generate(length = 8):
"""Generates a token of the given length. The default is 8."""
# Feel free to change this based on what you need your tokens to contain.
SYMBOLS = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890"
final = ""
for i in range(length):
final += SYMBOLS[random.randint(0, len(SYMBOLS) - 1)]
return final
| 31.625 | 78 | 0.70751 |
import random
def generate(length = 8):
SYMBOLS = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890"
final = ""
for i in range(length):
final += SYMBOLS[random.randint(0, len(SYMBOLS) - 1)]
return final
| true | true |
f7238c0e0ff13537a51277894506e248909f7d8c | 1,610 | py | Python | azure/mgmt/compute/v2015_06_15/models/api_error.py | EnjoyLifeFund/macHighSierra-py36-pkgs | 5668b5785296b314ea1321057420bcd077dba9ea | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | 1 | 2022-01-25T22:52:58.000Z | 2022-01-25T22:52:58.000Z | azure/mgmt/compute/v2015_06_15/models/api_error.py | EnjoyLifeFund/Debian_py36_packages | 1985d4c73fabd5f08f54b922e73a9306e09c77a5 | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | null | null | null | azure/mgmt/compute/v2015_06_15/models/api_error.py | EnjoyLifeFund/Debian_py36_packages | 1985d4c73fabd5f08f54b922e73a9306e09c77a5 | [
"BSD-3-Clause",
"BSD-2-Clause",
"MIT"
] | null | null | null | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class ApiError(Model):
"""Api error.
:param details: The Api error details
:type details: list of :class:`ApiErrorBase
<azure.mgmt.compute.v2015_06_15.models.ApiErrorBase>`
:param innererror: The Api inner error
:type innererror: :class:`InnerError
<azure.mgmt.compute.v2015_06_15.models.InnerError>`
:param code: The error code.
:type code: str
:param target: The target of the particular error.
:type target: str
:param message: The error message.
:type message: str
"""
_attribute_map = {
'details': {'key': 'details', 'type': '[ApiErrorBase]'},
'innererror': {'key': 'innererror', 'type': 'InnerError'},
'code': {'key': 'code', 'type': 'str'},
'target': {'key': 'target', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
}
def __init__(self, details=None, innererror=None, code=None, target=None, message=None):
self.details = details
self.innererror = innererror
self.code = code
self.target = target
self.message = message
| 35 | 92 | 0.589441 |
from msrest.serialization import Model
class ApiError(Model):
_attribute_map = {
'details': {'key': 'details', 'type': '[ApiErrorBase]'},
'innererror': {'key': 'innererror', 'type': 'InnerError'},
'code': {'key': 'code', 'type': 'str'},
'target': {'key': 'target', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
}
def __init__(self, details=None, innererror=None, code=None, target=None, message=None):
self.details = details
self.innererror = innererror
self.code = code
self.target = target
self.message = message
| true | true |
f7238c591b376df4ffed31b3f8cd6d3068f4258a | 338 | py | Python | z.Box of stuffs/0.Completed projects/Stock updater/Execution/send_sms.py | monacotime/dump_dump_dump | 51d6b4f58fe25416911a3bf545d326046fb6a475 | [
"MIT"
] | null | null | null | z.Box of stuffs/0.Completed projects/Stock updater/Execution/send_sms.py | monacotime/dump_dump_dump | 51d6b4f58fe25416911a3bf545d326046fb6a475 | [
"MIT"
] | null | null | null | z.Box of stuffs/0.Completed projects/Stock updater/Execution/send_sms.py | monacotime/dump_dump_dump | 51d6b4f58fe25416911a3bf545d326046fb6a475 | [
"MIT"
] | null | null | null | from twilio.rest import Client
from credentials import account_sid, auth_token, my_cell, my_twilio
# Find these values at https://twilio.com/user/account
client = Client(account_sid, auth_token)
my_msg = "Hi this is kabir"
message = client.messages.create(to=my_cell, from_=my_twilio,
body=my_msg)
| 30.727273 | 67 | 0.704142 | from twilio.rest import Client
from credentials import account_sid, auth_token, my_cell, my_twilio
client = Client(account_sid, auth_token)
my_msg = "Hi this is kabir"
message = client.messages.create(to=my_cell, from_=my_twilio,
body=my_msg)
| true | true |
f7238f02f65543d61ec937f28f164450253dfca2 | 25,530 | py | Python | mmseg/models/backbones/resnet.py | AIVIS-inc/mmsegmentation | 7d305d76f1ac7c96606d3ae7cf59d37a816d28e0 | [
"Apache-2.0"
] | 12 | 2021-08-31T17:20:18.000Z | 2022-03-10T20:58:59.000Z | mmseg/models/backbones/resnet.py | Junjun2016/LiteHRNet | e2b13de52e970215be566067cab7bd880010f062 | [
"Apache-2.0"
] | null | null | null | mmseg/models/backbones/resnet.py | Junjun2016/LiteHRNet | e2b13de52e970215be566067cab7bd880010f062 | [
"Apache-2.0"
] | 1 | 2021-09-12T03:14:22.000Z | 2021-09-12T03:14:22.000Z | import warnings
import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn import build_conv_layer, build_norm_layer, build_plugin_layer
from mmcv.runner import BaseModule
from mmcv.utils.parrots_wrapper import _BatchNorm
from ..builder import BACKBONES
from ..utils import ResLayer
class BasicBlock(BaseModule):
"""Basic block for ResNet."""
expansion = 1
def __init__(self,
inplanes,
planes,
stride=1,
dilation=1,
downsample=None,
style='pytorch',
with_cp=False,
conv_cfg=None,
norm_cfg=dict(type='BN'),
dcn=None,
plugins=None,
init_cfg=None):
super(BasicBlock, self).__init__(init_cfg)
assert dcn is None, 'Not implemented yet.'
assert plugins is None, 'Not implemented yet.'
self.norm1_name, norm1 = build_norm_layer(norm_cfg, planes, postfix=1)
self.norm2_name, norm2 = build_norm_layer(norm_cfg, planes, postfix=2)
self.conv1 = build_conv_layer(
conv_cfg,
inplanes,
planes,
3,
stride=stride,
padding=dilation,
dilation=dilation,
bias=False)
self.add_module(self.norm1_name, norm1)
self.conv2 = build_conv_layer(
conv_cfg, planes, planes, 3, padding=1, bias=False)
self.add_module(self.norm2_name, norm2)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
self.dilation = dilation
self.with_cp = with_cp
@property
def norm1(self):
"""nn.Module: normalization layer after the first convolution layer"""
return getattr(self, self.norm1_name)
@property
def norm2(self):
"""nn.Module: normalization layer after the second convolution layer"""
return getattr(self, self.norm2_name)
def forward(self, x):
"""Forward function."""
def _inner_forward(x):
identity = x
out = self.conv1(x)
out = self.norm1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.norm2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
return out
if self.with_cp and x.requires_grad:
out = cp.checkpoint(_inner_forward, x)
else:
out = _inner_forward(x)
out = self.relu(out)
return out
class Bottleneck(BaseModule):
"""Bottleneck block for ResNet.
If style is "pytorch", the stride-two layer is the 3x3 conv layer, if it is
"caffe", the stride-two layer is the first 1x1 conv layer.
"""
expansion = 4
def __init__(self,
inplanes,
planes,
stride=1,
dilation=1,
downsample=None,
style='pytorch',
with_cp=False,
conv_cfg=None,
norm_cfg=dict(type='BN'),
dcn=None,
plugins=None,
init_cfg=None):
super(Bottleneck, self).__init__(init_cfg)
assert style in ['pytorch', 'caffe']
assert dcn is None or isinstance(dcn, dict)
assert plugins is None or isinstance(plugins, list)
if plugins is not None:
allowed_position = ['after_conv1', 'after_conv2', 'after_conv3']
assert all(p['position'] in allowed_position for p in plugins)
self.inplanes = inplanes
self.planes = planes
self.stride = stride
self.dilation = dilation
self.style = style
self.with_cp = with_cp
self.conv_cfg = conv_cfg
self.norm_cfg = norm_cfg
self.dcn = dcn
self.with_dcn = dcn is not None
self.plugins = plugins
self.with_plugins = plugins is not None
if self.with_plugins:
# collect plugins for conv1/conv2/conv3
self.after_conv1_plugins = [
plugin['cfg'] for plugin in plugins
if plugin['position'] == 'after_conv1'
]
self.after_conv2_plugins = [
plugin['cfg'] for plugin in plugins
if plugin['position'] == 'after_conv2'
]
self.after_conv3_plugins = [
plugin['cfg'] for plugin in plugins
if plugin['position'] == 'after_conv3'
]
if self.style == 'pytorch':
self.conv1_stride = 1
self.conv2_stride = stride
else:
self.conv1_stride = stride
self.conv2_stride = 1
self.norm1_name, norm1 = build_norm_layer(norm_cfg, planes, postfix=1)
self.norm2_name, norm2 = build_norm_layer(norm_cfg, planes, postfix=2)
self.norm3_name, norm3 = build_norm_layer(
norm_cfg, planes * self.expansion, postfix=3)
self.conv1 = build_conv_layer(
conv_cfg,
inplanes,
planes,
kernel_size=1,
stride=self.conv1_stride,
bias=False)
self.add_module(self.norm1_name, norm1)
fallback_on_stride = False
if self.with_dcn:
fallback_on_stride = dcn.pop('fallback_on_stride', False)
if not self.with_dcn or fallback_on_stride:
self.conv2 = build_conv_layer(
conv_cfg,
planes,
planes,
kernel_size=3,
stride=self.conv2_stride,
padding=dilation,
dilation=dilation,
bias=False)
else:
assert self.conv_cfg is None, 'conv_cfg must be None for DCN'
self.conv2 = build_conv_layer(
dcn,
planes,
planes,
kernel_size=3,
stride=self.conv2_stride,
padding=dilation,
dilation=dilation,
bias=False)
self.add_module(self.norm2_name, norm2)
self.conv3 = build_conv_layer(
conv_cfg,
planes,
planes * self.expansion,
kernel_size=1,
bias=False)
self.add_module(self.norm3_name, norm3)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
if self.with_plugins:
self.after_conv1_plugin_names = self.make_block_plugins(
planes, self.after_conv1_plugins)
self.after_conv2_plugin_names = self.make_block_plugins(
planes, self.after_conv2_plugins)
self.after_conv3_plugin_names = self.make_block_plugins(
planes * self.expansion, self.after_conv3_plugins)
def make_block_plugins(self, in_channels, plugins):
"""make plugins for block.
Args:
in_channels (int): Input channels of plugin.
plugins (list[dict]): List of plugins cfg to build.
Returns:
list[str]: List of the names of plugin.
"""
assert isinstance(plugins, list)
plugin_names = []
for plugin in plugins:
plugin = plugin.copy()
name, layer = build_plugin_layer(
plugin,
in_channels=in_channels,
postfix=plugin.pop('postfix', ''))
assert not hasattr(self, name), f'duplicate plugin {name}'
self.add_module(name, layer)
plugin_names.append(name)
return plugin_names
def forward_plugin(self, x, plugin_names):
"""Forward function for plugins."""
out = x
for name in plugin_names:
out = getattr(self, name)(x)
return out
@property
def norm1(self):
"""nn.Module: normalization layer after the first convolution layer"""
return getattr(self, self.norm1_name)
@property
def norm2(self):
"""nn.Module: normalization layer after the second convolution layer"""
return getattr(self, self.norm2_name)
@property
def norm3(self):
"""nn.Module: normalization layer after the third convolution layer"""
return getattr(self, self.norm3_name)
def forward(self, x):
"""Forward function."""
def _inner_forward(x):
identity = x
out = self.conv1(x)
out = self.norm1(out)
out = self.relu(out)
if self.with_plugins:
out = self.forward_plugin(out, self.after_conv1_plugin_names)
out = self.conv2(out)
out = self.norm2(out)
out = self.relu(out)
if self.with_plugins:
out = self.forward_plugin(out, self.after_conv2_plugin_names)
out = self.conv3(out)
out = self.norm3(out)
if self.with_plugins:
out = self.forward_plugin(out, self.after_conv3_plugin_names)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
return out
if self.with_cp and x.requires_grad:
out = cp.checkpoint(_inner_forward, x)
else:
out = _inner_forward(x)
out = self.relu(out)
return out
@BACKBONES.register_module()
class ResNet(BaseModule):
"""ResNet backbone.
Args:
depth (int): Depth of resnet, from {18, 34, 50, 101, 152}.
in_channels (int): Number of input image channels. Default: 3.
stem_channels (int): Number of stem channels. Default: 64.
base_channels (int): Number of base channels of res layer. Default: 64.
num_stages (int): Resnet stages, normally 4. Default: 4.
strides (Sequence[int]): Strides of the first block of each stage.
Default: (1, 2, 2, 2).
dilations (Sequence[int]): Dilation of each stage.
Default: (1, 1, 1, 1).
out_indices (Sequence[int]): Output from which stages.
Default: (0, 1, 2, 3).
style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two
layer is the 3x3 conv layer, otherwise the stride-two layer is
the first 1x1 conv layer. Default: 'pytorch'.
deep_stem (bool): Replace 7x7 conv in input stem with 3 3x3 conv.
Default: False.
avg_down (bool): Use AvgPool instead of stride conv when
downsampling in the bottleneck. Default: False.
frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
-1 means not freezing any parameters. Default: -1.
conv_cfg (dict | None): Dictionary to construct and config conv layer.
When conv_cfg is None, cfg will be set to dict(type='Conv2d').
Default: None.
norm_cfg (dict): Dictionary to construct and config norm layer.
Default: dict(type='BN', requires_grad=True).
norm_eval (bool): Whether to set norm layers to eval mode, namely,
freeze running stats (mean and var). Note: Effect on Batch Norm
and its variants only. Default: False.
dcn (dict | None): Dictionary to construct and config DCN conv layer.
When dcn is not None, conv_cfg must be None. Default: None.
stage_with_dcn (Sequence[bool]): Whether to set DCN conv for each
stage. The length of stage_with_dcn is equal to num_stages.
Default: (False, False, False, False).
plugins (list[dict]): List of plugins for stages, each dict contains:
- cfg (dict, required): Cfg dict to build plugin.
- position (str, required): Position inside block to insert plugin,
options: 'after_conv1', 'after_conv2', 'after_conv3'.
- stages (tuple[bool], optional): Stages to apply plugin, length
should be same as 'num_stages'.
Default: None.
multi_grid (Sequence[int]|None): Multi grid dilation rates of last
stage. Default: None.
contract_dilation (bool): Whether contract first dilation of each layer
Default: False.
with_cp (bool): Use checkpoint or not. Using checkpoint will save some
memory while slowing down the training speed. Default: False.
zero_init_residual (bool): Whether to use zero init for last norm layer
in resblocks to let them behave as identity. Default: True.
pretrained (str, optional): model pretrained path. Default: None.
init_cfg (dict or list[dict], optional): Initialization config dict.
Default: None.
Example:
>>> from mmseg.models import ResNet
>>> import torch
>>> self = ResNet(depth=18)
>>> self.eval()
>>> inputs = torch.rand(1, 3, 32, 32)
>>> level_outputs = self.forward(inputs)
>>> for level_out in level_outputs:
... print(tuple(level_out.shape))
(1, 64, 8, 8)
(1, 128, 4, 4)
(1, 256, 2, 2)
(1, 512, 1, 1)
"""
arch_settings = {
18: (BasicBlock, (2, 2, 2, 2)),
34: (BasicBlock, (3, 4, 6, 3)),
50: (Bottleneck, (3, 4, 6, 3)),
101: (Bottleneck, (3, 4, 23, 3)),
152: (Bottleneck, (3, 8, 36, 3))
}
def __init__(self,
depth,
in_channels=3,
stem_channels=64,
base_channels=64,
num_stages=4,
strides=(1, 2, 2, 2),
dilations=(1, 1, 1, 1),
out_indices=(0, 1, 2, 3),
style='pytorch',
deep_stem=False,
avg_down=False,
frozen_stages=-1,
conv_cfg=None,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=False,
dcn=None,
stage_with_dcn=(False, False, False, False),
plugins=None,
multi_grid=None,
contract_dilation=False,
with_cp=False,
zero_init_residual=True,
pretrained=None,
init_cfg=None):
super(ResNet, self).__init__(init_cfg)
if depth not in self.arch_settings:
raise KeyError(f'invalid depth {depth} for resnet')
self.pretrained = pretrained
self.zero_init_residual = zero_init_residual
block_init_cfg = None
assert not (init_cfg and pretrained), \
'init_cfg and pretrained cannot be setting at the same time'
if isinstance(pretrained, str):
warnings.warn('DeprecationWarning: pretrained is a deprecated, '
'please use "init_cfg" instead')
self.init_cfg = dict(type='Pretrained', checkpoint=pretrained)
elif pretrained is None:
if init_cfg is None:
self.init_cfg = [
dict(type='Kaiming', layer='Conv2d'),
dict(
type='Constant',
val=1,
layer=['_BatchNorm', 'GroupNorm'])
]
block = self.arch_settings[depth][0]
if self.zero_init_residual:
if block is BasicBlock:
block_init_cfg = dict(
type='Constant',
val=0,
override=dict(name='norm2'))
elif block is Bottleneck:
block_init_cfg = dict(
type='Constant',
val=0,
override=dict(name='norm3'))
else:
raise TypeError('pretrained must be a str or None')
self.depth = depth
self.stem_channels = stem_channels
self.base_channels = base_channels
self.num_stages = num_stages
assert num_stages >= 1 and num_stages <= 4
self.strides = strides
self.dilations = dilations
assert len(strides) == len(dilations) == num_stages
self.out_indices = out_indices
assert max(out_indices) < num_stages
self.style = style
self.deep_stem = deep_stem
self.avg_down = avg_down
self.frozen_stages = frozen_stages
self.conv_cfg = conv_cfg
self.norm_cfg = norm_cfg
self.with_cp = with_cp
self.norm_eval = norm_eval
self.dcn = dcn
self.stage_with_dcn = stage_with_dcn
if dcn is not None:
assert len(stage_with_dcn) == num_stages
self.plugins = plugins
self.multi_grid = multi_grid
self.contract_dilation = contract_dilation
self.block, stage_blocks = self.arch_settings[depth]
self.stage_blocks = stage_blocks[:num_stages]
self.inplanes = stem_channels
self._make_stem_layer(in_channels, stem_channels)
self.res_layers = []
for i, num_blocks in enumerate(self.stage_blocks):
stride = strides[i]
dilation = dilations[i]
dcn = self.dcn if self.stage_with_dcn[i] else None
if plugins is not None:
stage_plugins = self.make_stage_plugins(plugins, i)
else:
stage_plugins = None
# multi grid is applied to last layer only
stage_multi_grid = multi_grid if i == len(
self.stage_blocks) - 1 else None
planes = base_channels * 2**i
res_layer = self.make_res_layer(
block=self.block,
inplanes=self.inplanes,
planes=planes,
num_blocks=num_blocks,
stride=stride,
dilation=dilation,
style=self.style,
avg_down=self.avg_down,
with_cp=with_cp,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
dcn=dcn,
plugins=stage_plugins,
multi_grid=stage_multi_grid,
contract_dilation=contract_dilation,
init_cfg=block_init_cfg)
self.inplanes = planes * self.block.expansion
layer_name = f'layer{i+1}'
self.add_module(layer_name, res_layer)
self.res_layers.append(layer_name)
self._freeze_stages()
self.feat_dim = self.block.expansion * base_channels * 2**(
len(self.stage_blocks) - 1)
def make_stage_plugins(self, plugins, stage_idx):
"""make plugins for ResNet 'stage_idx'th stage .
Currently we support to insert 'context_block',
'empirical_attention_block', 'nonlocal_block' into the backbone like
ResNet/ResNeXt. They could be inserted after conv1/conv2/conv3 of
Bottleneck.
An example of plugins format could be :
>>> plugins=[
... dict(cfg=dict(type='xxx', arg1='xxx'),
... stages=(False, True, True, True),
... position='after_conv2'),
... dict(cfg=dict(type='yyy'),
... stages=(True, True, True, True),
... position='after_conv3'),
... dict(cfg=dict(type='zzz', postfix='1'),
... stages=(True, True, True, True),
... position='after_conv3'),
... dict(cfg=dict(type='zzz', postfix='2'),
... stages=(True, True, True, True),
... position='after_conv3')
... ]
>>> self = ResNet(depth=18)
>>> stage_plugins = self.make_stage_plugins(plugins, 0)
>>> assert len(stage_plugins) == 3
Suppose 'stage_idx=0', the structure of blocks in the stage would be:
conv1-> conv2->conv3->yyy->zzz1->zzz2
Suppose 'stage_idx=1', the structure of blocks in the stage would be:
conv1-> conv2->xxx->conv3->yyy->zzz1->zzz2
If stages is missing, the plugin would be applied to all stages.
Args:
plugins (list[dict]): List of plugins cfg to build. The postfix is
required if multiple same type plugins are inserted.
stage_idx (int): Index of stage to build
Returns:
list[dict]: Plugins for current stage
"""
stage_plugins = []
for plugin in plugins:
plugin = plugin.copy()
stages = plugin.pop('stages', None)
assert stages is None or len(stages) == self.num_stages
# whether to insert plugin into current stage
if stages is None or stages[stage_idx]:
stage_plugins.append(plugin)
return stage_plugins
def make_res_layer(self, **kwargs):
"""Pack all blocks in a stage into a ``ResLayer``."""
return ResLayer(**kwargs)
@property
def norm1(self):
"""nn.Module: the normalization layer named "norm1" """
return getattr(self, self.norm1_name)
def _make_stem_layer(self, in_channels, stem_channels):
"""Make stem layer for ResNet."""
if self.deep_stem:
self.stem = nn.Sequential(
build_conv_layer(
self.conv_cfg,
in_channels,
stem_channels // 2,
kernel_size=3,
stride=2,
padding=1,
bias=False),
build_norm_layer(self.norm_cfg, stem_channels // 2)[1],
nn.ReLU(inplace=True),
build_conv_layer(
self.conv_cfg,
stem_channels // 2,
stem_channels // 2,
kernel_size=3,
stride=1,
padding=1,
bias=False),
build_norm_layer(self.norm_cfg, stem_channels // 2)[1],
nn.ReLU(inplace=True),
build_conv_layer(
self.conv_cfg,
stem_channels // 2,
stem_channels,
kernel_size=3,
stride=1,
padding=1,
bias=False),
build_norm_layer(self.norm_cfg, stem_channels)[1],
nn.ReLU(inplace=True))
else:
self.conv1 = build_conv_layer(
self.conv_cfg,
in_channels,
stem_channels,
kernel_size=7,
stride=2,
padding=3,
bias=False)
self.norm1_name, norm1 = build_norm_layer(
self.norm_cfg, stem_channels, postfix=1)
self.add_module(self.norm1_name, norm1)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
def _freeze_stages(self):
"""Freeze stages param and norm stats."""
if self.frozen_stages >= 0:
if self.deep_stem:
self.stem.eval()
for param in self.stem.parameters():
param.requires_grad = False
else:
self.norm1.eval()
for m in [self.conv1, self.norm1]:
for param in m.parameters():
param.requires_grad = False
for i in range(1, self.frozen_stages + 1):
m = getattr(self, f'layer{i}')
m.eval()
for param in m.parameters():
param.requires_grad = False
def forward(self, x):
"""Forward function."""
if self.deep_stem:
x = self.stem(x)
else:
x = self.conv1(x)
x = self.norm1(x)
x = self.relu(x)
x = self.maxpool(x)
outs = []
for i, layer_name in enumerate(self.res_layers):
res_layer = getattr(self, layer_name)
x = res_layer(x)
if i in self.out_indices:
outs.append(x)
return tuple(outs)
def train(self, mode=True):
"""Convert the model into training mode while keep normalization layer
freezed."""
super(ResNet, self).train(mode)
self._freeze_stages()
if mode and self.norm_eval:
for m in self.modules():
# trick: eval have effect on BatchNorm only
if isinstance(m, _BatchNorm):
m.eval()
@BACKBONES.register_module()
class ResNetV1c(ResNet):
"""ResNetV1c variant described in [1]_.
Compared with default ResNet(ResNetV1b), ResNetV1c replaces the 7x7 conv
in the input stem with three 3x3 convs.
References:
.. [1] https://arxiv.org/pdf/1812.01187.pdf
"""
def __init__(self, **kwargs):
super(ResNetV1c, self).__init__(
deep_stem=True, avg_down=False, **kwargs)
@BACKBONES.register_module()
class ResNetV1d(ResNet):
"""ResNetV1d variant described in [1]_.
Compared with default ResNet(ResNetV1b), ResNetV1d replaces the 7x7 conv in
the input stem with three 3x3 convs. And in the downsampling block, a 2x2
avg_pool with stride 2 is added before conv, whose stride is changed to 1.
"""
def __init__(self, **kwargs):
super(ResNetV1d, self).__init__(
deep_stem=True, avg_down=True, **kwargs)
| 35.856742 | 79 | 0.549667 | import warnings
import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn import build_conv_layer, build_norm_layer, build_plugin_layer
from mmcv.runner import BaseModule
from mmcv.utils.parrots_wrapper import _BatchNorm
from ..builder import BACKBONES
from ..utils import ResLayer
class BasicBlock(BaseModule):
expansion = 1
def __init__(self,
inplanes,
planes,
stride=1,
dilation=1,
downsample=None,
style='pytorch',
with_cp=False,
conv_cfg=None,
norm_cfg=dict(type='BN'),
dcn=None,
plugins=None,
init_cfg=None):
super(BasicBlock, self).__init__(init_cfg)
assert dcn is None, 'Not implemented yet.'
assert plugins is None, 'Not implemented yet.'
self.norm1_name, norm1 = build_norm_layer(norm_cfg, planes, postfix=1)
self.norm2_name, norm2 = build_norm_layer(norm_cfg, planes, postfix=2)
self.conv1 = build_conv_layer(
conv_cfg,
inplanes,
planes,
3,
stride=stride,
padding=dilation,
dilation=dilation,
bias=False)
self.add_module(self.norm1_name, norm1)
self.conv2 = build_conv_layer(
conv_cfg, planes, planes, 3, padding=1, bias=False)
self.add_module(self.norm2_name, norm2)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
self.dilation = dilation
self.with_cp = with_cp
@property
def norm1(self):
return getattr(self, self.norm1_name)
@property
def norm2(self):
return getattr(self, self.norm2_name)
def forward(self, x):
def _inner_forward(x):
identity = x
out = self.conv1(x)
out = self.norm1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.norm2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
return out
if self.with_cp and x.requires_grad:
out = cp.checkpoint(_inner_forward, x)
else:
out = _inner_forward(x)
out = self.relu(out)
return out
class Bottleneck(BaseModule):
expansion = 4
def __init__(self,
inplanes,
planes,
stride=1,
dilation=1,
downsample=None,
style='pytorch',
with_cp=False,
conv_cfg=None,
norm_cfg=dict(type='BN'),
dcn=None,
plugins=None,
init_cfg=None):
super(Bottleneck, self).__init__(init_cfg)
assert style in ['pytorch', 'caffe']
assert dcn is None or isinstance(dcn, dict)
assert plugins is None or isinstance(plugins, list)
if plugins is not None:
allowed_position = ['after_conv1', 'after_conv2', 'after_conv3']
assert all(p['position'] in allowed_position for p in plugins)
self.inplanes = inplanes
self.planes = planes
self.stride = stride
self.dilation = dilation
self.style = style
self.with_cp = with_cp
self.conv_cfg = conv_cfg
self.norm_cfg = norm_cfg
self.dcn = dcn
self.with_dcn = dcn is not None
self.plugins = plugins
self.with_plugins = plugins is not None
if self.with_plugins:
self.after_conv1_plugins = [
plugin['cfg'] for plugin in plugins
if plugin['position'] == 'after_conv1'
]
self.after_conv2_plugins = [
plugin['cfg'] for plugin in plugins
if plugin['position'] == 'after_conv2'
]
self.after_conv3_plugins = [
plugin['cfg'] for plugin in plugins
if plugin['position'] == 'after_conv3'
]
if self.style == 'pytorch':
self.conv1_stride = 1
self.conv2_stride = stride
else:
self.conv1_stride = stride
self.conv2_stride = 1
self.norm1_name, norm1 = build_norm_layer(norm_cfg, planes, postfix=1)
self.norm2_name, norm2 = build_norm_layer(norm_cfg, planes, postfix=2)
self.norm3_name, norm3 = build_norm_layer(
norm_cfg, planes * self.expansion, postfix=3)
self.conv1 = build_conv_layer(
conv_cfg,
inplanes,
planes,
kernel_size=1,
stride=self.conv1_stride,
bias=False)
self.add_module(self.norm1_name, norm1)
fallback_on_stride = False
if self.with_dcn:
fallback_on_stride = dcn.pop('fallback_on_stride', False)
if not self.with_dcn or fallback_on_stride:
self.conv2 = build_conv_layer(
conv_cfg,
planes,
planes,
kernel_size=3,
stride=self.conv2_stride,
padding=dilation,
dilation=dilation,
bias=False)
else:
assert self.conv_cfg is None, 'conv_cfg must be None for DCN'
self.conv2 = build_conv_layer(
dcn,
planes,
planes,
kernel_size=3,
stride=self.conv2_stride,
padding=dilation,
dilation=dilation,
bias=False)
self.add_module(self.norm2_name, norm2)
self.conv3 = build_conv_layer(
conv_cfg,
planes,
planes * self.expansion,
kernel_size=1,
bias=False)
self.add_module(self.norm3_name, norm3)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
if self.with_plugins:
self.after_conv1_plugin_names = self.make_block_plugins(
planes, self.after_conv1_plugins)
self.after_conv2_plugin_names = self.make_block_plugins(
planes, self.after_conv2_plugins)
self.after_conv3_plugin_names = self.make_block_plugins(
planes * self.expansion, self.after_conv3_plugins)
def make_block_plugins(self, in_channels, plugins):
assert isinstance(plugins, list)
plugin_names = []
for plugin in plugins:
plugin = plugin.copy()
name, layer = build_plugin_layer(
plugin,
in_channels=in_channels,
postfix=plugin.pop('postfix', ''))
assert not hasattr(self, name), f'duplicate plugin {name}'
self.add_module(name, layer)
plugin_names.append(name)
return plugin_names
def forward_plugin(self, x, plugin_names):
out = x
for name in plugin_names:
out = getattr(self, name)(x)
return out
@property
def norm1(self):
return getattr(self, self.norm1_name)
@property
def norm2(self):
return getattr(self, self.norm2_name)
@property
def norm3(self):
return getattr(self, self.norm3_name)
def forward(self, x):
def _inner_forward(x):
identity = x
out = self.conv1(x)
out = self.norm1(out)
out = self.relu(out)
if self.with_plugins:
out = self.forward_plugin(out, self.after_conv1_plugin_names)
out = self.conv2(out)
out = self.norm2(out)
out = self.relu(out)
if self.with_plugins:
out = self.forward_plugin(out, self.after_conv2_plugin_names)
out = self.conv3(out)
out = self.norm3(out)
if self.with_plugins:
out = self.forward_plugin(out, self.after_conv3_plugin_names)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
return out
if self.with_cp and x.requires_grad:
out = cp.checkpoint(_inner_forward, x)
else:
out = _inner_forward(x)
out = self.relu(out)
return out
@BACKBONES.register_module()
class ResNet(BaseModule):
arch_settings = {
18: (BasicBlock, (2, 2, 2, 2)),
34: (BasicBlock, (3, 4, 6, 3)),
50: (Bottleneck, (3, 4, 6, 3)),
101: (Bottleneck, (3, 4, 23, 3)),
152: (Bottleneck, (3, 8, 36, 3))
}
def __init__(self,
depth,
in_channels=3,
stem_channels=64,
base_channels=64,
num_stages=4,
strides=(1, 2, 2, 2),
dilations=(1, 1, 1, 1),
out_indices=(0, 1, 2, 3),
style='pytorch',
deep_stem=False,
avg_down=False,
frozen_stages=-1,
conv_cfg=None,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=False,
dcn=None,
stage_with_dcn=(False, False, False, False),
plugins=None,
multi_grid=None,
contract_dilation=False,
with_cp=False,
zero_init_residual=True,
pretrained=None,
init_cfg=None):
super(ResNet, self).__init__(init_cfg)
if depth not in self.arch_settings:
raise KeyError(f'invalid depth {depth} for resnet')
self.pretrained = pretrained
self.zero_init_residual = zero_init_residual
block_init_cfg = None
assert not (init_cfg and pretrained), \
'init_cfg and pretrained cannot be setting at the same time'
if isinstance(pretrained, str):
warnings.warn('DeprecationWarning: pretrained is a deprecated, '
'please use "init_cfg" instead')
self.init_cfg = dict(type='Pretrained', checkpoint=pretrained)
elif pretrained is None:
if init_cfg is None:
self.init_cfg = [
dict(type='Kaiming', layer='Conv2d'),
dict(
type='Constant',
val=1,
layer=['_BatchNorm', 'GroupNorm'])
]
block = self.arch_settings[depth][0]
if self.zero_init_residual:
if block is BasicBlock:
block_init_cfg = dict(
type='Constant',
val=0,
override=dict(name='norm2'))
elif block is Bottleneck:
block_init_cfg = dict(
type='Constant',
val=0,
override=dict(name='norm3'))
else:
raise TypeError('pretrained must be a str or None')
self.depth = depth
self.stem_channels = stem_channels
self.base_channels = base_channels
self.num_stages = num_stages
assert num_stages >= 1 and num_stages <= 4
self.strides = strides
self.dilations = dilations
assert len(strides) == len(dilations) == num_stages
self.out_indices = out_indices
assert max(out_indices) < num_stages
self.style = style
self.deep_stem = deep_stem
self.avg_down = avg_down
self.frozen_stages = frozen_stages
self.conv_cfg = conv_cfg
self.norm_cfg = norm_cfg
self.with_cp = with_cp
self.norm_eval = norm_eval
self.dcn = dcn
self.stage_with_dcn = stage_with_dcn
if dcn is not None:
assert len(stage_with_dcn) == num_stages
self.plugins = plugins
self.multi_grid = multi_grid
self.contract_dilation = contract_dilation
self.block, stage_blocks = self.arch_settings[depth]
self.stage_blocks = stage_blocks[:num_stages]
self.inplanes = stem_channels
self._make_stem_layer(in_channels, stem_channels)
self.res_layers = []
for i, num_blocks in enumerate(self.stage_blocks):
stride = strides[i]
dilation = dilations[i]
dcn = self.dcn if self.stage_with_dcn[i] else None
if plugins is not None:
stage_plugins = self.make_stage_plugins(plugins, i)
else:
stage_plugins = None
stage_multi_grid = multi_grid if i == len(
self.stage_blocks) - 1 else None
planes = base_channels * 2**i
res_layer = self.make_res_layer(
block=self.block,
inplanes=self.inplanes,
planes=planes,
num_blocks=num_blocks,
stride=stride,
dilation=dilation,
style=self.style,
avg_down=self.avg_down,
with_cp=with_cp,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
dcn=dcn,
plugins=stage_plugins,
multi_grid=stage_multi_grid,
contract_dilation=contract_dilation,
init_cfg=block_init_cfg)
self.inplanes = planes * self.block.expansion
layer_name = f'layer{i+1}'
self.add_module(layer_name, res_layer)
self.res_layers.append(layer_name)
self._freeze_stages()
self.feat_dim = self.block.expansion * base_channels * 2**(
len(self.stage_blocks) - 1)
def make_stage_plugins(self, plugins, stage_idx):
stage_plugins = []
for plugin in plugins:
plugin = plugin.copy()
stages = plugin.pop('stages', None)
assert stages is None or len(stages) == self.num_stages
if stages is None or stages[stage_idx]:
stage_plugins.append(plugin)
return stage_plugins
def make_res_layer(self, **kwargs):
return ResLayer(**kwargs)
@property
def norm1(self):
return getattr(self, self.norm1_name)
def _make_stem_layer(self, in_channels, stem_channels):
if self.deep_stem:
self.stem = nn.Sequential(
build_conv_layer(
self.conv_cfg,
in_channels,
stem_channels // 2,
kernel_size=3,
stride=2,
padding=1,
bias=False),
build_norm_layer(self.norm_cfg, stem_channels // 2)[1],
nn.ReLU(inplace=True),
build_conv_layer(
self.conv_cfg,
stem_channels // 2,
stem_channels // 2,
kernel_size=3,
stride=1,
padding=1,
bias=False),
build_norm_layer(self.norm_cfg, stem_channels // 2)[1],
nn.ReLU(inplace=True),
build_conv_layer(
self.conv_cfg,
stem_channels // 2,
stem_channels,
kernel_size=3,
stride=1,
padding=1,
bias=False),
build_norm_layer(self.norm_cfg, stem_channels)[1],
nn.ReLU(inplace=True))
else:
self.conv1 = build_conv_layer(
self.conv_cfg,
in_channels,
stem_channels,
kernel_size=7,
stride=2,
padding=3,
bias=False)
self.norm1_name, norm1 = build_norm_layer(
self.norm_cfg, stem_channels, postfix=1)
self.add_module(self.norm1_name, norm1)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
def _freeze_stages(self):
if self.frozen_stages >= 0:
if self.deep_stem:
self.stem.eval()
for param in self.stem.parameters():
param.requires_grad = False
else:
self.norm1.eval()
for m in [self.conv1, self.norm1]:
for param in m.parameters():
param.requires_grad = False
for i in range(1, self.frozen_stages + 1):
m = getattr(self, f'layer{i}')
m.eval()
for param in m.parameters():
param.requires_grad = False
def forward(self, x):
if self.deep_stem:
x = self.stem(x)
else:
x = self.conv1(x)
x = self.norm1(x)
x = self.relu(x)
x = self.maxpool(x)
outs = []
for i, layer_name in enumerate(self.res_layers):
res_layer = getattr(self, layer_name)
x = res_layer(x)
if i in self.out_indices:
outs.append(x)
return tuple(outs)
def train(self, mode=True):
super(ResNet, self).train(mode)
self._freeze_stages()
if mode and self.norm_eval:
for m in self.modules():
if isinstance(m, _BatchNorm):
m.eval()
@BACKBONES.register_module()
class ResNetV1c(ResNet):
def __init__(self, **kwargs):
super(ResNetV1c, self).__init__(
deep_stem=True, avg_down=False, **kwargs)
@BACKBONES.register_module()
class ResNetV1d(ResNet):
def __init__(self, **kwargs):
super(ResNetV1d, self).__init__(
deep_stem=True, avg_down=True, **kwargs)
| true | true |
f7238fad942b72cb7559f5c7ae76a3f775968a13 | 5,437 | py | Python | test/scenarios/synapse/output/ext_default_folder/src/synapse/azext_synapse/vendored_sdks/synapse/aio/operations/_sql_pool_connection_policies_operations.py | kairu-ms/autorest.az | c3370f3d4d394e580615d8d97df05515533b035e | [
"MIT"
] | null | null | null | test/scenarios/synapse/output/ext_default_folder/src/synapse/azext_synapse/vendored_sdks/synapse/aio/operations/_sql_pool_connection_policies_operations.py | kairu-ms/autorest.az | c3370f3d4d394e580615d8d97df05515533b035e | [
"MIT"
] | null | null | null | test/scenarios/synapse/output/ext_default_folder/src/synapse/azext_synapse/vendored_sdks/synapse/aio/operations/_sql_pool_connection_policies_operations.py | kairu-ms/autorest.az | c3370f3d4d394e580615d8d97df05515533b035e | [
"MIT"
] | 1 | 2021-03-21T03:59:29.000Z | 2021-03-21T03:59:29.000Z | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class SqlPoolConnectionPoliciesOperations:
"""SqlPoolConnectionPoliciesOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~synapse_management_client.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
async def get(
self,
resource_group_name: str,
workspace_name: str,
sql_pool_name: str,
connection_policy_name: Union[str, "models.ConnectionPolicyName"],
**kwargs
) -> "models.SqlPoolConnectionPolicy":
"""Get a Sql pool's connection policy, which is used with table auditing.
Get a Sql pool's connection policy, which is used with table auditing.
:param resource_group_name: The name of the resource group. The name is case insensitive.
:type resource_group_name: str
:param workspace_name: The name of the workspace.
:type workspace_name: str
:param sql_pool_name: SQL pool name.
:type sql_pool_name: str
:param connection_policy_name: The name of the connection policy.
:type connection_policy_name: str or ~synapse_management_client.models.ConnectionPolicyName
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SqlPoolConnectionPolicy, or the result of cls(response)
:rtype: ~synapse_management_client.models.SqlPoolConnectionPolicy
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["models.SqlPoolConnectionPolicy"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-06-01-preview"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str'),
'sqlPoolName': self._serialize.url("sql_pool_name", sql_pool_name, 'str'),
'connectionPolicyName': self._serialize.url("connection_policy_name", connection_policy_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('SqlPoolConnectionPolicy', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Synapse/workspaces/{workspaceName}/sqlPools/{sqlPoolName}/connectionPolicies/{connectionPolicyName}'} # type: ignore
| 49.427273 | 232 | 0.693397 |
from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.mgmt.core.exceptions import ARMErrorFormat
from ... import models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class SqlPoolConnectionPoliciesOperations:
models = models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
async def get(
self,
resource_group_name: str,
workspace_name: str,
sql_pool_name: str,
connection_policy_name: Union[str, "models.ConnectionPolicyName"],
**kwargs
) -> "models.SqlPoolConnectionPolicy":
cls = kwargs.pop('cls', None)
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-06-01-preview"
accept = "application/json"
url = self.get.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
'workspaceName': self._serialize.url("workspace_name", workspace_name, 'str'),
'sqlPoolName': self._serialize.url("sql_pool_name", sql_pool_name, 'str'),
'connectionPolicyName': self._serialize.url("connection_policy_name", connection_policy_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('SqlPoolConnectionPolicy', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Synapse/workspaces/{workspaceName}/sqlPools/{sqlPoolName}/connectionPolicies/{connectionPolicyName}'}
| true | true |
f72390583047884be266f3b829926a84f2d4d161 | 3,839 | py | Python | problems/codejam/2020/3/pen-testing/judge.py | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | 7 | 2020-10-15T22:37:10.000Z | 2022-02-26T17:23:49.000Z | problems/codejam/2020/3/pen-testing/judge.py | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | problems/codejam/2020/3/pen-testing/judge.py | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | # Usage: `python testing_tool.py test_number`, where the argument test_number
# is either 0 (first test set), 1 (second test set) or 2 (third test set).
# This can also be run as `python3 testing_tool.py test_number`.
from __future__ import print_function
import sys
import collections
import itertools
import random
import math
# Use raw_input in Python2.
try:
input = raw_input
except NameError:
pass
NUM_CASES = [20000, 20000, 100000]
N = 15
NEED_CORRECT = [10900, 12000, 63600]
class Error(Exception):
pass
class WrongAnswer(Exception):
pass
WRONG_NUM_TOKENS_ERROR = (
"Wrong number of tokens: expected {}, found {}.".format)
NOT_INTEGER_ERROR = "Not an integer: {}.".format
INVALID_LINE_ERROR = "Couldn't read a valid line."
ADDITIONAL_INPUT_ERROR = "Additional input after all cases finish: {}.".format
OUT_OF_BOUNDS_ERROR = "Request out of bounds: {}.".format
TOO_MANY_ROUNDS_ERROR = "Too many rounds"
SAME_PEN_TWICE_ERROR = "Taking the same pen twice"
TOO_FEW_CORRECT_ERROR = "Too few correct answers: {}.".format
INVALID_OUTPUT = -1
SUCCESSFUL = 1
NO_MORE_INK = 0
DID_NOT_WRITE = 0
def ReadValues(line, num_tokens):
t = line.split()
if len(t) != num_tokens:
raise Error(WRONG_NUM_TOKENS_ERROR(num_tokens, len(t)))
r = []
for s in t:
try:
v = int(s)
except:
raise Error(NOT_INTEGER_ERROR(s[:100]))
r.append(v)
return r
def Input():
try:
return input()
except EOFError:
raise
except:
raise Error(INVALID_LINE_ERROR)
def Output(line):
try:
print(line)
sys.stdout.flush()
except:
try:
sys.stdout.close()
except:
pass
def RunCases(num_cases, n, need_correct):
Output("{} {} {}".format(num_cases, n, need_correct))
remaining = [
list(range(n))
for _ in range(num_cases)]
# It is not guaranteed that the judge uses the same method of random number
# generation.
for i in range(num_cases):
random.shuffle(remaining[i])
max_rounds = n * (n + 1) // 2
num_rounds = 0
while True:
try:
moves = ReadValues(Input(), num_cases)
except EOFError:
raise Error(INVALID_LINE_ERROR)
for move in moves:
if move < 0 or move > n:
raise Error(OUT_OF_BOUNDS_ERROR(move))
if all(move == 0 for move in moves):
break
num_rounds += 1
if num_rounds > max_rounds:
raise Error(TOO_MANY_ROUNDS_ERROR)
results = []
for move, rem in zip(moves, remaining):
if move == 0:
results.append(DID_NOT_WRITE)
else:
move -= 1
got = rem[move]
if got > 0:
results.append(SUCCESSFUL)
rem[move] = got - 1
else:
results.append(NO_MORE_INK)
Output(' '.join(str(result) for result in results))
try:
guesses = ReadValues(Input(), 2 * num_cases)
except EOFError:
raise Error(INVALID_LINE_ERROR)
correct = 0
for v1, v2, rem in zip(guesses[0::2], guesses[1::2], remaining):
if v1 < 1 or v1 > n:
raise Error(OUT_OF_BOUNDS_ERROR(v1))
if v2 < 1 or v2 > n:
raise Error(OUT_OF_BOUNDS_ERROR(v2))
if v1 == v2:
raise Error(SAME_PEN_TWICE_ERROR)
v1 -= 1
v2 -= 1
if rem[v1] + rem[v2] >= n:
correct += 1
try:
extra_input = Input()
raise Error(ADDITIONAL_INPUT_ERROR(extra_input[:100]))
except EOFError:
pass
if correct < need_correct:
raise WrongAnswer(TOO_FEW_CORRECT_ERROR(correct))
def main():
assert len(sys.argv) == 2
index = int(sys.argv[1])
num_cases = NUM_CASES[index]
n = N
need_correct = NEED_CORRECT[index]
try:
RunCases(num_cases, n, need_correct)
except Error as error:
Output(INVALID_OUTPUT)
print(error, file=sys.stderr)
sys.exit(1)
except WrongAnswer as error:
print(error, file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
| 22.582353 | 78 | 0.6559 |
from __future__ import print_function
import sys
import collections
import itertools
import random
import math
try:
input = raw_input
except NameError:
pass
NUM_CASES = [20000, 20000, 100000]
N = 15
NEED_CORRECT = [10900, 12000, 63600]
class Error(Exception):
pass
class WrongAnswer(Exception):
pass
WRONG_NUM_TOKENS_ERROR = (
"Wrong number of tokens: expected {}, found {}.".format)
NOT_INTEGER_ERROR = "Not an integer: {}.".format
INVALID_LINE_ERROR = "Couldn't read a valid line."
ADDITIONAL_INPUT_ERROR = "Additional input after all cases finish: {}.".format
OUT_OF_BOUNDS_ERROR = "Request out of bounds: {}.".format
TOO_MANY_ROUNDS_ERROR = "Too many rounds"
SAME_PEN_TWICE_ERROR = "Taking the same pen twice"
TOO_FEW_CORRECT_ERROR = "Too few correct answers: {}.".format
INVALID_OUTPUT = -1
SUCCESSFUL = 1
NO_MORE_INK = 0
DID_NOT_WRITE = 0
def ReadValues(line, num_tokens):
t = line.split()
if len(t) != num_tokens:
raise Error(WRONG_NUM_TOKENS_ERROR(num_tokens, len(t)))
r = []
for s in t:
try:
v = int(s)
except:
raise Error(NOT_INTEGER_ERROR(s[:100]))
r.append(v)
return r
def Input():
try:
return input()
except EOFError:
raise
except:
raise Error(INVALID_LINE_ERROR)
def Output(line):
try:
print(line)
sys.stdout.flush()
except:
try:
sys.stdout.close()
except:
pass
def RunCases(num_cases, n, need_correct):
Output("{} {} {}".format(num_cases, n, need_correct))
remaining = [
list(range(n))
for _ in range(num_cases)]
# It is not guaranteed that the judge uses the same method of random number
# generation.
for i in range(num_cases):
random.shuffle(remaining[i])
max_rounds = n * (n + 1) // 2
num_rounds = 0
while True:
try:
moves = ReadValues(Input(), num_cases)
except EOFError:
raise Error(INVALID_LINE_ERROR)
for move in moves:
if move < 0 or move > n:
raise Error(OUT_OF_BOUNDS_ERROR(move))
if all(move == 0 for move in moves):
break
num_rounds += 1
if num_rounds > max_rounds:
raise Error(TOO_MANY_ROUNDS_ERROR)
results = []
for move, rem in zip(moves, remaining):
if move == 0:
results.append(DID_NOT_WRITE)
else:
move -= 1
got = rem[move]
if got > 0:
results.append(SUCCESSFUL)
rem[move] = got - 1
else:
results.append(NO_MORE_INK)
Output(' '.join(str(result) for result in results))
try:
guesses = ReadValues(Input(), 2 * num_cases)
except EOFError:
raise Error(INVALID_LINE_ERROR)
correct = 0
for v1, v2, rem in zip(guesses[0::2], guesses[1::2], remaining):
if v1 < 1 or v1 > n:
raise Error(OUT_OF_BOUNDS_ERROR(v1))
if v2 < 1 or v2 > n:
raise Error(OUT_OF_BOUNDS_ERROR(v2))
if v1 == v2:
raise Error(SAME_PEN_TWICE_ERROR)
v1 -= 1
v2 -= 1
if rem[v1] + rem[v2] >= n:
correct += 1
try:
extra_input = Input()
raise Error(ADDITIONAL_INPUT_ERROR(extra_input[:100]))
except EOFError:
pass
if correct < need_correct:
raise WrongAnswer(TOO_FEW_CORRECT_ERROR(correct))
def main():
assert len(sys.argv) == 2
index = int(sys.argv[1])
num_cases = NUM_CASES[index]
n = N
need_correct = NEED_CORRECT[index]
try:
RunCases(num_cases, n, need_correct)
except Error as error:
Output(INVALID_OUTPUT)
print(error, file=sys.stderr)
sys.exit(1)
except WrongAnswer as error:
print(error, file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
| true | true |
f72390dddd0d84854ce46859f4d24a972e0b715b | 314 | py | Python | bids/__init__.py | oesteban/pybids | 800d15053952991c9cd4a00cf0039288d489ca12 | [
"MIT"
] | null | null | null | bids/__init__.py | oesteban/pybids | 800d15053952991c9cd4a00cf0039288d489ca12 | [
"MIT"
] | null | null | null | bids/__init__.py | oesteban/pybids | 800d15053952991c9cd4a00cf0039288d489ca12 | [
"MIT"
] | null | null | null | from __future__ import absolute_import, division, print_function
from .version import __version__ # noqa
from .due import due, Doi
__all__ = ["grabbids"]
due.cite(Doi("10.1038/sdata.2016.44"),
description="Brain Imaging Data Structure",
tags=["reference-implementation"],
path='bids')
| 31.4 | 64 | 0.703822 | from __future__ import absolute_import, division, print_function
from .version import __version__
from .due import due, Doi
__all__ = ["grabbids"]
due.cite(Doi("10.1038/sdata.2016.44"),
description="Brain Imaging Data Structure",
tags=["reference-implementation"],
path='bids')
| true | true |
f72391302bc4de9c0cd1e5d8296951d9aa50d450 | 328 | py | Python | tkinter/minimal - class version/main-python2.py | whitmans-max/python-examples | 881a8f23f0eebc76816a0078e19951893f0daaaa | [
"MIT"
] | 140 | 2017-02-21T22:49:04.000Z | 2022-03-22T17:51:58.000Z | tkinter/minimal - class version/main-python2.py | whitmans-max/python-examples | 881a8f23f0eebc76816a0078e19951893f0daaaa | [
"MIT"
] | 5 | 2017-12-02T19:55:00.000Z | 2021-09-22T23:18:39.000Z | tkinter/minimal - class version/main-python2.py | whitmans-max/python-examples | 881a8f23f0eebc76816a0078e19951893f0daaaa | [
"MIT"
] | 79 | 2017-01-25T10:53:33.000Z | 2022-03-11T16:13:57.000Z | #!/usr/bin/env python
import Tkinter as tk # Python 2
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self) # Python 2
self.title('Main Window')
self.geometry('300x300')
# def run(self):
# self.mainloop()
#app = App()
#app.run()
#App().run()
App().mainloop()
| 13.666667 | 39 | 0.542683 |
import Tkinter as tk
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title('Main Window')
self.geometry('300x300')
App().mainloop()
| true | true |
f723917fb9c06445abc12f3ce329c4540d202994 | 24,250 | py | Python | okl4_kernel/okl4_2.1.1-patch.9/tools/magpie-parsers/src/magpieparsers/cplusplus/astgen.py | CyberQueenMara/baseband-research | e1605537e10c37e161fff1a3416b908c9894f204 | [
"MIT"
] | 77 | 2018-12-31T22:12:09.000Z | 2021-12-31T22:56:13.000Z | okl4_kernel/okl4_2.1.1-patch.9/tools/magpie-parsers/src/magpieparsers/cplusplus/astgen.py | CyberQueenMara/baseband-research | e1605537e10c37e161fff1a3416b908c9894f204 | [
"MIT"
] | null | null | null | okl4_kernel/okl4_2.1.1-patch.9/tools/magpie-parsers/src/magpieparsers/cplusplus/astgen.py | CyberQueenMara/baseband-research | e1605537e10c37e161fff1a3416b908c9894f204 | [
"MIT"
] | 24 | 2019-01-20T15:51:52.000Z | 2021-12-25T18:29:13.000Z | """
Transform the parse tree produced by parser.py to a higher-level tree using
recursive descent.
"""
from magpieparsers.parser_common import *
from magpieparsers.types.evaluator import evaluate
from magpieparsers.types.infogripper import *
from magpieparsers.cplusplus.normalise import normalise_type_list
from astexpr import get_expression
import operator
class Error(Exception):
pass
CLASS_SPECIFIERS = ('union', 'struct', 'class', 'enum_specifier')
# AST helper functions
def any_child(node, name_list):
"""
Return the first child of "node" with a name matching any
in "name_list"
"""
for child in node.children:
if child.name in name_list:
return child
def any_in_list(list1, list2):
""" Return the item if any items in list1 are present in list2"""
for item in list1:
if item in list2:
return item
def all_children(node, names):
for child_name in node.get_child_names():
if child_name not in names:
return False
return True
# AST generator
class ASTGen(object):
def __init__(self, types_only = True, experimental = False):
"""
If types_only is set to True, only typedefs are converted.
Conversion of entities other than typedefs is experimental
and is likely to fail with an exception.
If experimental is set to True, a slightly different (new-format)
data structure will be produced.
"""
self.types_only = types_only
self.experimental = experimental
def convert(self, ast, pt, filename, types_only = True):
""" Convert 'pt' to 'ast'.
"""
return self.translation_unit(ast, pt, filename)
def translation_unit(self, baseast, pt, filename):
#print 'PT'
#pt.print_tree()
#print 'PT done'
#ast = Node(baseast, "translation_unit")
#ast.leaf = filename
ast = baseast # Hmm - nfd
#ref_node = ast
for node in pt.children:
if node.name == 'declaration':
#print '*******************************\n\
# processing tree: '
#node.print_tree()
#decl_types = self.declaration(ref_node, node)
decl_types = self.declaration(ast, node)
ast.add_children(decl_types)
#ref_node = decl_types[-1]
#print '*******************************\n\
# new starting-tree: '
#ref_node.print_tree()
#print '*******************************\n\
# processing final-tree: '
#ast.print_tree()
elif node.name == 'function_definition':
if not self.types_only:
self.function_definition(ast, node)
#ast.add_child(Node(ast, 'unfinished_function_definition', source = node))
elif node.name == 'enum':
if not self.types_only:
self.enum(ast, node)
else:
ast.add_child(UnknownNode(ast, node, 'translation_unit', source = node))
return ast
def _wrap_node(self, name, parentast, ast):
result = Node(parentast, name, source = parentast)
result.add_child(ast)
return result
def enum(self, parent, pt):
"""
We look for:
enum
enum_specifier
enumerator_list
enumerator
...
enumerator
...
init_declarator_list (optional)
"""
# FIXME: Stub
ast = Node(parent, 'unfinished')
return ast
def function_definition(self, parent, pt):
"""
Yay a function! We expect it to look like this:
function_definition
declaration_specifiers - 'inline' etc plus return type
function_declarator - function name and parameters
declaration_list - function parameters (K&R only)
compound_statement - function body
"""
def walk_to_fdd(fd_pt):
""" Walks a chain of function declarators, collecting
indirection, until we get to function_direct_declarator.
"""
indirection = ''
while fd_pt:
if fd_pt.leaf == '*':
indirection += '*'
fdd_pt = fd_pt.get_child('function_direct_declarator')
fd_pt = fd_pt.get_child('function_declarator')
return indirection, fdd_pt
# Stick the node in the AST.
node = Node(parent, 'function', source = pt)
parent.add_child(node)
# Parts of the parse tree
# ... function_direct_declarator holds param list & name
retval_indirection, function_direct_declarator = \
walk_to_fdd(pt.get_child('function_declarator'))
declaration_specifiers = pt.get_child('declaration_specifiers')
compound_statement = pt.get_child('compound_statement')
# Get function name...
node.leaf = function_direct_declarator.leaf
# Function return type...
return_type_ast = Node(node, 'return_type', source = declaration_specifiers)
return_type_ast.add_attribute('indirection', retval_indirection)
return_type_ast.add_child(self._wrap_node('target', node,
self.get_type(node, declaration_specifiers)))
node.add_child(return_type_ast)
# Function parameters...
parameter_list = function_direct_declarator.get_child('parameter_list')
if parameter_list:
parameter_declaration_list = parameter_list.get_child('parameter_declaration_list')
for parameter_declaration in parameter_declaration_list.get_children_named('parameter_declaration'):
parameter_ast = self._function_parameter(node, parameter_declaration)
node.add_child(parameter_ast)
# We ignore K&R-style declaration list
# Function body.
body_ast = Node(node, 'body', source = compound_statement)
node.add_child(body_ast)
body_ast.add_children(self._compound_statement(body_ast, compound_statement))
def get_type(self, parentast, pt):
"""
Given a PT containing a type reference as a child, return the AST node
describing this type. The AST node may already exist, or it may be
created here.
"""
if pt.has_child('simple_type_specifier'):
#type_name = ' '.join(pt.get_child('simple_type_specifier').leaf)
#return TypeNode(parentast, None, type_name)
simple_type_specifier = pt.get_children_named('simple_type_specifier')[0]
type_list = [child_pt.name for child_pt in simple_type_specifier.children]
typenode = self.get_type_from_list(parentast, type_list)
elif any_child(pt, CLASS_SPECIFIERS):
child_pt = any_child(pt, CLASS_SPECIFIERS)
# We're either declaring an instance of an existing class, or
# creating a new one.
typenode = self.find_or_create_type(parentast, child_pt)
elif pt.my_children_are('enum_specifier'):
# FIXME: We still have bad handling of enums.
typenode = getTypenode('int', parentast)
else:
pt.print_tree()
parentast.print_tree()
raise Exception()
if typenode is None:
print "Couldn't find type node in here:"
pt.print_tree()
print "My parent is:"
parentast.print_tree()
assert typenode is not None
return typenode
def get_type_from_list(self, parentast, type_list):
type_list = normalise_type_list(type_list)
type_name = ' '.join(type_list)
return getTypenode(type_name, parentast)
def find_or_create_type(self, parentast, pt):
# Called when we're not sure if the current type must be created
# or not.
# FIXME: We could/should extend this to other types.
assert pt.type in CLASS_SPECIFIERS
# The class may exist
ast = None
if pt.leaf:
ast = getTypenode(pt.leaf, parentast)
# There is one case where getTypenode can succeed and yet the type
# can be defined below: when a previous forward declaration is
# being defined.
if ast and not ast.get_child('members') and pt.get_child('members'):
# We're defining it here - so forget about the previous reference
# and use this one.
ast = None
# By this point the name isn't declared, or we need to define a
# forward reference.
if not ast:
# The class doesn't exist - create it
ast = self.create_type(parentast, pt)
# Done: if we're None at this point something is broken.
assert ast is not None
return ast
def create_type(self, parentast, pt):
"""
Create a new type from a list of member_declarations
"""
# We know how to construct the following types:
# structs
# unions
# enums
# forward declarations of structs
if pt.name == 'struct':
handler = self.create_type_struct
elif pt.name == 'union':
handler = self.create_type_union
elif pt.name == 'enum_specifier':
handler = self.create_type_enum
else:
raise Error("Unknown parsed type '%s'" % (pt.type))
return handler(parentast, pt)
def create_type_struct(self, parentast, pt):
members_pt = pt.get_child('members')
if pt.leaf and members_pt and getTypenode(pt.leaf, parentast) is not None:
# This is a forward declaration!
# Modify the forward declaration in-place.
ast = getTypenode(pt.leaf, parentast)
else:
ast = TypeNode(parentast, None, leaf = pt.leaf, source = members_pt)
ast.add_attribute('meta_type', 'struct')
# We may not have a "members" tree if this was a forward decl
if members_pt:
ast.add_child(Node(ast, 'members', source = members_pt))
decls_list = self.make_declarations_list(ast, members_pt)
ast.get_child('members').add_children(decls_list)
return ast
def create_type_union(self, parentast, pt):
members_pt = pt.get_child('members')
ast = TypeNode(parentast, None, source = members_pt)
ast.add_attribute('meta_type', 'union')
if members_pt:
decls_list = self.make_declarations_list(ast, members_pt)
ast.add_child(Node(ast, 'members', children = decls_list, leaf = pt.leaf, source = members_pt))
ast.add_attribute('switch_type', None)
return ast
def create_type_enum(self, parentast, pt):
"""
FIXME: The code below is truly broken. In C++ enums can look like this:
enum Blah{...} blah;
enum {...} blah;
enum {...};
Where the {...} is a list of IDs with (optional) assignment to integers.
A helpful site:
http://cpptips.hyperformix.com/Enums.html
"""
members_pt = pt.get_child('enumerator_list')
ast = TypeNode(parentast, None, source = members_pt)
ast.add_attribute('meta_type', 'enum')
decls_list = self.make_declarations_list(ast, members_pt)
#print "There is only one Power in this world that knows all about the Rings and their effects.\n -> Use this Power to solve the BUG!"
ast.add_children(decls_list)
return ast
def make_declarations_list(self, ast, members_pt):
decls = []
for child in members_pt.children:
if child.name in ('declaration', 'member_declaration'):
decls.extend(self.declaration(ast, child))
return decls
def _is_declaration(self, pt):
return pt.name in ('declaration', 'using_declaration', 'linkage_specification')
def declaration(self, parentast, pt):
"""
Process a declaration.
Complicated because the declaration could be:
* A simple variable declaration
* A definition
* A forward declaration
It also supports member declarators (inside enums, typed class members, typedefs)
in addition to init declarators (all other types of declaration)
"""
# The first part of the declaration specifies the type.
# (the "int" part of "int x")
decl_specifier = pt.get_child('declaration_specifiers')
# This function is used for both member declarations (lists of declarators
# inside structs) and init declarators (values on the RHS of a declaration)
# so we test for both. This list contains intialisers and names.
# (the "x" part of "int x")
init_decl_list = pt.get_child('init_declarator_list')
if not init_decl_list:
init_decl_list = pt.get_child('member_declarator_list')
# Bail early if this doesn't look at all right.
if not decl_specifier:
return [UnknownNode(None, pt, name = 'declaration_type')]
if init_decl_list:
# The type referenced may already exist, or it may be declared here.
declarators = self._init_declarator_list(parentast, init_decl_list)
else:
# If there are no init declarators, that means that either:
# 1. This is a new type, or
# 2. This is a forward declaration.
declarators = []
# Now we're ready to create declarations. We create as many declarations
# as there are names members in the initialiser list.
newNodes = []
decl_type = [ds.name for ds in decl_specifier.children]
decl_type_node = self.get_type(parentast, decl_specifier)
def _any_combination(target, acceptable):
"""
Returns True if target has any combination of "acceptable" in it
(including zero elements - ie if target is [])
"""
for item in target:
if item not in acceptable:
return False
return True
if 'typedef' in decl_type:
node_template = TypeNode(None, source = init_decl_list)
node_template.add_attribute('meta_type', 'alias')
elif 'const' in decl_type:
node_template = Node(None, 'type_instance', source = init_decl_list)
node_template.add_attribute('meta_type', 'const')
elif init_decl_list and _any_combination(decl_type, ['static', 'inline']):
node_template = Node(None, 'type_instance', source = init_decl_list)
elif any_in_list(CLASS_SPECIFIERS, decl_type):
node_template = Node(None, 'type_instance', source = init_decl_list)
elif init_decl_list is not None:
node_template = Node(None, 'type_instance', source = init_decl_list)
if init_decl_list is None:
# Forward declaration.
newNodes.append(decl_type_node)
else:
# Build declarations from the node template.
for decl in declarators:
if decl.name == 'attribute':
# FIXME: Attributes are ignored right now
continue
newNode = node_template.copy()
newNode.leaf = decl.leaf
newNode.add_attribute('indirection',
decl.get_single_attribute('indirection', ''))
newNode.add_child(self._wrap_node('target', newNode, decl_type_node))
newNode.add_child(decl)
if 'static' in decl_type:
newNode.attributes['c_static'] = True
if 'inline' in decl_type:
newNode.attributes['c_inline'] = True
newNodes.append(newNode)
return newNodes
def _init_declarator_list(self, parentast, pt):
return self._some_declarator_list(parentast, pt)
def _some_declarator_list(self, parentast, pt):
"""
Init declarators are separated in source using commas.
"""
assert pt.name in ("init_declarator_list", "member_declarator_list")
init_declarators = []
for child in pt.children:
init_declarators.append(self.init_declarator(parentast, child))
return init_declarators
def init_declarator(self, parentast, pt):
"""
Return an init_declarator node.
We used to return:
name
expression
result
indirection
This now becomes a Node with name "name", child "expression", attribute
"indirection", a result, and possibly other children
"""
decl = Node(None, 'declarator')
if pt.name == 'member_declarator_bitfield':
decl.leaf = pt.leaf
decl.add_child(pt.get_child('expression'))
try:
decl.result = evaluate(pt.get_child('expression'), parentast)
except Exception:
decl.result = pt.get_child('expression').result
elif pt.name == 'attribute':
attribute_pt = pt.children[0]
# FIXME: Attribute support
decl.set_name('attribute')
decl.set_leaf(attribute_pt.name)
elif pt.name in ("init_declarator", "member_declarator"):
indirection = ''
# Now we want this:
# declarator *
# direct_declarator ID
#
# ... or any of these :
# direct_declarator ID <- function declaration
# parameter_list
# type_qualifier
# exception_specification
# direct_declarator ID <- class instantation / array declaration
# expression
# direct_declarator ID <- ?
# declarator <- function ptr
# declarator_suffixes
decl_pt = pt.get_child('declarator')
direct_decl_pt = pt.get_child('direct_declarator')
decl_suffixes_pt = None
# We want to get to a direct_declarator if it exists. This is a convoluted
# process -- probably best to refer to the relevant grammar section.
while decl_pt is not None:
if decl_pt.leaf == '*':
indirection += '*'
direct_decl_pt = decl_pt.get_child('direct_declarator')
if direct_decl_pt:
break
else:
decl_pt = decl_pt.get_child('declarator')
assert decl_pt
decl.add_attribute('indirection', indirection)
# Now we are down to direct_declarator.
if direct_decl_pt.has_child('declarator'):
# This is a function pointer - we don't support these too well.
decl_pt = direct_decl_pt.get_child('declarator')
direct_decl_pt = decl_pt.get_child('direct_declarator')
decl.leaf = direct_decl_pt.leaf
expr = pt.get_child('expression')
if not expr and pt.has_child('initializer'):
expr = pt.get_child('initializer').get_child('expression')
ast_expr = None
if expr:
ast_expr = get_expression(parentast, expr, self)
if ast_expr:
decl.add_child(ast_expr)
return decl
def _function_parameter(self, ast, pt):
"""
Looks like this:
parameter_declaration
declaration_specifiers
direct_declarator | declarator
"""
declaration_specifiers = pt.get_child('declaration_specifiers')
node = Node(ast, 'parameter', source = pt)
target_ast = self._wrap_node('target', ast,
self.get_type(node, declaration_specifiers))
node.add_child(target_ast)
indirection = ''
if pt.get_child('direct_declarator'):
final_declarator = pt
else:
declarator = pt.get_child('declarator')
final_declarator = declarator
while declarator:
indirection += declarator.leaf
final_declarator = declarator
declarator = declarator.get_child('declarator')
node.leaf = final_declarator.get_child('direct_declarator').leaf
indirection_ast = Node(node, 'indirection', leaf = indirection, source = final_declarator)
node.add_child(indirection_ast)
return node
def _statements(self, ast, pt):
"""
Returns a list of parsed statements from "ast".
"""
results = None
while pt.name == 'statement':
pt = pt.children[0]
if pt.name == 'jump_statement':
results = [self._jump_statement(ast, pt)]
elif pt.name == 'expression':
results = [get_expression(ast, pt, self)]
elif pt.name == 'selection_statement':
results = [self._selection_statement(ast, pt)]
elif pt.name == 'case_statement':
results = [self._case_statement(ast, pt)]
elif pt.name == 'default_statement':
results = [self._default_statement(ast, pt)]
elif pt.name == 'iteration_statement':
results = [self._iteration_statement(ast, pt)]
elif pt.name == 'compound_statement':
results = self._compound_statement(ast, pt)
elif pt.name == 'declaration':
results = self.declaration(ast, pt)
elif pt.name == 'asm_block':
results = [UnfinishedNode('asm_block')]
elif pt.name == 'blank':
results = []
else:
pt.print_tree()
raise Exception("Unknown statement '%s'" % (pt.name))
return results
def _compound_statement(self, ast, pt):
"""
Return a node representing a compound statement.
"""
statement_list = pt.get_child('statement_list')
results = []
# The compound statement may be empty - {} - in which case no statement
# list node is present.
if statement_list:
for statement_pt in statement_list.children:
results.extend(self._statements(ast, statement_pt))
return results
def _jump_statement(self, ast, pt):
node = Node(ast, 'exit', source = pt)
if pt.leaf == 'return':
expression = pt.get_child('expression')
if expression:
node.add_child(expression)
elif pt.leaf in ('break', 'continue'):
# No arguments
pass
else:
raise Exception("Unknown jump statement type %s" % (pt.leaf))
return node
def _selection_statement(self, ast, pt):
"""
Handle "switch() {} and if() {}"
The PT's two children should be an expression and a compound_statement.
We rewrite switch statements to be multiple "if" statements -
possibly stupidly...
"""
if pt.leaf == 'switch':
return self._selection_statement_switch(ast, pt)
elif pt.leaf == 'if':
return self._selection_statement_if(ast, pt)
else:
raise Exception("Unknown selection_statement %s" % (pt.leaf))
def _selection_statement_if(self, ast, pt):
""" Handle "if" statement. See caller for more info. """
condition_pt = pt.children[0]
cases_pt = pt.children[1]
expr_ast = get_expression(ast, condition_pt, self)
statements_ast = Node(ast, "body", source = cases_pt)
if_ast = Node(ast, 'if', [expr_ast, statements_ast], source = pt)
statements_ast.add_children(self._statements(statements_ast, cases_pt))
# Handle "else" cases.
else_clause_pt = pt.get_child('else')
if else_clause_pt:
else_statements_pt = else_clause_pt.child()
else_clause_ast = Node(if_ast, 'else', source = else_clause_pt)
if_ast.add_child(else_clause_ast)
statements_list = self._statements(else_clause_ast, else_statements_pt)
else_clause_ast.add_children(statements_list)
return if_ast
def _selection_statement_switch(self, ast, pt):
""" Handle "switch" statement. See caller for more info.
Output of type
switch
expression (to switch on)
expression (actions)
"""
# FIXME: Do we handle fall-through switching at all?
expr_pt, cases_pt = pt.children
expr_ast = get_expression(ast, expr_pt, self)
statements_ast = self._statements(ast, cases_pt)
return Node(ast, 'switch', children = [expr_ast] + statements_ast)
def _case_statement(self, ast, pt):
expr_pt, statement_pt = pt.children
expr_ast = get_expression(ast, expr_pt, self)
statements_ast = self._statements(ast, statement_pt)
return Node(ast, 'case', children = [expr_ast] + statements_ast)
def _default_statement(self, ast, pt):
statement_pt = pt.child()
statements_ast = self._statements(ast, statement_pt)
return Node(ast, 'default', children = statements_ast)
def _iteration_statement(self, ast, pt):
if pt.leaf == 'while':
return self._iteration_statement_while(ast, pt)
elif pt.leaf == 'do':
return self._iteration_statement_do(ast, pt)
elif pt.leaf == 'for':
return self._iteration_statement_for(ast, pt)
else:
pt.print_tree()
raise Error("Unknown iteration statement %s" % (pt.leaf))
def _iteration_statement_while(self, ast, pt):
expr_pt, statement_pt = pt.children
expr_ast = get_expression(ast, expr_pt, self)
statements_ast = Node(ast, "body", source = statement_pt)
statements_ast.add_children(self._statements(statements_ast, statement_pt))
return Node(ast, 'while', [expr_ast, statements_ast], source = pt)
def _iteration_statement_for(self, ast, pt):
init_pt, while_pt, post_pt, body_pt = pt.children
# init_pt is an expression or a declaration.
if init_pt.name == 'blank':
init_ast = Node(ast, 'blank')
elif self._is_declaration(init_pt):
init_ast = self.declaration(init_pt)
else:
init_ast = [get_expression(ast, init_pt, self)]
if while_pt.name != 'blank':
while_ast = get_expression(ast, while_pt, self)
else:
while_ast = Node(ast, 'blank')
if post_pt.name != 'blank':
post_ast = get_expression(ast, post_pt, self)
else:
post_ast = Node(ast, 'blank')
body_ast = self._statements(ast, body_pt)
return Node(ast, 'for', init_ast + [while_ast, post_ast] + body_ast)
def _construct_expr_from_value(self, parent_ast, value):
""" Cheesy hack to encode full (non-typechecked) values of expressions
as a string """
expr_ast = Node(parent_ast, 'expression', leaf = 'raw', source = parent_ast)
expr_ast.add_attribute('value', value)
return expr_ast
def find_or_create_type(self, parentast, pt):
# Called when we're not sure if the current type must be created
# or not.
# FIXME: We could/should extend this to other types.
assert pt.name in CLASS_SPECIFIERS
# The class may exist
ast = None
if pt.leaf:
ast = getTypenode(pt.leaf, parentast)
# There is one case where getTypenode can succeed and yet the type
# can be defined below: when a previous forward declaration is
# being defined.
if ast and not ast.get_child('members') and pt.get_child('members'):
# We're defining it here - so forget about the previous reference
# and use this one.
ast = None
# By this point the name isn't declared, or we need to define a
# forward reference.
if not ast:
# The class doesn't exist - create it
ast = self.create_type(parentast, pt)
# Done: if we're None at this point something is broken.
assert ast is not None
return ast
def _member_declarator_list(self, parentast, pt):
"""
Return a list of instance names.
"""
return self._some_declarator_list(parentast, pt)
def _init_declarator_get_value(self, pt):
pass
def gen(baseast, pt, filename, **kwargs):
astgen = ASTGen(**kwargs)
return astgen.convert(baseast, pt, filename)
| 31.53446 | 137 | 0.712619 | """
Transform the parse tree produced by parser.py to a higher-level tree using
recursive descent.
"""
from magpieparsers.parser_common import *
from magpieparsers.types.evaluator import evaluate
from magpieparsers.types.infogripper import *
from magpieparsers.cplusplus.normalise import normalise_type_list
from astexpr import get_expression
import operator
class Error(Exception):
pass
CLASS_SPECIFIERS = ('union', 'struct', 'class', 'enum_specifier')
def any_child(node, name_list):
"""
Return the first child of "node" with a name matching any
in "name_list"
"""
for child in node.children:
if child.name in name_list:
return child
def any_in_list(list1, list2):
""" Return the item if any items in list1 are present in list2"""
for item in list1:
if item in list2:
return item
def all_children(node, names):
for child_name in node.get_child_names():
if child_name not in names:
return False
return True
class ASTGen(object):
def __init__(self, types_only = True, experimental = False):
"""
If types_only is set to True, only typedefs are converted.
Conversion of entities other than typedefs is experimental
and is likely to fail with an exception.
If experimental is set to True, a slightly different (new-format)
data structure will be produced.
"""
self.types_only = types_only
self.experimental = experimental
def convert(self, ast, pt, filename, types_only = True):
""" Convert 'pt' to 'ast'.
"""
return self.translation_unit(ast, pt, filename)
def translation_unit(self, baseast, pt, filename):
ast = baseast
for node in pt.children:
if node.name == 'declaration':
# processing tree: '
decl_types = self.declaration(ast, node)
ast.add_children(decl_types)
# new starting-tree: '
# processing final-tree: '
elif node.name == 'function_definition':
if not self.types_only:
self.function_definition(ast, node)
elif node.name == 'enum':
if not self.types_only:
self.enum(ast, node)
else:
ast.add_child(UnknownNode(ast, node, 'translation_unit', source = node))
return ast
def _wrap_node(self, name, parentast, ast):
result = Node(parentast, name, source = parentast)
result.add_child(ast)
return result
def enum(self, parent, pt):
"""
We look for:
enum
enum_specifier
enumerator_list
enumerator
...
enumerator
...
init_declarator_list (optional)
"""
ast = Node(parent, 'unfinished')
return ast
def function_definition(self, parent, pt):
"""
Yay a function! We expect it to look like this:
function_definition
declaration_specifiers - 'inline' etc plus return type
function_declarator - function name and parameters
declaration_list - function parameters (K&R only)
compound_statement - function body
"""
def walk_to_fdd(fd_pt):
""" Walks a chain of function declarators, collecting
indirection, until we get to function_direct_declarator.
"""
indirection = ''
while fd_pt:
if fd_pt.leaf == '*':
indirection += '*'
fdd_pt = fd_pt.get_child('function_direct_declarator')
fd_pt = fd_pt.get_child('function_declarator')
return indirection, fdd_pt
node = Node(parent, 'function', source = pt)
parent.add_child(node)
retval_indirection, function_direct_declarator = \
walk_to_fdd(pt.get_child('function_declarator'))
declaration_specifiers = pt.get_child('declaration_specifiers')
compound_statement = pt.get_child('compound_statement')
node.leaf = function_direct_declarator.leaf
return_type_ast = Node(node, 'return_type', source = declaration_specifiers)
return_type_ast.add_attribute('indirection', retval_indirection)
return_type_ast.add_child(self._wrap_node('target', node,
self.get_type(node, declaration_specifiers)))
node.add_child(return_type_ast)
parameter_list = function_direct_declarator.get_child('parameter_list')
if parameter_list:
parameter_declaration_list = parameter_list.get_child('parameter_declaration_list')
for parameter_declaration in parameter_declaration_list.get_children_named('parameter_declaration'):
parameter_ast = self._function_parameter(node, parameter_declaration)
node.add_child(parameter_ast)
body_ast = Node(node, 'body', source = compound_statement)
node.add_child(body_ast)
body_ast.add_children(self._compound_statement(body_ast, compound_statement))
def get_type(self, parentast, pt):
"""
Given a PT containing a type reference as a child, return the AST node
describing this type. The AST node may already exist, or it may be
created here.
"""
if pt.has_child('simple_type_specifier'):
simple_type_specifier = pt.get_children_named('simple_type_specifier')[0]
type_list = [child_pt.name for child_pt in simple_type_specifier.children]
typenode = self.get_type_from_list(parentast, type_list)
elif any_child(pt, CLASS_SPECIFIERS):
child_pt = any_child(pt, CLASS_SPECIFIERS)
# creating a new one.
typenode = self.find_or_create_type(parentast, child_pt)
elif pt.my_children_are('enum_specifier'):
# FIXME: We still have bad handling of enums.
typenode = getTypenode('int', parentast)
else:
pt.print_tree()
parentast.print_tree()
raise Exception()
if typenode is None:
print "Couldn't find type node in here:"
pt.print_tree()
print "My parent is:"
parentast.print_tree()
assert typenode is not None
return typenode
def get_type_from_list(self, parentast, type_list):
type_list = normalise_type_list(type_list)
type_name = ' '.join(type_list)
return getTypenode(type_name, parentast)
def find_or_create_type(self, parentast, pt):
# or not.
# FIXME: We could/should extend this to other types.
assert pt.type in CLASS_SPECIFIERS
# The class may exist
ast = None
if pt.leaf:
ast = getTypenode(pt.leaf, parentast)
# There is one case where getTypenode can succeed and yet the type
# can be defined below: when a previous forward declaration is
# being defined.
if ast and not ast.get_child('members') and pt.get_child('members'):
# We're defining it here - so forget about the previous reference
ast = None
# forward reference.
if not ast:
# The class doesn't exist - create it
ast = self.create_type(parentast, pt)
assert ast is not None
return ast
def create_type(self, parentast, pt):
"""
Create a new type from a list of member_declarations
"""
# We know how to construct the following types:
# structs
# unions
# enums
# forward declarations of structs
if pt.name == 'struct':
handler = self.create_type_struct
elif pt.name == 'union':
handler = self.create_type_union
elif pt.name == 'enum_specifier':
handler = self.create_type_enum
else:
raise Error("Unknown parsed type '%s'" % (pt.type))
return handler(parentast, pt)
def create_type_struct(self, parentast, pt):
members_pt = pt.get_child('members')
if pt.leaf and members_pt and getTypenode(pt.leaf, parentast) is not None:
# This is a forward declaration!
# Modify the forward declaration in-place.
ast = getTypenode(pt.leaf, parentast)
else:
ast = TypeNode(parentast, None, leaf = pt.leaf, source = members_pt)
ast.add_attribute('meta_type', 'struct')
# We may not have a "members" tree if this was a forward decl
if members_pt:
ast.add_child(Node(ast, 'members', source = members_pt))
decls_list = self.make_declarations_list(ast, members_pt)
ast.get_child('members').add_children(decls_list)
return ast
def create_type_union(self, parentast, pt):
members_pt = pt.get_child('members')
ast = TypeNode(parentast, None, source = members_pt)
ast.add_attribute('meta_type', 'union')
if members_pt:
decls_list = self.make_declarations_list(ast, members_pt)
ast.add_child(Node(ast, 'members', children = decls_list, leaf = pt.leaf, source = members_pt))
ast.add_attribute('switch_type', None)
return ast
def create_type_enum(self, parentast, pt):
"""
FIXME: The code below is truly broken. In C++ enums can look like this:
enum Blah{...} blah;
enum {...} blah;
enum {...};
Where the {...} is a list of IDs with (optional) assignment to integers.
A helpful site:
http://cpptips.hyperformix.com/Enums.html
"""
members_pt = pt.get_child('enumerator_list')
ast = TypeNode(parentast, None, source = members_pt)
ast.add_attribute('meta_type', 'enum')
decls_list = self.make_declarations_list(ast, members_pt)
#print "There is only one Power in this world that knows all about the Rings and their effects.\n -> Use this Power to solve the BUG!"
ast.add_children(decls_list)
return ast
def make_declarations_list(self, ast, members_pt):
decls = []
for child in members_pt.children:
if child.name in ('declaration', 'member_declaration'):
decls.extend(self.declaration(ast, child))
return decls
def _is_declaration(self, pt):
return pt.name in ('declaration', 'using_declaration', 'linkage_specification')
def declaration(self, parentast, pt):
"""
Process a declaration.
Complicated because the declaration could be:
* A simple variable declaration
* A definition
* A forward declaration
It also supports member declarators (inside enums, typed class members, typedefs)
in addition to init declarators (all other types of declaration)
"""
# The first part of the declaration specifies the type.
# (the "int" part of "int x")
decl_specifier = pt.get_child('declaration_specifiers')
# This function is used for both member declarations (lists of declarators
# inside structs) and init declarators (values on the RHS of a declaration)
# so we test for both. This list contains intialisers and names.
# (the "x" part of "int x")
init_decl_list = pt.get_child('init_declarator_list')
if not init_decl_list:
init_decl_list = pt.get_child('member_declarator_list')
# Bail early if this doesn't look at all right.
if not decl_specifier:
return [UnknownNode(None, pt, name = 'declaration_type')]
if init_decl_list:
declarators = self._init_declarator_list(parentast, init_decl_list)
else:
declarators = []
# as there are names members in the initialiser list.
newNodes = []
decl_type = [ds.name for ds in decl_specifier.children]
decl_type_node = self.get_type(parentast, decl_specifier)
def _any_combination(target, acceptable):
"""
Returns True if target has any combination of "acceptable" in it
(including zero elements - ie if target is [])
"""
for item in target:
if item not in acceptable:
return False
return True
if 'typedef' in decl_type:
node_template = TypeNode(None, source = init_decl_list)
node_template.add_attribute('meta_type', 'alias')
elif 'const' in decl_type:
node_template = Node(None, 'type_instance', source = init_decl_list)
node_template.add_attribute('meta_type', 'const')
elif init_decl_list and _any_combination(decl_type, ['static', 'inline']):
node_template = Node(None, 'type_instance', source = init_decl_list)
elif any_in_list(CLASS_SPECIFIERS, decl_type):
node_template = Node(None, 'type_instance', source = init_decl_list)
elif init_decl_list is not None:
node_template = Node(None, 'type_instance', source = init_decl_list)
if init_decl_list is None:
# Forward declaration.
newNodes.append(decl_type_node)
else:
# Build declarations from the node template.
for decl in declarators:
if decl.name == 'attribute':
# FIXME: Attributes are ignored right now
continue
newNode = node_template.copy()
newNode.leaf = decl.leaf
newNode.add_attribute('indirection',
decl.get_single_attribute('indirection', ''))
newNode.add_child(self._wrap_node('target', newNode, decl_type_node))
newNode.add_child(decl)
if 'static' in decl_type:
newNode.attributes['c_static'] = True
if 'inline' in decl_type:
newNode.attributes['c_inline'] = True
newNodes.append(newNode)
return newNodes
def _init_declarator_list(self, parentast, pt):
return self._some_declarator_list(parentast, pt)
def _some_declarator_list(self, parentast, pt):
"""
Init declarators are separated in source using commas.
"""
assert pt.name in ("init_declarator_list", "member_declarator_list")
init_declarators = []
for child in pt.children:
init_declarators.append(self.init_declarator(parentast, child))
return init_declarators
def init_declarator(self, parentast, pt):
"""
Return an init_declarator node.
We used to return:
name
expression
result
indirection
This now becomes a Node with name "name", child "expression", attribute
"indirection", a result, and possibly other children
"""
decl = Node(None, 'declarator')
if pt.name == 'member_declarator_bitfield':
decl.leaf = pt.leaf
decl.add_child(pt.get_child('expression'))
try:
decl.result = evaluate(pt.get_child('expression'), parentast)
except Exception:
decl.result = pt.get_child('expression').result
elif pt.name == 'attribute':
attribute_pt = pt.children[0]
# FIXME: Attribute support
decl.set_name('attribute')
decl.set_leaf(attribute_pt.name)
elif pt.name in ("init_declarator", "member_declarator"):
indirection = ''
# Now we want this:
# declarator *
# direct_declarator ID
#
# ... or any of these :
# direct_declarator ID <- function declaration
# parameter_list
# type_qualifier
# exception_specification
# direct_declarator ID <- class instantation / array declaration
# expression
# direct_declarator ID <- ?
# declarator <- function ptr
# declarator_suffixes
decl_pt = pt.get_child('declarator')
direct_decl_pt = pt.get_child('direct_declarator')
decl_suffixes_pt = None
# We want to get to a direct_declarator if it exists. This is a convoluted
# process -- probably best to refer to the relevant grammar section.
while decl_pt is not None:
if decl_pt.leaf == '*':
indirection += '*'
direct_decl_pt = decl_pt.get_child('direct_declarator')
if direct_decl_pt:
break
else:
decl_pt = decl_pt.get_child('declarator')
assert decl_pt
decl.add_attribute('indirection', indirection)
# Now we are down to direct_declarator.
if direct_decl_pt.has_child('declarator'):
# This is a function pointer - we don't support these too well.
decl_pt = direct_decl_pt.get_child('declarator')
direct_decl_pt = decl_pt.get_child('direct_declarator')
decl.leaf = direct_decl_pt.leaf
expr = pt.get_child('expression')
if not expr and pt.has_child('initializer'):
expr = pt.get_child('initializer').get_child('expression')
ast_expr = None
if expr:
ast_expr = get_expression(parentast, expr, self)
if ast_expr:
decl.add_child(ast_expr)
return decl
def _function_parameter(self, ast, pt):
"""
Looks like this:
parameter_declaration
declaration_specifiers
direct_declarator | declarator
"""
declaration_specifiers = pt.get_child('declaration_specifiers')
node = Node(ast, 'parameter', source = pt)
target_ast = self._wrap_node('target', ast,
self.get_type(node, declaration_specifiers))
node.add_child(target_ast)
indirection = ''
if pt.get_child('direct_declarator'):
final_declarator = pt
else:
declarator = pt.get_child('declarator')
final_declarator = declarator
while declarator:
indirection += declarator.leaf
final_declarator = declarator
declarator = declarator.get_child('declarator')
node.leaf = final_declarator.get_child('direct_declarator').leaf
indirection_ast = Node(node, 'indirection', leaf = indirection, source = final_declarator)
node.add_child(indirection_ast)
return node
def _statements(self, ast, pt):
"""
Returns a list of parsed statements from "ast".
"""
results = None
while pt.name == 'statement':
pt = pt.children[0]
if pt.name == 'jump_statement':
results = [self._jump_statement(ast, pt)]
elif pt.name == 'expression':
results = [get_expression(ast, pt, self)]
elif pt.name == 'selection_statement':
results = [self._selection_statement(ast, pt)]
elif pt.name == 'case_statement':
results = [self._case_statement(ast, pt)]
elif pt.name == 'default_statement':
results = [self._default_statement(ast, pt)]
elif pt.name == 'iteration_statement':
results = [self._iteration_statement(ast, pt)]
elif pt.name == 'compound_statement':
results = self._compound_statement(ast, pt)
elif pt.name == 'declaration':
results = self.declaration(ast, pt)
elif pt.name == 'asm_block':
results = [UnfinishedNode('asm_block')]
elif pt.name == 'blank':
results = []
else:
pt.print_tree()
raise Exception("Unknown statement '%s'" % (pt.name))
return results
def _compound_statement(self, ast, pt):
"""
Return a node representing a compound statement.
"""
statement_list = pt.get_child('statement_list')
results = []
if statement_list:
for statement_pt in statement_list.children:
results.extend(self._statements(ast, statement_pt))
return results
def _jump_statement(self, ast, pt):
node = Node(ast, 'exit', source = pt)
if pt.leaf == 'return':
expression = pt.get_child('expression')
if expression:
node.add_child(expression)
elif pt.leaf in ('break', 'continue'):
pass
else:
raise Exception("Unknown jump statement type %s" % (pt.leaf))
return node
def _selection_statement(self, ast, pt):
"""
Handle "switch() {} and if() {}"
The PT's two children should be an expression and a compound_statement.
We rewrite switch statements to be multiple "if" statements -
possibly stupidly...
"""
if pt.leaf == 'switch':
return self._selection_statement_switch(ast, pt)
elif pt.leaf == 'if':
return self._selection_statement_if(ast, pt)
else:
raise Exception("Unknown selection_statement %s" % (pt.leaf))
def _selection_statement_if(self, ast, pt):
""" Handle "if" statement. See caller for more info. """
condition_pt = pt.children[0]
cases_pt = pt.children[1]
expr_ast = get_expression(ast, condition_pt, self)
statements_ast = Node(ast, "body", source = cases_pt)
if_ast = Node(ast, 'if', [expr_ast, statements_ast], source = pt)
statements_ast.add_children(self._statements(statements_ast, cases_pt))
# Handle "else" cases.
else_clause_pt = pt.get_child('else')
if else_clause_pt:
else_statements_pt = else_clause_pt.child()
else_clause_ast = Node(if_ast, 'else', source = else_clause_pt)
if_ast.add_child(else_clause_ast)
statements_list = self._statements(else_clause_ast, else_statements_pt)
else_clause_ast.add_children(statements_list)
return if_ast
def _selection_statement_switch(self, ast, pt):
""" Handle "switch" statement. See caller for more info.
Output of type
switch
expression (to switch on)
expression (actions)
"""
# FIXME: Do we handle fall-through switching at all?
expr_pt, cases_pt = pt.children
expr_ast = get_expression(ast, expr_pt, self)
statements_ast = self._statements(ast, cases_pt)
return Node(ast, 'switch', children = [expr_ast] + statements_ast)
def _case_statement(self, ast, pt):
expr_pt, statement_pt = pt.children
expr_ast = get_expression(ast, expr_pt, self)
statements_ast = self._statements(ast, statement_pt)
return Node(ast, 'case', children = [expr_ast] + statements_ast)
def _default_statement(self, ast, pt):
statement_pt = pt.child()
statements_ast = self._statements(ast, statement_pt)
return Node(ast, 'default', children = statements_ast)
def _iteration_statement(self, ast, pt):
if pt.leaf == 'while':
return self._iteration_statement_while(ast, pt)
elif pt.leaf == 'do':
return self._iteration_statement_do(ast, pt)
elif pt.leaf == 'for':
return self._iteration_statement_for(ast, pt)
else:
pt.print_tree()
raise Error("Unknown iteration statement %s" % (pt.leaf))
def _iteration_statement_while(self, ast, pt):
expr_pt, statement_pt = pt.children
expr_ast = get_expression(ast, expr_pt, self)
statements_ast = Node(ast, "body", source = statement_pt)
statements_ast.add_children(self._statements(statements_ast, statement_pt))
return Node(ast, 'while', [expr_ast, statements_ast], source = pt)
def _iteration_statement_for(self, ast, pt):
init_pt, while_pt, post_pt, body_pt = pt.children
# init_pt is an expression or a declaration.
if init_pt.name == 'blank':
init_ast = Node(ast, 'blank')
elif self._is_declaration(init_pt):
init_ast = self.declaration(init_pt)
else:
init_ast = [get_expression(ast, init_pt, self)]
if while_pt.name != 'blank':
while_ast = get_expression(ast, while_pt, self)
else:
while_ast = Node(ast, 'blank')
if post_pt.name != 'blank':
post_ast = get_expression(ast, post_pt, self)
else:
post_ast = Node(ast, 'blank')
body_ast = self._statements(ast, body_pt)
return Node(ast, 'for', init_ast + [while_ast, post_ast] + body_ast)
def _construct_expr_from_value(self, parent_ast, value):
""" Cheesy hack to encode full (non-typechecked) values of expressions
as a string """
expr_ast = Node(parent_ast, 'expression', leaf = 'raw', source = parent_ast)
expr_ast.add_attribute('value', value)
return expr_ast
def find_or_create_type(self, parentast, pt):
# Called when we're not sure if the current type must be created
assert pt.name in CLASS_SPECIFIERS
ast = None
if pt.leaf:
ast = getTypenode(pt.leaf, parentast)
if ast and not ast.get_child('members') and pt.get_child('members'):
# and use this one.
ast = None
# By this point the name isn't declared, or we need to define a
if not ast:
ast = self.create_type(parentast, pt)
# Done: if we're None at this point something is broken.
assert ast is not None
return ast
def _member_declarator_list(self, parentast, pt):
"""
Return a list of instance names.
"""
return self._some_declarator_list(parentast, pt)
def _init_declarator_get_value(self, pt):
pass
def gen(baseast, pt, filename, **kwargs):
astgen = ASTGen(**kwargs)
return astgen.convert(baseast, pt, filename)
| false | true |
f723919f35f433f2ae01be4bddf4076f7c54d945 | 135 | py | Python | tmdb/schema/tv_season.py | leandcesar/tmdb-python | a6933d4f8807b07d8f09d0cf9d45555b5a8212f7 | [
"MIT"
] | null | null | null | tmdb/schema/tv_season.py | leandcesar/tmdb-python | a6933d4f8807b07d8f09d0cf9d45555b5a8212f7 | [
"MIT"
] | 1 | 2022-03-08T15:08:34.000Z | 2022-03-08T15:08:34.000Z | tmdb/schema/tv_season.py | leandcesar/tmdb-python | a6933d4f8807b07d8f09d0cf9d45555b5a8212f7 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
from dataclasses import dataclass
from typing import Optional
@dataclass
class Season:
id: Optional[int]
| 15 | 33 | 0.718519 |
from dataclasses import dataclass
from typing import Optional
@dataclass
class Season:
id: Optional[int]
| true | true |
f72391e581e5477cb6c44e276c56fea7cf53fa01 | 479 | py | Python | alipay/aop/api/response/AlipayFundJointaccountOperationApproveResponse.py | antopen/alipay-sdk-python-all | 8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c | [
"Apache-2.0"
] | 213 | 2018-08-27T16:49:32.000Z | 2021-12-29T04:34:12.000Z | alipay/aop/api/response/AlipayFundJointaccountOperationApproveResponse.py | antopen/alipay-sdk-python-all | 8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c | [
"Apache-2.0"
] | 29 | 2018-09-29T06:43:00.000Z | 2021-09-02T03:27:32.000Z | alipay/aop/api/response/AlipayFundJointaccountOperationApproveResponse.py | antopen/alipay-sdk-python-all | 8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c | [
"Apache-2.0"
] | 59 | 2018-08-27T16:59:26.000Z | 2022-03-25T10:08:15.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayFundJointaccountOperationApproveResponse(AlipayResponse):
def __init__(self):
super(AlipayFundJointaccountOperationApproveResponse, self).__init__()
def parse_response_content(self, response_content):
response = super(AlipayFundJointaccountOperationApproveResponse, self).parse_response_content(response_content)
| 29.9375 | 119 | 0.797495 |
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayFundJointaccountOperationApproveResponse(AlipayResponse):
def __init__(self):
super(AlipayFundJointaccountOperationApproveResponse, self).__init__()
def parse_response_content(self, response_content):
response = super(AlipayFundJointaccountOperationApproveResponse, self).parse_response_content(response_content)
| true | true |
f7239210712c9f581702e80a31637eac0d0a7c86 | 19,536 | py | Python | resources/usr/local/lib/python2.7/dist-packages/sklearn/cluster/bicluster/spectral.py | edawson/parliament2 | 2632aa3484ef64c9539c4885026b705b737f6d1e | [
"Apache-2.0"
] | null | null | null | resources/usr/local/lib/python2.7/dist-packages/sklearn/cluster/bicluster/spectral.py | edawson/parliament2 | 2632aa3484ef64c9539c4885026b705b737f6d1e | [
"Apache-2.0"
] | null | null | null | resources/usr/local/lib/python2.7/dist-packages/sklearn/cluster/bicluster/spectral.py | edawson/parliament2 | 2632aa3484ef64c9539c4885026b705b737f6d1e | [
"Apache-2.0"
] | 1 | 2020-05-28T23:01:44.000Z | 2020-05-28T23:01:44.000Z | """Implements spectral biclustering algorithms.
Authors : Kemal Eren
License: BSD 3 clause
"""
from abc import ABCMeta, abstractmethod
import numpy as np
from scipy.sparse import dia_matrix
from scipy.sparse import issparse
from sklearn.base import BaseEstimator, BiclusterMixin
from sklearn.externals import six
from sklearn.utils.arpack import svds
from sklearn.utils.arpack import eigsh
from sklearn.cluster import KMeans
from sklearn.cluster import MiniBatchKMeans
from sklearn.utils.extmath import randomized_svd
from sklearn.utils.extmath import safe_sparse_dot
from sklearn.utils.extmath import make_nonnegative
from sklearn.utils.extmath import norm
from sklearn.utils.validation import assert_all_finite
from sklearn.utils.validation import check_arrays
from .utils import check_array_ndim
def _scale_normalize(X):
"""Normalize ``X`` by scaling rows and columns independently.
Returns the normalized matrix and the row and column scaling
factors.
"""
X = make_nonnegative(X)
row_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=1))).squeeze()
col_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=0))).squeeze()
row_diag = np.where(np.isnan(row_diag), 0, row_diag)
col_diag = np.where(np.isnan(col_diag), 0, col_diag)
if issparse(X):
n_rows, n_cols = X.shape
r = dia_matrix((row_diag, [0]), shape=(n_rows, n_rows))
c = dia_matrix((col_diag, [0]), shape=(n_cols, n_cols))
an = r * X * c
else:
an = row_diag[:, np.newaxis] * X * col_diag
return an, row_diag, col_diag
def _bistochastic_normalize(X, max_iter=1000, tol=1e-5):
"""Normalize rows and columns of ``X`` simultaneously so that all
rows sum to one constant and all columns sum to a different
constant.
"""
# According to paper, this can also be done more efficiently with
# deviation reduction and balancing algorithms.
X = make_nonnegative(X)
X_scaled = X
dist = None
for _ in range(max_iter):
X_new, _, _ = _scale_normalize(X_scaled)
if issparse(X):
dist = norm(X_scaled.data - X.data)
else:
dist = norm(X_scaled - X_new)
X_scaled = X_new
if dist is not None and dist < tol:
break
return X_scaled
def _log_normalize(X):
"""Normalize ``X`` according to Kluger's log-interactions scheme."""
X = make_nonnegative(X, min_value=1)
if issparse(X):
raise ValueError("Cannot compute log of a sparse matrix,"
" because log(x) diverges to -infinity as x"
" goes to 0.")
L = np.log(X)
row_avg = L.mean(axis=1)[:, np.newaxis]
col_avg = L.mean(axis=0)
avg = L.mean()
return L - row_avg - col_avg + avg
class BaseSpectral(six.with_metaclass(ABCMeta, BaseEstimator,
BiclusterMixin)):
"""Base class for spectral biclustering."""
@abstractmethod
def __init__(self, n_clusters=3, svd_method="randomized",
n_svd_vecs=None, mini_batch=False, init="k-means++",
n_init=10, n_jobs=1, random_state=None):
self.n_clusters = n_clusters
self.svd_method = svd_method
self.n_svd_vecs = n_svd_vecs
self.mini_batch = mini_batch
self.init = init
self.n_init = n_init
self.n_jobs = n_jobs
self.random_state = random_state
def _check_parameters(self):
legal_svd_methods = ('randomized', 'arpack')
if self.svd_method not in legal_svd_methods:
raise ValueError("Unknown SVD method: '{}'. svd_method must be"
" one of {}.".format(self.svd_method,
legal_svd_methods))
def fit(self, X):
"""Creates a biclustering for X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
"""
X, = check_arrays(X, sparse_format='csr', dtype=np.float64)
check_array_ndim(X)
self._check_parameters()
self._fit(X)
def _svd(self, array, n_components, n_discard):
"""Returns first `n_components` left and right singular
vectors u and v, discarding the first `n_discard`.
"""
if self.svd_method == 'randomized':
kwargs = {}
if self.n_svd_vecs is not None:
kwargs['n_oversamples'] = self.n_svd_vecs
u, _, vt = randomized_svd(array, n_components,
random_state=self.random_state,
**kwargs)
elif self.svd_method == 'arpack':
u, _, vt = svds(array, k=n_components, ncv=self.n_svd_vecs)
if np.any(np.isnan(vt)):
# some eigenvalues of A * A.T are negative, causing
# sqrt() to be np.nan. This causes some vectors in vt
# to be np.nan.
_, v = eigsh(safe_sparse_dot(array.T, array),
ncv=self.n_svd_vecs)
vt = v.T
if np.any(np.isnan(u)):
_, u = eigsh(safe_sparse_dot(array, array.T),
ncv=self.n_svd_vecs)
assert_all_finite(u)
assert_all_finite(vt)
u = u[:, n_discard:]
vt = vt[n_discard:]
return u, vt.T
def _k_means(self, data, n_clusters):
if self.mini_batch:
model = MiniBatchKMeans(n_clusters,
init=self.init,
n_init=self.n_init,
random_state=self.random_state)
else:
model = KMeans(n_clusters, init=self.init,
n_init=self.n_init, n_jobs=self.n_jobs,
random_state=self.random_state)
model.fit(data)
centroid = model.cluster_centers_
labels = model.labels_
return centroid, labels
class SpectralCoclustering(BaseSpectral):
"""Spectral Co-Clustering algorithm (Dhillon, 2001).
Clusters rows and columns of an array `X` to solve the relaxed
normalized cut of the bipartite graph created from `X` as follows:
the edge between row vertex `i` and column vertex `j` has weight
`X[i, j]`.
The resulting bicluster structure is block-diagonal, since each
row and each column belongs to exactly one bicluster.
Supports sparse matrices, as long as they are nonnegative.
Parameters
----------
n_clusters : integer, optional, default: 3
The number of biclusters to find.
svd_method : string, optional, default: 'randomized'
Selects the algorithm for finding singular vectors. May be
'randomized' or 'arpack'. If 'randomized', use
:func:`sklearn.utils.extmath.randomized_svd`, which may be faster
for large matrices. If 'arpack', use
:func:`sklearn.utils.arpack.svds`, which is more accurate, but
possibly slower in some cases.
n_svd_vecs : int, optional, default: None
Number of vectors to use in calculating the SVD. Corresponds
to `ncv` when `svd_method=arpack` and `n_oversamples` when
`svd_method` is 'randomized`.
mini_batch : bool, optional, default: False
Whether to use mini-batch k-means, which is faster but may get
different results.
init : {'k-means++', 'random' or an ndarray}
Method for initialization of k-means algorithm; defaults to
'k-means++'.
n_init : int, optional, default: 10
Number of random initializations that are tried with the
k-means algorithm.
If mini-batch k-means is used, the best initialization is
chosen and the algorithm runs once. Otherwise, the algorithm
is run for each initialization and the best solution chosen.
n_jobs : int, optional, default: 1
The number of jobs to use for the computation. This works by breaking
down the pairwise matrix into n_jobs even slices and computing them in
parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debuging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
random_state : int seed, RandomState instance, or None (default)
A pseudo random number generator used by the K-Means
initialization.
Attributes
----------
`rows_` : array-like, shape (n_row_clusters, n_rows)
Results of the clustering. `rows[i, r]` is True if cluster `i`
contains row `r`. Available only after calling ``fit``.
`columns_` : array-like, shape (n_column_clusters, n_columns)
Results of the clustering, like `rows`.
`row_labels_` : array-like, shape (n_rows,)
The bicluster label of each row.
`column_labels_` : array-like, shape (n_cols,)
The bicluster label of each column.
References
----------
* Dhillon, Inderjit S, 2001. `Co-clustering documents and words using
bipartite spectral graph partitioning
<http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.140.3011>`__.
"""
def __init__(self, n_clusters=3, svd_method='randomized',
n_svd_vecs=None, mini_batch=False, init='k-means++',
n_init=10, n_jobs=1, random_state=None):
super(SpectralCoclustering, self).__init__(n_clusters,
svd_method,
n_svd_vecs,
mini_batch,
init,
n_init,
n_jobs,
random_state)
def _fit(self, X):
normalized_data, row_diag, col_diag = _scale_normalize(X)
n_sv = 1 + int(np.ceil(np.log2(self.n_clusters)))
u, v = self._svd(normalized_data, n_sv, n_discard=1)
z = np.vstack((row_diag[:, np.newaxis] * u,
col_diag[:, np.newaxis] * v))
_, labels = self._k_means(z, self.n_clusters)
n_rows = X.shape[0]
self.row_labels_ = labels[:n_rows]
self.column_labels_ = labels[n_rows:]
self.rows_ = np.vstack(self.row_labels_ == c
for c in range(self.n_clusters))
self.columns_ = np.vstack(self.column_labels_ == c
for c in range(self.n_clusters))
class SpectralBiclustering(BaseSpectral):
"""Spectral biclustering (Kluger, 2003).
Partitions rows and columns under the assumption that the data has
an underlying checkerboard structure. For instance, if there are
two row partitions and three column partitions, each row will
belong to three biclusters, and each column will belong to two
biclusters. The outer product of the corresponding row and column
label vectors gives this checkerboard structure.
Parameters
----------
n_clusters : integer or tuple (n_row_clusters, n_column_clusters)
The number of row and column clusters in the checkerboard
structure.
method : string, optional, default: 'bistochastic'
Method of normalizing and converting singular vectors into
biclusters. May be one of 'scale', 'bistochastic', or 'log'.
The authors recommend using 'log'. If the data is sparse,
however, log normalization will not work, which is why the
default is 'bistochastic'. CAUTION: if `method='log'`, the
data must not be sparse.
n_components : integer, optional, default: 6
Number of singular vectors to check.
n_best : integer, optional, default: 3
Number of best singular vectors to which to project the data
for clustering.
svd_method : string, optional, default: 'randomized'
Selects the algorithm for finding singular vectors. May be
'randomized' or 'arpack'. If 'randomized', uses
`sklearn.utils.extmath.randomized_svd`, which may be faster
for large matrices. If 'arpack', uses
`sklearn.utils.arpack.svds`, which is more accurate, but
possibly slower in some cases.
n_svd_vecs : int, optional, default: None
Number of vectors to use in calculating the SVD. Corresponds
to `ncv` when `svd_method=arpack` and `n_oversamples` when
`svd_method` is 'randomized`.
mini_batch : bool, optional, default: False
Whether to use mini-batch k-means, which is faster but may get
different results.
init : {'k-means++', 'random' or an ndarray}
Method for initialization of k-means algorithm; defaults to
'k-means++'.
n_init : int, optional, default: 10
Number of random initializations that are tried with the
k-means algorithm.
If mini-batch k-means is used, the best initialization is
chosen and the algorithm runs once. Otherwise, the algorithm
is run for each initialization and the best solution chosen.
n_jobs : int, optional, default: 1
The number of jobs to use for the computation. This works by breaking
down the pairwise matrix into n_jobs even slices and computing them in
parallel.
If -1 all CPUs are used. If 1 is given, no parallel computing code is
used at all, which is useful for debuging. For n_jobs below -1,
(n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all CPUs but one
are used.
random_state : int seed, RandomState instance, or None (default)
A pseudo random number generator used by the K-Means
initialization.
Attributes
----------
`rows_` : array-like, shape (n_row_clusters, n_rows)
Results of the clustering. `rows[i, r]` is True if cluster `i`
contains row `r`. Available only after calling ``fit``.
`columns_` : array-like, shape (n_column_clusters, n_columns)
Results of the clustering, like `rows`.
`row_labels_` : array-like, shape (n_rows,)
Row partition labels.
`column_labels_` : array-like, shape (n_cols,)
Column partition labels.
References
----------
* Kluger, Yuval, et. al., 2003. `Spectral biclustering of microarray
data: coclustering genes and conditions
<http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.135.1608>`__.
"""
def __init__(self, n_clusters=3, method='bistochastic',
n_components=6, n_best=3, svd_method='randomized',
n_svd_vecs=None, mini_batch=False, init='k-means++',
n_init=10, n_jobs=1, random_state=None):
super(SpectralBiclustering, self).__init__(n_clusters,
svd_method,
n_svd_vecs,
mini_batch,
init,
n_init,
n_jobs,
random_state)
self.method = method
self.n_components = n_components
self.n_best = n_best
def _check_parameters(self):
super(SpectralBiclustering, self)._check_parameters()
legal_methods = ('bistochastic', 'scale', 'log')
if self.method not in legal_methods:
raise ValueError("Unknown method: '{}'. method must be"
" one of {}.".format(self.method, legal_methods))
try:
int(self.n_clusters)
except TypeError:
try:
r, c = self.n_clusters
int(r)
int(c)
except (ValueError, TypeError):
raise ValueError("Incorrect parameter n_clusters has value:"
" {}. It should either be a single integer"
" or an iterable with two integers:"
" (n_row_clusters, n_column_clusters)")
if self.n_components < 1:
raise ValueError("Parameter n_components must be greater than 0,"
" but its value is {}".format(self.n_components))
if self.n_best < 1:
raise ValueError("Parameter n_best must be greater than 0,"
" but its value is {}".format(self.n_best))
if self.n_best > self.n_components:
raise ValueError("n_best cannot be larger than"
" n_components, but {} > {}"
"".format(self.n_best, self.n_components))
def _fit(self, X):
n_sv = self.n_components
if self.method == 'bistochastic':
normalized_data = _bistochastic_normalize(X)
n_sv += 1
elif self.method == 'scale':
normalized_data, _, _ = _scale_normalize(X)
n_sv += 1
elif self.method == 'log':
normalized_data = _log_normalize(X)
n_discard = 0 if self.method == 'log' else 1
u, v = self._svd(normalized_data, n_sv, n_discard)
ut = u.T
vt = v.T
try:
n_row_clusters, n_col_clusters = self.n_clusters
except TypeError:
n_row_clusters = n_col_clusters = self.n_clusters
best_ut = self._fit_best_piecewise(ut, self.n_best,
n_row_clusters)
best_vt = self._fit_best_piecewise(vt, self.n_best,
n_col_clusters)
self.row_labels_ = self._project_and_cluster(X, best_vt.T,
n_row_clusters)
self.column_labels_ = self._project_and_cluster(X.T, best_ut.T,
n_col_clusters)
self.rows_ = np.vstack(self.row_labels_ == label
for label in range(n_row_clusters)
for _ in range(n_col_clusters))
self.columns_ = np.vstack(self.column_labels_ == label
for _ in range(n_row_clusters)
for label in range(n_col_clusters))
def _fit_best_piecewise(self, vectors, n_best, n_clusters):
"""Find the ``n_best`` vectors that are best approximated by piecewise
constant vectors.
The piecewise vectors are found by k-means; the best is chosen
according to Euclidean distance.
"""
def make_piecewise(v):
centroid, labels = self._k_means(v.reshape(-1, 1), n_clusters)
return centroid[labels].ravel()
piecewise_vectors = np.apply_along_axis(make_piecewise,
axis=1, arr=vectors)
dists = np.apply_along_axis(norm, axis=1,
arr=(vectors - piecewise_vectors))
result = vectors[np.argsort(dists)[:n_best]]
return result
def _project_and_cluster(self, data, vectors, n_clusters):
"""Project ``data`` to ``vectors`` and cluster the result."""
projected = safe_sparse_dot(data, vectors)
_, labels = self._k_means(projected, n_clusters)
return labels
| 39.466667 | 78 | 0.589373 | from abc import ABCMeta, abstractmethod
import numpy as np
from scipy.sparse import dia_matrix
from scipy.sparse import issparse
from sklearn.base import BaseEstimator, BiclusterMixin
from sklearn.externals import six
from sklearn.utils.arpack import svds
from sklearn.utils.arpack import eigsh
from sklearn.cluster import KMeans
from sklearn.cluster import MiniBatchKMeans
from sklearn.utils.extmath import randomized_svd
from sklearn.utils.extmath import safe_sparse_dot
from sklearn.utils.extmath import make_nonnegative
from sklearn.utils.extmath import norm
from sklearn.utils.validation import assert_all_finite
from sklearn.utils.validation import check_arrays
from .utils import check_array_ndim
def _scale_normalize(X):
X = make_nonnegative(X)
row_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=1))).squeeze()
col_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=0))).squeeze()
row_diag = np.where(np.isnan(row_diag), 0, row_diag)
col_diag = np.where(np.isnan(col_diag), 0, col_diag)
if issparse(X):
n_rows, n_cols = X.shape
r = dia_matrix((row_diag, [0]), shape=(n_rows, n_rows))
c = dia_matrix((col_diag, [0]), shape=(n_cols, n_cols))
an = r * X * c
else:
an = row_diag[:, np.newaxis] * X * col_diag
return an, row_diag, col_diag
def _bistochastic_normalize(X, max_iter=1000, tol=1e-5):
X = make_nonnegative(X)
X_scaled = X
dist = None
for _ in range(max_iter):
X_new, _, _ = _scale_normalize(X_scaled)
if issparse(X):
dist = norm(X_scaled.data - X.data)
else:
dist = norm(X_scaled - X_new)
X_scaled = X_new
if dist is not None and dist < tol:
break
return X_scaled
def _log_normalize(X):
X = make_nonnegative(X, min_value=1)
if issparse(X):
raise ValueError("Cannot compute log of a sparse matrix,"
" because log(x) diverges to -infinity as x"
" goes to 0.")
L = np.log(X)
row_avg = L.mean(axis=1)[:, np.newaxis]
col_avg = L.mean(axis=0)
avg = L.mean()
return L - row_avg - col_avg + avg
class BaseSpectral(six.with_metaclass(ABCMeta, BaseEstimator,
BiclusterMixin)):
@abstractmethod
def __init__(self, n_clusters=3, svd_method="randomized",
n_svd_vecs=None, mini_batch=False, init="k-means++",
n_init=10, n_jobs=1, random_state=None):
self.n_clusters = n_clusters
self.svd_method = svd_method
self.n_svd_vecs = n_svd_vecs
self.mini_batch = mini_batch
self.init = init
self.n_init = n_init
self.n_jobs = n_jobs
self.random_state = random_state
def _check_parameters(self):
legal_svd_methods = ('randomized', 'arpack')
if self.svd_method not in legal_svd_methods:
raise ValueError("Unknown SVD method: '{}'. svd_method must be"
" one of {}.".format(self.svd_method,
legal_svd_methods))
def fit(self, X):
X, = check_arrays(X, sparse_format='csr', dtype=np.float64)
check_array_ndim(X)
self._check_parameters()
self._fit(X)
def _svd(self, array, n_components, n_discard):
if self.svd_method == 'randomized':
kwargs = {}
if self.n_svd_vecs is not None:
kwargs['n_oversamples'] = self.n_svd_vecs
u, _, vt = randomized_svd(array, n_components,
random_state=self.random_state,
**kwargs)
elif self.svd_method == 'arpack':
u, _, vt = svds(array, k=n_components, ncv=self.n_svd_vecs)
if np.any(np.isnan(vt)):
_, v = eigsh(safe_sparse_dot(array.T, array),
ncv=self.n_svd_vecs)
vt = v.T
if np.any(np.isnan(u)):
_, u = eigsh(safe_sparse_dot(array, array.T),
ncv=self.n_svd_vecs)
assert_all_finite(u)
assert_all_finite(vt)
u = u[:, n_discard:]
vt = vt[n_discard:]
return u, vt.T
def _k_means(self, data, n_clusters):
if self.mini_batch:
model = MiniBatchKMeans(n_clusters,
init=self.init,
n_init=self.n_init,
random_state=self.random_state)
else:
model = KMeans(n_clusters, init=self.init,
n_init=self.n_init, n_jobs=self.n_jobs,
random_state=self.random_state)
model.fit(data)
centroid = model.cluster_centers_
labels = model.labels_
return centroid, labels
class SpectralCoclustering(BaseSpectral):
def __init__(self, n_clusters=3, svd_method='randomized',
n_svd_vecs=None, mini_batch=False, init='k-means++',
n_init=10, n_jobs=1, random_state=None):
super(SpectralCoclustering, self).__init__(n_clusters,
svd_method,
n_svd_vecs,
mini_batch,
init,
n_init,
n_jobs,
random_state)
def _fit(self, X):
normalized_data, row_diag, col_diag = _scale_normalize(X)
n_sv = 1 + int(np.ceil(np.log2(self.n_clusters)))
u, v = self._svd(normalized_data, n_sv, n_discard=1)
z = np.vstack((row_diag[:, np.newaxis] * u,
col_diag[:, np.newaxis] * v))
_, labels = self._k_means(z, self.n_clusters)
n_rows = X.shape[0]
self.row_labels_ = labels[:n_rows]
self.column_labels_ = labels[n_rows:]
self.rows_ = np.vstack(self.row_labels_ == c
for c in range(self.n_clusters))
self.columns_ = np.vstack(self.column_labels_ == c
for c in range(self.n_clusters))
class SpectralBiclustering(BaseSpectral):
def __init__(self, n_clusters=3, method='bistochastic',
n_components=6, n_best=3, svd_method='randomized',
n_svd_vecs=None, mini_batch=False, init='k-means++',
n_init=10, n_jobs=1, random_state=None):
super(SpectralBiclustering, self).__init__(n_clusters,
svd_method,
n_svd_vecs,
mini_batch,
init,
n_init,
n_jobs,
random_state)
self.method = method
self.n_components = n_components
self.n_best = n_best
def _check_parameters(self):
super(SpectralBiclustering, self)._check_parameters()
legal_methods = ('bistochastic', 'scale', 'log')
if self.method not in legal_methods:
raise ValueError("Unknown method: '{}'. method must be"
" one of {}.".format(self.method, legal_methods))
try:
int(self.n_clusters)
except TypeError:
try:
r, c = self.n_clusters
int(r)
int(c)
except (ValueError, TypeError):
raise ValueError("Incorrect parameter n_clusters has value:"
" {}. It should either be a single integer"
" or an iterable with two integers:"
" (n_row_clusters, n_column_clusters)")
if self.n_components < 1:
raise ValueError("Parameter n_components must be greater than 0,"
" but its value is {}".format(self.n_components))
if self.n_best < 1:
raise ValueError("Parameter n_best must be greater than 0,"
" but its value is {}".format(self.n_best))
if self.n_best > self.n_components:
raise ValueError("n_best cannot be larger than"
" n_components, but {} > {}"
"".format(self.n_best, self.n_components))
def _fit(self, X):
n_sv = self.n_components
if self.method == 'bistochastic':
normalized_data = _bistochastic_normalize(X)
n_sv += 1
elif self.method == 'scale':
normalized_data, _, _ = _scale_normalize(X)
n_sv += 1
elif self.method == 'log':
normalized_data = _log_normalize(X)
n_discard = 0 if self.method == 'log' else 1
u, v = self._svd(normalized_data, n_sv, n_discard)
ut = u.T
vt = v.T
try:
n_row_clusters, n_col_clusters = self.n_clusters
except TypeError:
n_row_clusters = n_col_clusters = self.n_clusters
best_ut = self._fit_best_piecewise(ut, self.n_best,
n_row_clusters)
best_vt = self._fit_best_piecewise(vt, self.n_best,
n_col_clusters)
self.row_labels_ = self._project_and_cluster(X, best_vt.T,
n_row_clusters)
self.column_labels_ = self._project_and_cluster(X.T, best_ut.T,
n_col_clusters)
self.rows_ = np.vstack(self.row_labels_ == label
for label in range(n_row_clusters)
for _ in range(n_col_clusters))
self.columns_ = np.vstack(self.column_labels_ == label
for _ in range(n_row_clusters)
for label in range(n_col_clusters))
def _fit_best_piecewise(self, vectors, n_best, n_clusters):
def make_piecewise(v):
centroid, labels = self._k_means(v.reshape(-1, 1), n_clusters)
return centroid[labels].ravel()
piecewise_vectors = np.apply_along_axis(make_piecewise,
axis=1, arr=vectors)
dists = np.apply_along_axis(norm, axis=1,
arr=(vectors - piecewise_vectors))
result = vectors[np.argsort(dists)[:n_best]]
return result
def _project_and_cluster(self, data, vectors, n_clusters):
projected = safe_sparse_dot(data, vectors)
_, labels = self._k_means(projected, n_clusters)
return labels
| true | true |
f723921ec1c066a63898e9c7ce22f1cda00adbe2 | 636 | py | Python | backoffice/core/migrations/0014_auto_20171121_1804.py | ParticipaPY/civic-crowdanalytics | b27aefb54a747d3155cc79f87faeb6361eb0503b | [
"MIT"
] | 8 | 2017-11-02T17:00:18.000Z | 2022-02-28T22:41:37.000Z | backoffice/core/migrations/0014_auto_20171121_1804.py | ParticipaPY/civic-crowdanalytics | b27aefb54a747d3155cc79f87faeb6361eb0503b | [
"MIT"
] | 84 | 2017-09-04T20:28:58.000Z | 2022-03-02T02:06:10.000Z | backoffice/core/migrations/0014_auto_20171121_1804.py | olivernash/collective-analytics | f494cd08841023cb667fa7dcd144b609d46a5f7b | [
"MIT"
] | 1 | 2017-09-19T01:35:45.000Z | 2017-09-19T01:35:45.000Z | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-11-21 21:04
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0013_auto_20171106_1017'),
]
operations = [
migrations.AlterField(
model_name='project',
name='description',
field=models.CharField(blank=True, max_length=250),
),
migrations.AlterField(
model_name='project',
name='location',
field=models.CharField(blank=True, max_length=150),
),
]
| 24.461538 | 63 | 0.600629 |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0013_auto_20171106_1017'),
]
operations = [
migrations.AlterField(
model_name='project',
name='description',
field=models.CharField(blank=True, max_length=250),
),
migrations.AlterField(
model_name='project',
name='location',
field=models.CharField(blank=True, max_length=150),
),
]
| true | true |
f72392b30432110c4ab3003a03ed07f9f652aa23 | 2,820 | py | Python | grouping.py | Noble-Lab/2021_asur_scaffolding | ceef5c8b897b83e9f80be35fb32f00377584798f | [
"MIT"
] | null | null | null | grouping.py | Noble-Lab/2021_asur_scaffolding | ceef5c8b897b83e9f80be35fb32f00377584798f | [
"MIT"
] | null | null | null | grouping.py | Noble-Lab/2021_asur_scaffolding | ceef5c8b897b83e9f80be35fb32f00377584798f | [
"MIT"
] | null | null | null | '''
Since scaffolds are not directly stored and instead are assocaited with each
contig, we must extract the total length of scaffolds in each assembly, as
well as the length of any intersections.
Then, we get the maximum weighted jaccard index for each reference scaffold,
which is defined as the length of the intersection divided by the length of
the union. To weight this in the averaging step, we then multiply this by
the length of the reference scaffold.
The sum of these maximum weighted indicies are then divided by the total
length of the reference scaffolds.
'''
def count(first, second):
first_contigs, first_positions = first
second_contigs, second_positions = second
intersection_scaffolds = {}
first_scaffolds = {}
second_scaffolds = {}
for contig in first_contigs:
# Get contig length and scaffold information.
contig_length = first_contigs[contig]['length']
first_scaffold_name = first_contigs[contig]['scaffold']
second_scaffold_name = second_contigs[contig]['scaffold']
# Iterate the count and length on the scaffold of the first assembly.
if first_scaffold_name not in first_scaffolds:
first_scaffolds[first_scaffold_name] = contig_length
else:
first_scaffolds[first_scaffold_name] += contig_length
# Iterate the count and length on the scaffold of the second assembly.
if second_scaffold_name not in second_scaffolds:
second_scaffolds[second_scaffold_name] = contig_length
else:
second_scaffolds[second_scaffold_name] += contig_length
# Iterate the count of the intersection.
intersection = (first_scaffold_name, second_scaffold_name)
if intersection not in intersection_scaffolds:
intersection_scaffolds[intersection] = contig_length
else:
intersection_scaffolds[intersection] += contig_length
weighted_jaccard = []
for i in first_scaffolds:
maximum = 0
for j in second_scaffolds:
# Get a value for the intersection.
if (i,j) not in intersection_scaffolds:
continue
# Get a value for the union.
weighted_union = \
first_scaffolds[i] + \
second_scaffolds[j] - \
intersection_scaffolds[(i,j)]
# Append the Jaccard index.
weighted_index = \
(intersection_scaffolds[(i,j)]/ \
weighted_union) * \
first_scaffolds[i]
if weighted_index > maximum:
maximum = weighted_index
weighted_jaccard.append(maximum)
return sum(weighted_jaccard)/sum(first_scaffolds.values())
| 37.105263 | 81 | 0.654965 |
def count(first, second):
first_contigs, first_positions = first
second_contigs, second_positions = second
intersection_scaffolds = {}
first_scaffolds = {}
second_scaffolds = {}
for contig in first_contigs:
contig_length = first_contigs[contig]['length']
first_scaffold_name = first_contigs[contig]['scaffold']
second_scaffold_name = second_contigs[contig]['scaffold']
if first_scaffold_name not in first_scaffolds:
first_scaffolds[first_scaffold_name] = contig_length
else:
first_scaffolds[first_scaffold_name] += contig_length
if second_scaffold_name not in second_scaffolds:
second_scaffolds[second_scaffold_name] = contig_length
else:
second_scaffolds[second_scaffold_name] += contig_length
intersection = (first_scaffold_name, second_scaffold_name)
if intersection not in intersection_scaffolds:
intersection_scaffolds[intersection] = contig_length
else:
intersection_scaffolds[intersection] += contig_length
weighted_jaccard = []
for i in first_scaffolds:
maximum = 0
for j in second_scaffolds:
if (i,j) not in intersection_scaffolds:
continue
weighted_union = \
first_scaffolds[i] + \
second_scaffolds[j] - \
intersection_scaffolds[(i,j)]
weighted_index = \
(intersection_scaffolds[(i,j)]/ \
weighted_union) * \
first_scaffolds[i]
if weighted_index > maximum:
maximum = weighted_index
weighted_jaccard.append(maximum)
return sum(weighted_jaccard)/sum(first_scaffolds.values())
| true | true |
f723939aa52182d56d21add558a5456b312bcdab | 4,520 | py | Python | ding/utils/time_helper.py | sailxjx/DI-engine | c6763f8e2ba885a2a02f611195a1b5f8b50bff00 | [
"Apache-2.0"
] | 464 | 2021-07-08T07:26:33.000Z | 2022-03-31T12:35:16.000Z | ding/utils/time_helper.py | sailxjx/DI-engine | c6763f8e2ba885a2a02f611195a1b5f8b50bff00 | [
"Apache-2.0"
] | 177 | 2021-07-09T08:22:55.000Z | 2022-03-31T07:35:22.000Z | ding/utils/time_helper.py | sailxjx/DI-engine | c6763f8e2ba885a2a02f611195a1b5f8b50bff00 | [
"Apache-2.0"
] | 92 | 2021-07-08T12:16:37.000Z | 2022-03-31T09:24:41.000Z | import signal
import time
from typing import Any, Callable
import torch
from easydict import EasyDict
from .time_helper_base import TimeWrapper
from .time_helper_cuda import get_cuda_time_wrapper
def build_time_helper(cfg: EasyDict = None, wrapper_type: str = None) -> Callable[[], 'TimeWrapper']:
r"""
Overview:
Build the timehelper
Arguments:
- cfg (:obj:`dict`):
The config file, which is a multilevel dict, have large domain like
evaluate, common, model, train etc, and each large domain
has it's smaller domain.
- wrapper_type (:obj:`str`): The type of wrapper returned, support ``['time', 'cuda']``
Returns:
- time_wrapper (:obj:`TimeWrapper`):
Return the corresponding timewrapper, Reference: ``ding.utils.timehelper.TimeWrapperTime``
and ``ding.utils.timehelper.get_cuda_time_wrapper``.
"""
# Note: wrapper_type has higher priority
if wrapper_type is not None:
time_wrapper_type = wrapper_type
elif cfg is not None:
time_wrapper_type = cfg.common.time_wrapper_type
else:
raise RuntimeError('Either wrapper_type or cfg should be provided.')
if time_wrapper_type == 'time':
return TimeWrapperTime
elif time_wrapper_type == 'cuda':
if torch.cuda.is_available():
# lazy initialize to make code runnable locally
return get_cuda_time_wrapper()
else:
return TimeWrapperTime
else:
raise KeyError('invalid time_wrapper_type: {}'.format(time_wrapper_type))
class EasyTimer:
r"""
Overview:
A decent timer wrapper that can be used easily.
Interface:
``__init__``, ``__enter__``, ``__exit__``
Example:
>>> wait_timer = EasyTimer()
>>> with wait_timer:
>>> func(...)
>>> time_ = wait_timer.value # in second
"""
def __init__(self, cuda=True):
r"""
Overview:
Init class EasyTimer
Arguments:
- cuda (:obj:`bool`): Whether to build timer with cuda type
"""
if torch.cuda.is_available() and cuda:
time_wrapper_type = "cuda"
else:
time_wrapper_type = "time"
self._timer = build_time_helper(wrapper_type=time_wrapper_type)
self.value = 0.0
def __enter__(self):
r"""
Overview:
Enter timer, start timing
"""
self.value = 0.0
self._timer.start_time()
def __exit__(self, *args):
r"""
Overview:
Exit timer, stop timing
"""
self.value = self._timer.end_time()
class TimeWrapperTime(TimeWrapper):
r"""
Overview:
A class method that inherit from ``TimeWrapper`` class
Interface:
``start_time``, ``end_time``
"""
# overwrite
@classmethod
def start_time(cls):
r"""
Overview:
Implement and overide the ``start_time`` method in ``TimeWrapper`` class
"""
cls.start = time.time()
# overwrite
@classmethod
def end_time(cls):
r"""
Overview:
Implement and overide the end_time method in ``TimeWrapper`` class
Returns:
- time(:obj:`float`): The time between ``start_time`` and end_time
"""
cls.end = time.time()
return cls.end - cls.start
class WatchDog(object):
"""
Overview:
Simple watchdog timer to detect timeouts
Arguments:
- timeout (:obj:`int`): Timeout value of the ``watchdog [seconds]``.
.. note::
If it is not reset before exceeding this value, ``TimeourError`` raised.
Interface:
``start``, ``stop``
Examples:
>>> watchdog = WatchDog(x) # x is a timeout value
>>> ...
>>> watchdog.start()
>>> ... # Some function
"""
def __init__(self, timeout: int = 1):
self._timeout = timeout + 1
self._failed = False
def start(self):
r"""
Overview:
Start watchdog.
"""
signal.signal(signal.SIGALRM, self._event)
signal.alarm(self._timeout)
@staticmethod
def _event(signum: Any, frame: Any):
raise TimeoutError()
def stop(self):
r"""
Overview:
Stop watchdog with ``alarm(0)``, ``SIGALRM``, and ``SIG_DFL`` signals.
"""
signal.alarm(0)
signal.signal(signal.SIGALRM, signal.SIG_DFL)
| 26.432749 | 102 | 0.580973 | import signal
import time
from typing import Any, Callable
import torch
from easydict import EasyDict
from .time_helper_base import TimeWrapper
from .time_helper_cuda import get_cuda_time_wrapper
def build_time_helper(cfg: EasyDict = None, wrapper_type: str = None) -> Callable[[], 'TimeWrapper']:
if wrapper_type is not None:
time_wrapper_type = wrapper_type
elif cfg is not None:
time_wrapper_type = cfg.common.time_wrapper_type
else:
raise RuntimeError('Either wrapper_type or cfg should be provided.')
if time_wrapper_type == 'time':
return TimeWrapperTime
elif time_wrapper_type == 'cuda':
if torch.cuda.is_available():
return get_cuda_time_wrapper()
else:
return TimeWrapperTime
else:
raise KeyError('invalid time_wrapper_type: {}'.format(time_wrapper_type))
class EasyTimer:
def __init__(self, cuda=True):
if torch.cuda.is_available() and cuda:
time_wrapper_type = "cuda"
else:
time_wrapper_type = "time"
self._timer = build_time_helper(wrapper_type=time_wrapper_type)
self.value = 0.0
def __enter__(self):
self.value = 0.0
self._timer.start_time()
def __exit__(self, *args):
self.value = self._timer.end_time()
class TimeWrapperTime(TimeWrapper):
@classmethod
def start_time(cls):
cls.start = time.time()
@classmethod
def end_time(cls):
cls.end = time.time()
return cls.end - cls.start
class WatchDog(object):
def __init__(self, timeout: int = 1):
self._timeout = timeout + 1
self._failed = False
def start(self):
signal.signal(signal.SIGALRM, self._event)
signal.alarm(self._timeout)
@staticmethod
def _event(signum: Any, frame: Any):
raise TimeoutError()
def stop(self):
signal.alarm(0)
signal.signal(signal.SIGALRM, signal.SIG_DFL)
| true | true |
f72393ae4620073561466c7e75f9bbe9747f2532 | 979 | py | Python | connectingPipelines/coins_ld.py | Shivakoreddi/CryptoDataApplication | ad620231a0614ed6f4f587dfcfb83249d1d16689 | [
"Apache-2.0"
] | 8 | 2021-10-29T19:59:09.000Z | 2022-02-04T05:48:23.000Z | connectingPipelines/coins_ld.py | Shivakoreddi/CryptoDataApplication | ad620231a0614ed6f4f587dfcfb83249d1d16689 | [
"Apache-2.0"
] | null | null | null | connectingPipelines/coins_ld.py | Shivakoreddi/CryptoDataApplication | ad620231a0614ed6f4f587dfcfb83249d1d16689 | [
"Apache-2.0"
] | null | null | null | from apiWrapper import coinAPI
from sqlalchemy import create_engine
from sqlalchemy import Table,Column,Integer,String,MetaData,ForeignKey
import sqlite3
from sqlite3 import Error
import pandas as pd
import os
def main():
path = "/CryptoDataApplication/"
for filename in os.listdir(path):
if filename.startswith('valid_coin'):
file = filename
coin_df = pd.read_csv(file,sep=',')
conn = sqlite3.connect('/CryptoDataApplication/transactionDB/tradingSchema.db')
cursor = conn.cursor()
query = []
##for index,row in coin_df.iterrows():
##query = """INSERT OR REPLACE INTO coins(id,symbol,name,image) VALUES('{0}','{1}','{2}','{3}')""".format(row['id'],row['symbol'],row['name'],row['image'])
#print(query[1])
##cursor.execute(query)
##conn.commit()
cursor.execute("select * from coins")
rows = cursor.fetchall()
for row in rows:
print(row)
if __name__=="__main__":
main()
| 27.971429 | 163 | 0.652707 | from apiWrapper import coinAPI
from sqlalchemy import create_engine
from sqlalchemy import Table,Column,Integer,String,MetaData,ForeignKey
import sqlite3
from sqlite3 import Error
import pandas as pd
import os
def main():
path = "/CryptoDataApplication/"
for filename in os.listdir(path):
if filename.startswith('valid_coin'):
file = filename
coin_df = pd.read_csv(file,sep=',')
conn = sqlite3.connect('/CryptoDataApplication/transactionDB/tradingSchema.db')
cursor = conn.cursor()
query = []
| true | true |
f72394108b2b48963e86a1dfb5530319995e885c | 4,375 | py | Python | tests/test_graph.py | Nikolay-Lysenko/gpn | a59f43e90536f85f8b0051c5ce6d0497081a5a8f | [
"MIT"
] | null | null | null | tests/test_graph.py | Nikolay-Lysenko/gpn | a59f43e90536f85f8b0051c5ce6d0497081a5a8f | [
"MIT"
] | null | null | null | tests/test_graph.py | Nikolay-Lysenko/gpn | a59f43e90536f85f8b0051c5ce6d0497081a5a8f | [
"MIT"
] | null | null | null | """
Test `graph.py` module.
Author: Nikolay Lysenko
"""
from typing import List, Tuple
import pytest
import tensorflow as tf
import numpy as np
from gpn.graph import sample_multiple_fragments
@pytest.mark.parametrize(
"images, corners, fragment_size, frame_size, n_channels, expected",
[
(
# `images`
np.array([
[
[[1, 0, 1, 0],
[0, 1, 0, 1],
[1, 0, 1, 0],
[0, 1, 0, 1]],
[[1, 1, 1, 1],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[1, 1, 1, 1]]
],
[
[[1, 1, 0, 0],
[1, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 1, 1, 0],
[0, 1, 1, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 1, 1],
[0, 0, 1, 1]]
]
]).swapaxes(1, 3),
# `corners`
[(1, 1), (0, 2)],
# `fragment_size`
4,
# `frame_size`
1,
# `n_channels`
3,
# `expected`
np.array([
[
[[1, 0, 1, 0],
[0, 1, 0, 1],
[1, 0, 1, 0],
[0, 1, 0, 1]],
[[1, 1, 1, 1],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[1, 1, 1, 1]]
],
[
[[1, 1, 0, 0],
[1, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 1, 1, 0],
[0, 1, 1, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 1, 1],
[0, 0, 1, 1]]
],
[
[[0, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 1, 1, 1],
[0, 0, 0, 0]]
],
[
[[0, 1, 1, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]],
[[0, 0, 1, 1],
[0, 0, 1, 1],
[0, 0, 0, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 0]]
],
]).swapaxes(1, 3)
)
]
)
def test_sample_multiple_fragments(
images: np.ndarray, corners: List[Tuple[int, int]],
fragment_size: int, frame_size: int, n_channels: int,
expected: np.ndarray
) -> None:
"""Test `sample_multiple_fragments` function."""
graph = tf.Graph()
with graph.as_default():
tensor_images = tf.placeholder(tf.float32, images.shape)
tensor_corners = [
tf.placeholder(tf.int32, (2,), name=f'corner_{i}')
for i, _ in enumerate(corners)
]
tensor_fragments = sample_multiple_fragments(
tensor_images, tensor_corners,
fragment_size, frame_size, n_channels
)
with tf.Session(graph=graph) as sess:
feed_dict = {
tensor_images: images,
**{k: v for k, v in zip(tensor_corners, corners)}
}
fragments = tensor_fragments.eval(feed_dict, sess)
np.testing.assert_array_equal(fragments, expected)
| 29.965753 | 71 | 0.275429 |
from typing import List, Tuple
import pytest
import tensorflow as tf
import numpy as np
from gpn.graph import sample_multiple_fragments
@pytest.mark.parametrize(
"images, corners, fragment_size, frame_size, n_channels, expected",
[
(
np.array([
[
[[1, 0, 1, 0],
[0, 1, 0, 1],
[1, 0, 1, 0],
[0, 1, 0, 1]],
[[1, 1, 1, 1],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[1, 1, 1, 1]]
],
[
[[1, 1, 0, 0],
[1, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 1, 1, 0],
[0, 1, 1, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 1, 1],
[0, 0, 1, 1]]
]
]).swapaxes(1, 3),
[(1, 1), (0, 2)],
4,
1,
3,
np.array([
[
[[1, 0, 1, 0],
[0, 1, 0, 1],
[1, 0, 1, 0],
[0, 1, 0, 1]],
[[1, 1, 1, 1],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[1, 1, 1, 1]]
],
[
[[1, 1, 0, 0],
[1, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 1, 1, 0],
[0, 1, 1, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 1, 1],
[0, 0, 1, 1]]
],
[
[[0, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 1, 1, 1],
[0, 0, 0, 0]]
],
[
[[0, 1, 1, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]],
[[0, 0, 1, 1],
[0, 0, 1, 1],
[0, 0, 0, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 0, 1],
[0, 0, 0, 0]]
],
]).swapaxes(1, 3)
)
]
)
def test_sample_multiple_fragments(
images: np.ndarray, corners: List[Tuple[int, int]],
fragment_size: int, frame_size: int, n_channels: int,
expected: np.ndarray
) -> None:
graph = tf.Graph()
with graph.as_default():
tensor_images = tf.placeholder(tf.float32, images.shape)
tensor_corners = [
tf.placeholder(tf.int32, (2,), name=f'corner_{i}')
for i, _ in enumerate(corners)
]
tensor_fragments = sample_multiple_fragments(
tensor_images, tensor_corners,
fragment_size, frame_size, n_channels
)
with tf.Session(graph=graph) as sess:
feed_dict = {
tensor_images: images,
**{k: v for k, v in zip(tensor_corners, corners)}
}
fragments = tensor_fragments.eval(feed_dict, sess)
np.testing.assert_array_equal(fragments, expected)
| true | true |
f723946834788c8fb399fa68eec9db13a1571953 | 2,318 | py | Python | cloud_virtual_machine/pipeline_stack.py | FarrOut/CloudVirtualMachine | cabd2ce877c6f1e04603439061120e1b6f6c2302 | [
"MIT"
] | 2 | 2021-12-01T13:48:36.000Z | 2022-03-14T14:48:10.000Z | cloud_virtual_machine/pipeline_stack.py | FarrOut/CloudVirtualMachine | cabd2ce877c6f1e04603439061120e1b6f6c2302 | [
"MIT"
] | null | null | null | cloud_virtual_machine/pipeline_stack.py | FarrOut/CloudVirtualMachine | cabd2ce877c6f1e04603439061120e1b6f6c2302 | [
"MIT"
] | null | null | null | import logging
import boto3
import json
import aws_cdk as cdk
from aws_cdk import aws_secretsmanager
from aws_cdk.pipelines import CodePipeline, CodePipelineSource, ShellStep
from constructs import Construct
secretsmanager = boto3.client('secretsmanager')
# from pipeline_stage import WorkshopPipelineStage
class PipelineStack(cdk.Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
logger = logging.getLogger()
connection_secret = aws_secretsmanager.Secret.from_secret_name_v2(self, "GitHubConnectionSecret",
'GitHub/FarrOut/connection')
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/secretsmanager.html#SecretsManager.Client.get_secret_value
connection_secret_value = json.loads(secretsmanager.get_secret_value(
SecretId='GitHub/FarrOut/connection',
)['SecretString'])
connection_arn_ = connection_secret_value['FarrOut']
cdk.CfnOutput(self, 'ConnectionArn',
description='ConnectionArn',
value=connection_arn_,
)
if connection_secret.secret_value is None:
logger.warning('Unable to retrieve GitHub Connection!')
else:
logger.info('Found GitHub Connection.')
pipeline = CodePipeline(self, "Sandpipe",
pipeline_name="Sandpipe",
cross_account_keys=True,
synth=ShellStep("Synth",
input=CodePipelineSource.connection(
"FarrOut/CloudVirtualMachine", "main",
connection_arn=connection_arn_,
),
commands=["npm install -g aws-cdk",
"python -m pip install -r requirements.txt",
"cdk synth"]
)
)
| 42.145455 | 143 | 0.526747 | import logging
import boto3
import json
import aws_cdk as cdk
from aws_cdk import aws_secretsmanager
from aws_cdk.pipelines import CodePipeline, CodePipelineSource, ShellStep
from constructs import Construct
secretsmanager = boto3.client('secretsmanager')
class PipelineStack(cdk.Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
logger = logging.getLogger()
connection_secret = aws_secretsmanager.Secret.from_secret_name_v2(self, "GitHubConnectionSecret",
'GitHub/FarrOut/connection')
.loads(secretsmanager.get_secret_value(
SecretId='GitHub/FarrOut/connection',
)['SecretString'])
connection_arn_ = connection_secret_value['FarrOut']
cdk.CfnOutput(self, 'ConnectionArn',
description='ConnectionArn',
value=connection_arn_,
)
if connection_secret.secret_value is None:
logger.warning('Unable to retrieve GitHub Connection!')
else:
logger.info('Found GitHub Connection.')
pipeline = CodePipeline(self, "Sandpipe",
pipeline_name="Sandpipe",
cross_account_keys=True,
synth=ShellStep("Synth",
input=CodePipelineSource.connection(
"FarrOut/CloudVirtualMachine", "main",
connection_arn=connection_arn_,
),
commands=["npm install -g aws-cdk",
"python -m pip install -r requirements.txt",
"cdk synth"]
)
)
| true | true |
f72397747880bd55bc2f3c6bce3f931203e40b4c | 733 | py | Python | 451.Sort_Characters_By_Frequency/sol2.py | nhanitvn/leetcode | 1c2ffe45cd71740b37aed7e502ffb0dcc16b5d14 | [
"MIT"
] | null | null | null | 451.Sort_Characters_By_Frequency/sol2.py | nhanitvn/leetcode | 1c2ffe45cd71740b37aed7e502ffb0dcc16b5d14 | [
"MIT"
] | null | null | null | 451.Sort_Characters_By_Frequency/sol2.py | nhanitvn/leetcode | 1c2ffe45cd71740b37aed7e502ffb0dcc16b5d14 | [
"MIT"
] | null | null | null | class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
# Firstly, we count frequencies
freq = {}
freq_to_chars = {}
result = []
for c in s:
if c in freq:
freq[c] += 1
else:
freq[c] = 1
for c, f in freq.iteritems():
if f in freq_to_chars:
freq_to_chars[f] = ''.join([freq_to_chars[f], c * f])
else:
freq_to_chars[f] = c * f
for i in range(len(s), 0, -1):
if i in freq_to_chars:
result.extend(freq_to_chars[i])
return ''.join(result)
| 26.178571 | 69 | 0.416098 | class Solution(object):
def frequencySort(self, s):
freq = {}
freq_to_chars = {}
result = []
for c in s:
if c in freq:
freq[c] += 1
else:
freq[c] = 1
for c, f in freq.iteritems():
if f in freq_to_chars:
freq_to_chars[f] = ''.join([freq_to_chars[f], c * f])
else:
freq_to_chars[f] = c * f
for i in range(len(s), 0, -1):
if i in freq_to_chars:
result.extend(freq_to_chars[i])
return ''.join(result)
| true | true |
f723987e351d46545a5ae560000c99831224a613 | 405 | wsgi | Python | wildcard/wsgi/django.wsgi | kickstandproject/wildcard | 0ef2a15d8ac6b1d37db964d0baa7e40f9f771bc9 | [
"Apache-2.0"
] | 2 | 2015-03-04T18:55:24.000Z | 2021-04-20T23:27:19.000Z | wildcard/wsgi/django.wsgi | kickstandproject/wildcard | 0ef2a15d8ac6b1d37db964d0baa7e40f9f771bc9 | [
"Apache-2.0"
] | null | null | null | wildcard/wsgi/django.wsgi | kickstandproject/wildcard | 0ef2a15d8ac6b1d37db964d0baa7e40f9f771bc9 | [
"Apache-2.0"
] | null | null | null | import logging
import os
import sys
import django.core.handlers.wsgi
from django.conf import settings
# Add this file path to sys.path in order to import settings
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), '../..'))
os.environ['DJANGO_SETTINGS_MODULE'] = 'wildcard.settings'
sys.stdout = sys.stderr
DEBUG = False
application = django.core.handlers.wsgi.WSGIHandler()
| 25.3125 | 86 | 0.767901 | import logging
import os
import sys
import django.core.handlers.wsgi
from django.conf import settings
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), '../..'))
os.environ['DJANGO_SETTINGS_MODULE'] = 'wildcard.settings'
sys.stdout = sys.stderr
DEBUG = False
application = django.core.handlers.wsgi.WSGIHandler()
| true | true |
f7239887d03b6c0821d9bceb7d409c9903769595 | 11,028 | py | Python | CSSCrypt.py | csmets/CSSCrypt | 4444b9921ae82e89a9ad7955fe46f0ae887ca527 | [
"MIT"
] | null | null | null | CSSCrypt.py | csmets/CSSCrypt | 4444b9921ae82e89a9ad7955fe46f0ae887ca527 | [
"MIT"
] | null | null | null | CSSCrypt.py | csmets/CSSCrypt | 4444b9921ae82e89a9ad7955fe46f0ae887ca527 | [
"MIT"
] | null | null | null | """
Clyde's Simple Shuffler Encryption
@Desc
This encryption algorthym is design for users to use their own keys to build
a unique encrypted output. It called shuffler as it uses the inputed key
to shuffle each character in the message, thus making it harder to crack.
I highly advise you to not use this for passwords. Paswords are secured by
hashing and not through encryption. Hashed values can't be decrypted where as
encryption can. Feel free to encrypt stuff for fun and use this as a learning
tool.
If you use this to encrypt something sensitive, use at your own discretion. I am
not responsible for messages you've created that's gotten cracked.
@author
Clyde Smets <clyde.smets@gmail.com>
@license
MIT
"""
import re
from pathlib import Path
class encryption:
# Character values within the list is used to encode the message.
# Default file 'key/encoding.txt' uses base64, change it to whatever.
__encodingValues = []
# Pad identifier. Padding is used in encoding to fit the bit block size
__pad = ''
# The bit size helps determine the encoding index value by x num of binary
# bits. For example base64 is 6 - it grabs 6 bits to create a decimal for
# assigning that index value to a charater. 010011 => 15 => T
# The default value is assigned at the top of the file 'key/encoding.txt'
__bitSize = 0
def __init__ (self):
# Check if encoding file exists
encodingFilePath = 'key/encoding.txt'
encodingFile = Path(encodingFilePath)
if encodingFile.is_file():
lines = self.__readByLine(encodingFilePath)
self.__encodingValues = lines[1:-1]
self.__bitSize = int(lines[0])
self.__pad = lines[-1]
else:
raise Exception('encoding.txt is not found')
def encrypt (self, message, key):
# Encode the message
encoded = self.__encode(message)
# count number of encoding pads
padNum = encoded.count(self.__pad)
# remove and store the encoding padded values
pads = encoded[-padNum:]
encoded = encoded[:-padNum]
# Extend the key to cover the length of the encoding values
key = self.__resize(key, len(encoded))
encrypted = ''
# Shift the encoded values according to the key.
# Values can only shift from 0-9.
for i in range(len(encoded)):
shift = self.__shift(encoded[i], int(key[i]))
encrypted = encrypted + shift
# reattached padding to the encrypted output
encrypted = encrypted + pads
return encrypted
def decrypt (self, encrypted, key):
# Resize the key to the length of the encrypted message
key = self.__resize(key, len(encrypted))
# Count number of encoding pads
padNum = encrypted.count(self.__pad)
# Remove and store the encoding padded values
pads = encrypted[-padNum:]
encrypted = encrypted[:-padNum]
decrypted = ''
# unshift the encrypted message to be decoded using the key.
for i in range(len(encrypted)):
unshift = self.__unshift(encrypted[i], int(key[i]))
decrypted = decrypted + unshift
# re-append the padding
decrypted = decrypted + pads
# decode the message and return the decrypted result.
decoded = self.__decode(decrypted)
return decoded
# Resize the length of a string to match the amount.
def __resize (self, string, amount):
if len(string) < amount:
index = 0
for i in range(len(string), amount):
string = string + string[index]
index = index + 1
elif len(string) > amount: # if it's larger cut it
cutAmount = amount - len(string) # negative value
string = string[:cutAmount]
return string
def __encode (self, message):
encoded = ''
longBinary = ''
# Loop through characters in message to convert it to binary
for i in range(len(message)):
# Convert to hexadecimal
hexChar = format(ord(message[i]), "x")
# Convert hexadecimal to decimal
decimal = int(hexChar, 16)
# Convert decimal to binary
binary = '{0:08b}'.format(decimal)
longBinary += binary
# Encoding requires 24 bit blocks. So the long binary has to be split
# into bits of 24. If a block doesn't complete 24 bits, pad it!
# so that it does. e.g. '100110110101' => '100110110101000000000000'
blockSize = 24
blocks = []
counter = 0
block = ''
# build the blocks
for i in range(len(longBinary)):
if longBinary[i]:
if counter < blockSize:
block += longBinary[i]
counter = counter + 1
else:
counter = 0
blocks.append(block)
block = longBinary[i]
# append last remaining block if it has values
if len(block) > 0:
blocks.append(block)
# pad the last block
for i in range(len(blocks)):
if len(blocks[i]) < blockSize:
# append padded 0
size = blockSize - len(blocks[i])
for b in range(size):
blocks[i] = blocks[i] + '0'
# convert back to long binary
longBinary = ''.join(blocks)
# group binary values by bit size
grouped = self.__groupBinary(longBinary, self.__bitSize)
# Get the encoded character for the binary group. But it will
# require the binary to be converted to decimal to find the index
# position.
# Find the number of groups that is required to make a block
numOfGroups = blockSize // self.__bitSize
# Loop through, except for the last group. Since we also know that to
# create a group it needs at least one group of bits, thus we can forget
# that one (i.e. numOfGroups - 1)
for gi in range(len(grouped) - (numOfGroups - 1)):
eDecimal = int(grouped[gi], 2)
encoded += self.__encodingValues[eDecimal]
# Size of padding
padding = ''
for n in range(self.__bitSize):
padding += '0'
# Check to see the last remaining groups are padded, and if they are,
# assign them a padded value.
for lgi in range(numOfGroups - 1):
target = len(grouped) - (3 - lgi)
if grouped[target] == padding:
encoded += self.__pad
else:
eDecimal = int(grouped[target], 2)
encoded += self.__encodingValues[eDecimal]
return encoded
def __decode (self, message):
decoded = ''
longBinary = ''
pads = ''
# Size of padding
padding = ''
for n in range(self.__bitSize):
padding += '0'
# Loop through encoded message and return values as binary
for i in range(len(message)):
# Find position of char in index
index = 0
# Find the index values from the encoding key
for mi in range(len(self.__encodingValues)):
if message[i] == self.__encodingValues[mi]:
index = mi
break
# Check if the character is a padding value or not
if message[i] == self.__pad:
pads += padding
break
# Convert index to binary following bit amount
binaryFormat = '{0:0' + str(self.__bitSize) + 'b}'
binary = binaryFormat.format(index)
longBinary += binary
# Append padding to converted indexes
longBinary = longBinary + pads
# group binary values to divisable of 8
grouped = self.__groupBinary(longBinary, 8)
# Decode
for i in range(len(grouped)):
# Get decimal from binary
decimal = int(grouped[i], 2)
# Get hexadecimal from decimal
hexadecimal = hex(decimal).split('x')[1]
# Get character from hex
if (hexadecimal != '0'):
char = bytes.fromhex(hexadecimal).decode('utf-8')
decoded += char
return decoded
# Write to content to file
def __write (self, file, contents):
f = open(file, 'w')
f.write(contents)
f.closed()
# Read a file line by line and return it as a list
def __readByLine (self, file):
contents = []
with open(file) as line:
contents = line.read().splitlines()
return contents
# Return a list of binary values grouped by bit size
def __groupBinary (self, binary, bitSize):
# group binary values by base number
grouped = re.findall('.{1,' + str(bitSize) + '}', binary)
# Fill the last value with any missing 0 - so groups are whole
# e.g. '01' will be changed to '000001' if bit size is 6
lastGroupSize = len(grouped[len(grouped) - 1])
if lastGroupSize < bitSize:
count = 0
amount = bitSize - lastGroupSize
while count < amount:
grouped[len(grouped) - 1] = '0' + grouped[len(grouped) - 1]
count = count + 1
return grouped
# Find the character in the list and find it's shifted value
def __shift (self, char, amount):
values = self.__encodingValues
index = self.__charPosition(char, values)
shift = index + amount
if shift < len(values):
return values[shift]
else:
remainder = len(self.__encodingValues) - (index + 1)
shift = (amount - remainder) - 1
return values[shift]
# Getting the original value unshifted value.
def __unshift (self, char, amount):
values = self.__encodingValues
index = self.__charPosition(char, values)
return values[index - amount]
# Return the index value of a matching character in a long string.
def __charPosition (self, char, string):
index = 0
# Get the index value of the character in the list
for i in range(len(string)):
if string[i] == char:
index = i
break
return index
| 29.805405 | 81 | 0.554044 | import re
from pathlib import Path
class encryption:
__encodingValues = []
__pad = ''
__bitSize = 0
def __init__ (self):
encodingFilePath = 'key/encoding.txt'
encodingFile = Path(encodingFilePath)
if encodingFile.is_file():
lines = self.__readByLine(encodingFilePath)
self.__encodingValues = lines[1:-1]
self.__bitSize = int(lines[0])
self.__pad = lines[-1]
else:
raise Exception('encoding.txt is not found')
def encrypt (self, message, key):
encoded = self.__encode(message)
padNum = encoded.count(self.__pad)
pads = encoded[-padNum:]
encoded = encoded[:-padNum]
key = self.__resize(key, len(encoded))
encrypted = ''
for i in range(len(encoded)):
shift = self.__shift(encoded[i], int(key[i]))
encrypted = encrypted + shift
encrypted = encrypted + pads
return encrypted
def decrypt (self, encrypted, key):
key = self.__resize(key, len(encrypted))
padNum = encrypted.count(self.__pad)
pads = encrypted[-padNum:]
encrypted = encrypted[:-padNum]
decrypted = ''
for i in range(len(encrypted)):
unshift = self.__unshift(encrypted[i], int(key[i]))
decrypted = decrypted + unshift
decrypted = decrypted + pads
decoded = self.__decode(decrypted)
return decoded
def __resize (self, string, amount):
if len(string) < amount:
index = 0
for i in range(len(string), amount):
string = string + string[index]
index = index + 1
elif len(string) > amount:
cutAmount = amount - len(string) # negative value
string = string[:cutAmount]
return string
def __encode (self, message):
encoded = ''
longBinary = ''
# Loop through characters in message to convert it to binary
for i in range(len(message)):
# Convert to hexadecimal
hexChar = format(ord(message[i]), "x")
# Convert hexadecimal to decimal
decimal = int(hexChar, 16)
# Convert decimal to binary
binary = '{0:08b}'.format(decimal)
longBinary += binary
# Encoding requires 24 bit blocks. So the long binary has to be split
# into bits of 24. If a block doesn't complete 24 bits, pad it!
blockSize = 24
blocks = []
counter = 0
block = ''
for i in range(len(longBinary)):
if longBinary[i]:
if counter < blockSize:
block += longBinary[i]
counter = counter + 1
else:
counter = 0
blocks.append(block)
block = longBinary[i]
if len(block) > 0:
blocks.append(block)
for i in range(len(blocks)):
if len(blocks[i]) < blockSize:
size = blockSize - len(blocks[i])
for b in range(size):
blocks[i] = blocks[i] + '0'
longBinary = ''.join(blocks)
grouped = self.__groupBinary(longBinary, self.__bitSize)
numOfGroups = blockSize // self.__bitSize
for gi in range(len(grouped) - (numOfGroups - 1)):
eDecimal = int(grouped[gi], 2)
encoded += self.__encodingValues[eDecimal]
padding = ''
for n in range(self.__bitSize):
padding += '0'
for lgi in range(numOfGroups - 1):
target = len(grouped) - (3 - lgi)
if grouped[target] == padding:
encoded += self.__pad
else:
eDecimal = int(grouped[target], 2)
encoded += self.__encodingValues[eDecimal]
return encoded
def __decode (self, message):
decoded = ''
longBinary = ''
pads = ''
padding = ''
for n in range(self.__bitSize):
padding += '0'
for i in range(len(message)):
index = 0
for mi in range(len(self.__encodingValues)):
if message[i] == self.__encodingValues[mi]:
index = mi
break
if message[i] == self.__pad:
pads += padding
break
binaryFormat = '{0:0' + str(self.__bitSize) + 'b}'
binary = binaryFormat.format(index)
longBinary += binary
longBinary = longBinary + pads
grouped = self.__groupBinary(longBinary, 8)
for i in range(len(grouped)):
decimal = int(grouped[i], 2)
hexadecimal = hex(decimal).split('x')[1]
if (hexadecimal != '0'):
char = bytes.fromhex(hexadecimal).decode('utf-8')
decoded += char
return decoded
def __write (self, file, contents):
f = open(file, 'w')
f.write(contents)
f.closed()
def __readByLine (self, file):
contents = []
with open(file) as line:
contents = line.read().splitlines()
return contents
def __groupBinary (self, binary, bitSize):
grouped = re.findall('.{1,' + str(bitSize) + '}', binary)
lastGroupSize = len(grouped[len(grouped) - 1])
if lastGroupSize < bitSize:
count = 0
amount = bitSize - lastGroupSize
while count < amount:
grouped[len(grouped) - 1] = '0' + grouped[len(grouped) - 1]
count = count + 1
return grouped
def __shift (self, char, amount):
values = self.__encodingValues
index = self.__charPosition(char, values)
shift = index + amount
if shift < len(values):
return values[shift]
else:
remainder = len(self.__encodingValues) - (index + 1)
shift = (amount - remainder) - 1
return values[shift]
# Getting the original value unshifted value.
def __unshift (self, char, amount):
values = self.__encodingValues
index = self.__charPosition(char, values)
return values[index - amount]
# Return the index value of a matching character in a long string.
def __charPosition (self, char, string):
index = 0
# Get the index value of the character in the list
for i in range(len(string)):
if string[i] == char:
index = i
break
return index
| true | true |
f72399689430fbb3dfe5ca368c2a9924216b6725 | 583 | py | Python | demo_sklearn/model/model_test.py | caserwin/daily-learning-python | 01fea4c5d4e86cbea2dbef8817146f018b5f1479 | [
"Apache-2.0"
] | 1 | 2019-05-04T07:27:18.000Z | 2019-05-04T07:27:18.000Z | demo_sklearn/model/model_test.py | caserwin/daily-learning-python | 01fea4c5d4e86cbea2dbef8817146f018b5f1479 | [
"Apache-2.0"
] | null | null | null | demo_sklearn/model/model_test.py | caserwin/daily-learning-python | 01fea4c5d4e86cbea2dbef8817146f018b5f1479 | [
"Apache-2.0"
] | 1 | 2018-09-20T01:49:36.000Z | 2018-09-20T01:49:36.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/5/19 下午2:08
# @Author : Erwin
from common.pickle_helper import read_model
import numpy as np
# noinspection PyUnresolvedReferences
from sklearn.neighbors import LocalOutlierFactor
# noinspection PyUnresolvedReferences
from sklearn.ensemble import IsolationForest
lof_model = read_model("./sklearn_LOF_demo1.pkl")
if_model = read_model("./sklearn_IsolationForest_demo1.pkl")
user_define = np.array([(2, 3), (5, 6), (2.3, 1.8)])
# -1表示异常点,1表示正常点。
print(lof_model.predict(user_define))
print(if_model.predict(user_define)) | 32.388889 | 60 | 0.768439 |
from common.pickle_helper import read_model
import numpy as np
from sklearn.neighbors import LocalOutlierFactor
from sklearn.ensemble import IsolationForest
lof_model = read_model("./sklearn_LOF_demo1.pkl")
if_model = read_model("./sklearn_IsolationForest_demo1.pkl")
user_define = np.array([(2, 3), (5, 6), (2.3, 1.8)])
print(lof_model.predict(user_define))
print(if_model.predict(user_define)) | true | true |
f72399c6f0ec17f8022360ea22ce941c355f64c2 | 743 | py | Python | test/system/array/MOUNT_ARRAY_ALD_MOUNTED_ERROR.py | mjlee34/poseidonos | 8eff75c5ba7af8090d3ff4ac51d7507b37571f9b | [
"BSD-3-Clause"
] | null | null | null | test/system/array/MOUNT_ARRAY_ALD_MOUNTED_ERROR.py | mjlee34/poseidonos | 8eff75c5ba7af8090d3ff4ac51d7507b37571f9b | [
"BSD-3-Clause"
] | null | null | null | test/system/array/MOUNT_ARRAY_ALD_MOUNTED_ERROR.py | mjlee34/poseidonos | 8eff75c5ba7af8090d3ff4ac51d7507b37571f9b | [
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python3
import subprocess
import os
import sys
sys.path.append("../lib/")
import json_parser
import ibofos
import cli
import test_result
import MOUNT_ARRAY_BASIC_1
def clear_result():
if os.path.exists( __file__ + ".result"):
os.remove( __file__ + ".result")
def set_result(detail):
code = json_parser.get_response_code(detail)
result = test_result.expect_false(code)
with open(__file__ + ".result", "w") as result_file:
result_file.write(result + " (" + str(code) + ")" + "\n" + detail)
def execute():
clear_result()
MOUNT_ARRAY_BASIC_1.execute()
out = cli.mount_ibofos()
return out
if __name__ == "__main__":
out = execute()
set_result(out)
ibofos.kill_ibofos() | 23.21875 | 74 | 0.679677 |
import subprocess
import os
import sys
sys.path.append("../lib/")
import json_parser
import ibofos
import cli
import test_result
import MOUNT_ARRAY_BASIC_1
def clear_result():
if os.path.exists( __file__ + ".result"):
os.remove( __file__ + ".result")
def set_result(detail):
code = json_parser.get_response_code(detail)
result = test_result.expect_false(code)
with open(__file__ + ".result", "w") as result_file:
result_file.write(result + " (" + str(code) + ")" + "\n" + detail)
def execute():
clear_result()
MOUNT_ARRAY_BASIC_1.execute()
out = cli.mount_ibofos()
return out
if __name__ == "__main__":
out = execute()
set_result(out)
ibofos.kill_ibofos() | true | true |
f7239a420b531e63ad6053c6b89a4028d5423d78 | 7,223 | py | Python | qa/rpc-tests/nulldummy.py | modong/qtum | e2d7f5e7b588443ac10ac31f7af18527e54abcb5 | [
"MIT"
] | 2 | 2017-07-31T14:18:36.000Z | 2021-07-19T21:35:56.000Z | qa/rpc-tests/nulldummy.py | yelongbao/qtum | e2d7f5e7b588443ac10ac31f7af18527e54abcb5 | [
"MIT"
] | null | null | null | qa/rpc-tests/nulldummy.py | yelongbao/qtum | e2d7f5e7b588443ac10ac31f7af18527e54abcb5 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, NetworkThread
from test_framework.blocktools import create_coinbase, create_block, add_witness_commitment
from test_framework.script import CScript
from io import BytesIO
import time
NULLDUMMY_ERROR = "64: non-mandatory-script-verify-flag (Dummy CHECKMULTISIG argument must be zero)"
def trueDummy(tx):
scriptSig = CScript(tx.vin[0].scriptSig)
newscript = []
for i in scriptSig:
if (len(newscript) == 0):
assert(len(i) == 0)
newscript.append(b'\x51')
else:
newscript.append(i)
tx.vin[0].scriptSig = CScript(newscript)
tx.rehash()
'''
This test is meant to exercise NULLDUMMY softfork.
Connect to a single node.
Generate 2 blocks (save the coinbases for later).
Generate 427 more blocks.
[Policy/Consensus] Check that NULLDUMMY compliant transactions are accepted in the 430th block.
[Policy] Check that non-NULLDUMMY transactions are rejected before activation.
[Consensus] Check that the new NULLDUMMY rules are not enforced on the 431st block.
[Policy/Consensus] Check that the new NULLDUMMY rules are enforced on the 432nd block.
'''
class NULLDUMMYTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 1
self.setup_clean_chain = True
def setup_network(self):
# Must set the blockversion for this test
self.nodes = start_nodes(self.num_nodes, self.options.tmpdir,
extra_args=[['-debug', '-whitelist=127.0.0.1', '-walletprematurewitness']])
def run_test(self):
self.address = self.nodes[0].getnewaddress()
self.ms_address = self.nodes[0].addmultisigaddress(1,[self.address])
self.wit_address = self.nodes[0].addwitnessaddress(self.address)
self.wit_ms_address = self.nodes[0].addwitnessaddress(self.ms_address)
NetworkThread().start() # Start up network handling in another thread
self.coinbase_blocks = self.nodes[0].generate(2) # Block 2
coinbase_txid = []
for i in self.coinbase_blocks:
coinbase_txid.append(self.nodes[0].getblock(i)['tx'][0])
# We submit a couple of blocks that do not signal to delay activation until our coinbases have matured
for i in range(COINBASE_MATURITY):
block = create_block(int(self.nodes[0].getbestblockhash(), 16), create_coinbase(self.nodes[0].getblockcount() + 1), int(time.time())+2+i)
block.nVersion = 4
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.nodes[0].submitblock(bytes_to_hex_str(block.serialize()))
# Generate the number blocks signalling that the continuation of the test case expects
self.nodes[0].generate(863-COINBASE_MATURITY-2-2)
self.lastblockhash = self.nodes[0].getbestblockhash()
self.tip = int("0x" + self.lastblockhash, 0)
self.lastblockheight = self.nodes[0].getblockcount()
self.lastblocktime = int(time.time()) + self.lastblockheight + 1
print ("Test 1: NULLDUMMY compliant base transactions should be accepted to mempool and mined before activation [430]")
test1txs = [self.create_transaction(self.nodes[0], coinbase_txid[0], self.ms_address, 49)]
txid1 = self.tx_submit(self.nodes[0], test1txs[0])
test1txs.append(self.create_transaction(self.nodes[0], txid1, self.ms_address, 48))
txid2 = self.tx_submit(self.nodes[0], test1txs[1])
test1txs.append(self.create_transaction(self.nodes[0], coinbase_txid[1], self.wit_ms_address, 49))
txid3 = self.tx_submit(self.nodes[0], test1txs[2])
self.block_submit(self.nodes[0], test1txs, False, True)
print ("Test 2: Non-NULLDUMMY base multisig transaction should not be accepted to mempool before activation")
test2tx = self.create_transaction(self.nodes[0], txid2, self.ms_address, 48)
trueDummy(test2tx)
txid4 = self.tx_submit(self.nodes[0], test2tx, NULLDUMMY_ERROR)
print ("Test 3: Non-NULLDUMMY base transactions should be accepted in a block before activation [431]")
self.block_submit(self.nodes[0], [test2tx], False, True)
print ("Test 4: Non-NULLDUMMY base multisig transaction is invalid after activation")
test4tx = self.create_transaction(self.nodes[0], txid4, self.address, 47)
test6txs=[CTransaction(test4tx)]
trueDummy(test4tx)
self.tx_submit(self.nodes[0], test4tx, NULLDUMMY_ERROR)
self.block_submit(self.nodes[0], [test4tx])
print ("Test 5: Non-NULLDUMMY P2WSH multisig transaction invalid after activation")
test5tx = self.create_transaction(self.nodes[0], txid3, self.wit_address, 48)
test6txs.append(CTransaction(test5tx))
test5tx.wit.vtxinwit[0].scriptWitness.stack[0] = b'\x01'
self.tx_submit(self.nodes[0], test5tx, NULLDUMMY_ERROR)
self.block_submit(self.nodes[0], [test5tx], True)
print ("Test 6: NULLDUMMY compliant base/witness transactions should be accepted to mempool and in block after activation [432]")
for i in test6txs:
self.tx_submit(self.nodes[0], i)
self.block_submit(self.nodes[0], test6txs, True, True)
def create_transaction(self, node, txid, to_address, amount):
inputs = [{ "txid" : txid, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
signresult = node.signrawtransaction(rawtx)
tx = CTransaction()
f = BytesIO(hex_str_to_bytes(signresult['hex']))
tx.deserialize(f)
return tx
def tx_submit(self, node, tx, msg = ""):
tx.rehash()
try:
node.sendrawtransaction(bytes_to_hex_str(tx.serialize_with_witness()), True)
except JSONRPCException as exp:
assert_equal(exp.error["message"], msg)
else:
assert_equal('', msg)
return tx.hash
def block_submit(self, node, txs, witness = False, accept = False):
block = create_block(self.tip, create_coinbase(self.lastblockheight + 1), self.lastblocktime + 1)
block.nVersion = 4
for tx in txs:
tx.rehash()
block.vtx.append(tx)
block.hashMerkleRoot = block.calc_merkle_root()
witness and add_witness_commitment(block)
block.rehash()
block.solve()
node.submitblock(bytes_to_hex_str(block.serialize(True)))
if (accept):
assert_equal(node.getbestblockhash(), block.hash)
self.tip = block.sha256
self.lastblockhash = block.hash
self.lastblocktime += 1
self.lastblockheight += 1
else:
assert_equal(node.getbestblockhash(), self.lastblockhash)
if __name__ == '__main__':
NULLDUMMYTest().main()
| 44.312883 | 149 | 0.674789 |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, NetworkThread
from test_framework.blocktools import create_coinbase, create_block, add_witness_commitment
from test_framework.script import CScript
from io import BytesIO
import time
NULLDUMMY_ERROR = "64: non-mandatory-script-verify-flag (Dummy CHECKMULTISIG argument must be zero)"
def trueDummy(tx):
scriptSig = CScript(tx.vin[0].scriptSig)
newscript = []
for i in scriptSig:
if (len(newscript) == 0):
assert(len(i) == 0)
newscript.append(b'\x51')
else:
newscript.append(i)
tx.vin[0].scriptSig = CScript(newscript)
tx.rehash()
class NULLDUMMYTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.num_nodes = 1
self.setup_clean_chain = True
def setup_network(self):
self.nodes = start_nodes(self.num_nodes, self.options.tmpdir,
extra_args=[['-debug', '-whitelist=127.0.0.1', '-walletprematurewitness']])
def run_test(self):
self.address = self.nodes[0].getnewaddress()
self.ms_address = self.nodes[0].addmultisigaddress(1,[self.address])
self.wit_address = self.nodes[0].addwitnessaddress(self.address)
self.wit_ms_address = self.nodes[0].addwitnessaddress(self.ms_address)
NetworkThread().start()
self.coinbase_blocks = self.nodes[0].generate(2)
coinbase_txid = []
for i in self.coinbase_blocks:
coinbase_txid.append(self.nodes[0].getblock(i)['tx'][0])
for i in range(COINBASE_MATURITY):
block = create_block(int(self.nodes[0].getbestblockhash(), 16), create_coinbase(self.nodes[0].getblockcount() + 1), int(time.time())+2+i)
block.nVersion = 4
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.nodes[0].submitblock(bytes_to_hex_str(block.serialize()))
self.nodes[0].generate(863-COINBASE_MATURITY-2-2)
self.lastblockhash = self.nodes[0].getbestblockhash()
self.tip = int("0x" + self.lastblockhash, 0)
self.lastblockheight = self.nodes[0].getblockcount()
self.lastblocktime = int(time.time()) + self.lastblockheight + 1
print ("Test 1: NULLDUMMY compliant base transactions should be accepted to mempool and mined before activation [430]")
test1txs = [self.create_transaction(self.nodes[0], coinbase_txid[0], self.ms_address, 49)]
txid1 = self.tx_submit(self.nodes[0], test1txs[0])
test1txs.append(self.create_transaction(self.nodes[0], txid1, self.ms_address, 48))
txid2 = self.tx_submit(self.nodes[0], test1txs[1])
test1txs.append(self.create_transaction(self.nodes[0], coinbase_txid[1], self.wit_ms_address, 49))
txid3 = self.tx_submit(self.nodes[0], test1txs[2])
self.block_submit(self.nodes[0], test1txs, False, True)
print ("Test 2: Non-NULLDUMMY base multisig transaction should not be accepted to mempool before activation")
test2tx = self.create_transaction(self.nodes[0], txid2, self.ms_address, 48)
trueDummy(test2tx)
txid4 = self.tx_submit(self.nodes[0], test2tx, NULLDUMMY_ERROR)
print ("Test 3: Non-NULLDUMMY base transactions should be accepted in a block before activation [431]")
self.block_submit(self.nodes[0], [test2tx], False, True)
print ("Test 4: Non-NULLDUMMY base multisig transaction is invalid after activation")
test4tx = self.create_transaction(self.nodes[0], txid4, self.address, 47)
test6txs=[CTransaction(test4tx)]
trueDummy(test4tx)
self.tx_submit(self.nodes[0], test4tx, NULLDUMMY_ERROR)
self.block_submit(self.nodes[0], [test4tx])
print ("Test 5: Non-NULLDUMMY P2WSH multisig transaction invalid after activation")
test5tx = self.create_transaction(self.nodes[0], txid3, self.wit_address, 48)
test6txs.append(CTransaction(test5tx))
test5tx.wit.vtxinwit[0].scriptWitness.stack[0] = b'\x01'
self.tx_submit(self.nodes[0], test5tx, NULLDUMMY_ERROR)
self.block_submit(self.nodes[0], [test5tx], True)
print ("Test 6: NULLDUMMY compliant base/witness transactions should be accepted to mempool and in block after activation [432]")
for i in test6txs:
self.tx_submit(self.nodes[0], i)
self.block_submit(self.nodes[0], test6txs, True, True)
def create_transaction(self, node, txid, to_address, amount):
inputs = [{ "txid" : txid, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
signresult = node.signrawtransaction(rawtx)
tx = CTransaction()
f = BytesIO(hex_str_to_bytes(signresult['hex']))
tx.deserialize(f)
return tx
def tx_submit(self, node, tx, msg = ""):
tx.rehash()
try:
node.sendrawtransaction(bytes_to_hex_str(tx.serialize_with_witness()), True)
except JSONRPCException as exp:
assert_equal(exp.error["message"], msg)
else:
assert_equal('', msg)
return tx.hash
def block_submit(self, node, txs, witness = False, accept = False):
block = create_block(self.tip, create_coinbase(self.lastblockheight + 1), self.lastblocktime + 1)
block.nVersion = 4
for tx in txs:
tx.rehash()
block.vtx.append(tx)
block.hashMerkleRoot = block.calc_merkle_root()
witness and add_witness_commitment(block)
block.rehash()
block.solve()
node.submitblock(bytes_to_hex_str(block.serialize(True)))
if (accept):
assert_equal(node.getbestblockhash(), block.hash)
self.tip = block.sha256
self.lastblockhash = block.hash
self.lastblocktime += 1
self.lastblockheight += 1
else:
assert_equal(node.getbestblockhash(), self.lastblockhash)
if __name__ == '__main__':
NULLDUMMYTest().main()
| true | true |
f7239b262b4d67fbcefe1216bd596169d62d9df8 | 8,687 | py | Python | Lib/site-packages/streamlit/proto/Slider_pb2.py | AbdelrahmanG/google_nl_api | 3252c1b6a24a5d763543efd15a799e97653a6cf3 | [
"0BSD"
] | null | null | null | Lib/site-packages/streamlit/proto/Slider_pb2.py | AbdelrahmanG/google_nl_api | 3252c1b6a24a5d763543efd15a799e97653a6cf3 | [
"0BSD"
] | null | null | null | Lib/site-packages/streamlit/proto/Slider_pb2.py | AbdelrahmanG/google_nl_api | 3252c1b6a24a5d763543efd15a799e97653a6cf3 | [
"0BSD"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: streamlit/proto/Slider.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='streamlit/proto/Slider.proto',
package='',
syntax='proto3',
serialized_options=None,
create_key=_descriptor._internal_create_key,
serialized_pb=b'\n\x1cstreamlit/proto/Slider.proto\"\xa5\x02\n\x06Slider\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0f\n\x07\x66orm_id\x18\x02 \x01(\t\x12\r\n\x05label\x18\x03 \x01(\t\x12\x0e\n\x06\x66ormat\x18\x04 \x01(\t\x12#\n\tdata_type\x18\x05 \x01(\x0e\x32\x10.Slider.DataType\x12\x0f\n\x07\x64\x65\x66\x61ult\x18\x06 \x03(\x01\x12\x0b\n\x03min\x18\x07 \x01(\x01\x12\x0b\n\x03max\x18\x08 \x01(\x01\x12\x0c\n\x04step\x18\t \x01(\x01\x12\r\n\x05value\x18\n \x03(\x01\x12\x11\n\tset_value\x18\x0b \x01(\x08\x12\x0f\n\x07options\x18\r \x03(\t\x12\x0c\n\x04help\x18\x0e \x01(\t\"@\n\x08\x44\x61taType\x12\x07\n\x03INT\x10\x00\x12\t\n\x05\x46LOAT\x10\x01\x12\x0c\n\x08\x44\x41TETIME\x10\x02\x12\x08\n\x04\x44\x41TE\x10\x03\x12\x08\n\x04TIME\x10\x04\x62\x06proto3'
)
_SLIDER_DATATYPE = _descriptor.EnumDescriptor(
name='DataType',
full_name='Slider.DataType',
filename=None,
file=DESCRIPTOR,
create_key=_descriptor._internal_create_key,
values=[
_descriptor.EnumValueDescriptor(
name='INT', index=0, number=0,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='FLOAT', index=1, number=1,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='DATETIME', index=2, number=2,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='DATE', index=3, number=3,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='TIME', index=4, number=4,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
],
containing_type=None,
serialized_options=None,
serialized_start=262,
serialized_end=326,
)
_sym_db.RegisterEnumDescriptor(_SLIDER_DATATYPE)
_SLIDER = _descriptor.Descriptor(
name='Slider',
full_name='Slider',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='id', full_name='Slider.id', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='form_id', full_name='Slider.form_id', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='label', full_name='Slider.label', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='format', full_name='Slider.format', index=3,
number=4, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='data_type', full_name='Slider.data_type', index=4,
number=5, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='default', full_name='Slider.default', index=5,
number=6, type=1, cpp_type=5, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='min', full_name='Slider.min', index=6,
number=7, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='max', full_name='Slider.max', index=7,
number=8, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='step', full_name='Slider.step', index=8,
number=9, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='value', full_name='Slider.value', index=9,
number=10, type=1, cpp_type=5, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='set_value', full_name='Slider.set_value', index=10,
number=11, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='options', full_name='Slider.options', index=11,
number=13, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='help', full_name='Slider.help', index=12,
number=14, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
_SLIDER_DATATYPE,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=33,
serialized_end=326,
)
_SLIDER.fields_by_name['data_type'].enum_type = _SLIDER_DATATYPE
_SLIDER_DATATYPE.containing_type = _SLIDER
DESCRIPTOR.message_types_by_name['Slider'] = _SLIDER
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
Slider = _reflection.GeneratedProtocolMessageType('Slider', (_message.Message,), {
'DESCRIPTOR' : _SLIDER,
'__module__' : 'streamlit.proto.Slider_pb2'
# @@protoc_insertion_point(class_scope:Slider)
})
_sym_db.RegisterMessage(Slider)
# @@protoc_insertion_point(module_scope)
| 43.873737 | 757 | 0.738114 |
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='streamlit/proto/Slider.proto',
package='',
syntax='proto3',
serialized_options=None,
create_key=_descriptor._internal_create_key,
serialized_pb=b'\n\x1cstreamlit/proto/Slider.proto\"\xa5\x02\n\x06Slider\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0f\n\x07\x66orm_id\x18\x02 \x01(\t\x12\r\n\x05label\x18\x03 \x01(\t\x12\x0e\n\x06\x66ormat\x18\x04 \x01(\t\x12#\n\tdata_type\x18\x05 \x01(\x0e\x32\x10.Slider.DataType\x12\x0f\n\x07\x64\x65\x66\x61ult\x18\x06 \x03(\x01\x12\x0b\n\x03min\x18\x07 \x01(\x01\x12\x0b\n\x03max\x18\x08 \x01(\x01\x12\x0c\n\x04step\x18\t \x01(\x01\x12\r\n\x05value\x18\n \x03(\x01\x12\x11\n\tset_value\x18\x0b \x01(\x08\x12\x0f\n\x07options\x18\r \x03(\t\x12\x0c\n\x04help\x18\x0e \x01(\t\"@\n\x08\x44\x61taType\x12\x07\n\x03INT\x10\x00\x12\t\n\x05\x46LOAT\x10\x01\x12\x0c\n\x08\x44\x41TETIME\x10\x02\x12\x08\n\x04\x44\x41TE\x10\x03\x12\x08\n\x04TIME\x10\x04\x62\x06proto3'
)
_SLIDER_DATATYPE = _descriptor.EnumDescriptor(
name='DataType',
full_name='Slider.DataType',
filename=None,
file=DESCRIPTOR,
create_key=_descriptor._internal_create_key,
values=[
_descriptor.EnumValueDescriptor(
name='INT', index=0, number=0,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='FLOAT', index=1, number=1,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='DATETIME', index=2, number=2,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='DATE', index=3, number=3,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
_descriptor.EnumValueDescriptor(
name='TIME', index=4, number=4,
serialized_options=None,
type=None,
create_key=_descriptor._internal_create_key),
],
containing_type=None,
serialized_options=None,
serialized_start=262,
serialized_end=326,
)
_sym_db.RegisterEnumDescriptor(_SLIDER_DATATYPE)
_SLIDER = _descriptor.Descriptor(
name='Slider',
full_name='Slider',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='id', full_name='Slider.id', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='form_id', full_name='Slider.form_id', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='label', full_name='Slider.label', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='format', full_name='Slider.format', index=3,
number=4, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='data_type', full_name='Slider.data_type', index=4,
number=5, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='default', full_name='Slider.default', index=5,
number=6, type=1, cpp_type=5, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='min', full_name='Slider.min', index=6,
number=7, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='max', full_name='Slider.max', index=7,
number=8, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='step', full_name='Slider.step', index=8,
number=9, type=1, cpp_type=5, label=1,
has_default_value=False, default_value=float(0),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='value', full_name='Slider.value', index=9,
number=10, type=1, cpp_type=5, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='set_value', full_name='Slider.set_value', index=10,
number=11, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='options', full_name='Slider.options', index=11,
number=13, type=9, cpp_type=9, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='help', full_name='Slider.help', index=12,
number=14, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
_SLIDER_DATATYPE,
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=33,
serialized_end=326,
)
_SLIDER.fields_by_name['data_type'].enum_type = _SLIDER_DATATYPE
_SLIDER_DATATYPE.containing_type = _SLIDER
DESCRIPTOR.message_types_by_name['Slider'] = _SLIDER
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
Slider = _reflection.GeneratedProtocolMessageType('Slider', (_message.Message,), {
'DESCRIPTOR' : _SLIDER,
'__module__' : 'streamlit.proto.Slider_pb2'
})
_sym_db.RegisterMessage(Slider)
| true | true |
f7239b97cd52c2880b48477424c60dd1c9d743a8 | 1,879 | py | Python | 2018/stig-runner/oscap-out.py | mbobbitt3/HPCCEA | da2f62a73cca24b30be4a27d199db14785d1f574 | [
"MIT"
] | 10 | 2019-08-12T23:00:20.000Z | 2021-08-06T17:06:48.000Z | 2018/stig-runner/oscap-out.py | mbobbitt3/HPCCEA | da2f62a73cca24b30be4a27d199db14785d1f574 | [
"MIT"
] | 5 | 2020-06-18T23:51:58.000Z | 2021-07-28T17:50:34.000Z | 2018/stig-runner/oscap-out.py | mbobbitt3/HPCCEA | da2f62a73cca24b30be4a27d199db14785d1f574 | [
"MIT"
] | 21 | 2019-06-10T21:03:03.000Z | 2021-08-06T17:57:25.000Z | # script which runs the oscap command for RHEL7
# prints out one line to stdout of pass/fail/other counter
# sends fail ID's to fail.txt and syslog
# written by Alicja Gornicka
import subprocess
import sys
import socket
import syslog
import string
# runs oscap command for rhel7
test = subprocess.Popen(['/usr/bin/oscap', 'xccdf', 'eval', '--fetch-remote-resources', '--profile', 'xccdf_org.ssgproject.content_profile_stig-rhel7-disa', '--results', 'results.xml', '--report', 'report.html', '/usr/share/xml/scap/ssg/content/ssg-rhel7-ds.xml'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# counter variables for pass, fail, and other
passCount = 0
failCount = 0
other = 0 # notchecked and notapplicable
# colors for the output
GREEN = '\33[92m'
RED = '\33[91m'
LAVENDER = '\33[94m'
ORANGE = '\33[93m'
END = '\033[0m'
# opens fail.txt
fail = open("fail.txt",'wb')
fail.write("These are the failed rules.\n")
fail.write("To see more details, cp report.html /var/www/html/ and lynx http://boroni/report.html\n")
fail.write("\n" + socket.gethostname() + ":\n\n")
# grabs rule ID from stdout
# if rules failed, prints rule ID to fail.txt and syslog
for line in test.stdout:
if "Rule" in line:
rule = string.replace(line,'\r','') # needed to remove ^M characters from fail.txt
if "Result" in line:
if 'fail' in line:
failCount += 1
fail.write(rule)
syslog.syslog(rule)
elif 'pass' in line:
passCount += 1
elif 'notchecked' or 'notapplicable' in line:
other += 1
# total number of rules checked
total = passCount + failCount + other
print (ORANGE + socket.gethostname() + END) + ": " + (GREEN + "Pass count: " + END) + str(passCount) + "/" + str(total) + (RED + " Fail count: " + END) + str(failCount) + "/" + str(total) + (LAVENDER + " Other count: " + END) + str(other) + "/" + str(total)
fail.close()
| 34.796296 | 325 | 0.671634 |
# written by Alicja Gornicka
import subprocess
import sys
import socket
import syslog
import string
# runs oscap command for rhel7
test = subprocess.Popen(['/usr/bin/oscap', 'xccdf', 'eval', '--fetch-remote-resources', '--profile', 'xccdf_org.ssgproject.content_profile_stig-rhel7-disa', '--results', 'results.xml', '--report', 'report.html', '/usr/share/xml/scap/ssg/content/ssg-rhel7-ds.xml'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# counter variables for pass, fail, and other
passCount = 0
failCount = 0
other = 0 # notchecked and notapplicable
# colors for the output
GREEN = '\33[92m'
RED = '\33[91m'
LAVENDER = '\33[94m'
ORANGE = '\33[93m'
END = '\033[0m'
# opens fail.txt
fail = open("fail.txt",'wb')
fail.write("These are the failed rules.\n")
fail.write("To see more details, cp report.html /var/www/html/ and lynx http://boroni/report.html\n")
fail.write("\n" + socket.gethostname() + ":\n\n")
# grabs rule ID from stdout
# if rules failed, prints rule ID to fail.txt and syslog
for line in test.stdout:
if "Rule" in line:
rule = string.replace(line,'\r','') # needed to remove ^M characters from fail.txt
if "Result" in line:
if 'fail' in line:
failCount += 1
fail.write(rule)
syslog.syslog(rule)
elif 'pass' in line:
passCount += 1
elif 'notchecked' or 'notapplicable' in line:
other += 1
# total number of rules checked
total = passCount + failCount + other
print (ORANGE + socket.gethostname() + END) + ": " + (GREEN + "Pass count: " + END) + str(passCount) + "/" + str(total) + (RED + " Fail count: " + END) + str(failCount) + "/" + str(total) + (LAVENDER + " Other count: " + END) + str(other) + "/" + str(total)
fail.close()
| true | true |
f7239bc98f0d21d39813daaf13a82d78d14ec803 | 1,081 | py | Python | cootbx/hydrogens_button.py | dperl-sol/cctbx_project | b9e390221a2bc4fd00b9122e97c3b79c632c6664 | [
"BSD-3-Clause-LBNL"
] | 155 | 2016-11-23T12:52:16.000Z | 2022-03-31T15:35:44.000Z | cootbx/hydrogens_button.py | dperl-sol/cctbx_project | b9e390221a2bc4fd00b9122e97c3b79c632c6664 | [
"BSD-3-Clause-LBNL"
] | 590 | 2016-12-10T11:31:18.000Z | 2022-03-30T23:10:09.000Z | cootbx/hydrogens_button.py | dperl-sol/cctbx_project | b9e390221a2bc4fd00b9122e97c3b79c632c6664 | [
"BSD-3-Clause-LBNL"
] | 115 | 2016-11-15T08:17:28.000Z | 2022-02-09T15:30:14.000Z | from __future__ import absolute_import, division, print_function
class hydrogen_toggle(object):
def __init__(self, separator=False):
import coot # import dependency
import coot_python
import gtk
toolbar = coot_python.main_toolbar()
assert (toolbar is not None)
if (separator):
toolbar.insert(gtk.SeparatorToolItem(), -1)
self.h_button = gtk.ToggleToolButton()
self.h_button.set_label("Hydrogens off")
self.h_button.set_is_important(True)
toolbar.insert(self.h_button, -1)
self.h_button.connect("clicked", self.OnToggleHydrogens)
self.h_button.set_active(True)
self.h_button.show()
def OnToggleHydrogens(self, *args):
import coot # import dependency
if self.h_button.get_active():
self.h_button.set_label("Hydrogens on")
for imol in model_molecule_list():
set_draw_hydrogens(imol, True)
else :
self.h_button.set_label("Hydrogens off")
for imol in model_molecule_list():
set_draw_hydrogens(imol, False)
if (__name__ == "__main__"):
hydrogen_toggle(separator=True)
| 32.757576 | 64 | 0.716004 | from __future__ import absolute_import, division, print_function
class hydrogen_toggle(object):
def __init__(self, separator=False):
import coot
import coot_python
import gtk
toolbar = coot_python.main_toolbar()
assert (toolbar is not None)
if (separator):
toolbar.insert(gtk.SeparatorToolItem(), -1)
self.h_button = gtk.ToggleToolButton()
self.h_button.set_label("Hydrogens off")
self.h_button.set_is_important(True)
toolbar.insert(self.h_button, -1)
self.h_button.connect("clicked", self.OnToggleHydrogens)
self.h_button.set_active(True)
self.h_button.show()
def OnToggleHydrogens(self, *args):
import coot
if self.h_button.get_active():
self.h_button.set_label("Hydrogens on")
for imol in model_molecule_list():
set_draw_hydrogens(imol, True)
else :
self.h_button.set_label("Hydrogens off")
for imol in model_molecule_list():
set_draw_hydrogens(imol, False)
if (__name__ == "__main__"):
hydrogen_toggle(separator=True)
| true | true |
f7239c1d08d1ef8a263efa287a2dac09fce8ae67 | 8,980 | py | Python | src/utils/rst_lib.py | Akanni96/feng-hirst-rst-parser | 973dba0156a099ba4f1ad2dc3e18ea72530c64e0 | [
"BSD-2-Clause"
] | 1 | 2021-08-19T14:01:09.000Z | 2021-08-19T14:01:09.000Z | src/utils/rst_lib.py | Akanni96/feng-hirst-rst-parser | 973dba0156a099ba4f1ad2dc3e18ea72530c64e0 | [
"BSD-2-Clause"
] | null | null | null | src/utils/rst_lib.py | Akanni96/feng-hirst-rst-parser | 973dba0156a099ba4f1ad2dc3e18ea72530c64e0 | [
"BSD-2-Clause"
] | null | null | null | '''
Created on 2014-01-17
@author: Vanessa Wei Feng
'''
import os
import fnmatch
import re
from operator import itemgetter
from trees.parse_tree import ParseTree
from nltk.tree import Tree
#from nltk.draw.tree import *
try:
from utils.RST_Classes import *
import utils.treebank_parser
except Exception as e:
from RST_Classes import *
import treebank_parser
def locate(pattern, root=os.getcwd()):
for path, dirs, files in os.walk(root):
for filename in [os.path.abspath(os.path.join(path, filename)) for filename in files if fnmatch.fnmatch(filename, pattern)]:
yield filename
def common_ancestor(L1, L2):
i = 0
while i < len(L1) and i < len(L2) and L1[i] == L2[i]:
i+=1
return L1[0:i]
def common_ancestor_list(LL):
i = 0
L1 = LL[0]
stop = False
while not stop:
for L in LL:
if i >= len(L) or L[i] != L1[i]:
stop = True
i+=1
return L1[0:i-1]
def concat_2_lists(A, B):
A.extend(B)
return A
def concat_lists(L):
return reduce(concat_2_lists, L, [])
def get_concat_text(T, tags = None):
if tags is not None:
no_nps = []
for word_tag in tags:
word = ' '.join(word_tag.split('/')[ : -1])
tag = word_tag.split('/')[-1]
#print word, tag
if tag.startswith('N'):
no_nps.append(word)
if isinstance(T, Tree):
leaves = T.leaves()
if tags is not None:
return (concat_lists(leaves), len(leaves), T.height()-2, no_nps)
return (concat_lists(leaves), len(leaves), T.height()-2)
else:
if tags is not None:
return (T, 1, 0, no_nps)
return (T, 1, 0)
def slice_text(mystr):
#splitter = re.compile('(\$?\'?\d+\.\d+|\'s|\$?\'?\d[\d\/\%,:s\)]*|[a-z\-]*\'[a-z\-]+)|\s([a-z]\.[a-z\.]*)|\s|(<p>|--)|[^a-zA-Z0-9\-\%\s]')
#return [part.lower() for part in splitter.split(mystr.lower().replace("\\)", ")")) if part]
return mystr.lower().split()
def get_ngrams(items, n, NList = {}):
# NList = {}
if n > 1:
myitems = ["<!"] + items + ["!>"]
else:
myitems = items
for i in range(len(myitems) - n + 1):
ngram = "_".join(myitems[i:i+n]).lower()
if ngram in NList:
NList[ngram] += 1
else:
NList[ngram] = 1
return NList
def get_one_ngram(items, n, freq_word_dict = None):
if freq_word_dict is not None:
items1 = []
for item in items:
if item not in freq_word_dict:
items1.append(item)
# if n > 1 or n < -1:
# myitems = ["<!"] + items1 + ["!>"]
# else:
# myitems = items1
if n > 0:
return "_".join(items1[0:n]).lower()
else:
return "_".join(items1[n:]).lower()
# if n > 1 or n < -1:
# myitems = ["<!"] + items + ["!>"]
# else:
# myitems = items
if n > 0:
return "_".join(items[0:n]).lower()
else:
return "_".join(items[n:]).lower()
def filter_ngrams(ngrams, threshold = 1, max_threshold = 0):
ngrams_sel = {}
max_f = 0
for (item, freq) in ngrams.items():
max_f = max([max_f, freq])
if freq > threshold and (max_threshold <= 0 or freq < max_threshold):
ngrams_sel[item] = freq
elif max_threshold > 0 and freq >= max_threshold:
print ("(x) %s %i > %2f" % (item, freq, max_threshold))
return ngrams_sel
def extract_relations(T):
if isinstance(T, Tree):
ret = [T.label()]
for child in T:
ret += extract_relations(child)
return ret
else:
return []
def traverse_tree(T, fn):
if isinstance(T, Tree):
fn (T)
for child in T:
traverse_tree(child, fn)
def traverse_tree_with_offset(T, fn, offset = 0):
if isinstance(T, Tree):
fn (T, offset)
for child in T:
traverse_tree_with_offset(child, fn, offset)
if isinstance(child, Tree):
offset += len(child.leaves())
else:
offset += 1
def traverse_tree_path(T, fn, path_len, arg = None, cur_path = []):
if len(cur_path) > path_len:
return
fn (T, cur_path, arg)
if isinstance(T, Tree):
traverse_tree_path(T[0], fn, path_len, arg, cur_path + [0])
traverse_tree_path(T[1], fn, path_len, arg, cur_path + [1])
else:
traverse_tree_path(None, fn, path_len, arg, cur_path + [0])
traverse_tree_path(None, fn, path_len, arg, cur_path + [1])
def convert_tree(t):
label = None
if t.label() == "text":
return slice_text(t[0])
children = []
for elem in t:
if not isinstance(elem, Tree) or (elem.label() != "span" and elem.label() != "rel2par" and elem.label() != "leaf"):
children.append(elem)
if isinstance(elem, Tree) and (label is None or label[0] == "span"):
for sub in (s for s in elem if isinstance(s, Tree)):
if sub.label() == "rel2par":
label = sub
break;
if len(children) == 1:
return convert_tree(children[0])
label_rel = rel2class[label[0].lower()] + "[" + children[0].label()[0:1] + "][" + children[1].label()[0:1] + "]"
if len(children) > 2:
for item in children[1:]:
item._parent = None
return ParseTree(label_rel, [convert_tree(children[0]),
ParseTree(label_rel, [convert_tree(children[1]),
convert_tree(ParseTree("temp", children[2:]))])])
else:
return ParseTree(label_rel, [convert_tree(children[0]), convert_tree(children[1])])
def load_tree(filename):
str = open(filename).read()
return load_tree_from_string(str)
def load_tree_from_string(str):
return convert_tree(treebank_parser.parse(str))
def load_raw_tree(filename):
str = open(filename).read()
return treebank_parser.parse(str)
def get_main_edus(T, pos = []):
if not isinstance(T, Tree):
#print 'not tree'
return [pos];
ret = [];
if T.label()[-5:-4] == 'N':
ret += get_main_edus(T[0], pos + [0])
if T.label()[-2:-1] == 'N':
ret += get_main_edus(T[1], pos + [1])
# print T
# print ret
#print ret
return ret
def is_left_nucleus(T):
return isinstance(T, Tree) and T.label()[-5:-4] == 'N'
def is_right_nucleus(T):
return isinstance(T, Tree) and T.label()[-2:-1] == 'N'
def filter_lexical_head(head_str):
if not re.sub('^[0-9\\./\\\\,]*', '', head_str):
return "#NUM#";
return head_str.lower()
def filter_syntactic_tag(syntactic_tag):
return syntactic_tag
#return re.sub('[0-9\-=]*$', '', syntactic_tag.lower())
def get_word_list_from_main_edus(span):
word_list = []
if isinstance(span, Tree):
all_main_pos = get_main_edus(span)
for main_pos in all_main_pos:
word_list.extend(get_word_list_from_span(span[main_pos]))
else:
word_list = get_word_list_from_span(span)
return word_list
def get_word_list_from_span(span):
word_list = []
if isinstance(span, Tree):
for leaf in span.leaves():
word_list.extend(leaf)
else:
word_list = span
return word_list
def get_main_spans(span, offset):
main_span_list = []
if isinstance(span, Tree):
for main_pos in get_main_edus(span):
main_span = span[main_pos]
''' find out the index of this edu '''
for i in range(len(span.leaves())):
if list(span.leaf_treeposition(i)) == main_pos:
break
#print i, span.leaf_treeposition(i), main_pos
main_offset = offset + i
main_span_list.append((main_span, main_offset))
else:
main_span_list = [(span, offset)]
return main_span_list
def get_PoS_list_from_span(syntax_trees, span_pos):
(start_sent_id, start_edu_offset, start_word_offset, end_sent_id, end_edu_offset, end_word_offset) = span_pos
pos_list = []
if start_sent_id == end_sent_id:
for i in range(start_word_offset, end_word_offset + 1):
pos_list.append(syntax_trees[start_sent_id].pos()[i][1])
else:
for i in range(start_word_offset, len(syntax_trees[start_sent_id].leaves())):
pos_list.append(syntax_trees[start_sent_id].pos()[i][1])
for sent_id in range(start_sent_id + 1, end_sent_id - 1):
for i in range(len(syntax_trees[sent_id].leaves())):
pos_list.append(syntax_trees[sent_id].pos()[i][1])
for i in range(end_word_offset + 1):
pos_list.append(syntax_trees[end_sent_id].pos()[i][1])
return pos_list
| 29.833887 | 143 | 0.558909 |
import os
import fnmatch
import re
from operator import itemgetter
from trees.parse_tree import ParseTree
from nltk.tree import Tree
try:
from utils.RST_Classes import *
import utils.treebank_parser
except Exception as e:
from RST_Classes import *
import treebank_parser
def locate(pattern, root=os.getcwd()):
for path, dirs, files in os.walk(root):
for filename in [os.path.abspath(os.path.join(path, filename)) for filename in files if fnmatch.fnmatch(filename, pattern)]:
yield filename
def common_ancestor(L1, L2):
i = 0
while i < len(L1) and i < len(L2) and L1[i] == L2[i]:
i+=1
return L1[0:i]
def common_ancestor_list(LL):
i = 0
L1 = LL[0]
stop = False
while not stop:
for L in LL:
if i >= len(L) or L[i] != L1[i]:
stop = True
i+=1
return L1[0:i-1]
def concat_2_lists(A, B):
A.extend(B)
return A
def concat_lists(L):
return reduce(concat_2_lists, L, [])
def get_concat_text(T, tags = None):
if tags is not None:
no_nps = []
for word_tag in tags:
word = ' '.join(word_tag.split('/')[ : -1])
tag = word_tag.split('/')[-1]
if tag.startswith('N'):
no_nps.append(word)
if isinstance(T, Tree):
leaves = T.leaves()
if tags is not None:
return (concat_lists(leaves), len(leaves), T.height()-2, no_nps)
return (concat_lists(leaves), len(leaves), T.height()-2)
else:
if tags is not None:
return (T, 1, 0, no_nps)
return (T, 1, 0)
def slice_text(mystr):
return mystr.lower().split()
def get_ngrams(items, n, NList = {}):
if n > 1:
myitems = ["<!"] + items + ["!>"]
else:
myitems = items
for i in range(len(myitems) - n + 1):
ngram = "_".join(myitems[i:i+n]).lower()
if ngram in NList:
NList[ngram] += 1
else:
NList[ngram] = 1
return NList
def get_one_ngram(items, n, freq_word_dict = None):
if freq_word_dict is not None:
items1 = []
for item in items:
if item not in freq_word_dict:
items1.append(item)
if n > 0:
return "_".join(items1[0:n]).lower()
else:
return "_".join(items1[n:]).lower()
if n > 0:
return "_".join(items[0:n]).lower()
else:
return "_".join(items[n:]).lower()
def filter_ngrams(ngrams, threshold = 1, max_threshold = 0):
ngrams_sel = {}
max_f = 0
for (item, freq) in ngrams.items():
max_f = max([max_f, freq])
if freq > threshold and (max_threshold <= 0 or freq < max_threshold):
ngrams_sel[item] = freq
elif max_threshold > 0 and freq >= max_threshold:
print ("(x) %s %i > %2f" % (item, freq, max_threshold))
return ngrams_sel
def extract_relations(T):
if isinstance(T, Tree):
ret = [T.label()]
for child in T:
ret += extract_relations(child)
return ret
else:
return []
def traverse_tree(T, fn):
if isinstance(T, Tree):
fn (T)
for child in T:
traverse_tree(child, fn)
def traverse_tree_with_offset(T, fn, offset = 0):
if isinstance(T, Tree):
fn (T, offset)
for child in T:
traverse_tree_with_offset(child, fn, offset)
if isinstance(child, Tree):
offset += len(child.leaves())
else:
offset += 1
def traverse_tree_path(T, fn, path_len, arg = None, cur_path = []):
if len(cur_path) > path_len:
return
fn (T, cur_path, arg)
if isinstance(T, Tree):
traverse_tree_path(T[0], fn, path_len, arg, cur_path + [0])
traverse_tree_path(T[1], fn, path_len, arg, cur_path + [1])
else:
traverse_tree_path(None, fn, path_len, arg, cur_path + [0])
traverse_tree_path(None, fn, path_len, arg, cur_path + [1])
def convert_tree(t):
label = None
if t.label() == "text":
return slice_text(t[0])
children = []
for elem in t:
if not isinstance(elem, Tree) or (elem.label() != "span" and elem.label() != "rel2par" and elem.label() != "leaf"):
children.append(elem)
if isinstance(elem, Tree) and (label is None or label[0] == "span"):
for sub in (s for s in elem if isinstance(s, Tree)):
if sub.label() == "rel2par":
label = sub
break;
if len(children) == 1:
return convert_tree(children[0])
label_rel = rel2class[label[0].lower()] + "[" + children[0].label()[0:1] + "][" + children[1].label()[0:1] + "]"
if len(children) > 2:
for item in children[1:]:
item._parent = None
return ParseTree(label_rel, [convert_tree(children[0]),
ParseTree(label_rel, [convert_tree(children[1]),
convert_tree(ParseTree("temp", children[2:]))])])
else:
return ParseTree(label_rel, [convert_tree(children[0]), convert_tree(children[1])])
def load_tree(filename):
str = open(filename).read()
return load_tree_from_string(str)
def load_tree_from_string(str):
return convert_tree(treebank_parser.parse(str))
def load_raw_tree(filename):
str = open(filename).read()
return treebank_parser.parse(str)
def get_main_edus(T, pos = []):
if not isinstance(T, Tree):
return [pos];
ret = [];
if T.label()[-5:-4] == 'N':
ret += get_main_edus(T[0], pos + [0])
if T.label()[-2:-1] == 'N':
ret += get_main_edus(T[1], pos + [1])
return ret
def is_left_nucleus(T):
return isinstance(T, Tree) and T.label()[-5:-4] == 'N'
def is_right_nucleus(T):
return isinstance(T, Tree) and T.label()[-2:-1] == 'N'
def filter_lexical_head(head_str):
if not re.sub('^[0-9\\./\\\\,]*', '', head_str):
return "#NUM#";
return head_str.lower()
def filter_syntactic_tag(syntactic_tag):
return syntactic_tag
def get_word_list_from_main_edus(span):
word_list = []
if isinstance(span, Tree):
all_main_pos = get_main_edus(span)
for main_pos in all_main_pos:
word_list.extend(get_word_list_from_span(span[main_pos]))
else:
word_list = get_word_list_from_span(span)
return word_list
def get_word_list_from_span(span):
word_list = []
if isinstance(span, Tree):
for leaf in span.leaves():
word_list.extend(leaf)
else:
word_list = span
return word_list
def get_main_spans(span, offset):
main_span_list = []
if isinstance(span, Tree):
for main_pos in get_main_edus(span):
main_span = span[main_pos]
for i in range(len(span.leaves())):
if list(span.leaf_treeposition(i)) == main_pos:
break
main_offset = offset + i
main_span_list.append((main_span, main_offset))
else:
main_span_list = [(span, offset)]
return main_span_list
def get_PoS_list_from_span(syntax_trees, span_pos):
(start_sent_id, start_edu_offset, start_word_offset, end_sent_id, end_edu_offset, end_word_offset) = span_pos
pos_list = []
if start_sent_id == end_sent_id:
for i in range(start_word_offset, end_word_offset + 1):
pos_list.append(syntax_trees[start_sent_id].pos()[i][1])
else:
for i in range(start_word_offset, len(syntax_trees[start_sent_id].leaves())):
pos_list.append(syntax_trees[start_sent_id].pos()[i][1])
for sent_id in range(start_sent_id + 1, end_sent_id - 1):
for i in range(len(syntax_trees[sent_id].leaves())):
pos_list.append(syntax_trees[sent_id].pos()[i][1])
for i in range(end_word_offset + 1):
pos_list.append(syntax_trees[end_sent_id].pos()[i][1])
return pos_list
| true | true |
f7239ca588b56176a6289edb12b10d6c7e38bfe1 | 1,252 | py | Python | mmseg/datasets/pipelines/__init__.py | yunchu/mmsegmentation | 404f3e0e8859991931b6a39a583de412348e98f0 | [
"Apache-2.0"
] | null | null | null | mmseg/datasets/pipelines/__init__.py | yunchu/mmsegmentation | 404f3e0e8859991931b6a39a583de412348e98f0 | [
"Apache-2.0"
] | null | null | null | mmseg/datasets/pipelines/__init__.py | yunchu/mmsegmentation | 404f3e0e8859991931b6a39a583de412348e98f0 | [
"Apache-2.0"
] | null | null | null | # Copyright (c) 2020-2021 The MMSegmentation Authors
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
from .compose import Compose, ProbCompose, MaskCompose
from .formating import (Collect, ImageToTensor, ToDataContainer, ToTensor,
Transpose, to_tensor)
from .loading import LoadAnnotations, LoadImageFromFile
from .test_time_aug import MultiScaleFlipAug
from .transforms import (CLAHE, AdjustGamma, Normalize, Pad,
PhotoMetricDistortion, RandomCrop, RandomFlip,
RandomRotate, Rerange, Resize, RGB2Gray, SegRescale,
CrossNorm, MixUp, BorderWeighting, Empty)
__all__ = [
'Compose',
'ProbCompose',
'MaskCompose',
'to_tensor',
'ToTensor',
'ImageToTensor',
'ToDataContainer',
'Transpose',
'Collect',
'LoadAnnotations',
'LoadImageFromFile',
'MultiScaleFlipAug',
'Resize',
'RandomFlip',
'Pad',
'RandomCrop',
'Normalize',
'SegRescale',
'PhotoMetricDistortion',
'RandomRotate',
'AdjustGamma',
'CLAHE',
'Rerange',
'RGB2Gray',
'CrossNorm',
'MixUp',
'BorderWeighting',
'Empty',
]
| 26.083333 | 77 | 0.641374 |
from .compose import Compose, ProbCompose, MaskCompose
from .formating import (Collect, ImageToTensor, ToDataContainer, ToTensor,
Transpose, to_tensor)
from .loading import LoadAnnotations, LoadImageFromFile
from .test_time_aug import MultiScaleFlipAug
from .transforms import (CLAHE, AdjustGamma, Normalize, Pad,
PhotoMetricDistortion, RandomCrop, RandomFlip,
RandomRotate, Rerange, Resize, RGB2Gray, SegRescale,
CrossNorm, MixUp, BorderWeighting, Empty)
__all__ = [
'Compose',
'ProbCompose',
'MaskCompose',
'to_tensor',
'ToTensor',
'ImageToTensor',
'ToDataContainer',
'Transpose',
'Collect',
'LoadAnnotations',
'LoadImageFromFile',
'MultiScaleFlipAug',
'Resize',
'RandomFlip',
'Pad',
'RandomCrop',
'Normalize',
'SegRescale',
'PhotoMetricDistortion',
'RandomRotate',
'AdjustGamma',
'CLAHE',
'Rerange',
'RGB2Gray',
'CrossNorm',
'MixUp',
'BorderWeighting',
'Empty',
]
| true | true |
f7239ccf001f7f9fac5e2fc4cea6dff558efd55c | 53,051 | py | Python | qa/rpc-tests/p2p-fullblocktest.py | rhodium-tech/rhypton | 04d5db1e20054e427d5f22fb9280634393fb3cd1 | [
"MIT"
] | null | null | null | qa/rpc-tests/p2p-fullblocktest.py | rhodium-tech/rhypton | 04d5db1e20054e427d5f22fb9280634393fb3cd1 | [
"MIT"
] | null | null | null | qa/rpc-tests/p2p-fullblocktest.py | rhodium-tech/rhypton | 04d5db1e20054e427d5f22fb9280634393fb3cd1 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test block processing.
This reimplements tests from the bitcoinj/FullBlockTestGenerator used
by the pull-tester.
We use the testing framework in which we expect a particular answer from
each test.
"""
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.comptool import TestManager, TestInstance, RejectResult
from test_framework.blocktools import *
from test_framework.key import CECKey
from test_framework.script import *
import struct
class PreviousSpendableOutput(object):
def __init__(self, tx = CTransaction(), n = -1):
self.tx = tx
self.n = n # the output we're spending
# Use this class for tests that require behavior other than normal "mininode" behavior.
# For now, it is used to serialize a bloated varint (b64).
class CBrokenBlock(CBlock):
def __init__(self, header=None):
super(CBrokenBlock, self).__init__(header)
def initialize(self, base_block):
self.vtx = copy.deepcopy(base_block.vtx)
self.hashMerkleRoot = self.calc_merkle_root()
def serialize(self):
r = b""
r += super(CBlock, self).serialize()
r += struct.pack("<BQ", 255, len(self.vtx))
for tx in self.vtx:
r += tx.serialize()
return r
def normal_serialize(self):
r = b""
r += super(CBrokenBlock, self).serialize()
return r
class FullBlockTest(ComparisonTestFramework):
# Can either run this test as 1 node with expected answers, or two and compare them.
# Change the "outcome" variable from each TestInstance object to only do the comparison.
def __init__(self):
super().__init__()
self.num_nodes = 1
self.block_heights = {}
self.coinbase_key = CECKey()
self.coinbase_key.set_secretbytes(b"horsebattery")
self.coinbase_pubkey = self.coinbase_key.get_pubkey()
self.tip = None
self.blocks = {}
def setup_network(self):
# Must set '-dip3params=2000:2000' to create pre-dip3 blocks only
self.nodes = start_nodes(self.num_nodes, self.options.tmpdir,
extra_args=[['-whitelist=127.0.0.1', '-dip3params=2000:2000']],
binary=[self.options.testbinary])
def add_options(self, parser):
super().add_options(parser)
parser.add_option("--runbarelyexpensive", dest="runbarelyexpensive", default=True)
def run_test(self):
self.test = TestManager(self, self.options.tmpdir)
self.test.add_all_connections(self.nodes)
NetworkThread().start() # Start up network handling in another thread
sync_masternodes(self.nodes, True)
self.test.run()
def add_transactions_to_block(self, block, tx_list):
[ tx.rehash() for tx in tx_list ]
block.vtx.extend(tx_list)
# this is a little handier to use than the version in blocktools.py
def create_tx(self, spend_tx, n, value, script=CScript([OP_TRUE])):
tx = create_transaction(spend_tx, n, b"", value, script)
return tx
# sign a transaction, using the key we know about
# this signs input 0 in tx, which is assumed to be spending output n in spend_tx
def sign_tx(self, tx, spend_tx, n):
scriptPubKey = bytearray(spend_tx.vout[n].scriptPubKey)
if (scriptPubKey[0] == OP_TRUE): # an anyone-can-spend
tx.vin[0].scriptSig = CScript()
return
(sighash, err) = SignatureHash(spend_tx.vout[n].scriptPubKey, tx, 0, SIGHASH_ALL)
tx.vin[0].scriptSig = CScript([self.coinbase_key.sign(sighash) + bytes(bytearray([SIGHASH_ALL]))])
def create_and_sign_transaction(self, spend_tx, n, value, script=CScript([OP_TRUE])):
tx = self.create_tx(spend_tx, n, value, script)
self.sign_tx(tx, spend_tx, n)
tx.rehash()
return tx
def next_block(self, number, spend=None, additional_coinbase_value=0, script=CScript([OP_TRUE]), solve=True):
if self.tip == None:
base_block_hash = self.genesis_hash
block_time = get_mocktime() + 1
else:
base_block_hash = self.tip.sha256
block_time = self.tip.nTime + 1
# First create the coinbase
height = self.block_heights[base_block_hash] + 1
coinbase = create_coinbase(height, self.coinbase_pubkey)
coinbase.vout[0].nValue += additional_coinbase_value
coinbase.rehash()
if spend == None:
block = create_block(base_block_hash, coinbase, block_time)
else:
coinbase.vout[0].nValue += spend.tx.vout[spend.n].nValue - 1 # all but one satoshi to fees
coinbase.rehash()
block = create_block(base_block_hash, coinbase, block_time)
tx = create_transaction(spend.tx, spend.n, b"", 1, script) # spend 1 satoshi
self.sign_tx(tx, spend.tx, spend.n)
self.add_transactions_to_block(block, [tx])
block.hashMerkleRoot = block.calc_merkle_root()
if solve:
block.solve()
self.tip = block
self.block_heights[block.sha256] = height
assert number not in self.blocks
self.blocks[number] = block
return block
def get_tests(self):
self.genesis_hash = int(self.nodes[0].getbestblockhash(), 16)
self.block_heights[self.genesis_hash] = 0
spendable_outputs = []
# save the current tip so it can be spent by a later block
def save_spendable_output():
spendable_outputs.append(self.tip)
# get an output that we previously marked as spendable
def get_spendable_output():
return PreviousSpendableOutput(spendable_outputs.pop(0).vtx[0], 0)
# returns a test case that asserts that the current tip was accepted
def accepted():
return TestInstance([[self.tip, True]])
# returns a test case that asserts that the current tip was rejected
def rejected(reject = None):
if reject is None:
return TestInstance([[self.tip, False]])
else:
return TestInstance([[self.tip, reject]])
# move the tip back to a previous block
def tip(number):
self.tip = self.blocks[number]
# adds transactions to the block and updates state
def update_block(block_number, new_transactions):
block = self.blocks[block_number]
self.add_transactions_to_block(block, new_transactions)
old_sha256 = block.sha256
block.hashMerkleRoot = block.calc_merkle_root()
block.solve()
# Update the internal state just like in next_block
self.tip = block
if block.sha256 != old_sha256:
self.block_heights[block.sha256] = self.block_heights[old_sha256]
del self.block_heights[old_sha256]
self.blocks[block_number] = block
return block
# shorthand for functions
block = self.next_block
create_tx = self.create_tx
create_and_sign_tx = self.create_and_sign_transaction
# these must be updated if consensus changes
MAX_BLOCK_SIGOPS = 20000
# Create a new block
block(0)
save_spendable_output()
yield accepted()
# Now we need that block to mature so we can spend the coinbase.
test = TestInstance(sync_every_block=False)
for i in range(99):
block(5000 + i)
test.blocks_and_transactions.append([self.tip, True])
save_spendable_output()
yield test
# collect spendable outputs now to avoid cluttering the code later on
out = []
for i in range(33):
out.append(get_spendable_output())
# Start by building a couple of blocks on top (which output is spent is
# in parentheses):
# genesis -> b1 (0) -> b2 (1)
block(1, spend=out[0])
save_spendable_output()
yield accepted()
block(2, spend=out[1])
yield accepted()
save_spendable_output()
# so fork like this:
#
# genesis -> b1 (0) -> b2 (1)
# \-> b3 (1)
#
# Nothing should happen at this point. We saw b2 first so it takes priority.
tip(1)
b3 = block(3, spend=out[1])
txout_b3 = PreviousSpendableOutput(b3.vtx[1], 0)
yield rejected()
# Now we add another block to make the alternative chain longer.
#
# genesis -> b1 (0) -> b2 (1)
# \-> b3 (1) -> b4 (2)
block(4, spend=out[2])
yield accepted()
# ... and back to the first chain.
# genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3)
# \-> b3 (1) -> b4 (2)
tip(2)
block(5, spend=out[2])
save_spendable_output()
yield rejected()
block(6, spend=out[3])
yield accepted()
# Try to create a fork that double-spends
# genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3)
# \-> b7 (2) -> b8 (4)
# \-> b3 (1) -> b4 (2)
tip(5)
block(7, spend=out[2])
yield rejected()
block(8, spend=out[4])
yield rejected()
# Try to create a block that has too much fee
# genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3)
# \-> b9 (4)
# \-> b3 (1) -> b4 (2)
tip(6)
block(9, spend=out[4], additional_coinbase_value=1)
yield rejected(RejectResult(16, b'bad-cb-amount'))
# Create a fork that ends in a block with too much fee (the one that causes the reorg)
# genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3)
# \-> b10 (3) -> b11 (4)
# \-> b3 (1) -> b4 (2)
tip(5)
block(10, spend=out[3])
yield rejected()
block(11, spend=out[4], additional_coinbase_value=1)
yield rejected(RejectResult(16, b'bad-cb-amount'))
# Try again, but with a valid fork first
# genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3)
# \-> b12 (3) -> b13 (4) -> b14 (5)
# (b12 added last)
# \-> b3 (1) -> b4 (2)
tip(5)
b12 = block(12, spend=out[3])
save_spendable_output()
b13 = block(13, spend=out[4])
# Deliver the block header for b12, and the block b13.
# b13 should be accepted but the tip won't advance until b12 is delivered.
yield TestInstance([[CBlockHeader(b12), None], [b13, False]])
save_spendable_output()
# b14 is invalid, but the node won't know that until it tries to connect
# Tip still can't advance because b12 is missing
block(14, spend=out[5], additional_coinbase_value=1)
yield rejected()
yield TestInstance([[b12, True, b13.sha256]]) # New tip should be b13.
# Add a block with MAX_BLOCK_SIGOPS and one with one more sigop
# genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3)
# \-> b12 (3) -> b13 (4) -> b15 (5) -> b16 (6)
# \-> b3 (1) -> b4 (2)
# Test that a block with a lot of checksigs is okay
lots_of_checksigs = CScript([OP_CHECKSIG] * (MAX_BLOCK_SIGOPS - 1))
tip(13)
block(15, spend=out[5], script=lots_of_checksigs)
yield accepted()
save_spendable_output()
# Test that a block with too many checksigs is rejected
too_many_checksigs = CScript([OP_CHECKSIG] * (MAX_BLOCK_SIGOPS))
block(16, spend=out[6], script=too_many_checksigs)
yield rejected(RejectResult(16, b'bad-blk-sigops'))
# Attempt to spend a transaction created on a different fork
# genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3)
# \-> b12 (3) -> b13 (4) -> b15 (5) -> b17 (b3.vtx[1])
# \-> b3 (1) -> b4 (2)
tip(15)
block(17, spend=txout_b3)
yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent'))
# Attempt to spend a transaction created on a different fork (on a fork this time)
# genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3)
# \-> b12 (3) -> b13 (4) -> b15 (5)
# \-> b18 (b3.vtx[1]) -> b19 (6)
# \-> b3 (1) -> b4 (2)
tip(13)
block(18, spend=txout_b3)
yield rejected()
block(19, spend=out[6])
yield rejected()
# Attempt to spend a coinbase at depth too low
# genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3)
# \-> b12 (3) -> b13 (4) -> b15 (5) -> b20 (7)
# \-> b3 (1) -> b4 (2)
tip(15)
block(20, spend=out[7])
yield rejected(RejectResult(16, b'bad-txns-premature-spend-of-coinbase'))
# Attempt to spend a coinbase at depth too low (on a fork this time)
# genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3)
# \-> b12 (3) -> b13 (4) -> b15 (5)
# \-> b21 (6) -> b22 (5)
# \-> b3 (1) -> b4 (2)
tip(13)
block(21, spend=out[6])
yield rejected()
block(22, spend=out[5])
yield rejected()
# Create a block on either side of MAX_BLOCK_SIZE and make sure its accepted/rejected
# genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3)
# \-> b12 (3) -> b13 (4) -> b15 (5) -> b23 (6)
# \-> b24 (6) -> b25 (7)
# \-> b3 (1) -> b4 (2)
tip(15)
b23 = block(23, spend=out[6])
tx = CTransaction()
script_length = MAX_BLOCK_SIZE - len(b23.serialize()) - 69
script_output = CScript([b'\x00' * script_length])
tx.vout.append(CTxOut(0, script_output))
tx.vin.append(CTxIn(COutPoint(b23.vtx[1].sha256, 0)))
b23 = update_block(23, [tx])
# Make sure the math above worked out to produce a max-sized block
assert_equal(len(b23.serialize()), MAX_BLOCK_SIZE)
yield accepted()
save_spendable_output()
# Make the next block one byte bigger and check that it fails
tip(15)
b24 = block(24, spend=out[6])
script_length = MAX_BLOCK_SIZE - len(b24.serialize()) - 69
script_output = CScript([b'\x00' * (script_length+1)])
tx.vout = [CTxOut(0, script_output)]
b24 = update_block(24, [tx])
assert_equal(len(b24.serialize()), MAX_BLOCK_SIZE+1)
yield rejected(RejectResult(16, b'bad-blk-length'))
block(25, spend=out[7])
yield rejected()
# Create blocks with a coinbase input script size out of range
# genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3)
# \-> b12 (3) -> b13 (4) -> b15 (5) -> b23 (6) -> b30 (7)
# \-> ... (6) -> ... (7)
# \-> b3 (1) -> b4 (2)
tip(15)
b26 = block(26, spend=out[6])
b26.vtx[0].vin[0].scriptSig = b'\x00'
b26.vtx[0].rehash()
# update_block causes the merkle root to get updated, even with no new
# transactions, and updates the required state.
b26 = update_block(26, [])
yield rejected(RejectResult(16, b'bad-cb-length'))
# Extend the b26 chain to make sure bitcoind isn't accepting b26
b27 = block(27, spend=out[7])
yield rejected(RejectResult(0, b'bad-prevblk'))
# Now try a too-large-coinbase script
tip(15)
b28 = block(28, spend=out[6])
b28.vtx[0].vin[0].scriptSig = b'\x00' * 101
b28.vtx[0].rehash()
b28 = update_block(28, [])
yield rejected(RejectResult(16, b'bad-cb-length'))
# Extend the b28 chain to make sure bitcoind isn't accepting b28
b29 = block(29, spend=out[7])
yield rejected(RejectResult(0, b'bad-prevblk'))
# b30 has a max-sized coinbase scriptSig.
tip(23)
b30 = block(30)
b30.vtx[0].vin[0].scriptSig = b'\x00' * 100
b30.vtx[0].rehash()
b30 = update_block(30, [])
yield accepted()
save_spendable_output()
# b31 - b35 - check sigops of OP_CHECKMULTISIG / OP_CHECKMULTISIGVERIFY / OP_CHECKSIGVERIFY
#
# genesis -> ... -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10)
# \-> b36 (11)
# \-> b34 (10)
# \-> b32 (9)
#
# MULTISIG: each op code counts as 20 sigops. To create the edge case, pack another 19 sigops at the end.
lots_of_multisigs = CScript([OP_CHECKMULTISIG] * ((MAX_BLOCK_SIGOPS-1) // 20) + [OP_CHECKSIG] * 19)
b31 = block(31, spend=out[8], script=lots_of_multisigs)
assert_equal(get_legacy_sigopcount_block(b31), MAX_BLOCK_SIGOPS)
yield accepted()
save_spendable_output()
# this goes over the limit because the coinbase has one sigop
too_many_multisigs = CScript([OP_CHECKMULTISIG] * (MAX_BLOCK_SIGOPS // 20))
b32 = block(32, spend=out[9], script=too_many_multisigs)
assert_equal(get_legacy_sigopcount_block(b32), MAX_BLOCK_SIGOPS + 1)
yield rejected(RejectResult(16, b'bad-blk-sigops'))
# CHECKMULTISIGVERIFY
tip(31)
lots_of_multisigs = CScript([OP_CHECKMULTISIGVERIFY] * ((MAX_BLOCK_SIGOPS-1) // 20) + [OP_CHECKSIG] * 19)
block(33, spend=out[9], script=lots_of_multisigs)
yield accepted()
save_spendable_output()
too_many_multisigs = CScript([OP_CHECKMULTISIGVERIFY] * (MAX_BLOCK_SIGOPS // 20))
block(34, spend=out[10], script=too_many_multisigs)
yield rejected(RejectResult(16, b'bad-blk-sigops'))
# CHECKSIGVERIFY
tip(33)
lots_of_checksigs = CScript([OP_CHECKSIGVERIFY] * (MAX_BLOCK_SIGOPS - 1))
b35 = block(35, spend=out[10], script=lots_of_checksigs)
yield accepted()
save_spendable_output()
too_many_checksigs = CScript([OP_CHECKSIGVERIFY] * (MAX_BLOCK_SIGOPS))
block(36, spend=out[11], script=too_many_checksigs)
yield rejected(RejectResult(16, b'bad-blk-sigops'))
# Check spending of a transaction in a block which failed to connect
#
# b6 (3)
# b12 (3) -> b13 (4) -> b15 (5) -> b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10)
# \-> b37 (11)
# \-> b38 (11/37)
#
# save 37's spendable output, but then double-spend out11 to invalidate the block
tip(35)
b37 = block(37, spend=out[11])
txout_b37 = PreviousSpendableOutput(b37.vtx[1], 0)
tx = create_and_sign_tx(out[11].tx, out[11].n, 0)
b37 = update_block(37, [tx])
yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent'))
# attempt to spend b37's first non-coinbase tx, at which point b37 was still considered valid
tip(35)
block(38, spend=txout_b37)
yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent'))
# Check P2SH SigOp counting
#
#
# 13 (4) -> b15 (5) -> b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b41 (12)
# \-> b40 (12)
#
# b39 - create some P2SH outputs that will require 6 sigops to spend:
#
# redeem_script = COINBASE_PUBKEY, (OP_2DUP+OP_CHECKSIGVERIFY) * 5, OP_CHECKSIG
# p2sh_script = OP_HASH160, ripemd160(sha256(script)), OP_EQUAL
#
tip(35)
b39 = block(39)
b39_outputs = 0
b39_sigops_per_output = 6
# Build the redeem script, hash it, use hash to create the p2sh script
redeem_script = CScript([self.coinbase_pubkey] + [OP_2DUP, OP_CHECKSIGVERIFY]*5 + [OP_CHECKSIG])
redeem_script_hash = hash160(redeem_script)
p2sh_script = CScript([OP_HASH160, redeem_script_hash, OP_EQUAL])
# Create a transaction that spends one satoshi to the p2sh_script, the rest to OP_TRUE
# This must be signed because it is spending a coinbase
spend = out[11]
tx = create_tx(spend.tx, spend.n, 1, p2sh_script)
tx.vout.append(CTxOut(spend.tx.vout[spend.n].nValue - 1, CScript([OP_TRUE])))
self.sign_tx(tx, spend.tx, spend.n)
tx.rehash()
b39 = update_block(39, [tx])
b39_outputs += 1
# Until block is full, add tx's with 1 satoshi to p2sh_script, the rest to OP_TRUE
tx_new = None
tx_last = tx
total_size=len(b39.serialize())
while(total_size < MAX_BLOCK_SIZE):
tx_new = create_tx(tx_last, 1, 1, p2sh_script)
tx_new.vout.append(CTxOut(tx_last.vout[1].nValue - 1, CScript([OP_TRUE])))
tx_new.rehash()
total_size += len(tx_new.serialize())
if total_size >= MAX_BLOCK_SIZE:
break
b39.vtx.append(tx_new) # add tx to block
tx_last = tx_new
b39_outputs += 1
b39 = update_block(39, [])
yield accepted()
save_spendable_output()
# Test sigops in P2SH redeem scripts
#
# b40 creates 3333 tx's spending the 6-sigop P2SH outputs from b39 for a total of 24605 sigops.
# The first tx has one sigop and then at the end we add 2 more to put us just over the max.
#
# b41 does the same, less one, so it has the maximum sigops permitted.
#
tip(39)
b40 = block(40, spend=out[12])
sigops = get_legacy_sigopcount_block(b40)
numTxes = (MAX_BLOCK_SIGOPS - sigops) // b39_sigops_per_output
assert_equal(numTxes <= b39_outputs, True)
lastOutpoint = COutPoint(b40.vtx[1].sha256, 0)
new_txs = []
for i in range(1, numTxes+1):
tx = CTransaction()
tx.vout.append(CTxOut(1, CScript([OP_TRUE])))
tx.vin.append(CTxIn(lastOutpoint, b''))
# second input is corresponding P2SH output from b39
tx.vin.append(CTxIn(COutPoint(b39.vtx[i].sha256, 0), b''))
# Note: must pass the redeem_script (not p2sh_script) to the signature hash function
(sighash, err) = SignatureHash(redeem_script, tx, 1, SIGHASH_ALL)
sig = self.coinbase_key.sign(sighash) + bytes(bytearray([SIGHASH_ALL]))
scriptSig = CScript([sig, redeem_script])
tx.vin[1].scriptSig = scriptSig
tx.rehash()
new_txs.append(tx)
lastOutpoint = COutPoint(tx.sha256, 0)
b40_sigops_to_fill = MAX_BLOCK_SIGOPS - (numTxes * b39_sigops_per_output + sigops) + 1
tx = CTransaction()
tx.vin.append(CTxIn(lastOutpoint, b''))
tx.vout.append(CTxOut(1, CScript([OP_CHECKSIG] * b40_sigops_to_fill)))
tx.rehash()
new_txs.append(tx)
update_block(40, new_txs)
yield rejected(RejectResult(16, b'bad-blk-sigops'))
# same as b40, but one less sigop
tip(39)
b41 = block(41, spend=None)
update_block(41, b40.vtx[1:-1])
b41_sigops_to_fill = b40_sigops_to_fill - 1
tx = CTransaction()
tx.vin.append(CTxIn(lastOutpoint, b''))
tx.vout.append(CTxOut(1, CScript([OP_CHECKSIG] * b41_sigops_to_fill)))
tx.rehash()
update_block(41, [tx])
yield accepted()
# Fork off of b39 to create a constant base again
#
# b23 (6) -> b30 (7) -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13)
# \-> b41 (12)
#
tip(39)
block(42, spend=out[12])
yield rejected()
save_spendable_output()
block(43, spend=out[13])
yield accepted()
save_spendable_output()
# Test a number of really invalid scenarios
#
# -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b44 (14)
# \-> ??? (15)
# The next few blocks are going to be created "by hand" since they'll do funky things, such as having
# the first transaction be non-coinbase, etc. The purpose of b44 is to make sure this works.
height = self.block_heights[self.tip.sha256] + 1
coinbase = create_coinbase(height, self.coinbase_pubkey)
b44 = CBlock()
b44.nTime = self.tip.nTime + 1
b44.hashPrevBlock = self.tip.sha256
b44.nBits = 0x207fffff
b44.vtx.append(coinbase)
b44.hashMerkleRoot = b44.calc_merkle_root()
b44.solve()
self.tip = b44
self.block_heights[b44.sha256] = height
self.blocks[44] = b44
yield accepted()
# A block with a non-coinbase as the first tx
non_coinbase = create_tx(out[15].tx, out[15].n, 1)
b45 = CBlock()
b45.nTime = self.tip.nTime + 1
b45.hashPrevBlock = self.tip.sha256
b45.nBits = 0x207fffff
b45.vtx.append(non_coinbase)
b45.hashMerkleRoot = b45.calc_merkle_root()
b45.calc_sha256()
b45.solve()
self.block_heights[b45.sha256] = self.block_heights[self.tip.sha256]+1
self.tip = b45
self.blocks[45] = b45
yield rejected(RejectResult(16, b'bad-cb-missing'))
# A block with no txns
tip(44)
b46 = CBlock()
b46.nTime = b44.nTime+1
b46.hashPrevBlock = b44.sha256
b46.nBits = 0x207fffff
b46.vtx = []
b46.hashMerkleRoot = 0
b46.solve()
self.block_heights[b46.sha256] = self.block_heights[b44.sha256]+1
self.tip = b46
assert 46 not in self.blocks
self.blocks[46] = b46
s = ser_uint256(b46.hashMerkleRoot)
yield rejected(RejectResult(16, b'bad-blk-length'))
# A block with invalid work
tip(44)
b47 = block(47, solve=False)
target = uint256_from_compact(b47.nBits)
while b47.sha256 < target: #changed > to <
b47.nNonce += 1
b47.rehash()
yield rejected(RejectResult(16, b'high-hash'))
# A block with timestamp > 2 hrs in the future
tip(44)
b48 = block(48, solve=False)
b48.nTime = get_mocktime() + 60 * 60 * 3
b48.solve()
yield rejected(RejectResult(16, b'time-too-new'))
# A block with an invalid merkle hash
tip(44)
b49 = block(49)
b49.hashMerkleRoot += 1
b49.solve()
yield rejected(RejectResult(16, b'bad-txnmrklroot'))
# A block with an incorrect POW limit
tip(44)
b50 = block(50)
b50.nBits = b50.nBits - 1
b50.solve()
yield rejected(RejectResult(16, b'bad-diffbits'))
# A block with two coinbase txns
tip(44)
b51 = block(51)
cb2 = create_coinbase(51, self.coinbase_pubkey)
b51 = update_block(51, [cb2])
yield rejected(RejectResult(16, b'bad-cb-multiple'))
# A block w/ duplicate txns
# Note: txns have to be in the right position in the merkle tree to trigger this error
tip(44)
b52 = block(52, spend=out[15])
tx = create_tx(b52.vtx[1], 0, 1)
b52 = update_block(52, [tx, tx])
yield rejected(RejectResult(16, b'bad-txns-duplicate'))
# Test block timestamps
# -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15)
# \-> b54 (15)
#
tip(43)
block(53, spend=out[14])
yield rejected() # rejected since b44 is at same height
save_spendable_output()
# invalid timestamp (b35 is 5 blocks back, so its time is MedianTimePast)
b54 = block(54, spend=out[15])
b54.nTime = b35.nTime - 1
b54.solve()
yield rejected(RejectResult(16, b'time-too-old'))
# valid timestamp
tip(53)
b55 = block(55, spend=out[15])
b55.nTime = b35.nTime
update_block(55, [])
yield accepted()
save_spendable_output()
# Test CVE-2012-2459
#
# -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57p2 (16)
# \-> b57 (16)
# \-> b56p2 (16)
# \-> b56 (16)
#
# Merkle tree malleability (CVE-2012-2459): repeating sequences of transactions in a block without
# affecting the merkle root of a block, while still invalidating it.
# See: src/consensus/merkle.h
#
# b57 has three txns: coinbase, tx, tx1. The merkle root computation will duplicate tx.
# Result: OK
#
# b56 copies b57 but duplicates tx1 and does not recalculate the block hash. So it has a valid merkle
# root but duplicate transactions.
# Result: Fails
#
# b57p2 has six transactions in its merkle tree:
# - coinbase, tx, tx1, tx2, tx3, tx4
# Merkle root calculation will duplicate as necessary.
# Result: OK.
#
# b56p2 copies b57p2 but adds both tx3 and tx4. The purpose of the test is to make sure the code catches
# duplicate txns that are not next to one another with the "bad-txns-duplicate" error (which indicates
# that the error was caught early, avoiding a DOS vulnerability.)
# b57 - a good block with 2 txs, don't submit until end
tip(55)
b57 = block(57)
tx = create_and_sign_tx(out[16].tx, out[16].n, 1)
tx1 = create_tx(tx, 0, 1)
b57 = update_block(57, [tx, tx1])
# b56 - copy b57, add a duplicate tx
tip(55)
b56 = copy.deepcopy(b57)
self.blocks[56] = b56
assert_equal(len(b56.vtx),3)
b56 = update_block(56, [tx1])
assert_equal(b56.hash, b57.hash)
yield rejected(RejectResult(16, b'bad-txns-duplicate'))
# b57p2 - a good block with 6 tx'es, don't submit until end
tip(55)
b57p2 = block("57p2")
tx = create_and_sign_tx(out[16].tx, out[16].n, 1)
tx1 = create_tx(tx, 0, 1)
tx2 = create_tx(tx1, 0, 1)
tx3 = create_tx(tx2, 0, 1)
tx4 = create_tx(tx3, 0, 1)
b57p2 = update_block("57p2", [tx, tx1, tx2, tx3, tx4])
# b56p2 - copy b57p2, duplicate two non-consecutive tx's
tip(55)
b56p2 = copy.deepcopy(b57p2)
self.blocks["b56p2"] = b56p2
assert_equal(b56p2.hash, b57p2.hash)
assert_equal(len(b56p2.vtx),6)
b56p2 = update_block("b56p2", [tx3, tx4])
yield rejected(RejectResult(16, b'bad-txns-duplicate'))
tip("57p2")
yield accepted()
tip(57)
yield rejected() #rejected because 57p2 seen first
save_spendable_output()
# Test a few invalid tx types
#
# -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17)
# \-> ??? (17)
#
# tx with prevout.n out of range
tip(57)
b58 = block(58, spend=out[17])
tx = CTransaction()
assert(len(out[17].tx.vout) < 42)
tx.vin.append(CTxIn(COutPoint(out[17].tx.sha256, 42), CScript([OP_TRUE]), 0xffffffff))
tx.vout.append(CTxOut(0, b""))
tx.calc_sha256()
b58 = update_block(58, [tx])
yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent'))
# tx with output value > input value out of range
tip(57)
b59 = block(59)
tx = create_and_sign_tx(out[17].tx, out[17].n, 510*COIN)
b59 = update_block(59, [tx])
yield rejected(RejectResult(16, b'bad-txns-in-belowout'))
# reset to good chain
tip(57)
b60 = block(60, spend=out[17])
yield accepted()
save_spendable_output()
# Test BIP30
#
# -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17)
# \-> b61 (18)
#
# Blocks are not allowed to contain a transaction whose id matches that of an earlier,
# not-fully-spent transaction in the same chain. To test, make identical coinbases;
# the second one should be rejected.
#
tip(60)
b61 = block(61, spend=out[18])
b61.vtx[0].vin[0].scriptSig = b60.vtx[0].vin[0].scriptSig #equalize the coinbases
b61.vtx[0].rehash()
b61 = update_block(61, [])
assert_equal(b60.vtx[0].serialize(), b61.vtx[0].serialize())
yield rejected(RejectResult(16, b'bad-txns-BIP30'))
# Test tx.isFinal is properly rejected (not an exhaustive tx.isFinal test, that should be in data-driven transaction tests)
#
# -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17)
# \-> b62 (18)
#
tip(60)
b62 = block(62)
tx = CTransaction()
tx.nLockTime = 0xffffffff #this locktime is non-final
assert(out[18].n < len(out[18].tx.vout))
tx.vin.append(CTxIn(COutPoint(out[18].tx.sha256, out[18].n))) # don't set nSequence
tx.vout.append(CTxOut(0, CScript([OP_TRUE])))
assert(tx.vin[0].nSequence < 0xffffffff)
tx.calc_sha256()
b62 = update_block(62, [tx])
yield rejected(RejectResult(16, b'bad-txns-nonfinal'))
# Test a non-final coinbase is also rejected
#
# -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17)
# \-> b63 (-)
#
tip(60)
b63 = block(63)
b63.vtx[0].nLockTime = 0xffffffff
b63.vtx[0].vin[0].nSequence = 0xDEADBEEF
b63.vtx[0].rehash()
b63 = update_block(63, [])
yield rejected(RejectResult(16, b'bad-txns-nonfinal'))
# This checks that a block with a bloated VARINT between the block_header and the array of tx such that
# the block is > MAX_BLOCK_SIZE with the bloated varint, but <= MAX_BLOCK_SIZE without the bloated varint,
# does not cause a subsequent, identical block with canonical encoding to be rejected. The test does not
# care whether the bloated block is accepted or rejected; it only cares that the second block is accepted.
#
# What matters is that the receiving node should not reject the bloated block, and then reject the canonical
# block on the basis that it's the same as an already-rejected block (which would be a consensus failure.)
#
# -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18)
# \
# b64a (18)
# b64a is a bloated block (non-canonical varint)
# b64 is a good block (same as b64 but w/ canonical varint)
#
tip(60)
regular_block = block("64a", spend=out[18])
# make it a "broken_block," with non-canonical serialization
b64a = CBrokenBlock(regular_block)
b64a.initialize(regular_block)
self.blocks["64a"] = b64a
self.tip = b64a
tx = CTransaction()
# use canonical serialization to calculate size
script_length = MAX_BLOCK_SIZE - len(b64a.normal_serialize()) - 69
script_output = CScript([b'\x00' * script_length])
tx.vout.append(CTxOut(0, script_output))
tx.vin.append(CTxIn(COutPoint(b64a.vtx[1].sha256, 0)))
b64a = update_block("64a", [tx])
assert_equal(len(b64a.serialize()), MAX_BLOCK_SIZE + 8)
yield TestInstance([[self.tip, None]])
# comptool workaround: to make sure b64 is delivered, manually erase b64a from blockstore
self.test.block_store.erase(b64a.sha256)
tip(60)
b64 = CBlock(b64a)
b64.vtx = copy.deepcopy(b64a.vtx)
assert_equal(b64.hash, b64a.hash)
assert_equal(len(b64.serialize()), MAX_BLOCK_SIZE)
self.blocks[64] = b64
update_block(64, [])
yield accepted()
save_spendable_output()
# Spend an output created in the block itself
#
# -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19)
#
tip(64)
b65 = block(65)
tx1 = create_and_sign_tx(out[19].tx, out[19].n, out[19].tx.vout[0].nValue)
tx2 = create_and_sign_tx(tx1, 0, 0)
update_block(65, [tx1, tx2])
yield accepted()
save_spendable_output()
# Attempt to spend an output created later in the same block
#
# -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19)
# \-> b66 (20)
tip(65)
b66 = block(66)
tx1 = create_and_sign_tx(out[20].tx, out[20].n, out[20].tx.vout[0].nValue)
tx2 = create_and_sign_tx(tx1, 0, 1)
update_block(66, [tx2, tx1])
yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent'))
# Attempt to double-spend a transaction created in a block
#
# -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19)
# \-> b67 (20)
#
#
tip(65)
b67 = block(67)
tx1 = create_and_sign_tx(out[20].tx, out[20].n, out[20].tx.vout[0].nValue)
tx2 = create_and_sign_tx(tx1, 0, 1)
tx3 = create_and_sign_tx(tx1, 0, 2)
update_block(67, [tx1, tx2, tx3])
yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent'))
# More tests of block subsidy
#
# -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20)
# \-> b68 (20)
#
# b68 - coinbase with an extra 10 satoshis,
# creates a tx that has 9 satoshis from out[20] go to fees
# this fails because the coinbase is trying to claim 1 satoshi too much in fees
#
# b69 - coinbase with extra 10 satoshis, and a tx that gives a 10 satoshi fee
# this succeeds
#
tip(65)
b68 = block(68, additional_coinbase_value=10)
tx = create_and_sign_tx(out[20].tx, out[20].n, out[20].tx.vout[0].nValue-9)
update_block(68, [tx])
yield rejected(RejectResult(16, b'bad-cb-amount'))
tip(65)
b69 = block(69, additional_coinbase_value=10)
tx = create_and_sign_tx(out[20].tx, out[20].n, out[20].tx.vout[0].nValue-10)
update_block(69, [tx])
yield accepted()
save_spendable_output()
# Test spending the outpoint of a non-existent transaction
#
# -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20)
# \-> b70 (21)
#
tip(69)
block(70, spend=out[21])
bogus_tx = CTransaction()
bogus_tx.sha256 = uint256_from_str(b"23c70ed7c0506e9178fc1a987f40a33946d4ad4c962b5ae3a52546da53af0c5c")
tx = CTransaction()
tx.vin.append(CTxIn(COutPoint(bogus_tx.sha256, 0), b"", 0xffffffff))
tx.vout.append(CTxOut(1, b""))
update_block(70, [tx])
yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent'))
# Test accepting an invalid block which has the same hash as a valid one (via merkle tree tricks)
#
# -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b72 (21)
# \-> b71 (21)
#
# b72 is a good block.
# b71 is a copy of 72, but re-adds one of its transactions. However, it has the same hash as b71.
#
tip(69)
b72 = block(72)
tx1 = create_and_sign_tx(out[21].tx, out[21].n, 2)
tx2 = create_and_sign_tx(tx1, 0, 1)
b72 = update_block(72, [tx1, tx2]) # now tip is 72
b71 = copy.deepcopy(b72)
b71.vtx.append(tx2) # add duplicate tx2
self.block_heights[b71.sha256] = self.block_heights[b69.sha256] + 1 # b71 builds off b69
self.blocks[71] = b71
assert_equal(len(b71.vtx), 4)
assert_equal(len(b72.vtx), 3)
assert_equal(b72.sha256, b71.sha256)
tip(71)
yield rejected(RejectResult(16, b'bad-txns-duplicate'))
tip(72)
yield accepted()
save_spendable_output()
# Test some invalid scripts and MAX_BLOCK_SIGOPS
#
# -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b72 (21)
# \-> b** (22)
#
# b73 - tx with excessive sigops that are placed after an excessively large script element.
# The purpose of the test is to make sure those sigops are counted.
#
# script is a bytearray of size 20,526
#
# bytearray[0-19,998] : OP_CHECKSIG
# bytearray[19,999] : OP_PUSHDATA4
# bytearray[20,000-20,003]: 521 (max_script_element_size+1, in little-endian format)
# bytearray[20,004-20,525]: unread data (script_element)
# bytearray[20,526] : OP_CHECKSIG (this puts us over the limit)
#
tip(72)
b73 = block(73)
size = MAX_BLOCK_SIGOPS - 1 + MAX_SCRIPT_ELEMENT_SIZE + 1 + 5 + 1
a = bytearray([OP_CHECKSIG] * size)
a[MAX_BLOCK_SIGOPS - 1] = int("4e",16) # OP_PUSHDATA4
element_size = MAX_SCRIPT_ELEMENT_SIZE + 1
a[MAX_BLOCK_SIGOPS] = element_size % 256
a[MAX_BLOCK_SIGOPS+1] = element_size // 256
a[MAX_BLOCK_SIGOPS+2] = 0
a[MAX_BLOCK_SIGOPS+3] = 0
tx = create_and_sign_tx(out[22].tx, 0, 1, CScript(a))
b73 = update_block(73, [tx])
assert_equal(get_legacy_sigopcount_block(b73), MAX_BLOCK_SIGOPS+1)
yield rejected(RejectResult(16, b'bad-blk-sigops'))
# b74/75 - if we push an invalid script element, all prevous sigops are counted,
# but sigops after the element are not counted.
#
# The invalid script element is that the push_data indicates that
# there will be a large amount of data (0xffffff bytes), but we only
# provide a much smaller number. These bytes are CHECKSIGS so they would
# cause b75 to fail for excessive sigops, if those bytes were counted.
#
# b74 fails because we put MAX_BLOCK_SIGOPS+1 before the element
# b75 succeeds because we put MAX_BLOCK_SIGOPS before the element
#
#
tip(72)
b74 = block(74)
size = MAX_BLOCK_SIGOPS - 1 + MAX_SCRIPT_ELEMENT_SIZE + 42 # total = 20,561
a = bytearray([OP_CHECKSIG] * size)
a[MAX_BLOCK_SIGOPS] = 0x4e
a[MAX_BLOCK_SIGOPS+1] = 0xfe
a[MAX_BLOCK_SIGOPS+2] = 0xff
a[MAX_BLOCK_SIGOPS+3] = 0xff
a[MAX_BLOCK_SIGOPS+4] = 0xff
tx = create_and_sign_tx(out[22].tx, 0, 1, CScript(a))
b74 = update_block(74, [tx])
yield rejected(RejectResult(16, b'bad-blk-sigops'))
tip(72)
b75 = block(75)
size = MAX_BLOCK_SIGOPS - 1 + MAX_SCRIPT_ELEMENT_SIZE + 42
a = bytearray([OP_CHECKSIG] * size)
a[MAX_BLOCK_SIGOPS-1] = 0x4e
a[MAX_BLOCK_SIGOPS] = 0xff
a[MAX_BLOCK_SIGOPS+1] = 0xff
a[MAX_BLOCK_SIGOPS+2] = 0xff
a[MAX_BLOCK_SIGOPS+3] = 0xff
tx = create_and_sign_tx(out[22].tx, 0, 1, CScript(a))
b75 = update_block(75, [tx])
yield accepted()
save_spendable_output()
# Check that if we push an element filled with CHECKSIGs, they are not counted
tip(75)
b76 = block(76)
size = MAX_BLOCK_SIGOPS - 1 + MAX_SCRIPT_ELEMENT_SIZE + 1 + 5
a = bytearray([OP_CHECKSIG] * size)
a[MAX_BLOCK_SIGOPS-1] = 0x4e # PUSHDATA4, but leave the following bytes as just checksigs
tx = create_and_sign_tx(out[23].tx, 0, 1, CScript(a))
b76 = update_block(76, [tx])
yield accepted()
save_spendable_output()
# Test transaction resurrection
#
# -> b77 (24) -> b78 (25) -> b79 (26)
# \-> b80 (25) -> b81 (26) -> b82 (27)
#
# b78 creates a tx, which is spent in b79. After b82, both should be in mempool
#
# The tx'es must be unsigned and pass the node's mempool policy. It is unsigned for the
# rather obscure reason that the Python signature code does not distinguish between
# Low-S and High-S values (whereas the bitcoin code has custom code which does so);
# as a result of which, the odds are 50% that the python code will use the right
# value and the transaction will be accepted into the mempool. Until we modify the
# test framework to support low-S signing, we are out of luck.
#
# To get around this issue, we construct transactions which are not signed and which
# spend to OP_TRUE. If the standard-ness rules change, this test would need to be
# updated. (Perhaps to spend to a P2SH OP_TRUE script)
#
tip(76)
block(77)
tx77 = create_and_sign_tx(out[24].tx, out[24].n, 10*COIN)
update_block(77, [tx77])
yield accepted()
save_spendable_output()
block(78)
tx78 = create_tx(tx77, 0, 9*COIN)
update_block(78, [tx78])
yield accepted()
block(79)
tx79 = create_tx(tx78, 0, 8*COIN)
update_block(79, [tx79])
yield accepted()
# mempool should be empty
assert_equal(len(self.nodes[0].getrawmempool()), 0)
tip(77)
block(80, spend=out[25])
yield rejected()
save_spendable_output()
block(81, spend=out[26])
yield rejected() # other chain is same length
save_spendable_output()
block(82, spend=out[27])
yield accepted() # now this chain is longer, triggers re-org
save_spendable_output()
# now check that tx78 and tx79 have been put back into the peer's mempool
mempool = self.nodes[0].getrawmempool()
assert_equal(len(mempool), 2)
assert(tx78.hash in mempool)
assert(tx79.hash in mempool)
# Test invalid opcodes in dead execution paths.
#
# -> b81 (26) -> b82 (27) -> b83 (28)
#
b83 = block(83)
op_codes = [OP_IF, OP_INVALIDOPCODE, OP_ELSE, OP_TRUE, OP_ENDIF]
script = CScript(op_codes)
tx1 = create_and_sign_tx(out[28].tx, out[28].n, out[28].tx.vout[0].nValue, script)
tx2 = create_and_sign_tx(tx1, 0, 0, CScript([OP_TRUE]))
tx2.vin[0].scriptSig = CScript([OP_FALSE])
tx2.rehash()
update_block(83, [tx1, tx2])
yield accepted()
save_spendable_output()
# Reorg on/off blocks that have OP_RETURN in them (and try to spend them)
#
# -> b81 (26) -> b82 (27) -> b83 (28) -> b84 (29) -> b87 (30) -> b88 (31)
# \-> b85 (29) -> b86 (30) \-> b89a (32)
#
#
b84 = block(84)
tx1 = create_tx(out[29].tx, out[29].n, 0, CScript([OP_RETURN]))
tx1.vout.append(CTxOut(0, CScript([OP_TRUE])))
tx1.vout.append(CTxOut(0, CScript([OP_TRUE])))
tx1.vout.append(CTxOut(0, CScript([OP_TRUE])))
tx1.vout.append(CTxOut(0, CScript([OP_TRUE])))
tx1.calc_sha256()
self.sign_tx(tx1, out[29].tx, out[29].n)
tx1.rehash()
tx2 = create_tx(tx1, 1, 0, CScript([OP_RETURN]))
tx2.vout.append(CTxOut(0, CScript([OP_RETURN])))
tx3 = create_tx(tx1, 2, 0, CScript([OP_RETURN]))
tx3.vout.append(CTxOut(0, CScript([OP_TRUE])))
tx4 = create_tx(tx1, 3, 0, CScript([OP_TRUE]))
tx4.vout.append(CTxOut(0, CScript([OP_RETURN])))
tx5 = create_tx(tx1, 4, 0, CScript([OP_RETURN]))
update_block(84, [tx1,tx2,tx3,tx4,tx5])
yield accepted()
save_spendable_output()
tip(83)
block(85, spend=out[29])
yield rejected()
block(86, spend=out[30])
yield accepted()
tip(84)
block(87, spend=out[30])
yield rejected()
save_spendable_output()
block(88, spend=out[31])
yield accepted()
save_spendable_output()
# trying to spend the OP_RETURN output is rejected
block("89a", spend=out[32])
tx = create_tx(tx1, 0, 0, CScript([OP_TRUE]))
update_block("89a", [tx])
yield rejected()
# Test re-org of a ~2 days' worth of blocks (1088 blocks)
# This test takes a minute or two and can be accomplished in memory
#
if self.options.runbarelyexpensive:
tip(88)
LARGE_REORG_SIZE = 1088
test1 = TestInstance(sync_every_block=False)
spend=out[32]
for i in range(89, LARGE_REORG_SIZE + 89):
b = block(i, spend)
tx = CTransaction()
script_length = MAX_BLOCK_SIZE - len(b.serialize()) - 69
script_output = CScript([b'\x00' * script_length])
tx.vout.append(CTxOut(0, script_output))
tx.vin.append(CTxIn(COutPoint(b.vtx[1].sha256, 0)))
b = update_block(i, [tx])
assert_equal(len(b.serialize()), MAX_BLOCK_SIZE)
test1.blocks_and_transactions.append([self.tip, True])
save_spendable_output()
spend = get_spendable_output()
yield test1
chain1_tip = i
# now create alt chain of same length
tip(88)
test2 = TestInstance(sync_every_block=False)
for i in range(89, LARGE_REORG_SIZE + 89):
block("alt"+str(i))
test2.blocks_and_transactions.append([self.tip, False])
yield test2
# extend alt chain to trigger re-org
block("alt" + str(chain1_tip + 1))
yield accepted()
# ... and re-org back to the first chain
tip(chain1_tip)
block(chain1_tip + 1)
yield rejected()
block(chain1_tip + 2)
yield accepted()
chain1_tip += 2
if __name__ == '__main__':
FullBlockTest().main()
| 40.902853 | 131 | 0.544495 |
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.comptool import TestManager, TestInstance, RejectResult
from test_framework.blocktools import *
from test_framework.key import CECKey
from test_framework.script import *
import struct
class PreviousSpendableOutput(object):
def __init__(self, tx = CTransaction(), n = -1):
self.tx = tx
self.n = n
# Use this class for tests that require behavior other than normal "mininode" behavior.
# For now, it is used to serialize a bloated varint (b64).
class CBrokenBlock(CBlock):
def __init__(self, header=None):
super(CBrokenBlock, self).__init__(header)
def initialize(self, base_block):
self.vtx = copy.deepcopy(base_block.vtx)
self.hashMerkleRoot = self.calc_merkle_root()
def serialize(self):
r = b""
r += super(CBlock, self).serialize()
r += struct.pack("<BQ", 255, len(self.vtx))
for tx in self.vtx:
r += tx.serialize()
return r
def normal_serialize(self):
r = b""
r += super(CBrokenBlock, self).serialize()
return r
class FullBlockTest(ComparisonTestFramework):
# Can either run this test as 1 node with expected answers, or two and compare them.
# Change the "outcome" variable from each TestInstance object to only do the comparison.
def __init__(self):
super().__init__()
self.num_nodes = 1
self.block_heights = {}
self.coinbase_key = CECKey()
self.coinbase_key.set_secretbytes(b"horsebattery")
self.coinbase_pubkey = self.coinbase_key.get_pubkey()
self.tip = None
self.blocks = {}
def setup_network(self):
# Must set '-dip3params=2000:2000' to create pre-dip3 blocks only
self.nodes = start_nodes(self.num_nodes, self.options.tmpdir,
extra_args=[['-whitelist=127.0.0.1', '-dip3params=2000:2000']],
binary=[self.options.testbinary])
def add_options(self, parser):
super().add_options(parser)
parser.add_option("--runbarelyexpensive", dest="runbarelyexpensive", default=True)
def run_test(self):
self.test = TestManager(self, self.options.tmpdir)
self.test.add_all_connections(self.nodes)
NetworkThread().start() # Start up network handling in another thread
sync_masternodes(self.nodes, True)
self.test.run()
def add_transactions_to_block(self, block, tx_list):
[ tx.rehash() for tx in tx_list ]
block.vtx.extend(tx_list)
# this is a little handier to use than the version in blocktools.py
def create_tx(self, spend_tx, n, value, script=CScript([OP_TRUE])):
tx = create_transaction(spend_tx, n, b"", value, script)
return tx
# sign a transaction, using the key we know about
# this signs input 0 in tx, which is assumed to be spending output n in spend_tx
def sign_tx(self, tx, spend_tx, n):
scriptPubKey = bytearray(spend_tx.vout[n].scriptPubKey)
if (scriptPubKey[0] == OP_TRUE): # an anyone-can-spend
tx.vin[0].scriptSig = CScript()
return
(sighash, err) = SignatureHash(spend_tx.vout[n].scriptPubKey, tx, 0, SIGHASH_ALL)
tx.vin[0].scriptSig = CScript([self.coinbase_key.sign(sighash) + bytes(bytearray([SIGHASH_ALL]))])
def create_and_sign_transaction(self, spend_tx, n, value, script=CScript([OP_TRUE])):
tx = self.create_tx(spend_tx, n, value, script)
self.sign_tx(tx, spend_tx, n)
tx.rehash()
return tx
def next_block(self, number, spend=None, additional_coinbase_value=0, script=CScript([OP_TRUE]), solve=True):
if self.tip == None:
base_block_hash = self.genesis_hash
block_time = get_mocktime() + 1
else:
base_block_hash = self.tip.sha256
block_time = self.tip.nTime + 1
# First create the coinbase
height = self.block_heights[base_block_hash] + 1
coinbase = create_coinbase(height, self.coinbase_pubkey)
coinbase.vout[0].nValue += additional_coinbase_value
coinbase.rehash()
if spend == None:
block = create_block(base_block_hash, coinbase, block_time)
else:
coinbase.vout[0].nValue += spend.tx.vout[spend.n].nValue - 1 # all but one satoshi to fees
coinbase.rehash()
block = create_block(base_block_hash, coinbase, block_time)
tx = create_transaction(spend.tx, spend.n, b"", 1, script) # spend 1 satoshi
self.sign_tx(tx, spend.tx, spend.n)
self.add_transactions_to_block(block, [tx])
block.hashMerkleRoot = block.calc_merkle_root()
if solve:
block.solve()
self.tip = block
self.block_heights[block.sha256] = height
assert number not in self.blocks
self.blocks[number] = block
return block
def get_tests(self):
self.genesis_hash = int(self.nodes[0].getbestblockhash(), 16)
self.block_heights[self.genesis_hash] = 0
spendable_outputs = []
# save the current tip so it can be spent by a later block
def save_spendable_output():
spendable_outputs.append(self.tip)
# get an output that we previously marked as spendable
def get_spendable_output():
return PreviousSpendableOutput(spendable_outputs.pop(0).vtx[0], 0)
# returns a test case that asserts that the current tip was accepted
def accepted():
return TestInstance([[self.tip, True]])
# returns a test case that asserts that the current tip was rejected
def rejected(reject = None):
if reject is None:
return TestInstance([[self.tip, False]])
else:
return TestInstance([[self.tip, reject]])
# move the tip back to a previous block
def tip(number):
self.tip = self.blocks[number]
# adds transactions to the block and updates state
def update_block(block_number, new_transactions):
block = self.blocks[block_number]
self.add_transactions_to_block(block, new_transactions)
old_sha256 = block.sha256
block.hashMerkleRoot = block.calc_merkle_root()
block.solve()
# Update the internal state just like in next_block
self.tip = block
if block.sha256 != old_sha256:
self.block_heights[block.sha256] = self.block_heights[old_sha256]
del self.block_heights[old_sha256]
self.blocks[block_number] = block
return block
# shorthand for functions
block = self.next_block
create_tx = self.create_tx
create_and_sign_tx = self.create_and_sign_transaction
# these must be updated if consensus changes
MAX_BLOCK_SIGOPS = 20000
# Create a new block
block(0)
save_spendable_output()
yield accepted()
# Now we need that block to mature so we can spend the coinbase.
test = TestInstance(sync_every_block=False)
for i in range(99):
block(5000 + i)
test.blocks_and_transactions.append([self.tip, True])
save_spendable_output()
yield test
# collect spendable outputs now to avoid cluttering the code later on
out = []
for i in range(33):
out.append(get_spendable_output())
# Start by building a couple of blocks on top (which output is spent is
# in parentheses):
# genesis -> b1 (0) -> b2 (1)
block(1, spend=out[0])
save_spendable_output()
yield accepted()
block(2, spend=out[1])
yield accepted()
save_spendable_output()
# so fork like this:
#
# genesis -> b1 (0) -> b2 (1)
# \-> b3 (1)
#
# Nothing should happen at this point. We saw b2 first so it takes priority.
tip(1)
b3 = block(3, spend=out[1])
txout_b3 = PreviousSpendableOutput(b3.vtx[1], 0)
yield rejected()
# Now we add another block to make the alternative chain longer.
#
# genesis -> b1 (0) -> b2 (1)
# \-> b3 (1) -> b4 (2)
block(4, spend=out[2])
yield accepted()
# ... and back to the first chain.
# genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3)
# \-> b3 (1) -> b4 (2)
tip(2)
block(5, spend=out[2])
save_spendable_output()
yield rejected()
block(6, spend=out[3])
yield accepted()
# Try to create a fork that double-spends
# genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3)
# \-> b7 (2) -> b8 (4)
# \-> b3 (1) -> b4 (2)
tip(5)
block(7, spend=out[2])
yield rejected()
block(8, spend=out[4])
yield rejected()
# Try to create a block that has too much fee
# genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3)
# \-> b9 (4)
# \-> b3 (1) -> b4 (2)
tip(6)
block(9, spend=out[4], additional_coinbase_value=1)
yield rejected(RejectResult(16, b'bad-cb-amount'))
# Create a fork that ends in a block with too much fee (the one that causes the reorg)
# genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3)
# \-> b10 (3) -> b11 (4)
# \-> b3 (1) -> b4 (2)
tip(5)
block(10, spend=out[3])
yield rejected()
block(11, spend=out[4], additional_coinbase_value=1)
yield rejected(RejectResult(16, b'bad-cb-amount'))
# Try again, but with a valid fork first
# genesis -> b1 (0) -> b2 (1) -> b5 (2) -> b6 (3)
# \-> b12 (3) -> b13 (4) -> b14 (5)
# (b12 added last)
# \-> b3 (1) -> b4 (2)
tip(5)
b12 = block(12, spend=out[3])
save_spendable_output()
b13 = block(13, spend=out[4])
# Deliver the block header for b12, and the block b13.
# b13 should be accepted but the tip won't advance until b12 is delivered.
yield TestInstance([[CBlockHeader(b12), None], [b13, False]])
save_spendable_output()
# Tip still can't advance because b12 is missing
block(14, spend=out[5], additional_coinbase_value=1)
yield rejected()
yield TestInstance([[b12, True, b13.sha256]])
lots_of_checksigs = CScript([OP_CHECKSIG] * (MAX_BLOCK_SIGOPS - 1))
tip(13)
block(15, spend=out[5], script=lots_of_checksigs)
yield accepted()
save_spendable_output()
too_many_checksigs = CScript([OP_CHECKSIG] * (MAX_BLOCK_SIGOPS))
block(16, spend=out[6], script=too_many_checksigs)
yield rejected(RejectResult(16, b'bad-blk-sigops'))
tip(15)
block(17, spend=txout_b3)
yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent'))
tip(13)
block(18, spend=txout_b3)
yield rejected()
block(19, spend=out[6])
yield rejected()
tip(15)
block(20, spend=out[7])
yield rejected(RejectResult(16, b'bad-txns-premature-spend-of-coinbase'))
tip(13)
block(21, spend=out[6])
yield rejected()
block(22, spend=out[5])
yield rejected()
tip(15)
b23 = block(23, spend=out[6])
tx = CTransaction()
script_length = MAX_BLOCK_SIZE - len(b23.serialize()) - 69
script_output = CScript([b'\x00' * script_length])
tx.vout.append(CTxOut(0, script_output))
tx.vin.append(CTxIn(COutPoint(b23.vtx[1].sha256, 0)))
b23 = update_block(23, [tx])
assert_equal(len(b23.serialize()), MAX_BLOCK_SIZE)
yield accepted()
save_spendable_output()
tip(15)
b24 = block(24, spend=out[6])
script_length = MAX_BLOCK_SIZE - len(b24.serialize()) - 69
script_output = CScript([b'\x00' * (script_length+1)])
tx.vout = [CTxOut(0, script_output)]
b24 = update_block(24, [tx])
assert_equal(len(b24.serialize()), MAX_BLOCK_SIZE+1)
yield rejected(RejectResult(16, b'bad-blk-length'))
block(25, spend=out[7])
yield rejected()
tip(15)
b26 = block(26, spend=out[6])
b26.vtx[0].vin[0].scriptSig = b'\x00'
b26.vtx[0].rehash()
b26 = update_block(26, [])
yield rejected(RejectResult(16, b'bad-cb-length'))
b27 = block(27, spend=out[7])
yield rejected(RejectResult(0, b'bad-prevblk'))
# Now try a too-large-coinbase script
tip(15)
b28 = block(28, spend=out[6])
b28.vtx[0].vin[0].scriptSig = b'\x00' * 101
b28.vtx[0].rehash()
b28 = update_block(28, [])
yield rejected(RejectResult(16, b'bad-cb-length'))
# Extend the b28 chain to make sure bitcoind isn't accepting b28
b29 = block(29, spend=out[7])
yield rejected(RejectResult(0, b'bad-prevblk'))
tip(23)
b30 = block(30)
b30.vtx[0].vin[0].scriptSig = b'\x00' * 100
b30.vtx[0].rehash()
b30 = update_block(30, [])
yield accepted()
save_spendable_output()
lots_of_multisigs = CScript([OP_CHECKMULTISIG] * ((MAX_BLOCK_SIGOPS-1) // 20) + [OP_CHECKSIG] * 19)
b31 = block(31, spend=out[8], script=lots_of_multisigs)
assert_equal(get_legacy_sigopcount_block(b31), MAX_BLOCK_SIGOPS)
yield accepted()
save_spendable_output()
too_many_multisigs = CScript([OP_CHECKMULTISIG] * (MAX_BLOCK_SIGOPS // 20))
b32 = block(32, spend=out[9], script=too_many_multisigs)
assert_equal(get_legacy_sigopcount_block(b32), MAX_BLOCK_SIGOPS + 1)
yield rejected(RejectResult(16, b'bad-blk-sigops'))
tip(31)
lots_of_multisigs = CScript([OP_CHECKMULTISIGVERIFY] * ((MAX_BLOCK_SIGOPS-1) // 20) + [OP_CHECKSIG] * 19)
block(33, spend=out[9], script=lots_of_multisigs)
yield accepted()
save_spendable_output()
too_many_multisigs = CScript([OP_CHECKMULTISIGVERIFY] * (MAX_BLOCK_SIGOPS // 20))
block(34, spend=out[10], script=too_many_multisigs)
yield rejected(RejectResult(16, b'bad-blk-sigops'))
tip(33)
lots_of_checksigs = CScript([OP_CHECKSIGVERIFY] * (MAX_BLOCK_SIGOPS - 1))
b35 = block(35, spend=out[10], script=lots_of_checksigs)
yield accepted()
save_spendable_output()
too_many_checksigs = CScript([OP_CHECKSIGVERIFY] * (MAX_BLOCK_SIGOPS))
block(36, spend=out[11], script=too_many_checksigs)
yield rejected(RejectResult(16, b'bad-blk-sigops'))
tip(35)
b37 = block(37, spend=out[11])
txout_b37 = PreviousSpendableOutput(b37.vtx[1], 0)
tx = create_and_sign_tx(out[11].tx, out[11].n, 0)
b37 = update_block(37, [tx])
yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent'))
# attempt to spend b37's first non-coinbase tx, at which point b37 was still considered valid
tip(35)
block(38, spend=txout_b37)
yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent'))
tip(35)
b39 = block(39)
b39_outputs = 0
b39_sigops_per_output = 6
redeem_script = CScript([self.coinbase_pubkey] + [OP_2DUP, OP_CHECKSIGVERIFY]*5 + [OP_CHECKSIG])
redeem_script_hash = hash160(redeem_script)
p2sh_script = CScript([OP_HASH160, redeem_script_hash, OP_EQUAL])
spend = out[11]
tx = create_tx(spend.tx, spend.n, 1, p2sh_script)
tx.vout.append(CTxOut(spend.tx.vout[spend.n].nValue - 1, CScript([OP_TRUE])))
self.sign_tx(tx, spend.tx, spend.n)
tx.rehash()
b39 = update_block(39, [tx])
b39_outputs += 1
tx_new = None
tx_last = tx
total_size=len(b39.serialize())
while(total_size < MAX_BLOCK_SIZE):
tx_new = create_tx(tx_last, 1, 1, p2sh_script)
tx_new.vout.append(CTxOut(tx_last.vout[1].nValue - 1, CScript([OP_TRUE])))
tx_new.rehash()
total_size += len(tx_new.serialize())
if total_size >= MAX_BLOCK_SIZE:
break
b39.vtx.append(tx_new) # add tx to block
tx_last = tx_new
b39_outputs += 1
b39 = update_block(39, [])
yield accepted()
save_spendable_output()
# Test sigops in P2SH redeem scripts
#
# b40 creates 3333 tx's spending the 6-sigop P2SH outputs from b39 for a total of 24605 sigops.
tip(39)
b40 = block(40, spend=out[12])
sigops = get_legacy_sigopcount_block(b40)
numTxes = (MAX_BLOCK_SIGOPS - sigops) // b39_sigops_per_output
assert_equal(numTxes <= b39_outputs, True)
lastOutpoint = COutPoint(b40.vtx[1].sha256, 0)
new_txs = []
for i in range(1, numTxes+1):
tx = CTransaction()
tx.vout.append(CTxOut(1, CScript([OP_TRUE])))
tx.vin.append(CTxIn(lastOutpoint, b''))
tx.vin.append(CTxIn(COutPoint(b39.vtx[i].sha256, 0), b''))
(sighash, err) = SignatureHash(redeem_script, tx, 1, SIGHASH_ALL)
sig = self.coinbase_key.sign(sighash) + bytes(bytearray([SIGHASH_ALL]))
scriptSig = CScript([sig, redeem_script])
tx.vin[1].scriptSig = scriptSig
tx.rehash()
new_txs.append(tx)
lastOutpoint = COutPoint(tx.sha256, 0)
b40_sigops_to_fill = MAX_BLOCK_SIGOPS - (numTxes * b39_sigops_per_output + sigops) + 1
tx = CTransaction()
tx.vin.append(CTxIn(lastOutpoint, b''))
tx.vout.append(CTxOut(1, CScript([OP_CHECKSIG] * b40_sigops_to_fill)))
tx.rehash()
new_txs.append(tx)
update_block(40, new_txs)
yield rejected(RejectResult(16, b'bad-blk-sigops'))
tip(39)
b41 = block(41, spend=None)
update_block(41, b40.vtx[1:-1])
b41_sigops_to_fill = b40_sigops_to_fill - 1
tx = CTransaction()
tx.vin.append(CTxIn(lastOutpoint, b''))
tx.vout.append(CTxOut(1, CScript([OP_CHECKSIG] * b41_sigops_to_fill)))
tx.rehash()
update_block(41, [tx])
yield accepted()
tip(39)
block(42, spend=out[12])
yield rejected()
save_spendable_output()
block(43, spend=out[13])
yield accepted()
save_spendable_output()
# the first transaction be non-coinbase, etc. The purpose of b44 is to make sure this works.
height = self.block_heights[self.tip.sha256] + 1
coinbase = create_coinbase(height, self.coinbase_pubkey)
b44 = CBlock()
b44.nTime = self.tip.nTime + 1
b44.hashPrevBlock = self.tip.sha256
b44.nBits = 0x207fffff
b44.vtx.append(coinbase)
b44.hashMerkleRoot = b44.calc_merkle_root()
b44.solve()
self.tip = b44
self.block_heights[b44.sha256] = height
self.blocks[44] = b44
yield accepted()
# A block with a non-coinbase as the first tx
non_coinbase = create_tx(out[15].tx, out[15].n, 1)
b45 = CBlock()
b45.nTime = self.tip.nTime + 1
b45.hashPrevBlock = self.tip.sha256
b45.nBits = 0x207fffff
b45.vtx.append(non_coinbase)
b45.hashMerkleRoot = b45.calc_merkle_root()
b45.calc_sha256()
b45.solve()
self.block_heights[b45.sha256] = self.block_heights[self.tip.sha256]+1
self.tip = b45
self.blocks[45] = b45
yield rejected(RejectResult(16, b'bad-cb-missing'))
# A block with no txns
tip(44)
b46 = CBlock()
b46.nTime = b44.nTime+1
b46.hashPrevBlock = b44.sha256
b46.nBits = 0x207fffff
b46.vtx = []
b46.hashMerkleRoot = 0
b46.solve()
self.block_heights[b46.sha256] = self.block_heights[b44.sha256]+1
self.tip = b46
assert 46 not in self.blocks
self.blocks[46] = b46
s = ser_uint256(b46.hashMerkleRoot)
yield rejected(RejectResult(16, b'bad-blk-length'))
# A block with invalid work
tip(44)
b47 = block(47, solve=False)
target = uint256_from_compact(b47.nBits)
while b47.sha256 < target: #changed > to <
b47.nNonce += 1
b47.rehash()
yield rejected(RejectResult(16, b'high-hash'))
# A block with timestamp > 2 hrs in the future
tip(44)
b48 = block(48, solve=False)
b48.nTime = get_mocktime() + 60 * 60 * 3
b48.solve()
yield rejected(RejectResult(16, b'time-too-new'))
# A block with an invalid merkle hash
tip(44)
b49 = block(49)
b49.hashMerkleRoot += 1
b49.solve()
yield rejected(RejectResult(16, b'bad-txnmrklroot'))
# A block with an incorrect POW limit
tip(44)
b50 = block(50)
b50.nBits = b50.nBits - 1
b50.solve()
yield rejected(RejectResult(16, b'bad-diffbits'))
# A block with two coinbase txns
tip(44)
b51 = block(51)
cb2 = create_coinbase(51, self.coinbase_pubkey)
b51 = update_block(51, [cb2])
yield rejected(RejectResult(16, b'bad-cb-multiple'))
# A block w/ duplicate txns
# Note: txns have to be in the right position in the merkle tree to trigger this error
tip(44)
b52 = block(52, spend=out[15])
tx = create_tx(b52.vtx[1], 0, 1)
b52 = update_block(52, [tx, tx])
yield rejected(RejectResult(16, b'bad-txns-duplicate'))
# Test block timestamps
# -> b31 (8) -> b33 (9) -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15)
# \-> b54 (15)
#
tip(43)
block(53, spend=out[14])
yield rejected() # rejected since b44 is at same height
save_spendable_output()
# invalid timestamp (b35 is 5 blocks back, so its time is MedianTimePast)
b54 = block(54, spend=out[15])
b54.nTime = b35.nTime - 1
b54.solve()
yield rejected(RejectResult(16, b'time-too-old'))
# valid timestamp
tip(53)
b55 = block(55, spend=out[15])
b55.nTime = b35.nTime
update_block(55, [])
yield accepted()
save_spendable_output()
# Test CVE-2012-2459
#
# -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57p2 (16)
# \-> b57 (16)
# \-> b56p2 (16)
# \-> b56 (16)
#
# Merkle tree malleability (CVE-2012-2459): repeating sequences of transactions in a block without
# affecting the merkle root of a block, while still invalidating it.
# See: src/consensus/merkle.h
#
# b57 has three txns: coinbase, tx, tx1. The merkle root computation will duplicate tx.
# Result: OK
#
# b56 copies b57 but duplicates tx1 and does not recalculate the block hash. So it has a valid merkle
# root but duplicate transactions.
# Result: Fails
#
# b57p2 has six transactions in its merkle tree:
# - coinbase, tx, tx1, tx2, tx3, tx4
# Merkle root calculation will duplicate as necessary.
# Result: OK.
#
# b56p2 copies b57p2 but adds both tx3 and tx4. The purpose of the test is to make sure the code catches
# duplicate txns that are not next to one another with the "bad-txns-duplicate" error (which indicates
# that the error was caught early, avoiding a DOS vulnerability.)
# b57 - a good block with 2 txs, don't submit until end
tip(55)
b57 = block(57)
tx = create_and_sign_tx(out[16].tx, out[16].n, 1)
tx1 = create_tx(tx, 0, 1)
b57 = update_block(57, [tx, tx1])
tip(55)
b56 = copy.deepcopy(b57)
self.blocks[56] = b56
assert_equal(len(b56.vtx),3)
b56 = update_block(56, [tx1])
assert_equal(b56.hash, b57.hash)
yield rejected(RejectResult(16, b'bad-txns-duplicate'))
tip(55)
b57p2 = block("57p2")
tx = create_and_sign_tx(out[16].tx, out[16].n, 1)
tx1 = create_tx(tx, 0, 1)
tx2 = create_tx(tx1, 0, 1)
tx3 = create_tx(tx2, 0, 1)
tx4 = create_tx(tx3, 0, 1)
b57p2 = update_block("57p2", [tx, tx1, tx2, tx3, tx4])
tip(55)
b56p2 = copy.deepcopy(b57p2)
self.blocks["b56p2"] = b56p2
assert_equal(b56p2.hash, b57p2.hash)
assert_equal(len(b56p2.vtx),6)
b56p2 = update_block("b56p2", [tx3, tx4])
yield rejected(RejectResult(16, b'bad-txns-duplicate'))
tip("57p2")
yield accepted()
tip(57)
yield rejected() #rejected because 57p2 seen first
save_spendable_output()
# Test a few invalid tx types
#
# -> b35 (10) -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17)
# \-> ??? (17)
#
# tx with prevout.n out of range
tip(57)
b58 = block(58, spend=out[17])
tx = CTransaction()
assert(len(out[17].tx.vout) < 42)
tx.vin.append(CTxIn(COutPoint(out[17].tx.sha256, 42), CScript([OP_TRUE]), 0xffffffff))
tx.vout.append(CTxOut(0, b""))
tx.calc_sha256()
b58 = update_block(58, [tx])
yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent'))
# tx with output value > input value out of range
tip(57)
b59 = block(59)
tx = create_and_sign_tx(out[17].tx, out[17].n, 510*COIN)
b59 = update_block(59, [tx])
yield rejected(RejectResult(16, b'bad-txns-in-belowout'))
# reset to good chain
tip(57)
b60 = block(60, spend=out[17])
yield accepted()
save_spendable_output()
# Test BIP30
#
# -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17)
# \-> b61 (18)
#
# Blocks are not allowed to contain a transaction whose id matches that of an earlier,
# not-fully-spent transaction in the same chain. To test, make identical coinbases;
# the second one should be rejected.
#
tip(60)
b61 = block(61, spend=out[18])
b61.vtx[0].vin[0].scriptSig = b60.vtx[0].vin[0].scriptSig #equalize the coinbases
b61.vtx[0].rehash()
b61 = update_block(61, [])
assert_equal(b60.vtx[0].serialize(), b61.vtx[0].serialize())
yield rejected(RejectResult(16, b'bad-txns-BIP30'))
# Test tx.isFinal is properly rejected (not an exhaustive tx.isFinal test, that should be in data-driven transaction tests)
#
# -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17)
# \-> b62 (18)
#
tip(60)
b62 = block(62)
tx = CTransaction()
tx.nLockTime = 0xffffffff #this locktime is non-final
assert(out[18].n < len(out[18].tx.vout))
tx.vin.append(CTxIn(COutPoint(out[18].tx.sha256, out[18].n))) # don't set nSequence
tx.vout.append(CTxOut(0, CScript([OP_TRUE])))
assert(tx.vin[0].nSequence < 0xffffffff)
tx.calc_sha256()
b62 = update_block(62, [tx])
yield rejected(RejectResult(16, b'bad-txns-nonfinal'))
tip(60)
b63 = block(63)
b63.vtx[0].nLockTime = 0xffffffff
b63.vtx[0].vin[0].nSequence = 0xDEADBEEF
b63.vtx[0].rehash()
b63 = update_block(63, [])
yield rejected(RejectResult(16, b'bad-txns-nonfinal'))
#
# -> b39 (11) -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18)
# \
# b64a (18)
# b64a is a bloated block (non-canonical varint)
# b64 is a good block (same as b64 but w/ canonical varint)
#
tip(60)
regular_block = block("64a", spend=out[18])
# make it a "broken_block," with non-canonical serialization
b64a = CBrokenBlock(regular_block)
b64a.initialize(regular_block)
self.blocks["64a"] = b64a
self.tip = b64a
tx = CTransaction()
# use canonical serialization to calculate size
script_length = MAX_BLOCK_SIZE - len(b64a.normal_serialize()) - 69
script_output = CScript([b'\x00' * script_length])
tx.vout.append(CTxOut(0, script_output))
tx.vin.append(CTxIn(COutPoint(b64a.vtx[1].sha256, 0)))
b64a = update_block("64a", [tx])
assert_equal(len(b64a.serialize()), MAX_BLOCK_SIZE + 8)
yield TestInstance([[self.tip, None]])
# comptool workaround: to make sure b64 is delivered, manually erase b64a from blockstore
self.test.block_store.erase(b64a.sha256)
tip(60)
b64 = CBlock(b64a)
b64.vtx = copy.deepcopy(b64a.vtx)
assert_equal(b64.hash, b64a.hash)
assert_equal(len(b64.serialize()), MAX_BLOCK_SIZE)
self.blocks[64] = b64
update_block(64, [])
yield accepted()
save_spendable_output()
# Spend an output created in the block itself
#
# -> b42 (12) -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19)
#
tip(64)
b65 = block(65)
tx1 = create_and_sign_tx(out[19].tx, out[19].n, out[19].tx.vout[0].nValue)
tx2 = create_and_sign_tx(tx1, 0, 0)
update_block(65, [tx1, tx2])
yield accepted()
save_spendable_output()
# Attempt to spend an output created later in the same block
#
# -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19)
# \-> b66 (20)
tip(65)
b66 = block(66)
tx1 = create_and_sign_tx(out[20].tx, out[20].n, out[20].tx.vout[0].nValue)
tx2 = create_and_sign_tx(tx1, 0, 1)
update_block(66, [tx2, tx1])
yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent'))
# Attempt to double-spend a transaction created in a block
#
# -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19)
# \-> b67 (20)
#
#
tip(65)
b67 = block(67)
tx1 = create_and_sign_tx(out[20].tx, out[20].n, out[20].tx.vout[0].nValue)
tx2 = create_and_sign_tx(tx1, 0, 1)
tx3 = create_and_sign_tx(tx1, 0, 2)
update_block(67, [tx1, tx2, tx3])
yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent'))
# More tests of block subsidy
#
# -> b43 (13) -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20)
# \-> b68 (20)
#
# b68 - coinbase with an extra 10 satoshis,
# creates a tx that has 9 satoshis from out[20] go to fees
# this fails because the coinbase is trying to claim 1 satoshi too much in fees
#
# b69 - coinbase with extra 10 satoshis, and a tx that gives a 10 satoshi fee
# this succeeds
#
tip(65)
b68 = block(68, additional_coinbase_value=10)
tx = create_and_sign_tx(out[20].tx, out[20].n, out[20].tx.vout[0].nValue-9)
update_block(68, [tx])
yield rejected(RejectResult(16, b'bad-cb-amount'))
tip(65)
b69 = block(69, additional_coinbase_value=10)
tx = create_and_sign_tx(out[20].tx, out[20].n, out[20].tx.vout[0].nValue-10)
update_block(69, [tx])
yield accepted()
save_spendable_output()
# Test spending the outpoint of a non-existent transaction
#
# -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20)
# \-> b70 (21)
#
tip(69)
block(70, spend=out[21])
bogus_tx = CTransaction()
bogus_tx.sha256 = uint256_from_str(b"23c70ed7c0506e9178fc1a987f40a33946d4ad4c962b5ae3a52546da53af0c5c")
tx = CTransaction()
tx.vin.append(CTxIn(COutPoint(bogus_tx.sha256, 0), b"", 0xffffffff))
tx.vout.append(CTxOut(1, b""))
update_block(70, [tx])
yield rejected(RejectResult(16, b'bad-txns-inputs-missingorspent'))
# Test accepting an invalid block which has the same hash as a valid one (via merkle tree tricks)
#
# -> b53 (14) -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b72 (21)
# \-> b71 (21)
#
# b72 is a good block.
# b71 is a copy of 72, but re-adds one of its transactions. However, it has the same hash as b71.
#
tip(69)
b72 = block(72)
tx1 = create_and_sign_tx(out[21].tx, out[21].n, 2)
tx2 = create_and_sign_tx(tx1, 0, 1)
b72 = update_block(72, [tx1, tx2]) # now tip is 72
b71 = copy.deepcopy(b72)
b71.vtx.append(tx2) # add duplicate tx2
self.block_heights[b71.sha256] = self.block_heights[b69.sha256] + 1 # b71 builds off b69
self.blocks[71] = b71
assert_equal(len(b71.vtx), 4)
assert_equal(len(b72.vtx), 3)
assert_equal(b72.sha256, b71.sha256)
tip(71)
yield rejected(RejectResult(16, b'bad-txns-duplicate'))
tip(72)
yield accepted()
save_spendable_output()
# Test some invalid scripts and MAX_BLOCK_SIGOPS
#
# -> b55 (15) -> b57 (16) -> b60 (17) -> b64 (18) -> b65 (19) -> b69 (20) -> b72 (21)
# \-> b** (22)
#
# b73 - tx with excessive sigops that are placed after an excessively large script element.
# The purpose of the test is to make sure those sigops are counted.
#
# script is a bytearray of size 20,526
#
# bytearray[0-19,998] : OP_CHECKSIG
# bytearray[19,999] : OP_PUSHDATA4
# bytearray[20,000-20,003]: 521 (max_script_element_size+1, in little-endian format)
# bytearray[20,004-20,525]: unread data (script_element)
# bytearray[20,526] : OP_CHECKSIG (this puts us over the limit)
#
tip(72)
b73 = block(73)
size = MAX_BLOCK_SIGOPS - 1 + MAX_SCRIPT_ELEMENT_SIZE + 1 + 5 + 1
a = bytearray([OP_CHECKSIG] * size)
a[MAX_BLOCK_SIGOPS - 1] = int("4e",16) # OP_PUSHDATA4
element_size = MAX_SCRIPT_ELEMENT_SIZE + 1
a[MAX_BLOCK_SIGOPS] = element_size % 256
a[MAX_BLOCK_SIGOPS+1] = element_size // 256
a[MAX_BLOCK_SIGOPS+2] = 0
a[MAX_BLOCK_SIGOPS+3] = 0
tx = create_and_sign_tx(out[22].tx, 0, 1, CScript(a))
b73 = update_block(73, [tx])
assert_equal(get_legacy_sigopcount_block(b73), MAX_BLOCK_SIGOPS+1)
yield rejected(RejectResult(16, b'bad-blk-sigops'))
# b74/75 - if we push an invalid script element, all prevous sigops are counted,
# but sigops after the element are not counted.
#
# The invalid script element is that the push_data indicates that
# there will be a large amount of data (0xffffff bytes), but we only
# provide a much smaller number. These bytes are CHECKSIGS so they would
# cause b75 to fail for excessive sigops, if those bytes were counted.
#
# b74 fails because we put MAX_BLOCK_SIGOPS+1 before the element
# b75 succeeds because we put MAX_BLOCK_SIGOPS before the element
#
#
tip(72)
b74 = block(74)
size = MAX_BLOCK_SIGOPS - 1 + MAX_SCRIPT_ELEMENT_SIZE + 42 # total = 20,561
a = bytearray([OP_CHECKSIG] * size)
a[MAX_BLOCK_SIGOPS] = 0x4e
a[MAX_BLOCK_SIGOPS+1] = 0xfe
a[MAX_BLOCK_SIGOPS+2] = 0xff
a[MAX_BLOCK_SIGOPS+3] = 0xff
a[MAX_BLOCK_SIGOPS+4] = 0xff
tx = create_and_sign_tx(out[22].tx, 0, 1, CScript(a))
b74 = update_block(74, [tx])
yield rejected(RejectResult(16, b'bad-blk-sigops'))
tip(72)
b75 = block(75)
size = MAX_BLOCK_SIGOPS - 1 + MAX_SCRIPT_ELEMENT_SIZE + 42
a = bytearray([OP_CHECKSIG] * size)
a[MAX_BLOCK_SIGOPS-1] = 0x4e
a[MAX_BLOCK_SIGOPS] = 0xff
a[MAX_BLOCK_SIGOPS+1] = 0xff
a[MAX_BLOCK_SIGOPS+2] = 0xff
a[MAX_BLOCK_SIGOPS+3] = 0xff
tx = create_and_sign_tx(out[22].tx, 0, 1, CScript(a))
b75 = update_block(75, [tx])
yield accepted()
save_spendable_output()
# Check that if we push an element filled with CHECKSIGs, they are not counted
tip(75)
b76 = block(76)
size = MAX_BLOCK_SIGOPS - 1 + MAX_SCRIPT_ELEMENT_SIZE + 1 + 5
a = bytearray([OP_CHECKSIG] * size)
a[MAX_BLOCK_SIGOPS-1] = 0x4e # PUSHDATA4, but leave the following bytes as just checksigs
tx = create_and_sign_tx(out[23].tx, 0, 1, CScript(a))
b76 = update_block(76, [tx])
yield accepted()
save_spendable_output()
# Test transaction resurrection
#
# -> b77 (24) -> b78 (25) -> b79 (26)
# \-> b80 (25) -> b81 (26) -> b82 (27)
#
# b78 creates a tx, which is spent in b79. After b82, both should be in mempool
#
# The tx'es must be unsigned and pass the node's mempool policy. It is unsigned for the
# rather obscure reason that the Python signature code does not distinguish between
# Low-S and High-S values (whereas the bitcoin code has custom code which does so);
# as a result of which, the odds are 50% that the python code will use the right
# value and the transaction will be accepted into the mempool. Until we modify the
# test framework to support low-S signing, we are out of luck.
#
# To get around this issue, we construct transactions which are not signed and which
# spend to OP_TRUE. If the standard-ness rules change, this test would need to be
# updated. (Perhaps to spend to a P2SH OP_TRUE script)
#
tip(76)
block(77)
tx77 = create_and_sign_tx(out[24].tx, out[24].n, 10*COIN)
update_block(77, [tx77])
yield accepted()
save_spendable_output()
block(78)
tx78 = create_tx(tx77, 0, 9*COIN)
update_block(78, [tx78])
yield accepted()
block(79)
tx79 = create_tx(tx78, 0, 8*COIN)
update_block(79, [tx79])
yield accepted()
# mempool should be empty
assert_equal(len(self.nodes[0].getrawmempool()), 0)
tip(77)
block(80, spend=out[25])
yield rejected()
save_spendable_output()
block(81, spend=out[26])
yield rejected() # other chain is same length
save_spendable_output()
block(82, spend=out[27])
yield accepted() # now this chain is longer, triggers re-org
save_spendable_output()
# now check that tx78 and tx79 have been put back into the peer's mempool
mempool = self.nodes[0].getrawmempool()
assert_equal(len(mempool), 2)
assert(tx78.hash in mempool)
assert(tx79.hash in mempool)
b83 = block(83)
op_codes = [OP_IF, OP_INVALIDOPCODE, OP_ELSE, OP_TRUE, OP_ENDIF]
script = CScript(op_codes)
tx1 = create_and_sign_tx(out[28].tx, out[28].n, out[28].tx.vout[0].nValue, script)
tx2 = create_and_sign_tx(tx1, 0, 0, CScript([OP_TRUE]))
tx2.vin[0].scriptSig = CScript([OP_FALSE])
tx2.rehash()
update_block(83, [tx1, tx2])
yield accepted()
save_spendable_output()
b84 = block(84)
tx1 = create_tx(out[29].tx, out[29].n, 0, CScript([OP_RETURN]))
tx1.vout.append(CTxOut(0, CScript([OP_TRUE])))
tx1.vout.append(CTxOut(0, CScript([OP_TRUE])))
tx1.vout.append(CTxOut(0, CScript([OP_TRUE])))
tx1.vout.append(CTxOut(0, CScript([OP_TRUE])))
tx1.calc_sha256()
self.sign_tx(tx1, out[29].tx, out[29].n)
tx1.rehash()
tx2 = create_tx(tx1, 1, 0, CScript([OP_RETURN]))
tx2.vout.append(CTxOut(0, CScript([OP_RETURN])))
tx3 = create_tx(tx1, 2, 0, CScript([OP_RETURN]))
tx3.vout.append(CTxOut(0, CScript([OP_TRUE])))
tx4 = create_tx(tx1, 3, 0, CScript([OP_TRUE]))
tx4.vout.append(CTxOut(0, CScript([OP_RETURN])))
tx5 = create_tx(tx1, 4, 0, CScript([OP_RETURN]))
update_block(84, [tx1,tx2,tx3,tx4,tx5])
yield accepted()
save_spendable_output()
tip(83)
block(85, spend=out[29])
yield rejected()
block(86, spend=out[30])
yield accepted()
tip(84)
block(87, spend=out[30])
yield rejected()
save_spendable_output()
block(88, spend=out[31])
yield accepted()
save_spendable_output()
block("89a", spend=out[32])
tx = create_tx(tx1, 0, 0, CScript([OP_TRUE]))
update_block("89a", [tx])
yield rejected()
# This test takes a minute or two and can be accomplished in memory
#
if self.options.runbarelyexpensive:
tip(88)
LARGE_REORG_SIZE = 1088
test1 = TestInstance(sync_every_block=False)
spend=out[32]
for i in range(89, LARGE_REORG_SIZE + 89):
b = block(i, spend)
tx = CTransaction()
script_length = MAX_BLOCK_SIZE - len(b.serialize()) - 69
script_output = CScript([b'\x00' * script_length])
tx.vout.append(CTxOut(0, script_output))
tx.vin.append(CTxIn(COutPoint(b.vtx[1].sha256, 0)))
b = update_block(i, [tx])
assert_equal(len(b.serialize()), MAX_BLOCK_SIZE)
test1.blocks_and_transactions.append([self.tip, True])
save_spendable_output()
spend = get_spendable_output()
yield test1
chain1_tip = i
# now create alt chain of same length
tip(88)
test2 = TestInstance(sync_every_block=False)
for i in range(89, LARGE_REORG_SIZE + 89):
block("alt"+str(i))
test2.blocks_and_transactions.append([self.tip, False])
yield test2
# extend alt chain to trigger re-org
block("alt" + str(chain1_tip + 1))
yield accepted()
# ... and re-org back to the first chain
tip(chain1_tip)
block(chain1_tip + 1)
yield rejected()
block(chain1_tip + 2)
yield accepted()
chain1_tip += 2
if __name__ == '__main__':
FullBlockTest().main()
| true | true |
f7239d89f1cae0a248d550f1657075e1707e6633 | 7,727 | py | Python | apps/asg5/common.py | zesenzip/py4web | f7fc80a64544c2f1e477e7f2f951a5efcffa053b | [
"BSD-3-Clause"
] | null | null | null | apps/asg5/common.py | zesenzip/py4web | f7fc80a64544c2f1e477e7f2f951a5efcffa053b | [
"BSD-3-Clause"
] | null | null | null | apps/asg5/common.py | zesenzip/py4web | f7fc80a64544c2f1e477e7f2f951a5efcffa053b | [
"BSD-3-Clause"
] | null | null | null | """
This file defines cache, session, and translator T object for the app
These are fixtures that every app needs so probably you will not be editing this file
"""
import copy
import os
import sys
import logging
from py4web import Session, Cache, Translator, Flash, DAL, Field, action
from py4web.utils.mailer import Mailer
from py4web.utils.auth import Auth
from py4web.utils.downloader import downloader
from py4web.utils.tags import Tags
from py4web.utils.factories import ActionFactory
from py4web.utils.form import FormStyleBulma
from . import settings
# #######################################################
# implement custom loggers form settings.LOGGERS
# #######################################################
logger = logging.getLogger("py4web:" + settings.APP_NAME)
formatter = logging.Formatter(
"%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s"
)
for item in settings.LOGGERS:
level, filename = item.split(":", 1)
if filename in ("stdout", "stderr"):
handler = logging.StreamHandler(getattr(sys, filename))
else:
handler = logging.FileHandler(filename)
handler.setFormatter(formatter)
logger.setLevel(getattr(logging, level.upper(), "DEBUG"))
logger.addHandler(handler)
# #######################################################
# connect to db
# #######################################################
db = DAL(
settings.DB_URI,
folder=settings.DB_FOLDER,
pool_size=settings.DB_POOL_SIZE,
migrate=settings.DB_MIGRATE,
fake_migrate=settings.DB_FAKE_MIGRATE,
)
# #######################################################
# define global objects that may or may not be used by the actions
# #######################################################
cache = Cache(size=1000)
T = Translator(settings.T_FOLDER)
flash = Flash()
# #######################################################
# pick the session type that suits you best
# #######################################################
if settings.SESSION_TYPE == "cookies":
session = Session(secret=settings.SESSION_SECRET_KEY)
elif settings.SESSION_TYPE == "redis":
import redis
host, port = settings.REDIS_SERVER.split(":")
# for more options: https://github.com/andymccurdy/redis-py/blob/master/redis/client.py
conn = redis.Redis(host=host, port=int(port))
conn.set = (
lambda k, v, e, cs=conn.set, ct=conn.ttl: cs(k, v, ct(k))
if ct(k) >= 0
else cs(k, v, e)
)
session = Session(secret=settings.SESSION_SECRET_KEY, storage=conn)
elif settings.SESSION_TYPE == "memcache":
import memcache, time
conn = memcache.Client(settings.MEMCACHE_CLIENTS, debug=0)
session = Session(secret=settings.SESSION_SECRET_KEY, storage=conn)
elif settings.SESSION_TYPE == "database":
from py4web.utils.dbstore import DBStore
session = Session(secret=settings.SESSION_SECRET_KEY, storage=DBStore(db))
# #######################################################
# Instantiate the object and actions that handle auth
# #######################################################
auth = Auth(session, db, define_tables=False)
# Fixes the messages.
auth_messages = copy.deepcopy(auth.MESSAGES)
auth_messages['buttons']['sign-in'] = "Log in"
auth_messages['buttons']['sign-up'] = "Sign up"
auth_messages['buttons']['lost-password'] = "Lost password"
# And button classes.
auth_button_classes = {
"lost-password": "button is-danger is-light",
"register": "button is-info is-light",
"request": "button is-primary",
"sign-in": "button is-primary",
"sign-up": "button is-success",
"submit": "button is-primary",
}
auth.use_username = False
auth.param.button_classes = auth_button_classes
auth.param.registration_requires_confirmation = False
auth.param.registration_requires_approval = False
auth.param.allowed_actions = settings.ALLOWED_ACTIONS
auth.param.login_expiration_time = 3600
# FIXME: Readd for production.
auth.param.password_complexity = {"entropy": 2}
auth.param.block_previous_password_num = 3
auth.param.formstyle = FormStyleBulma
auth.define_tables()
# #######################################################
# Configure email sender for auth
# #######################################################
if settings.SMTP_SERVER:
auth.sender = Mailer(
server=settings.SMTP_SERVER,
sender=settings.SMTP_SENDER,
login=settings.SMTP_LOGIN,
tls=settings.SMTP_TLS,
ssl=settings.SMTP_SSL,
)
# #######################################################
# Create a table to tag users as group members
# #######################################################
if auth.db:
groups = Tags(db.auth_user, "groups")
# #######################################################
# Enable optional auth plugin
# #######################################################
if settings.USE_PAM:
from py4web.utils.auth_plugins.pam_plugin import PamPlugin
auth.register_plugin(PamPlugin())
if settings.USE_LDAP:
from py4web.utils.auth_plugins.ldap_plugin import LDAPPlugin
auth.register_plugin(LDAPPlugin(db=db, groups=groups, **settings.LDAP_SETTINGS))
if settings.OAUTH2GOOGLE_CLIENT_ID:
from py4web.utils.auth_plugins.oauth2google import OAuth2Google # TESTED
auth.register_plugin(
OAuth2Google(
client_id=settings.OAUTH2GOOGLE_CLIENT_ID,
client_secret=settings.OAUTH2GOOGLE_CLIENT_SECRET,
callback_url="auth/plugin/oauth2google/callback",
)
)
if settings.OAUTH2FACEBOOK_CLIENT_ID:
from py4web.utils.auth_plugins.oauth2facebook import OAuth2Facebook # UNTESTED
auth.register_plugin(
OAuth2Facebook(
client_id=settings.OAUTH2FACEBOOK_CLIENT_ID,
client_secret=settings.OAUTH2FACEBOOK_CLIENT_SECRET,
callback_url="auth/plugin/oauth2facebook/callback",
)
)
if settings.OAUTH2OKTA_CLIENT_ID:
from py4web.utils.auth_plugins.oauth2okta import OAuth2Okta # TESTED
auth.register_plugin(
OAuth2Okta(
client_id=settings.OAUTH2OKTA_CLIENT_ID,
client_secret=settings.OAUTH2OKTA_CLIENT_SECRET,
callback_url="auth/plugin/oauth2okta/callback",
)
)
# #######################################################
# Define a convenience action to allow users to download
# files uploaded and reference by Field(type='upload')
# #######################################################
if settings.UPLOAD_FOLDER:
@action('download/<filename>')
@action.uses(db)
def download(filename):
return downloader(db, settings.UPLOAD_FOLDER, filename)
# To take advantage of this in Form(s)
# for every field of type upload you MUST specify:
#
# field.upload_path = settings.UPLOAD_FOLDER
# field.download_url = lambda filename: URL('download/%s' % filename)
# #######################################################
# Optionally configure celery
# #######################################################
if settings.USE_CELERY:
from celery import Celery
# to use "from .common import scheduler" and then use it according
# to celery docs, examples in tasks.py
scheduler = Celery(
"apps.%s.tasks" % settings.APP_NAME, broker=settings.CELERY_BROKER
)
# #######################################################
# Enable authentication
# #######################################################
auth.enable(uses=(session, T, db), env=dict(T=T))
# #######################################################
# Define convenience decorators
# #######################################################
unauthenticated = ActionFactory(db, session, T, flash, auth)
authenticated = ActionFactory(db, session, T, flash, auth.user)
| 35.939535 | 91 | 0.596609 | import copy
import os
import sys
import logging
from py4web import Session, Cache, Translator, Flash, DAL, Field, action
from py4web.utils.mailer import Mailer
from py4web.utils.auth import Auth
from py4web.utils.downloader import downloader
from py4web.utils.tags import Tags
from py4web.utils.factories import ActionFactory
from py4web.utils.form import FormStyleBulma
from . import settings
| true | true |
f7239dcfb39f7f414e578d22472fa4ac35901f2e | 1,159 | py | Python | examples/create_scripts/extensions/e-analysis.py | bendichter/api-python | 52e97e7642021913ae6505ab63b7cc77d2622d76 | [
"BSD-3-Clause"
] | 32 | 2015-08-21T14:14:44.000Z | 2017-08-31T09:33:14.000Z | examples/create_scripts/extensions/e-analysis.py | bendichter/api-python | 52e97e7642021913ae6505ab63b7cc77d2622d76 | [
"BSD-3-Clause"
] | 24 | 2015-11-18T11:17:04.000Z | 2019-12-31T19:44:18.000Z | examples/create_scripts/extensions/e-analysis.py | bendichter/api-python | 52e97e7642021913ae6505ab63b7cc77d2622d76 | [
"BSD-3-Clause"
] | 18 | 2015-10-07T03:04:41.000Z | 2022-03-11T18:52:20.000Z |
{"fs": {"aibs_ct_an": {
"info": {
"name": "AIBS cell types - analysis",
"version": "0.9.2",
"date": "May 6, 2016",
"author": "Jeff Teeters, based on Allen Institute cell types DB HDF5 file",
"contact": "jteeters@berkeley.edu",
"description": "NWB extension for AIBS cell types data base NWB files /analysis section."
},
"schema": {
"/analysis/": {
"aibs_spike_times/": {
"description": "Group for storing AIBS specific spike times",
"attributes": {
"comments": {
"data_type": "text",
"value": "Spike times are relative to sweep start. The are NOT absolute times."}
},
"<aibs_sweep>": {
"attributes": {
"comments": {
"data_type": "text",
"value": "Spike times are relative to sweep start. The are NOT absolute times."}
},
"description": "Times associated with a single sweep",
"dimensions": ["numSamples"],
"data_type": "float64!"
}
}
}
}
}}}
| 30.5 | 104 | 0.486626 |
{"fs": {"aibs_ct_an": {
"info": {
"name": "AIBS cell types - analysis",
"version": "0.9.2",
"date": "May 6, 2016",
"author": "Jeff Teeters, based on Allen Institute cell types DB HDF5 file",
"contact": "jteeters@berkeley.edu",
"description": "NWB extension for AIBS cell types data base NWB files /analysis section."
},
"schema": {
"/analysis/": {
"aibs_spike_times/": {
"description": "Group for storing AIBS specific spike times",
"attributes": {
"comments": {
"data_type": "text",
"value": "Spike times are relative to sweep start. The are NOT absolute times."}
},
"<aibs_sweep>": {
"attributes": {
"comments": {
"data_type": "text",
"value": "Spike times are relative to sweep start. The are NOT absolute times."}
},
"description": "Times associated with a single sweep",
"dimensions": ["numSamples"],
"data_type": "float64!"
}
}
}
}
}}}
| true | true |
f7239ec42a9b70cf3d4d5ff6a47e08b820d7b968 | 112 | py | Python | examples/robodk/constants.py | StrayRobots/stray | ea775a3c8ec52f32305fe30417bc3152eb9b532b | [
"MIT"
] | 1 | 2022-02-09T12:19:53.000Z | 2022-02-09T12:19:53.000Z | examples/robodk/constants.py | StrayRobots/stray | ea775a3c8ec52f32305fe30417bc3152eb9b532b | [
"MIT"
] | null | null | null | examples/robodk/constants.py | StrayRobots/stray | ea775a3c8ec52f32305fe30417bc3152eb9b532b | [
"MIT"
] | null | null | null |
FAR_LENGTH = 2**32
IMAGE_WIDTH = 640
IMAGE_HEIGHT = 480
FIELD_OF_VIEW = 50.0 # in degrees
BELT_VELOCITY = 0.1
| 14 | 33 | 0.732143 |
FAR_LENGTH = 2**32
IMAGE_WIDTH = 640
IMAGE_HEIGHT = 480
FIELD_OF_VIEW = 50.0
BELT_VELOCITY = 0.1
| true | true |
f7239ffecd0ed16acaef9fc9d087691c79827057 | 4,446 | py | Python | lambdata/helper_functions.py | doffing81/lambdata-AshleyBrooks213 | 9c5d4b5f49094e1b2d43f51e7e42ece2e98e3bb6 | [
"MIT"
] | null | null | null | lambdata/helper_functions.py | doffing81/lambdata-AshleyBrooks213 | 9c5d4b5f49094e1b2d43f51e7e42ece2e98e3bb6 | [
"MIT"
] | null | null | null | lambdata/helper_functions.py | doffing81/lambdata-AshleyBrooks213 | 9c5d4b5f49094e1b2d43f51e7e42ece2e98e3bb6 | [
"MIT"
] | null | null | null | """A collection of Data Science helper functions"""
import pandas as pd
import numpy as np
import random
def df_cleaner(df):
"""Clean a df of nulls"""
return df.dropna()
"""Check to make sure that code works"""
print("df_cleaner is working!")
def null_count(df):
"""Check a dataframe for nulls and return the
number of missing values"""
return df.isnull().sum().sum()
"""Check to make sure that code works"""
print("null_count is working!")
def train_test_split(df, frac):
"""
Create a Train/Test split function for a dataframe and return both
the Training and Testing sets.
Frac refers to the percent of data you would like to set aside
for training.
"""
frac = round(len(df)*frac)
train = df[:frac]
test = df[frac:]
return train, test
"""Check to make sure that code works"""
print("train_test_split is working!")
def randomize(df, seed):
"""
Testing randomize(df) function: Develop a
randomization function that randomizes all of
a dataframes cells then returns that randomized dataframe
"""
"""NOTE: I am not sure about the seed part."""
#seed = np.random.seed(0)
"""Randomly sample 100% of your df"""
df = df.sample(frac=1, random_state=seed)#.reset_index(drop=True)
return df
"""Check to make sure that code works"""
print("randomize is working!")
def addy_split(add_series):
cities = []
states = []
zipcodes = []
for row in add_series.iterrows():
alist = row.split()
#if statements to find city
city = [word for word in alist if word[-1] == ',']
cities.append(city)
#if statements to find state
state = [piece for piece in alist if len(piece) == 2 and piece[:2].isupper() == True]
states.append(state)
# if statements to zipcode
zipcode = [n for n in alist if len(n) == 5 and n.isdigit() == True]
zipcodes.append(zipcode)
df = pd.DataFrame({'city': cities, 'state': states, 'zip': zipcodes})
return df
"""Check to make sure that code works"""
print("addy_split is working!")
def abbr_2_st(state_series, abbr_2_st=True):
"""
Return a new column with the full name from a State
abbreviation column -> An input of FL would return Florida.
This function should also take a boolean (abbr_2_state)
and when False takes full state names and return state abbreviations.
-> An input of Florida would return Fl.
"""
us_state_abbrev = {
'Alabama': 'AL',
'Alaska': 'AK',
'American Samoa': 'AS',
'Arizona': 'AZ',
'Arkansas': 'AR',
'California': 'CA',
'Colorado': 'CO',
'Connecticut': 'CT',
'Delaware': 'DE',
'District of Columbia': 'DC',
'Florida': 'FL',
'Georgia': 'GA',
'Guam': 'GU',
'Hawaii': 'HI',
'Idaho': 'ID',
'Illinois': 'IL',
'Indiana': 'IN',
'Iowa': 'IA',
'Kansas': 'KS',
'Kentucky': 'KY',
'Louisiana': 'LA',
'Maine': 'ME',
'Maryland': 'MD',
'Massachusetts': 'MA',
'Michigan': 'MI',
'Minnesota': 'MN',
'Mississippi': 'MS',
'Missouri': 'MO',
'Montana': 'MT',
'Nebraska': 'NE',
'Nevada': 'NV',
'New Hampshire': 'NH',
'New Jersey': 'NJ',
'New Mexico': 'NM',
'New York': 'NY',
'North Carolina': 'NC',
'North Dakota': 'ND',
'Northern Mariana Islands':'MP',
'Ohio': 'OH',
'Oklahoma': 'OK',
'Oregon': 'OR',
'Pennsylvania': 'PA',
'Puerto Rico': 'PR',
'Rhode Island': 'RI',
'South Carolina': 'SC',
'South Dakota': 'SD',
'Tennessee': 'TN',
'Texas': 'TX',
'Utah': 'UT',
'Vermont': 'VT',
'Virgin Islands': 'VI',
'Virginia': 'VA',
'Washington': 'WA',
'West Virginia': 'WV',
'Wisconsin': 'WI',
'Wyoming': 'WY'
}
if abbr_2_st == True:
inv_map = {v: k for k, v in us_state_abbrev.items()}
full_names = []
for abbv in state_series:
full_names.append(inv_map[abbv])
return full_names
else:
# Return Abbreviation
abbvs = []
for full_name in state_series:
abbvs.append(us_state_abbrev[full_name])
return abbvs
FAVORITE_ANIMALS = ['dolphin', 'whale', 'seadragon', 'wolf', 'tiger']
FAVORITE_COLORS = ['pink', 'blue', 'purple', 'green']
def add(x1, x2):
return x1 + x2
def increment(x):
return x + 1
"""Check to make sure code works all the way through"""
print("it worked!") | 25.118644 | 93 | 0.591543 |
import pandas as pd
import numpy as np
import random
def df_cleaner(df):
return df.dropna()
print("df_cleaner is working!")
def null_count(df):
return df.isnull().sum().sum()
print("null_count is working!")
def train_test_split(df, frac):
frac = round(len(df)*frac)
train = df[:frac]
test = df[frac:]
return train, test
print("train_test_split is working!")
def randomize(df, seed):
df = df.sample(frac=1, random_state=seed)
return df
print("randomize is working!")
def addy_split(add_series):
cities = []
states = []
zipcodes = []
for row in add_series.iterrows():
alist = row.split()
city = [word for word in alist if word[-1] == ',']
cities.append(city)
state = [piece for piece in alist if len(piece) == 2 and piece[:2].isupper() == True]
states.append(state)
zipcode = [n for n in alist if len(n) == 5 and n.isdigit() == True]
zipcodes.append(zipcode)
df = pd.DataFrame({'city': cities, 'state': states, 'zip': zipcodes})
return df
print("addy_split is working!")
def abbr_2_st(state_series, abbr_2_st=True):
us_state_abbrev = {
'Alabama': 'AL',
'Alaska': 'AK',
'American Samoa': 'AS',
'Arizona': 'AZ',
'Arkansas': 'AR',
'California': 'CA',
'Colorado': 'CO',
'Connecticut': 'CT',
'Delaware': 'DE',
'District of Columbia': 'DC',
'Florida': 'FL',
'Georgia': 'GA',
'Guam': 'GU',
'Hawaii': 'HI',
'Idaho': 'ID',
'Illinois': 'IL',
'Indiana': 'IN',
'Iowa': 'IA',
'Kansas': 'KS',
'Kentucky': 'KY',
'Louisiana': 'LA',
'Maine': 'ME',
'Maryland': 'MD',
'Massachusetts': 'MA',
'Michigan': 'MI',
'Minnesota': 'MN',
'Mississippi': 'MS',
'Missouri': 'MO',
'Montana': 'MT',
'Nebraska': 'NE',
'Nevada': 'NV',
'New Hampshire': 'NH',
'New Jersey': 'NJ',
'New Mexico': 'NM',
'New York': 'NY',
'North Carolina': 'NC',
'North Dakota': 'ND',
'Northern Mariana Islands':'MP',
'Ohio': 'OH',
'Oklahoma': 'OK',
'Oregon': 'OR',
'Pennsylvania': 'PA',
'Puerto Rico': 'PR',
'Rhode Island': 'RI',
'South Carolina': 'SC',
'South Dakota': 'SD',
'Tennessee': 'TN',
'Texas': 'TX',
'Utah': 'UT',
'Vermont': 'VT',
'Virgin Islands': 'VI',
'Virginia': 'VA',
'Washington': 'WA',
'West Virginia': 'WV',
'Wisconsin': 'WI',
'Wyoming': 'WY'
}
if abbr_2_st == True:
inv_map = {v: k for k, v in us_state_abbrev.items()}
full_names = []
for abbv in state_series:
full_names.append(inv_map[abbv])
return full_names
else:
abbvs = []
for full_name in state_series:
abbvs.append(us_state_abbrev[full_name])
return abbvs
FAVORITE_ANIMALS = ['dolphin', 'whale', 'seadragon', 'wolf', 'tiger']
FAVORITE_COLORS = ['pink', 'blue', 'purple', 'green']
def add(x1, x2):
return x1 + x2
def increment(x):
return x + 1
print("it worked!") | true | true |
f723a002c1e478fefd21d40fee2f0c102b845ca3 | 1,387 | py | Python | nipype/interfaces/mrtrix/tests/test_auto_Erode.py | vferat/nipype | 536c57da150d157dcb5c121af43aaeab71cdbd5f | [
"Apache-2.0"
] | null | null | null | nipype/interfaces/mrtrix/tests/test_auto_Erode.py | vferat/nipype | 536c57da150d157dcb5c121af43aaeab71cdbd5f | [
"Apache-2.0"
] | 2 | 2018-04-17T19:18:16.000Z | 2020-03-04T22:05:02.000Z | nipype/interfaces/mrtrix/tests/test_auto_Erode.py | oesteban/nipype | c14f24eba1da08711bbb894e049ee858ed740096 | [
"Apache-2.0"
] | null | null | null | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..preprocess import Erode
def test_Erode_inputs():
input_map = dict(
args=dict(argstr='%s', ),
debug=dict(
argstr='-debug',
position=1,
),
dilate=dict(
argstr='-dilate',
position=1,
),
environ=dict(
nohash=True,
usedefault=True,
),
in_file=dict(
argstr='%s',
extensions=None,
mandatory=True,
position=-2,
),
number_of_passes=dict(argstr='-npass %s', ),
out_filename=dict(
argstr='%s',
extensions=None,
genfile=True,
position=-1,
),
quiet=dict(
argstr='-quiet',
position=1,
),
)
inputs = Erode.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value
def test_Erode_outputs():
output_map = dict(out_file=dict(extensions=None, ), )
outputs = Erode.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metakey) == value
| 27.196078 | 67 | 0.533526 |
from __future__ import unicode_literals
from ..preprocess import Erode
def test_Erode_inputs():
input_map = dict(
args=dict(argstr='%s', ),
debug=dict(
argstr='-debug',
position=1,
),
dilate=dict(
argstr='-dilate',
position=1,
),
environ=dict(
nohash=True,
usedefault=True,
),
in_file=dict(
argstr='%s',
extensions=None,
mandatory=True,
position=-2,
),
number_of_passes=dict(argstr='-npass %s', ),
out_filename=dict(
argstr='%s',
extensions=None,
genfile=True,
position=-1,
),
quiet=dict(
argstr='-quiet',
position=1,
),
)
inputs = Erode.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value
def test_Erode_outputs():
output_map = dict(out_file=dict(extensions=None, ), )
outputs = Erode.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metakey) == value
| true | true |
f723a0333b9741dda97ec33e33286546932e175e | 15,499 | py | Python | src/opt/optimizer_robot.py | tianjuxue/AmorFEA | 5ddf6c1c9d4489e74a207d5d63ca00af57911ab0 | [
"MIT"
] | 8 | 2020-07-20T04:12:18.000Z | 2022-03-05T18:45:22.000Z | src/opt/optimizer_robot.py | tianjuxue/AmorFEA | 5ddf6c1c9d4489e74a207d5d63ca00af57911ab0 | [
"MIT"
] | 2 | 2020-11-16T12:46:56.000Z | 2020-12-28T02:52:18.000Z | src/opt/optimizer_robot.py | tianjuxue/AmorFEA | 5ddf6c1c9d4489e74a207d5d63ca00af57911ab0 | [
"MIT"
] | 1 | 2021-03-11T16:07:29.000Z | 2021-03-11T16:07:29.000Z | import numpy as np
import torch
import scipy.optimize as opt
import time
from .optimizer import Optimizer
from ..ml.trainer_robot import TrainerRobot
from ..ml.models import RobotNetwork, RobotSolver
from .. import arguments
from ..graph.visualization import scalar_field_paraview
class OptimizerRobot(Optimizer):
def __init__(self, args):
super(OptimizerRobot, self).__init__(args)
self.tip_x1_index = 6
self.tip_x2_index = 7
self.trainer = TrainerRobot(args, opt=True)
self.path = self.args.root_path + '/' + self.args.model_path + '/' + \
self.trainer.poisson.name + '/model_s'
self.model = RobotNetwork(self.args, self.trainer.graph_info)
self.model.load_state_dict(torch.load(self.path))
class OptimizerRobotTrajectory(OptimizerRobot):
def __init__(self, args):
super(OptimizerRobotTrajectory, self).__init__(args)
self.target_coos = heart_shape()
self.n_pts = self.target_coos.shape[1]
def optimize(self):
x_initial = np.zeros(self.args.input_size * self.n_pts)
options = {'eps': 1e-15, 'maxiter': 1000,
'disp': True}
res = opt.minimize(fun=self._objective,
x0=x_initial,
method='CG',
jac=self._derivative,
callback=None,
options=options)
x_opt = res.x.reshape(-1, self.args.input_size)
source = torch.tensor(x_opt, dtype=torch.float)
solution = self.model(source)
print("NN surrogate, loss is", self.trainer.loss_function(
source, solution).data.numpy())
for i in range(31):
scalar_field_paraview(self.args, solution.data.numpy()[
i], self.trainer.poisson, "/robot/time_series_nn/u" + str(i))
for i in range(31):
gt_sol = self.trainer.forward_prediction(x_opt[i], self.model)
scalar_field_paraview(
self.args, gt_sol, self.trainer.poisson, "/robot/time_series_gt/u" + str(i))
return res.x
def _obj(self, source):
source = source.reshape(-1, self.args.input_size)
solution = self.model(source)
sol_tip = solution[:, [self.tip_x1_index, self.tip_x2_index]]
tar_tip = torch.tensor(self.target_coos.transpose(), dtype=torch.float)
L_dist = ((sol_tip - tar_tip)**2).sum()
L_reg = ((source[1:, :] - source[:-1, :])**2).sum()
alpha = 0 * 1e-3
L = L_dist + alpha * L_reg
return L
class OptimizerRobotPoint(OptimizerRobot):
def __init__(self, args):
super(OptimizerRobotPoint, self).__init__(args)
self.target_point = np.array([0, -2])
self.para_data = None
def _opt(self, alpha=1e-2, x_initial=None, maxiter=200, log_interval=20):
if x_initial is None:
x_initial = np.zeros(self.args.input_size)
x = x_initial
start = time.time()
wall_time = [0]
objective = []
source = [x]
for i in range(maxiter):
obj = self._objective(x)
der = self._derivative(x)
x = x - alpha * der
if i % log_interval == 0:
print("loop {} obj {}".format(i, obj))
wall_time.append(time.time() - start)
objective.append(obj)
source.append(x)
x_opt = x
objective.append(self._objective(x))
return x_opt, np.asarray(wall_time), np.asarray(objective), np.asarray(source)
def L_dist(self, solution):
L = (solution[0][self.tip_x1_index] - self.target_point[0])**2 \
+ (solution[0][self.tip_x2_index] - self.target_point[1])**2
return L
def evaluate(self, source):
solution, _ = self.trainer.forward_prediction(source, model=self.model)
L = self.L_dist(np.expand_dims(solution, axis=0))
return L, solution
def batch_evaluate(self, source):
Ls = []
sols = []
for s in source:
L, sol = self.evaluate(s)
Ls.append(L)
sols.append(sol)
print("Evaluated L", L)
return np.asarray(Ls), np.asarray(sols)
class OptimizerRobotPointFree(OptimizerRobotPoint):
def __init__(self, args):
super(OptimizerRobotPointFree, self).__init__(args)
def optimize(self, x_initial=None):
if x_initial is None:
x_initial = 0.1 * np.ones(self.args.input_size)
x = x_initial
self._obj(x)
options = {'maxiter': 100, 'disp': True,
'adaptive': True}
res = opt.minimize(fun=self._obj,
x0=x_initial,
method='Nelder-Mead',
options=options)
x_opt = x
return x_opt
def _obj(self, source):
solution, _ = self.trainer.forward_prediction(
source, model=None, para_data=self.para_data)
L = self.L_dist(torch.tensor(solution, dtype=torch.float).unsqueeze(0))
print(L)
return L.item()
class OptimizerRobotPointSurrogate(OptimizerRobotPoint):
def __init__(self, args):
super(OptimizerRobotPointSurrogate, self).__init__(args)
def optimize(self, alpha=1e-2, x_initial=None, maxiter=100, log_interval=100):
return self._opt(alpha=alpha, x_initial=x_initial, maxiter=maxiter, log_interval=log_interval)
def _obj(self, source):
source = source.unsqueeze(0)
solution = self.model(source)
L = self.L_dist(solution)
return L
class OptimizerRobotPointAdjoint(OptimizerRobotPoint):
def __init__(self, args):
super(OptimizerRobotPointAdjoint, self).__init__(args)
def optimize(self, alpha=2 * 1e-2, x_initial=None, maxiter=20, log_interval=1):
return self._opt(alpha=alpha, x_initial=x_initial, maxiter=maxiter, log_interval=log_interval)
def _objective(self, source):
_, self.para_data = self.trainer.forward_prediction(
source, model=None, para_data=self.para_data)
_, _, L = self._objective_partials(source, self.para_data)
return L
def _derivative(self, source):
dcdx, dcdy = self._constraint_partials(source, self.para_data)
dLdx, dLdy, _ = self._objective_partials(source, self.para_data)
J = self._adjoint_derivative(dcdx, dcdy, dLdx, dLdy)
return J
def _adjoint_derivative(self, dcdx, dcdy, dLdx, dLdy):
dcdx_T = dcdx.transpose()
adjoint_sol = np.linalg.solve(dcdx_T, dLdx)
total_derivative = -np.matmul(adjoint_sol, dcdy) + dLdy
return total_derivative
def _objective_partials(self, source, para_data):
solver = RobotSolver(self.args, self.trainer.graph_info)
solver.reset_parameters_data(para_data)
source = torch.tensor(source, requires_grad=True, dtype=torch.float)
source_input = source.unsqueeze(0)
solution = solver(source_input)
L = self.L_dist(solution)
dLdx = torch.autograd.grad(
L, solver.para, create_graph=True, retain_graph=True)[0]
dLdy = torch.autograd.grad(
L, source, create_graph=True, retain_graph=True)[0]
return dLdx.data.numpy(), dLdy.data.numpy(), L.data.numpy()
def _constraint_partials(self, source, para_data):
solver = RobotSolver(self.args, self.trainer.graph_info)
solver.reset_parameters_data(para_data)
source = torch.tensor(source, requires_grad=True, dtype=torch.float)
source_input = source.unsqueeze(0)
solution = solver(source_input)
L = self.trainer.loss_function(source_input, solution)
c = torch.autograd.grad(
L, solver.para, create_graph=True, retain_graph=True)[0]
dcdx = torch.stack([torch.autograd.grad(
c[i], solver.para, create_graph=True, retain_graph=True)[0] for i in range(len(c))])
dcdy = torch.stack([torch.autograd.grad(
c[i], source, create_graph=True, retain_graph=True)[0] for i in range(len(c))])
return dcdx.data.numpy(), dcdy.data.numpy()
'''Helpers'''
def heart_shape():
def x_para(t):
return 16 * np.sin(t)**3
def y_para(t):
return 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t) - 5
vertical_dist = 2
norm_factor = vertical_dist / (y_para(0) - y_para(np.pi))
t = np.linspace(0, 2 * np.pi, 31)
x = norm_factor * x_para(t)
y = norm_factor * y_para(t)
return np.asarray([x, y])
def circle_shape():
t = np.linspace(0, np.pi, 4)
x = 2 * np.cos(t - np.pi / 2.)
y = 2 * np.sin(t - np.pi / 2.)
return np.asarray([x, y])
def run_mixed_opt(alpha_nn,
alpha_ad,
maxiter_nn,
maxiter_ad,
log_interval_nn,
log_interval_ad,
optimizer_nn,
optimizer_ad
):
x_opt, wall_time_nn, objective_nn, source_nn = optimizer_nn.optimize(alpha=alpha_nn,
x_initial=None,
maxiter=maxiter_nn,
log_interval=log_interval_nn)
solver = RobotSolver(optimizer_nn.args, optimizer_nn.trainer.graph_info)
solver.reset_parameters_network(torch.tensor(
x_opt, dtype=torch.float).unsqueeze(0), optimizer_nn.model)
para_data = solver.para.data
optimizer_ad.para_data = para_data
x_opt, wall_time_ad, objective_ad, source_ad = optimizer_ad.optimize(alpha=alpha_ad,
x_initial=x_opt,
maxiter=maxiter_ad,
log_interval=log_interval_ad)
wall_time_mix = np.concatenate(
(wall_time_nn, wall_time_ad[1:] + wall_time_nn[-1]))
objective_mix = np.concatenate((objective_nn, objective_ad[1:]))
source_mix = np.concatenate((source_nn, source_ad[1:]))
return x_opt, wall_time_mix, objective_mix, source_mix
def run_single_opt(alpha,
maxiter,
log_interval,
optimizer
):
x_opt, wall_time, objective, source = optimizer.optimize(alpha=alpha,
x_initial=None,
maxiter=maxiter,
log_interval=log_interval)
return x_opt, wall_time, objective, source
def run_one_case(args,
alpha_nn,
alpha_ad1,
alpha_ad2,
maxiter_nn,
maxiter_ad1,
maxiter_ad2,
log_interval_nn,
log_interval_ad1,
log_interval_ad2,
target_point,
case_number
):
print("\ncase number {}".format(case_number))
optimizer_nn = OptimizerRobotPointSurrogate(args)
optimizer_nn.target_point = target_point
optimizer_ad = OptimizerRobotPointAdjoint(args)
optimizer_ad.target_point = target_point
_, wall_time_ad, objective_ad, source_ad = run_single_opt(
alpha_ad1, maxiter_ad1, log_interval_ad1, optimizer_ad)
print("\n")
_, wall_time_mix, objective_mix, source_mix = run_mixed_opt(alpha_nn,
alpha_ad2,
maxiter_nn,
maxiter_ad2,
log_interval_nn,
log_interval_ad2,
optimizer_nn,
optimizer_ad)
nn_number = maxiter_nn // log_interval_nn
objective_mix[
:nn_number + 1], _ = optimizer_nn.batch_evaluate(source_mix[:nn_number + 1])
_, optimal_solution = optimizer_nn.evaluate(source_mix[-1])
print("true error ad", objective_ad[-1])
print("true error mix", objective_mix[-1])
np.savez(args.root_path + '/' + args.numpy_path
+ '/robot/deploy/case' + str(case_number) + '.npz',
wall_time_ad=wall_time_ad,
objective_ad=objective_ad,
nn_number=nn_number,
wall_time_mix=wall_time_mix,
objective_mix=objective_mix,
target_point=target_point
)
scalar_field_paraview(args, optimal_solution,
optimizer_nn.trainer.poisson, "/robot/deploy/u" + str(case_number))
def run_walltime(args):
target_coos = circle_shape()
alpha_ad1_list = [1e-2, 1e-2, 2 * 1e-3, 2 * 1e-3]
alpha_nn_list = [1e-2, 1e-2, 2 * 1e-3, 2 * 1e-3]
alpha_ad2_list = [1e-2, 1e-2, 2 * 1e-3, 2 * 1e-3]
maxiter_ad1_list = [20, 20, 20, 20]
maxiter_nn_list = [400, 400, 4000, 6000]
maxiter_ad2_list = [20, 20, 20, 20]
log_interval_ad1_list = [1, 1, 1, 1]
log_interval_nn_list = [40, 40, 400, 600]
log_interval_ad2_list = [1, 1, 1, 1]
for i in range(3, 4):
run_one_case(args,
alpha_nn_list[i],
alpha_ad1_list[i],
alpha_ad2_list[i],
maxiter_nn_list[i],
maxiter_ad1_list[i],
maxiter_ad2_list[i],
log_interval_nn_list[i],
log_interval_ad1_list[i],
log_interval_ad2_list[i],
target_coos[:, i],
i)
def run_step(args):
target_coos = circle_shape()
alpha_list = [1e-2, 1e-2, 2 * 1e-3, 2 * 1e-3]
for case_number in range(2, 4):
optimizer_nn = OptimizerRobotPointSurrogate(args)
optimizer_ad = OptimizerRobotPointAdjoint(args)
print("case_number", case_number)
target_point = target_coos[:, case_number]
optimizer_nn.target_point = target_point
optimizer_ad.target_point = target_point
_, wall_time_ad, objective_ad, source_ad = run_single_opt(
alpha_list[case_number], 100, 1, optimizer_ad)
_, wall_time_nn, objective_nn, source_nn = run_single_opt(
alpha_list[case_number], 100, 1, optimizer_nn)
objective_nn, _ = optimizer_nn.batch_evaluate(source_nn)
np.savez(args.root_path + '/' + args.numpy_path
+ '/robot/deploy/case_step' + str(case_number) + '.npz',
objective_ad=objective_ad,
objective_nn=objective_nn,
target_point=target_point,
wall_time_ad=wall_time_ad,
wall_time_nn=wall_time_nn
)
def run_gradient_free(args):
target_coos = circle_shape()
target_point = target_coos[:, 1]
optimizer_fr = OptimizerRobotPointFree(args)
optimizer_fr.target_point = target_point
optimizer_fr.optimize()
if __name__ == '__main__':
args = arguments.args
run_walltime(args)
# run_step(args)
| 37.346988 | 102 | 0.570295 | import numpy as np
import torch
import scipy.optimize as opt
import time
from .optimizer import Optimizer
from ..ml.trainer_robot import TrainerRobot
from ..ml.models import RobotNetwork, RobotSolver
from .. import arguments
from ..graph.visualization import scalar_field_paraview
class OptimizerRobot(Optimizer):
def __init__(self, args):
super(OptimizerRobot, self).__init__(args)
self.tip_x1_index = 6
self.tip_x2_index = 7
self.trainer = TrainerRobot(args, opt=True)
self.path = self.args.root_path + '/' + self.args.model_path + '/' + \
self.trainer.poisson.name + '/model_s'
self.model = RobotNetwork(self.args, self.trainer.graph_info)
self.model.load_state_dict(torch.load(self.path))
class OptimizerRobotTrajectory(OptimizerRobot):
def __init__(self, args):
super(OptimizerRobotTrajectory, self).__init__(args)
self.target_coos = heart_shape()
self.n_pts = self.target_coos.shape[1]
def optimize(self):
x_initial = np.zeros(self.args.input_size * self.n_pts)
options = {'eps': 1e-15, 'maxiter': 1000,
'disp': True}
res = opt.minimize(fun=self._objective,
x0=x_initial,
method='CG',
jac=self._derivative,
callback=None,
options=options)
x_opt = res.x.reshape(-1, self.args.input_size)
source = torch.tensor(x_opt, dtype=torch.float)
solution = self.model(source)
print("NN surrogate, loss is", self.trainer.loss_function(
source, solution).data.numpy())
for i in range(31):
scalar_field_paraview(self.args, solution.data.numpy()[
i], self.trainer.poisson, "/robot/time_series_nn/u" + str(i))
for i in range(31):
gt_sol = self.trainer.forward_prediction(x_opt[i], self.model)
scalar_field_paraview(
self.args, gt_sol, self.trainer.poisson, "/robot/time_series_gt/u" + str(i))
return res.x
def _obj(self, source):
source = source.reshape(-1, self.args.input_size)
solution = self.model(source)
sol_tip = solution[:, [self.tip_x1_index, self.tip_x2_index]]
tar_tip = torch.tensor(self.target_coos.transpose(), dtype=torch.float)
L_dist = ((sol_tip - tar_tip)**2).sum()
L_reg = ((source[1:, :] - source[:-1, :])**2).sum()
alpha = 0 * 1e-3
L = L_dist + alpha * L_reg
return L
class OptimizerRobotPoint(OptimizerRobot):
def __init__(self, args):
super(OptimizerRobotPoint, self).__init__(args)
self.target_point = np.array([0, -2])
self.para_data = None
def _opt(self, alpha=1e-2, x_initial=None, maxiter=200, log_interval=20):
if x_initial is None:
x_initial = np.zeros(self.args.input_size)
x = x_initial
start = time.time()
wall_time = [0]
objective = []
source = [x]
for i in range(maxiter):
obj = self._objective(x)
der = self._derivative(x)
x = x - alpha * der
if i % log_interval == 0:
print("loop {} obj {}".format(i, obj))
wall_time.append(time.time() - start)
objective.append(obj)
source.append(x)
x_opt = x
objective.append(self._objective(x))
return x_opt, np.asarray(wall_time), np.asarray(objective), np.asarray(source)
def L_dist(self, solution):
L = (solution[0][self.tip_x1_index] - self.target_point[0])**2 \
+ (solution[0][self.tip_x2_index] - self.target_point[1])**2
return L
def evaluate(self, source):
solution, _ = self.trainer.forward_prediction(source, model=self.model)
L = self.L_dist(np.expand_dims(solution, axis=0))
return L, solution
def batch_evaluate(self, source):
Ls = []
sols = []
for s in source:
L, sol = self.evaluate(s)
Ls.append(L)
sols.append(sol)
print("Evaluated L", L)
return np.asarray(Ls), np.asarray(sols)
class OptimizerRobotPointFree(OptimizerRobotPoint):
def __init__(self, args):
super(OptimizerRobotPointFree, self).__init__(args)
def optimize(self, x_initial=None):
if x_initial is None:
x_initial = 0.1 * np.ones(self.args.input_size)
x = x_initial
self._obj(x)
options = {'maxiter': 100, 'disp': True,
'adaptive': True}
res = opt.minimize(fun=self._obj,
x0=x_initial,
method='Nelder-Mead',
options=options)
x_opt = x
return x_opt
def _obj(self, source):
solution, _ = self.trainer.forward_prediction(
source, model=None, para_data=self.para_data)
L = self.L_dist(torch.tensor(solution, dtype=torch.float).unsqueeze(0))
print(L)
return L.item()
class OptimizerRobotPointSurrogate(OptimizerRobotPoint):
def __init__(self, args):
super(OptimizerRobotPointSurrogate, self).__init__(args)
def optimize(self, alpha=1e-2, x_initial=None, maxiter=100, log_interval=100):
return self._opt(alpha=alpha, x_initial=x_initial, maxiter=maxiter, log_interval=log_interval)
def _obj(self, source):
source = source.unsqueeze(0)
solution = self.model(source)
L = self.L_dist(solution)
return L
class OptimizerRobotPointAdjoint(OptimizerRobotPoint):
def __init__(self, args):
super(OptimizerRobotPointAdjoint, self).__init__(args)
def optimize(self, alpha=2 * 1e-2, x_initial=None, maxiter=20, log_interval=1):
return self._opt(alpha=alpha, x_initial=x_initial, maxiter=maxiter, log_interval=log_interval)
def _objective(self, source):
_, self.para_data = self.trainer.forward_prediction(
source, model=None, para_data=self.para_data)
_, _, L = self._objective_partials(source, self.para_data)
return L
def _derivative(self, source):
dcdx, dcdy = self._constraint_partials(source, self.para_data)
dLdx, dLdy, _ = self._objective_partials(source, self.para_data)
J = self._adjoint_derivative(dcdx, dcdy, dLdx, dLdy)
return J
def _adjoint_derivative(self, dcdx, dcdy, dLdx, dLdy):
dcdx_T = dcdx.transpose()
adjoint_sol = np.linalg.solve(dcdx_T, dLdx)
total_derivative = -np.matmul(adjoint_sol, dcdy) + dLdy
return total_derivative
def _objective_partials(self, source, para_data):
solver = RobotSolver(self.args, self.trainer.graph_info)
solver.reset_parameters_data(para_data)
source = torch.tensor(source, requires_grad=True, dtype=torch.float)
source_input = source.unsqueeze(0)
solution = solver(source_input)
L = self.L_dist(solution)
dLdx = torch.autograd.grad(
L, solver.para, create_graph=True, retain_graph=True)[0]
dLdy = torch.autograd.grad(
L, source, create_graph=True, retain_graph=True)[0]
return dLdx.data.numpy(), dLdy.data.numpy(), L.data.numpy()
def _constraint_partials(self, source, para_data):
solver = RobotSolver(self.args, self.trainer.graph_info)
solver.reset_parameters_data(para_data)
source = torch.tensor(source, requires_grad=True, dtype=torch.float)
source_input = source.unsqueeze(0)
solution = solver(source_input)
L = self.trainer.loss_function(source_input, solution)
c = torch.autograd.grad(
L, solver.para, create_graph=True, retain_graph=True)[0]
dcdx = torch.stack([torch.autograd.grad(
c[i], solver.para, create_graph=True, retain_graph=True)[0] for i in range(len(c))])
dcdy = torch.stack([torch.autograd.grad(
c[i], source, create_graph=True, retain_graph=True)[0] for i in range(len(c))])
return dcdx.data.numpy(), dcdy.data.numpy()
def heart_shape():
def x_para(t):
return 16 * np.sin(t)**3
def y_para(t):
return 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t) - 5
vertical_dist = 2
norm_factor = vertical_dist / (y_para(0) - y_para(np.pi))
t = np.linspace(0, 2 * np.pi, 31)
x = norm_factor * x_para(t)
y = norm_factor * y_para(t)
return np.asarray([x, y])
def circle_shape():
t = np.linspace(0, np.pi, 4)
x = 2 * np.cos(t - np.pi / 2.)
y = 2 * np.sin(t - np.pi / 2.)
return np.asarray([x, y])
def run_mixed_opt(alpha_nn,
alpha_ad,
maxiter_nn,
maxiter_ad,
log_interval_nn,
log_interval_ad,
optimizer_nn,
optimizer_ad
):
x_opt, wall_time_nn, objective_nn, source_nn = optimizer_nn.optimize(alpha=alpha_nn,
x_initial=None,
maxiter=maxiter_nn,
log_interval=log_interval_nn)
solver = RobotSolver(optimizer_nn.args, optimizer_nn.trainer.graph_info)
solver.reset_parameters_network(torch.tensor(
x_opt, dtype=torch.float).unsqueeze(0), optimizer_nn.model)
para_data = solver.para.data
optimizer_ad.para_data = para_data
x_opt, wall_time_ad, objective_ad, source_ad = optimizer_ad.optimize(alpha=alpha_ad,
x_initial=x_opt,
maxiter=maxiter_ad,
log_interval=log_interval_ad)
wall_time_mix = np.concatenate(
(wall_time_nn, wall_time_ad[1:] + wall_time_nn[-1]))
objective_mix = np.concatenate((objective_nn, objective_ad[1:]))
source_mix = np.concatenate((source_nn, source_ad[1:]))
return x_opt, wall_time_mix, objective_mix, source_mix
def run_single_opt(alpha,
maxiter,
log_interval,
optimizer
):
x_opt, wall_time, objective, source = optimizer.optimize(alpha=alpha,
x_initial=None,
maxiter=maxiter,
log_interval=log_interval)
return x_opt, wall_time, objective, source
def run_one_case(args,
alpha_nn,
alpha_ad1,
alpha_ad2,
maxiter_nn,
maxiter_ad1,
maxiter_ad2,
log_interval_nn,
log_interval_ad1,
log_interval_ad2,
target_point,
case_number
):
print("\ncase number {}".format(case_number))
optimizer_nn = OptimizerRobotPointSurrogate(args)
optimizer_nn.target_point = target_point
optimizer_ad = OptimizerRobotPointAdjoint(args)
optimizer_ad.target_point = target_point
_, wall_time_ad, objective_ad, source_ad = run_single_opt(
alpha_ad1, maxiter_ad1, log_interval_ad1, optimizer_ad)
print("\n")
_, wall_time_mix, objective_mix, source_mix = run_mixed_opt(alpha_nn,
alpha_ad2,
maxiter_nn,
maxiter_ad2,
log_interval_nn,
log_interval_ad2,
optimizer_nn,
optimizer_ad)
nn_number = maxiter_nn // log_interval_nn
objective_mix[
:nn_number + 1], _ = optimizer_nn.batch_evaluate(source_mix[:nn_number + 1])
_, optimal_solution = optimizer_nn.evaluate(source_mix[-1])
print("true error ad", objective_ad[-1])
print("true error mix", objective_mix[-1])
np.savez(args.root_path + '/' + args.numpy_path
+ '/robot/deploy/case' + str(case_number) + '.npz',
wall_time_ad=wall_time_ad,
objective_ad=objective_ad,
nn_number=nn_number,
wall_time_mix=wall_time_mix,
objective_mix=objective_mix,
target_point=target_point
)
scalar_field_paraview(args, optimal_solution,
optimizer_nn.trainer.poisson, "/robot/deploy/u" + str(case_number))
def run_walltime(args):
target_coos = circle_shape()
alpha_ad1_list = [1e-2, 1e-2, 2 * 1e-3, 2 * 1e-3]
alpha_nn_list = [1e-2, 1e-2, 2 * 1e-3, 2 * 1e-3]
alpha_ad2_list = [1e-2, 1e-2, 2 * 1e-3, 2 * 1e-3]
maxiter_ad1_list = [20, 20, 20, 20]
maxiter_nn_list = [400, 400, 4000, 6000]
maxiter_ad2_list = [20, 20, 20, 20]
log_interval_ad1_list = [1, 1, 1, 1]
log_interval_nn_list = [40, 40, 400, 600]
log_interval_ad2_list = [1, 1, 1, 1]
for i in range(3, 4):
run_one_case(args,
alpha_nn_list[i],
alpha_ad1_list[i],
alpha_ad2_list[i],
maxiter_nn_list[i],
maxiter_ad1_list[i],
maxiter_ad2_list[i],
log_interval_nn_list[i],
log_interval_ad1_list[i],
log_interval_ad2_list[i],
target_coos[:, i],
i)
def run_step(args):
target_coos = circle_shape()
alpha_list = [1e-2, 1e-2, 2 * 1e-3, 2 * 1e-3]
for case_number in range(2, 4):
optimizer_nn = OptimizerRobotPointSurrogate(args)
optimizer_ad = OptimizerRobotPointAdjoint(args)
print("case_number", case_number)
target_point = target_coos[:, case_number]
optimizer_nn.target_point = target_point
optimizer_ad.target_point = target_point
_, wall_time_ad, objective_ad, source_ad = run_single_opt(
alpha_list[case_number], 100, 1, optimizer_ad)
_, wall_time_nn, objective_nn, source_nn = run_single_opt(
alpha_list[case_number], 100, 1, optimizer_nn)
objective_nn, _ = optimizer_nn.batch_evaluate(source_nn)
np.savez(args.root_path + '/' + args.numpy_path
+ '/robot/deploy/case_step' + str(case_number) + '.npz',
objective_ad=objective_ad,
objective_nn=objective_nn,
target_point=target_point,
wall_time_ad=wall_time_ad,
wall_time_nn=wall_time_nn
)
def run_gradient_free(args):
target_coos = circle_shape()
target_point = target_coos[:, 1]
optimizer_fr = OptimizerRobotPointFree(args)
optimizer_fr.target_point = target_point
optimizer_fr.optimize()
if __name__ == '__main__':
args = arguments.args
run_walltime(args)
| true | true |
f723a076d2741f0be112d64860b4aba73727bf6a | 1,659 | py | Python | misc/jp2_kakadu_pillow.py | kebe/myloris | e426687d8461e8cc11f93f20b8cba610c8bacdec | [
"BSD-2-Clause",
"BSD-3-Clause"
] | null | null | null | misc/jp2_kakadu_pillow.py | kebe/myloris | e426687d8461e8cc11f93f20b8cba610c8bacdec | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 1 | 2019-08-04T10:50:35.000Z | 2019-08-04T16:37:36.000Z | misc/jp2_kakadu_pillow.py | kebe/myloris | e426687d8461e8cc11f93f20b8cba610c8bacdec | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 1 | 2019-08-04T03:19:31.000Z | 2019-08-04T03:19:31.000Z | # This the basic flow for getting from a JP2 to a jpg w/ kdu_expand and Pillow
# Useful for debugging the scenario independent of the server.
from PIL import Image
from PIL.ImageFile import Parser
from os import makedirs, path, unlink
import subprocess
import sys
KDU_EXPAND='/usr/local/bin/kdu_expand'
LIB_KDU='/usr/local/lib/libkdu_v72R.so'
TMP='/tmp'
INPUT_JP2='/home/jstroop/workspace/loris/tests/img/corrupt.jp2'
OUT_JPG='/tmp/test.jpg'
REDUCE=0
### cmds, etc.
pipe_fp = '%s/mypipe.bmp' % (TMP,)
kdu_cmd = '%s -i %s -o %s -num_threads 4 -reduce %d' % (KDU_EXPAND, INPUT_JP2, pipe_fp, REDUCE)
mkfifo_cmd = '/usr/bin/mkfifo %s' % (pipe_fp,)
rmfifo_cmd = '/bin/rm %s' % (pipe_fp,)
# make a named pipe
mkfifo_resp = subprocess.check_call(mkfifo_cmd, shell=True)
if mkfifo_resp == 0:
print 'mkfifo OK'
# write kdu_expand's output to the named pipe
kdu_expand_proc = subprocess.Popen(kdu_cmd, shell=True,
bufsize=-1, stderr=subprocess.PIPE, stdout=subprocess.PIPE,
env={ 'LD_LIBRARY_PATH' : LIB_KDU })
# open the named pipe and parse the stream
with open(pipe_fp, 'rb') as f:
p = Parser()
while True:
s = f.read(1024)
if not s:
break
p.feed(s)
im = p.close()
# finish kdu
kdu_exit = kdu_expand_proc.wait()
if kdu_exit != 0:
map(sys.stderr.write, kdu_expand_proc.stderr)
else:
# if kdu was successful, save to a jpg
map(sys.stdout.write, kdu_expand_proc.stdout)
im = im.resize((719,900), resample=Image.ANTIALIAS)
im.save(OUT_JPG, quality=95)
# remove the named pipe
rmfifo_resp = subprocess.check_call(rmfifo_cmd, shell=True)
if rmfifo_resp == 0:
print 'rm fifo OK'
| 29.105263 | 95 | 0.698614 |
from PIL import Image
from PIL.ImageFile import Parser
from os import makedirs, path, unlink
import subprocess
import sys
KDU_EXPAND='/usr/local/bin/kdu_expand'
LIB_KDU='/usr/local/lib/libkdu_v72R.so'
TMP='/tmp'
INPUT_JP2='/home/jstroop/workspace/loris/tests/img/corrupt.jp2'
OUT_JPG='/tmp/test.jpg'
REDUCE=0
' % (TMP,)
kdu_cmd = '%s -i %s -o %s -num_threads 4 -reduce %d' % (KDU_EXPAND, INPUT_JP2, pipe_fp, REDUCE)
mkfifo_cmd = '/usr/bin/mkfifo %s' % (pipe_fp,)
rmfifo_cmd = '/bin/rm %s' % (pipe_fp,)
mkfifo_resp = subprocess.check_call(mkfifo_cmd, shell=True)
if mkfifo_resp == 0:
print 'mkfifo OK'
kdu_expand_proc = subprocess.Popen(kdu_cmd, shell=True,
bufsize=-1, stderr=subprocess.PIPE, stdout=subprocess.PIPE,
env={ 'LD_LIBRARY_PATH' : LIB_KDU })
# open the named pipe and parse the stream
with open(pipe_fp, 'rb') as f:
p = Parser()
while True:
s = f.read(1024)
if not s:
break
p.feed(s)
im = p.close()
# finish kdu
kdu_exit = kdu_expand_proc.wait()
if kdu_exit != 0:
map(sys.stderr.write, kdu_expand_proc.stderr)
else:
# if kdu was successful, save to a jpg
map(sys.stdout.write, kdu_expand_proc.stdout)
im = im.resize((719,900), resample=Image.ANTIALIAS)
im.save(OUT_JPG, quality=95)
# remove the named pipe
rmfifo_resp = subprocess.check_call(rmfifo_cmd, shell=True)
if rmfifo_resp == 0:
print 'rm fifo OK'
| false | true |
f723a08e1f91cd45f928370e3124e0153ba343e1 | 7,408 | py | Python | examples/rough_translated1/osgpoints.py | JaneliaSciComp/osgpyplusplus | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | [
"BSD-3-Clause"
] | 17 | 2015-06-01T12:19:46.000Z | 2022-02-12T02:37:48.000Z | examples/rough_translated1/osgpoints.py | cmbruns/osgpyplusplus | f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75 | [
"BSD-3-Clause"
] | 7 | 2015-07-04T14:36:49.000Z | 2015-07-23T18:09:49.000Z | examples/rough_translated1/osgpoints.py | cmbruns/osgpyplusplus | f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75 | [
"BSD-3-Clause"
] | 7 | 2015-11-28T17:00:31.000Z | 2020-01-08T07:00:59.000Z | #!/bin/env python
# Automatically translated python version of
# OpenSceneGraph example program "osgpoints"
# !!! This program will need manual tuning before it will work. !!!
import sys
from osgpypp import osg
from osgpypp import osgDB
from osgpypp import osgUtil
from osgpypp import osgViewer
# Translated from file 'osgpoints.cpp'
# OpenSceneGraph example, osgpoints.
#*
#* Permission is hereby granted, free of charge, to any person obtaining a copy
#* of this software and associated documentation files (the "Software"), to deal
#* in the Software without restriction, including without limitation the rights
#* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#* copies of the Software, and to permit persons to whom the Software is
#* furnished to do so, subject to the following conditions:
#*
#* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#* THE SOFTWARE.
#
#include <osgDB/ReadFile>
#include <osgUtil/Optimizer>
#include <osgViewer/Viewer>
#include <osg/Point>
#include <osg/BlendFunc>
#include <osg/Texture2D>
#include <osg/PointSprite>
#include <osg/PolygonMode>
#include <iostream>
class KeyboardEventHandler (osgGA.GUIEventHandler) :
KeyboardEventHandler(osg.StateSet* stateset):
_stateset(stateset)
_point = osg.Point()
_point.setDistanceAttenuation(osg.Vec3(0.0,0.0000,0.05))
_stateset.setAttribute(_point)
virtual bool handle( osgGA.GUIEventAdapter ea,osgGA.GUIActionAdapter)
switch(ea.getEventType())
case(osgGA.GUIEventAdapter.KEYDOWN):
if ea.getKey()==ord("+") or ea.getKey()==osgGA.GUIEventAdapter.KEY_KP_Add :
changePointSize(1.0)
return True
elif ea.getKey()==ord("-") or ea.getKey()==osgGA.GUIEventAdapter.KEY_KP_Subtract :
changePointSize(-1.0)
return True
elif ea.getKey()==ord("<") :
changePointAttenuation(1.1)
return True
elif ea.getKey()==ord(">") :
changePointAttenuation(1.0/1.1)
return True
break
default:
break
return False
def getPointSize():
return _point.getSize()
def setPointSize(psize):
if psize>0.0 :
_point.setSize(psize)
print "Point size ", psize
def changePointSize(delta):
setPointSize(getPointSize()+delta)
def changePointAttenuation(scale):
_point.setDistanceAttenuation(_point.getDistanceAttenuation()*scale)
_stateset = osg.StateSet()
_point = osg.Point()
def main(argv):
# use an ArgumentParser object to manage the program arguments.
arguments = osg.ArgumentParser(argv)
# set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage().setApplicationName(arguments.getApplicationName())
arguments.getApplicationUsage().setDescription(arguments.getApplicationName()+" example provides an interactive viewer for visualising point clouds..")
arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...")
arguments.getApplicationUsage().addCommandLineOption("-h or --help","Display this information")
arguments.getApplicationUsage().addCommandLineOption("--sprites","Point sprites.")
arguments.getApplicationUsage().addCommandLineOption("--points","Sets the polygon mode to GL_POINT for front and back faces.")
# construct the viewer.
viewer = osgViewer.Viewer()
shader = False
while arguments.read("--shader") : shader = True
# if user request help write it out to cout.
if arguments.read("-h") or arguments.read("--help") :
arguments.getApplicationUsage().write(std.cout)
return 1
usePointSprites = False
while arguments.read("--sprites") : usePointSprites = True
forcePointMode = False
while arguments.read("--points") : forcePointMode = True
if arguments.argc()<=1 :
arguments.getApplicationUsage().write(std.cout,osg.ApplicationUsage.COMMAND_LINE_OPTION)
return 1
# read the scene from the list of file specified commandline args.
loadedModel = osgDB.readNodeFiles(arguments)
# if no model has been successfully loaded report failure.
if not loadedModel :
print arguments.getApplicationName(), ": No data loaded"
return 1
# optimize the scene graph, remove redundant nodes and state etc.
optimizer = osgUtil.Optimizer()
optimizer.optimize(loadedModel)
# set the scene to render
viewer.setSceneData(loadedModel)
stateset = loadedModel.getOrCreateStateSet()
if usePointSprites :
#/ Setup cool blending
fn = osg.BlendFunc()
stateset.setAttributeAndModes(fn, osg.StateAttribute.ON)
#/ Setup the point sprites
sprite = osg.PointSprite()
stateset.setTextureAttributeAndModes(0, sprite, osg.StateAttribute.ON)
#/ The texture for the sprites
tex = osg.Texture2D()
tex.setImage(osgDB.readImageFile("Images/particle.rgb"))
stateset.setTextureAttributeAndModes(0, tex, osg.StateAttribute.ON)
if forcePointMode :
#/ Set polygon mode to GL_POINT
pm = osg.PolygonMode(
osg.PolygonMode.FRONT_AND_BACK, osg.PolygonMode.POINT )
stateset.setAttributeAndModes( pm, osg.StateAttribute.ON | osg.StateAttribute.OVERRIDE)
# register the handler for modifying the point size
viewer.addEventHandler(KeyboardEventHandler(viewer.getCamera().getOrCreateStateSet()))
if shader :
stateset = loadedModel.getOrCreateStateSet()
#################################/
# vertex shader using just Vec4 coefficients
char vertexShaderSource[] =
"void main(void) \n"
" \n"
"\n"
" gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex\n"
"\n"
program = osg.Program()
stateset.setAttribute(program)
vertex_shader = osg.Shader(osg.Shader.VERTEX, vertexShaderSource)
program.addShader(vertex_shader)
#if 0
#################################
# fragment shader
#
char fragmentShaderSource[] =
"void main(void) \n"
" \n"
" gl_FragColor = gl_Color \n"
"\n"
fragment_shader = osg.Shader(osg.Shader.FRAGMENT, fragmentShaderSource)
program.addShader(fragment_shader)
#endif
return viewer.run()
if __name__ == "__main__":
main(sys.argv)
| 33.071429 | 155 | 0.637419 |
import sys
from osgpypp import osg
from osgpypp import osgDB
from osgpypp import osgUtil
from osgpypp import osgViewer
class KeyboardEventHandler (osgGA.GUIEventHandler) :
KeyboardEventHandler(osg.StateSet* stateset):
_stateset(stateset)
_point = osg.Point()
_point.setDistanceAttenuation(osg.Vec3(0.0,0.0000,0.05))
_stateset.setAttribute(_point)
virtual bool handle( osgGA.GUIEventAdapter ea,osgGA.GUIActionAdapter)
switch(ea.getEventType())
case(osgGA.GUIEventAdapter.KEYDOWN):
if ea.getKey()==ord("+") or ea.getKey()==osgGA.GUIEventAdapter.KEY_KP_Add :
changePointSize(1.0)
return True
elif ea.getKey()==ord("-") or ea.getKey()==osgGA.GUIEventAdapter.KEY_KP_Subtract :
changePointSize(-1.0)
return True
elif ea.getKey()==ord("<") :
changePointAttenuation(1.1)
return True
elif ea.getKey()==ord(">") :
changePointAttenuation(1.0/1.1)
return True
break
default:
break
return False
def getPointSize():
return _point.getSize()
def setPointSize(psize):
if psize>0.0 :
_point.setSize(psize)
print "Point size ", psize
def changePointSize(delta):
setPointSize(getPointSize()+delta)
def changePointAttenuation(scale):
_point.setDistanceAttenuation(_point.getDistanceAttenuation()*scale)
_stateset = osg.StateSet()
_point = osg.Point()
def main(argv):
arguments = osg.ArgumentParser(argv)
arguments.getApplicationUsage().setApplicationName(arguments.getApplicationName())
arguments.getApplicationUsage().setDescription(arguments.getApplicationName()+" example provides an interactive viewer for visualising point clouds..")
arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...")
arguments.getApplicationUsage().addCommandLineOption("-h or --help","Display this information")
arguments.getApplicationUsage().addCommandLineOption("--sprites","Point sprites.")
arguments.getApplicationUsage().addCommandLineOption("--points","Sets the polygon mode to GL_POINT for front and back faces.")
viewer = osgViewer.Viewer()
shader = False
while arguments.read("--shader") : shader = True
if arguments.read("-h") or arguments.read("--help") :
arguments.getApplicationUsage().write(std.cout)
return 1
usePointSprites = False
while arguments.read("--sprites") : usePointSprites = True
forcePointMode = False
while arguments.read("--points") : forcePointMode = True
if arguments.argc()<=1 :
arguments.getApplicationUsage().write(std.cout,osg.ApplicationUsage.COMMAND_LINE_OPTION)
return 1
loadedModel = osgDB.readNodeFiles(arguments)
if not loadedModel :
print arguments.getApplicationName(), ": No data loaded"
return 1
optimizer = osgUtil.Optimizer()
optimizer.optimize(loadedModel)
viewer.setSceneData(loadedModel)
stateset = loadedModel.getOrCreateStateSet()
if usePointSprites :
fn = osg.BlendFunc()
stateset.setAttributeAndModes(fn, osg.StateAttribute.ON)
sprite = osg.PointSprite()
stateset.setTextureAttributeAndModes(0, sprite, osg.StateAttribute.ON)
tex = osg.Texture2D()
tex.setImage(osgDB.readImageFile("Images/particle.rgb"))
stateset.setTextureAttributeAndModes(0, tex, osg.StateAttribute.ON)
if forcePointMode :
pm = osg.PolygonMode(
osg.PolygonMode.FRONT_AND_BACK, osg.PolygonMode.POINT )
stateset.setAttributeAndModes( pm, osg.StateAttribute.ON | osg.StateAttribute.OVERRIDE)
viewer.addEventHandler(KeyboardEventHandler(viewer.getCamera().getOrCreateStateSet()))
if shader :
stateset = loadedModel.getOrCreateStateSet()
| false | true |
f723a1646810b50d3ff12250f9cc268b8132cf39 | 44,316 | py | Python | active_learning.py | alfrunesiq/SemanticSegmentationActiveLearning | 3f953a22c8fd95828c9bd4c5ce52a53e991391e4 | [
"MIT"
] | 9 | 2019-06-14T07:29:28.000Z | 2021-03-27T09:45:56.000Z | active_learning.py | alfrunesiq/SemanticSegmentationActiveLearning | 3f953a22c8fd95828c9bd4c5ce52a53e991391e4 | [
"MIT"
] | 2 | 2020-08-10T10:18:21.000Z | 2021-03-18T20:30:04.000Z | active_learning.py | alfrunesiq/SemanticSegmentationActiveLearning | 3f953a22c8fd95828c9bd4c5ce52a53e991391e4 | [
"MIT"
] | 1 | 2020-03-07T08:37:12.000Z | 2020-03-07T08:37:12.000Z | # Python standard libraries
import argparse
import glob
import json
import logging
import logging.config
import os
import sys
# Non-standard includes
import numpy as np
import tensorflow as tf
# Maybe import tqdm
show_progress = False
try:
import tqdm
show_progress = True
except ImportError:
pass
try:
import tkinter
tkinter.Tk().withdraw()
except ImportError:
if args.unlabelled == None:
pass
else:
raise ImportError("Could not import tkinter, make sukre Tk "
"dependencies are installed")
except Exception as e:
print(e)
pass
# User includes
import models
import datasets
import tensortools as tt
# Lowest representable float32
EPSILON = np.finfo(np.float32).tiny
def main(args, logger):
# Retrieve training parameters for convenience
params = args.params # All parameters
hparams = params["hyperparams"] # Hyperparamters
alparams = params["active_learning"] # Active learning parameters
state = None # State dict
# Define state and config filenames
state_filename = os.path.join(args.log_dir, "state.json")
config_filename = os.path.join(args.log_dir, "config.json")
if not os.path.exists(args.log_dir):
os.makedirs(args.log_dir)
# Dump parameter config
with open(config_filename, "w+") as f:
json.dump(params, f, indent=4)
# Retrieve dataset specific object
if args.dataset == "cityscapes":
dataset = datasets.Cityscapes(coarse=args.coarse)
test_examples_glob = os.path.join(args.data_dir, "val", "*.tfrecord")
elif args.dataset == "freiburg":
dataset = datasets.Freiburg()
test_examples_glob = os.path.join(args.data_dir, "test", "*.tfrecord")
elif args.dataset == "vistas":
dataset = datasets.Vistas()
test_examples_glob = os.path.join(args.data_dir, "val", "*.tfrecord")
else:
raise NotImplementedError("Dataset \"%s\" not supported" % args.dataset)
# Prepare dataset example file paths.
train_examples_glob = os.path.join(args.data_dir, "train", "*.tfrecord")
if not os.path.exists(state_filename):
# Initialize state
# Resolve example filenames
train_val_examples = np.sort(np.array(glob.glob(train_examples_glob)))
# Pick examples from training set to use for validation
val_examples = train_val_examples[:alparams["num_validation"]]
# Use the rest as training examples
train_examples = train_val_examples[alparams["num_validation"]:]
# Use annotated test set, NOTE: cityscapes validation set
test_examples = np.array(glob.glob(test_examples_glob))
# Draw random train examples and mark as annotated
train_indices = np.arange(len(train_examples), dtype=np.int32)
np.random.shuffle(train_indices)
initially_labelled = alparams["num_initially_labelled"]
if initially_labelled < 0:
# Use rest of labelled examples
initially_labelled = len(train_examples)
# Possibly add actually unlabelled examples
no_label_indices = np.empty(0, dtype=str)
if args.unlabelled is not None:
no_label_glob = os.path.join(args.unlabelled, "*.tfrecord")
no_label_examples = glob.glob(no_label_glob)
no_label_indices = np.arange(
len(train_indices), len(train_indices)+len(no_label_examples)
)
train_examples = np.concatenate(train_examples,
no_label_examples)
train_indices = np.concatenate((train_indices, no_label_indices))
labelled = train_indices[:initially_labelled]
unlabelled = train_indices[initially_labelled:]
del train_indices
# Setup initial state
state = {
"checkpoint" : None, # Keep track of latest checkpoint.
"iteration" : 0,
"dataset" : {
"train" : {
"filenames" : list(train_examples),
"labelled" : labelled.tolist(),
"unlabelled" : unlabelled.tolist(),
"no_label" : no_label_indices.tolist()
},
"val" : {
"filenames" : list(val_examples)
},
"test" : {
"filenames" : list(test_examples)
}
}
}
with open(state_filename, "w+") as f:
json.dump(state, f, indent=2)
else:
# Load state
with open(state_filename, "r") as f:
state = json.load(f)
# Extract filename properties
train_examples = np.array(state["dataset"]["train"]["filenames"])
val_examples = np.array(state["dataset"]["val"]["filenames"])
test_examples = np.array(state["dataset"]["test"]["filenames"])
labelled = np.array(state["dataset"]["train"]["labelled"])
unlabelled = np.array(state["dataset"]["train"]["unlabelled"])
no_label_indices = np.array(state["dataset"]["train"]["no_label"])
train_input_labelled = np.full_like(train_examples, False, dtype=bool)
train_input_labelled[labelled] = True
train_input_indices = np.arange(len(train_examples))
with tf.device("/device:CPU:0"):
with tf.name_scope("Datasets"):
# Create input placeholders
train_input = tt.input.NumpyCapsule()
train_input.filenames = train_examples
train_input.labelled = train_input_labelled
train_input.indices = train_input_indices
val_input = tt.input.NumpyCapsule()
val_input.filenames = val_examples
test_input = tt.input.NumpyCapsule()
test_input.filenames = test_examples
# Setup input pipelines
train_input_stage = tt.input.InputStage(
input_shape=[params["network"]["input"]["height"],
params["network"]["input"]["width"]])
# Validation AND Test input stage
val_input_stage = tt.input.InputStage(
input_shape=[params["network"]["input"]["height"],
params["network"]["input"]["width"]])
# Add datasets
train_input_stage.add_dataset_from_placeholders(
"train", train_input.filenames,
train_input.labelled, train_input.indices,
batch_size=params["batch_size"],
augment=True)
# Validation set
val_input_stage.add_dataset_from_placeholders(
"val", val_input.filenames,
batch_size=params["batch_size"])
# Test set
val_input_stage.add_dataset_from_placeholders(
"test", test_input.filenames,
batch_size=params["batch_size"])
# Calculate number of batches in each iterator
val_batches = (len(val_examples) - 1)//params["batch_size"] + 1
test_batches = (len(test_examples) - 1)//params["batch_size"] + 1
# Get iterator outputs
train_image_raw, train_image, train_label, train_mask, \
train_labelled, train_index = train_input_stage.get_output()
val_image, val_label, val_mask = val_input_stage.get_output()
# Create step variables
with tf.variable_scope("StepCounters"):
global_step = tf.Variable(0, dtype=tf.int64,
trainable=False, name="GlobalStep")
local_step = tf.Variable(0, dtype=tf.int64,
trainable=False, name="LocalStep")
global_step_op = tf.assign_add(global_step, local_step)
epoch_step = tf.Variable(0, trainable=False, name="EpochStep")
epoch_step_inc = tf.assign_add(epoch_step, 1)
# Build training- and validation network
regularization = {"drop_rates": hparams["dropout_rates"]}
if hparams["weight_reg"]["L2"] > 0.0 \
or hparams["weight_reg"]["L1"] > 0.0:
regularization = {
"weight_regularization" : tf.keras.regularizers.l1_l2(
l1=hparams["weight_reg"]["L1"],
l2=hparams["weight_reg"]["L2"]),
"regularization_scaling" : hparams["weight_reg"]["glorot_scaling"],
}
# Initialize networks
train_net = models.ENet(
dataset.num_classes,
**regularization
)
val_net = models.ENet(dataset.num_classes)
with tf.device("/device:GPU:0"):
# Build graph for training
train_logits = train_net(train_image, training=True)
# Compute predictions: use @train_pred for metrics and
# @pseudo_label for pseudo_annotation process.
train_pred = tf.math.argmax(train_logits, axis=-1,
name="TrainPredictions")
with tf.name_scope("PseudoAnnotation"):
# Build ops one more time without dropout.
pseudo_logits = train_net(train_image_raw, training=False)
# Just make sure not to propagate gradients a second time.
pseudo_logits = tf.stop_gradient(pseudo_logits)
pseudo_label = tf.math.argmax(pseudo_logits, axis=-1,
name="TrainPredictions")
pseudo_label = tf.cast(pseudo_label, tf.uint8)
# Configure on-line high confidence pseudo labeling.
pseudo_prob = tf.nn.softmax(pseudo_logits, axis=-1, name="TrainProb")
if alparams["measure"] == "entropy":
# Reduce entropy over last dimension.
# Compute prediction entropy
entropy = - pseudo_prob * tf.math.log(pseudo_prob+EPSILON)
entropy = tf.math.reduce_sum(entropy, axis=-1)
# Convert logarithm base to units of number of classes
# NOTE this will make the metric independent of number of
# classes as well the range in [0,1]
log_base = tf.math.log(np.float32(dataset.num_classes))
entropy = entropy / log_base
# Convert entropy to confidence
pseudo_confidence = 1.0 - entropy
elif alparams["measure"] == "margin":
# Difference between the two largest entries in last dimension.
values, indices = tf.math.top_k(pseudo_prob, k=2)
pseudo_confidence = values[:,:,:,0] - values[:,:,:,1]
elif alparams["measure"] == "confidence":
# Reduce max over last dimension.
pseudo_confidence = tf.math.reduce_max(pseudo_prob, axis=-1)
else:
raise NotImplementedError("Uncertainty function not implemented.")
pseudo_mean_confidence = tf.reduce_mean(
tf.cast(pseudo_confidence, tf.float64),
axis=(1,2))
# Pseudo annotate high-confidence unlabeled example pixels
pseudo_mask = tf.where(tf.math.less(pseudo_confidence, alparams["threshold"]),
tf.zeros_like(pseudo_label,
dtype=train_label.dtype),
tf.ones_like(pseudo_label,
dtype=train_label.dtype))
# Pseudo annotation logic (think of it as @tf.cond maped
# over batch dimension)
train_label = tf.where(train_labelled, train_label,
pseudo_label, name="MaybeGenLabel")
train_mask = tf.where(train_labelled, train_mask,
pseudo_mask, name="MaybeGenMask")
with tf.device("/device:GPU:1"):
# Build validation network.
val_logits = val_net(val_image, training=False)
val_pred = tf.math.argmax(val_logits, axis=-1,
name="ValidationPredictions")
# Build cost function
with tf.name_scope("Cost"):
with tf.device("/device:GPU:0"):
# Establish loss function
if hparams["softmax"]["multiscale"]:
loss, loss_weights = \
tt.losses.multiscale_masked_softmax_cross_entropy(
train_label,
train_net.endpoint_outputs[0],
train_mask, dataset.num_classes,
weight=hparams["softmax"]["loginverse_scaling"],
label_smoothing=hparams["softmax"]["label_smoothing"],
scope="XEntropy")
# NOTE: this will make @loss_weights checkpointed
train_net.loss_scale_weights = loss_weights
else:
loss = tt.losses.masked_softmax_cross_entropy(
train_label,
train_logits,
train_mask, dataset.num_classes,
weight=hparams["softmax"]["loginverse_scaling"],
label_smoothing=hparams["softmax"]["label_smoothing"],
scope="XEntropy")
cost = loss
# Add regularization to cost function
if len(train_net.losses) > 0:
regularization_loss = tf.math.add_n(train_net.losses, name="Regularization")
cost += tf.cast(regularization_loss, dtype=tf.float64)
# Setup learning rate
learning_rate = hparams["learning_rate"]
if hparams["learning_rate_decay"] > 0.0:
# Inverse time learning_rate if lr_decay specified
learning_rate = tf.train.inverse_time_decay(
learning_rate, local_step,
decay_steps=train_batches,
decay_rate=hparams["learning_rate_decay"])
# Create optimization procedure
optimizer = tf.train.AdamOptimizer(learning_rate, **hparams["optimizer"]["kwargs"])
# Create training op
train_op = optimizer.minimize(cost, global_step=local_step,
name="TrainOp")
# END tf.device("/device:GPU:0")
# END tf.name_scope("Cost")
# Create summary operations for training and validation network
with tf.name_scope("Summary"):
# Create colormap for image summaries
colormap = tf.constant(dataset.colormap, dtype=tf.uint8,
name="Colormap")
# Create metric evaluation and summaries
with tf.device("/device:GPU:0"):
with tf.name_scope("TrainMetrics"):
# Create metrics object for training network.
train_metrics = tt.metrics.Metrics(train_pred, train_label,
dataset.num_classes, train_mask)
# Get Tensorflow update op.
metric_update_op = train_metrics.get_update_op()
# Get Tensorflow summary operations.
metric_summaries = train_metrics.get_summaries()
train_summary_iter = tf.summary.merge(
[
# Summaries run at each iteration.
tf.summary.scalar("CrossEntropyLoss", loss,
family="Losses"),
tf.summary.scalar("TotalCost", cost,
family="Losses"),
tf.summary.scalar("LearningRate", learning_rate,
family="Losses")
], name="IterationSummaries"
)
with tf.control_dependencies([metric_update_op]):
train_summary_epoch = tf.summary.merge(
[
# Summaries run at epoch boundaries.
metric_summaries["Metrics"],
metric_summaries["ConfusionMat"]
], name="EpochSummaries"
)
train_image_summary = tf.summary.merge(
[
tf.summary.image(
"PseudoLabel/input",
train_image_raw,
family="PseudoLabel"
),
tf.summary.image(
"PseudoLabel/confidence",
tf.expand_dims(pseudo_confidence, axis=-1),
family="PseudoLabel"
),
tf.summary.image(
"PseudoLabel",
tf.gather(dataset.colormap,
tf.cast(pseudo_label*pseudo_mask \
+ (1 - pseudo_mask)*255,
tf.int32)),
family="PseudoLabel"
)
]
)
# Create metric evaluation and summaries
with tf.device("/device:GPU:1"):
with tf.name_scope("ValidationTestMetrics"):
# Create metrics object
val_metrics = tt.metrics.Metrics(val_pred, val_label,
dataset.num_classes, val_mask)
# Get update tensorflow ops
val_metric_update_op = val_metrics.get_update_op()
# Get metric sumaries
val_metric_summaries = val_metrics.get_summaries()
with tf.control_dependencies([val_metric_update_op]):
val_metric_summary = tf.summary.merge(
[
# "Expensive" summaries run at epoch boundaries.
val_metric_summaries["Metrics"],
val_metric_summaries["ClassMetrics"],
val_metric_summaries["ConfusionMat"]
], name="EpochSummaries"
)
val_image_summary = tf.summary.merge(
[
tf.summary.image("Input", val_image),
tf.summary.image("Label", tf.gather(
colormap, tf.cast(val_label + 255*(1-val_mask),
tf.int32))),
tf.summary.image("Predictions", tf.gather(
colormap, tf.cast(val_pred, tf.int32)))
]
)
val_summary_epoch = val_metric_summary
test_summary_epoch = tf.summary.merge([
val_metric_summary,
val_image_summary
]
)
conf_summary_ph = tf.placeholder(tf.float64, shape=[None])
conf_summary = tf.summary.histogram("ConfidenceDistribution",
conf_summary_ph)
# END name_scope("Summary")
# Create session with soft device placement
# - some ops neet to run on the CPU
sess_config = tf.ConfigProto(allow_soft_placement=True)
sess_config.gpu_options.allow_growth = True
with tf.Session(config=sess_config) as sess:
logger.debug("Initializing variables...")
sess.run(tf.global_variables_initializer())
# Create checkpoint object
with tf.name_scope("Checkpoint"):
checkpoint = tf.train.Checkpoint(model=train_net,
epoch=epoch_step,
step=global_step,
optimizer=optimizer)
checkpoint_name = os.path.join(args.log_dir, "model")
if args.checkpoint is not None:
# CMDline checkpoint given
ckpt = args.checkpoint
if os.path.isdir(ckpt):
ckpt = tf.train.latest_checkpoint(ckpt)
if ckpt is None:
logger.error("Checkpoint path \"%s\" is invalid.")
return 1
logger.info("Resuming from checkpoint \"%s\"" % ckpt)
status = checkpoint.restore(ckpt)
if tf.__version__ < "1.14.0":
status.assert_existing_objects_matched()
else:
status.expect_partial()
status.initialize_or_restore(sess)
if args.reinitialize_output:
sess.run(train_net.Final.kernel.initializer)
elif state["checkpoint"] != None:
# Try to restore from checkpoint in logdir
ckpt = state["checkpoint"]
logger.info("Resuming from checkpoint \"%s\"" % ckpt)
status = checkpoint.restore(ckpt)
if tf.__version__ < "1.14.0":
status.assert_existing_objects_matched()
else:
status.expect_partial()
status.initialize_or_restore(sess)
with tf.name_scope("UpdateValidationWeights"):
update_val_op = []
for i in range(len(val_net.layers)):
for j in range(len(val_net.layers[i].variables)):
update_val_op.append(
tf.assign(val_net.layers[i].variables[j],
train_net.layers[i].variables[j]))
update_val_op = tf.group(update_val_op)
ckpt_manager = tt.checkpoint_manager.CheckpointManager(checkpoint,
args.log_dir)
# END scope Checkpoint
# Prepare global fetches dict
fetches = {
"train" : {
"iteration" : {
"step" : global_step_op,
"summary" : train_summary_iter,
"train_op" : train_op,
"update" : metric_update_op,
"updates" : train_net.updates
},
"epoch" : {
"step" : epoch_step,
"summary" : train_summary_epoch,
"summary/image" : train_image_summary
}
},
"val" : { # Validation and test fetches
"iteration" : {
"update" : val_metric_update_op
},
"epoch" : {
"step" : epoch_step,
"MeanIoU" : val_metrics.metrics["MeanIoU"],
"summary" : val_summary_epoch,
# Also add image summary, however only added to
# writer every N epochs.
"summary/image" : val_image_summary
}
},
"test" : {
"iteration" : {"update" : val_metric_update_op},
"epoch" : {"summary" : test_summary_epoch}
}
}
# Train loop (until convergence) -> Pick unlabeled examples -> test_loop
def train_loop(summary_writer):
"""
Train loop closure.
Runs training loop untill no improvement is seen in
@params["epochs"] epochs before returning.
"""
# How many epoch until counting @no_improvement
_initial_grace_period = alparams["epochs/warm_up"]
best_ckpt = state["checkpoint"]
best_mean_iou = 0.0
log_subdir = summary_writer.get_logdir()
run_name = os.path.basename(log_subdir)
checkpoint_prefix = os.path.join(log_subdir, "model")
num_iter_per_epoch = np.maximum(train_input.size,
val_input.size)
no_improvement_count = 0
while no_improvement_count < params["epochs"] \
or _initial_grace_period >= 0:
_initial_grace_period -= 1
# Increment in-graph epoch counter.
epoch = sess.run(epoch_step_inc)
# Prepare inner loop iterator
_iter = range(0, num_iter_per_epoch, params["batch_size"])
if show_progress:
_iter = tqdm.tqdm(_iter, desc="%s[%d]" % (run_name, epoch),
dynamic_ncols=True,
ascii=True,
postfix={"NIC": no_improvement_count})
# Initialize iterators
train_input_stage.init_iterator(
"train", sess, train_input.feed_dict)
val_input_stage.init_iterator(
"val", sess, val_input.feed_dict)
# Reset confusion matrices
train_metrics.reset_metrics(sess)
val_metrics.reset_metrics(sess)
# Prepare iteration fetches
_fetches = {
"train" : {"iteration" : fetches["train"]["iteration"]},
"val" : {"iteration" : fetches["val"]["iteration"]}
}
# Update validation network weights
sess.run(update_val_op)
try:
for i in _iter:
if train_input.size-params["batch_size"] <= i < train_input.size:
# Fetches for last training iteration.
_fetches["train"]["epoch"] = fetches["train"]["epoch"]
if val_input.size-params["batch_size"] <= i < val_input.size:
_fetches["val"]["epoch"] = fetches["val"]["epoch"]
# Run fetches
results = sess.run(_fetches)
if "train" in results.keys():
# Add iteration summary
summary_writer.add_summary(
results["train"]["iteration"]["summary"],
results["train"]["iteration"]["step"])
# Maybe add epoch summary
if "epoch" in results["train"].keys():
summary_writer.add_summary(
results["train"]["epoch"]["summary"],
results["train"]["epoch"]["step"]
)
# Pop fetches to prohibit OutOfRangeError due to
# asymmetric train-/val- input size.
if results["train"]["epoch"]["step"] % 100 == 0:
summary_writer.add_summary(
results["train"]["epoch"]["summary/image"],
results["train"]["epoch"]["step"]
)
_fetches.pop("train")
if "val" in results.keys() and \
"epoch" in results["val"].keys():
# Add summaries to event log.
summary_writer.add_summary(
results["val"]["epoch"]["summary"],
results["val"]["epoch"]["step"]
)
if results["val"]["epoch"]["step"] % 100 == 0:
# Only report image summary every 100th epoch.
summary_writer.add_summary(
results["val"]["epoch"]["summary/image"],
results["val"]["epoch"]["step"]
)
# Check if MeanIoU improved and
# update counter and best
if results["val"]["epoch"]["MeanIoU"] > best_mean_iou:
best_mean_iou = results["val"]["epoch"]["MeanIoU"]
# Update checkpoint file used for
# @tf.train.latest_checkpoint to point at
# current best.
_ckpt_name = ckpt_manager.commit(
checkpoint_prefix, sess)
if _ckpt_name != "":
best_ckpt = _ckpt_name
# Reset counter
no_improvement_count = 0
else:
# Result has not improved, increment counter.
no_improvement_count += 1
if no_improvement_count >= params["epochs"] and \
_initial_grace_period < 0:
_iter.close()
break
if show_progress:
_iter.set_postfix(NIC=no_improvement_count)
# Pop fetches to prohibit OutOfRangeError due to
# asymmetric train-/val- input size.
_fetches.pop("val")
# END "maybe add epoch summary"
except tf.errors.OutOfRangeError:
logger.error("Out of range error. Attempting to continue.")
pass
summary_writer.flush()
ckpt_manager.cache(sess)
# END while no_improvement_count < params["epochs"]
return best_ckpt
def test_loop(summary_writer):
"""
Test loop closure.
"""
_step = len(labelled)
# Initialize validation input stage with test set
val_input_stage.init_iterator("test", sess, test_input.feed_dict)
_iter = range(0, test_input.size, params["batch_size"])
if show_progress:
_iter = tqdm.tqdm(_iter, desc="test[%d]" % (_step),
ascii=True,
dynamic_ncols=True)
summary_proto = None
val_metrics.reset_metrics(sess)
try:
for i in _iter:
# Accumulate confusion matrix
if i < test_input.size - params["batch_size"]:
sess.run(fetches["test"]["iteration"]["update"])
else:
# Run summary operation last iteration
_, summary_proto = sess.run([fetches["test"]["iteration"]["update"],
fetches["test"]["epoch"]["summary"]])
except tf.errors.OutOfRangeError:
pass
# Add summary with number of labelled examples as step.
# NOTE this only runs on each major iteration.
summary_writer.add_summary(
summary_proto, _step
)
def rank_confidence():
# Allocate array to store all confidence scores
num_examples = len(state["dataset"]["train"]["filenames"])
confidence = np.zeros(num_examples, dtype=np.float32)
# Initialize input stage
train_input_stage.init_iterator("train", sess,
train_input.feed_dict)
_iter = range(0, train_input.size, params["batch_size"])
if show_progress:
_iter = tqdm.tqdm(_iter, desc="ranking[%d]" % len(labelled),
ascii=True,
dynamic_ncols=True)
try:
for i in _iter:
# Loop over all examples and compute confidence
batch_confidence, batch_indices = sess.run(
[pseudo_mean_confidence, train_index])
# Add to list of confidence
confidence[batch_indices] = batch_confidence
except tf.errors.OutOfRangeError:
pass
# Filter out labelled examples
unlabelled_confidence = confidence[unlabelled]
selection_size = np.minimum(len(unlabelled),
alparams["selection_size"])
# Get the lowest confidence indices of unlabelled subset
example_indices = np.argpartition(unlabelled_confidence,
selection_size)
example_indices = example_indices[:selection_size]
# Convert to indices into all filenames list
low_conf_examples = unlabelled[example_indices]
return low_conf_examples, unlabelled_confidence
checkpoint_path = state["checkpoint"]
# Only add graph to first event file
_graph = sess.graph if checkpoint_path == None else None
with tf.summary.FileWriter(args.log_dir, graph=_graph) as test_writer:
iterations = alparams["iterations"]
if iterations < 0:
# Iterate untill all data is consumed
iterations = np.ceil(len(unlabelled)
/ float(alparams["selection_size"]))
logger.info("Iteration count: %d" % iterations)
while state["iteration"] < iterations:
# Step 1: train_loop
train_input.set_indices(labelled)
if state["iteration"] == 0:
# Pretrain
log_subdir = os.path.join(args.log_dir, "pretrain")
# Only use labelled subset
else:
# Any other iteration
log_subdir = os.path.join(args.log_dir, "iter-%d" %
state["iteration"])
# Sample from the unlabelled set
p = alparams["pseudo_labelling_proportion"]
sample_size = int(len(labelled)*p/(1-p))
sample_size = np.minimum(sample_size, len(unlabelled))
train_input.set_sample_size(sample_size)
# Create subdir if it doesn't exist
if not os.path.exists(log_subdir):
os.mkdir(log_subdir)
# Change checkpoint manager directory
ckpt_manager.chdir(log_subdir)
with tf.summary.FileWriter(log_subdir) as train_val_writer:
# Enter train loop
try:
checkpoint_path = train_loop(train_val_writer)
except KeyboardInterrupt as exception:
# Quickly store state
if ckpt_manager.latest_checkpoint != "":
state["checkpoint"] = ckpt_manager.latest_checkpoint
with open(state_filename, "w") as f:
json.dump(state, f, indent=2)
f.truncate()
raise exception
# Reload best checkpoint
status = checkpoint.restore(checkpoint_path)
status.run_restore_ops(sess)
sess.run(update_val_op)
# Step 2: test_loop
if test_input.size > 0:
# This step may be omitted on deployment
test_loop(test_writer)
# Step 3: Find low confidence examples
# Reset train_input to use all examples for ranking
train_input.set_indices()
if alparams["selection_size"] > 0:
low_conf_examples, unlabelled_conf = rank_confidence()
_hist_summary = sess.run(conf_summary,
{conf_summary_ph:
unlabelled_conf})
test_writer.add_summary(_hist_summary, state["iteration"])
else:
# Draw examples randomly
selection_size = np.minimum(alparams["selection_size"],
len(unlabelled.tolist()))
if selection_size != 0:
low_conf_examples = np.random.choice(
unlabelled, np.abs(alparams["selection_size"]))
else:
low_conf_examples = []
# (maybe) Pause for user to annotate
to_annotate_indices = no_label_indices[np.isin(
no_label_indices, low_conf_examples)]
while len(to_annotate_indices) > 0:
to_annotate = train_examples[to_annotate_indices]
# Poll user for filenames of annotated examples
logger.info("Please annotate the following examples:\n%s" %
"\n".join(to_annotate_basename.tolist()))
filenames = tkinter.filedialog.askopenfilename(
multiple=1,
filetypes=(("TFRecord", "*.tfrecord"),))
hit = [] # List of matching filename indices
for filename in filenames:
basename = os.path.basename(filename)
idx = -1
for i in range(len(to_annotate)):
if to_annotate[i].endswith(basename):
idx = i
break
if idx != -1:
# Update state filenames
train_examples[to_annotate_indices[idx]] = filename
hit.append(idx)
else:
logger.info("Unrecognized filepath: %s" % filename)
# Remove matched paths
to_annotate_indices = np.delete(to_annotate_indices, hit)
# Remove annotated examples from unlabelled set
no_label_indices = no_label_indices[np.isin(no_label_indices,
low_conf_examples,
invert=True)]
logger.info(
"Moving following examples to labelled set:\n%s" %
"\n".join(train_examples[low_conf_examples].tolist())
)
# First make the update to input stage before
# commiting state change
train_input_labelled[low_conf_examples] = True
train_input.labelled = train_input_labelled
# Step 4: Update state information
labelled = np.append(labelled, low_conf_examples)
unlabelled = unlabelled[np.isin(unlabelled, low_conf_examples,
assume_unique=True, invert=True)]
state["dataset"]["train"]["filenames"] = train_examples.tolist()
state["dataset"]["train"]["labelled"] = labelled.tolist()
state["dataset"]["train"]["unlabelled"] = unlabelled.tolist()
state["iteration"] += 1
state["checkpoint"] = checkpoint_path
# Dump updated state
with open(state_filename, "w") as f:
json.dump(state, f, indent=2)
f.truncate()
return 0
class HelpfullParser(argparse.ArgumentParser):
# Prints help instead of usage string on error
def error(self, message):
self.print_help()
self.exit(2, "error: %s\n" % message)
def parse_arguments():
"""
Handles parseing of commandline arguments
:returns: The parsed commandline options
:rtype: argparse.Namespace
"""
# Required arguments
req_parser = argparse.ArgumentParser(add_help=False)
req_group = req_parser.add_argument_group(title="Required arguments")
req_group.add_argument(
"-d", "--data-dir",
required=True,
type=str,
dest="data_dir",
help="Path to dataset root directory"
)
req_group.add_argument(
"-l", "--log-dir",
required=True,
type=str,
dest="log_dir",
metavar="LOG_DIR",
help="Logdirectory for the session."
)
req_group.add_argument(
"-p", "--parameters",
required=True,
type=str,
dest="params",
metavar="PARAM_FILE",
help="Path to parameter configuration file, see conf subdirectory."
)
#Optional arguments
opt_parser = argparse.ArgumentParser(add_help=False)
opt_parser.add_argument(
"-c", "--checkpoint",
type=str,
dest="checkpoint", required=False,
metavar="CHECKPOINT",
help="Path to pretrained checkpoint directory or model."
)
opt_parser.add_argument(
"-r", "--reinitialize-output-layer",
action="store_true",
dest="reinitialize_output", required=False,
help="Reinitialize last layer of model (if checkpoint specified)."
)
opt_parser.add_argument(
"-u", "--unlabelled-dir",
type=str,
default=None,
dest="unlabelled",
metavar="UNLABELLED_GLOB",
help="Path to directory containing only feature data."
)
# Create parser hierarchy
# Top parser
top_parser = argparse.ArgumentParser(
usage="%s {cityscapes,freiburg,vistas} [-h/--help]"
% sys.argv[0])
# Dataset specific parsers inherits required arguments.
data_parsers = top_parser.add_subparsers(parser_class=HelpfullParser)
# Cityscapes dataset
cityscapes = data_parsers.add_parser(
"cityscapes",
usage="%s {cityscapes,freiburg} -d DATA_DIR -l LOG_DIR [options]"
% sys.argv[0],
parents=[req_parser,opt_parser],
conflict_handler="resolve",
help="The Cityscapes dataset.")
cityscapes.set_defaults(dataset="cityscapes")
cityscapes.add_argument("--use-coarse",
action="store_true",
required=False,
dest="coarse")
# Mapillary Vistas dataset
vistas = data_parsers.add_parser(
"vistas",
usage="%s {cityscapes,freiburg,vistas} -d DATA_DIR -l LOG_DIR [options]"
% sys.argv[0],
parents=[req_parser,opt_parser],
conflict_handler="resolve",
help="The Mapillary Vistas dataset.")
vistas.set_defaults(dataset="vistas")
# Freiburg forrest dataset
freiburg = data_parsers.add_parser(
"freiburg",
usage="%s {cityscapes,freiburg} -d DATA_DIR -l LOG_DIR [options]"
% sys.argv[0],
parents=[req_parser,opt_parser],
conflict_handler="resolve",
help="The Freiburg Forest dataset.")
freiburg.set_defaults(dataset="freiburg")
freiburg.add_argument("-m", "--modalities",
type=str,
nargs="+",
required=False,
default=[],
help="Path to Freiburg Forest root directory.")
if not "freiburg" in sys.argv and \
not "cityscapes" in sys.argv and \
not "vistas" in sys.argv:
top_parser.print_help()
sys.exit(0)
args = top_parser.parse_args()
return args
if __name__ == "__main__":
# Get and configure logger
logger = logging.getLogger(__name__)
with open("util/logging.json") as conf:
conf_dict = json.load(conf)
logging.config.dictConfig(conf_dict)
del conf_dict
args = parse_arguments()
# Load parameters
parameters = None
with open(args.params, "r") as f:
parameters = json.load(f)
# Overwrite with parameter dict
args.params = parameters
sys.exit(main(args, logger))
| 44.763636 | 95 | 0.516224 |
import argparse
import glob
import json
import logging
import logging.config
import os
import sys
import numpy as np
import tensorflow as tf
show_progress = False
try:
import tqdm
show_progress = True
except ImportError:
pass
try:
import tkinter
tkinter.Tk().withdraw()
except ImportError:
if args.unlabelled == None:
pass
else:
raise ImportError("Could not import tkinter, make sukre Tk "
"dependencies are installed")
except Exception as e:
print(e)
pass
import models
import datasets
import tensortools as tt
EPSILON = np.finfo(np.float32).tiny
def main(args, logger):
params = args.params
hparams = params["hyperparams"]
alparams = params["active_learning"]
state = None
state_filename = os.path.join(args.log_dir, "state.json")
config_filename = os.path.join(args.log_dir, "config.json")
if not os.path.exists(args.log_dir):
os.makedirs(args.log_dir)
with open(config_filename, "w+") as f:
json.dump(params, f, indent=4)
if args.dataset == "cityscapes":
dataset = datasets.Cityscapes(coarse=args.coarse)
test_examples_glob = os.path.join(args.data_dir, "val", "*.tfrecord")
elif args.dataset == "freiburg":
dataset = datasets.Freiburg()
test_examples_glob = os.path.join(args.data_dir, "test", "*.tfrecord")
elif args.dataset == "vistas":
dataset = datasets.Vistas()
test_examples_glob = os.path.join(args.data_dir, "val", "*.tfrecord")
else:
raise NotImplementedError("Dataset \"%s\" not supported" % args.dataset)
train_examples_glob = os.path.join(args.data_dir, "train", "*.tfrecord")
if not os.path.exists(state_filename):
train_val_examples = np.sort(np.array(glob.glob(train_examples_glob)))
val_examples = train_val_examples[:alparams["num_validation"]]
train_examples = train_val_examples[alparams["num_validation"]:]
test_examples = np.array(glob.glob(test_examples_glob))
train_indices = np.arange(len(train_examples), dtype=np.int32)
np.random.shuffle(train_indices)
initially_labelled = alparams["num_initially_labelled"]
if initially_labelled < 0:
initially_labelled = len(train_examples)
no_label_indices = np.empty(0, dtype=str)
if args.unlabelled is not None:
no_label_glob = os.path.join(args.unlabelled, "*.tfrecord")
no_label_examples = glob.glob(no_label_glob)
no_label_indices = np.arange(
len(train_indices), len(train_indices)+len(no_label_examples)
)
train_examples = np.concatenate(train_examples,
no_label_examples)
train_indices = np.concatenate((train_indices, no_label_indices))
labelled = train_indices[:initially_labelled]
unlabelled = train_indices[initially_labelled:]
del train_indices
state = {
"checkpoint" : None,
"iteration" : 0,
"dataset" : {
"train" : {
"filenames" : list(train_examples),
"labelled" : labelled.tolist(),
"unlabelled" : unlabelled.tolist(),
"no_label" : no_label_indices.tolist()
},
"val" : {
"filenames" : list(val_examples)
},
"test" : {
"filenames" : list(test_examples)
}
}
}
with open(state_filename, "w+") as f:
json.dump(state, f, indent=2)
else:
with open(state_filename, "r") as f:
state = json.load(f)
train_examples = np.array(state["dataset"]["train"]["filenames"])
val_examples = np.array(state["dataset"]["val"]["filenames"])
test_examples = np.array(state["dataset"]["test"]["filenames"])
labelled = np.array(state["dataset"]["train"]["labelled"])
unlabelled = np.array(state["dataset"]["train"]["unlabelled"])
no_label_indices = np.array(state["dataset"]["train"]["no_label"])
train_input_labelled = np.full_like(train_examples, False, dtype=bool)
train_input_labelled[labelled] = True
train_input_indices = np.arange(len(train_examples))
with tf.device("/device:CPU:0"):
with tf.name_scope("Datasets"):
train_input = tt.input.NumpyCapsule()
train_input.filenames = train_examples
train_input.labelled = train_input_labelled
train_input.indices = train_input_indices
val_input = tt.input.NumpyCapsule()
val_input.filenames = val_examples
test_input = tt.input.NumpyCapsule()
test_input.filenames = test_examples
train_input_stage = tt.input.InputStage(
input_shape=[params["network"]["input"]["height"],
params["network"]["input"]["width"]])
val_input_stage = tt.input.InputStage(
input_shape=[params["network"]["input"]["height"],
params["network"]["input"]["width"]])
train_input_stage.add_dataset_from_placeholders(
"train", train_input.filenames,
train_input.labelled, train_input.indices,
batch_size=params["batch_size"],
augment=True)
val_input_stage.add_dataset_from_placeholders(
"val", val_input.filenames,
batch_size=params["batch_size"])
val_input_stage.add_dataset_from_placeholders(
"test", test_input.filenames,
batch_size=params["batch_size"])
val_batches = (len(val_examples) - 1)//params["batch_size"] + 1
test_batches = (len(test_examples) - 1)//params["batch_size"] + 1
train_image_raw, train_image, train_label, train_mask, \
train_labelled, train_index = train_input_stage.get_output()
val_image, val_label, val_mask = val_input_stage.get_output()
with tf.variable_scope("StepCounters"):
global_step = tf.Variable(0, dtype=tf.int64,
trainable=False, name="GlobalStep")
local_step = tf.Variable(0, dtype=tf.int64,
trainable=False, name="LocalStep")
global_step_op = tf.assign_add(global_step, local_step)
epoch_step = tf.Variable(0, trainable=False, name="EpochStep")
epoch_step_inc = tf.assign_add(epoch_step, 1)
regularization = {"drop_rates": hparams["dropout_rates"]}
if hparams["weight_reg"]["L2"] > 0.0 \
or hparams["weight_reg"]["L1"] > 0.0:
regularization = {
"weight_regularization" : tf.keras.regularizers.l1_l2(
l1=hparams["weight_reg"]["L1"],
l2=hparams["weight_reg"]["L2"]),
"regularization_scaling" : hparams["weight_reg"]["glorot_scaling"],
}
train_net = models.ENet(
dataset.num_classes,
**regularization
)
val_net = models.ENet(dataset.num_classes)
with tf.device("/device:GPU:0"):
train_logits = train_net(train_image, training=True)
train_pred = tf.math.argmax(train_logits, axis=-1,
name="TrainPredictions")
with tf.name_scope("PseudoAnnotation"):
pseudo_logits = train_net(train_image_raw, training=False)
pseudo_logits = tf.stop_gradient(pseudo_logits)
pseudo_label = tf.math.argmax(pseudo_logits, axis=-1,
name="TrainPredictions")
pseudo_label = tf.cast(pseudo_label, tf.uint8)
pseudo_prob = tf.nn.softmax(pseudo_logits, axis=-1, name="TrainProb")
if alparams["measure"] == "entropy":
entropy = - pseudo_prob * tf.math.log(pseudo_prob+EPSILON)
entropy = tf.math.reduce_sum(entropy, axis=-1)
log_base = tf.math.log(np.float32(dataset.num_classes))
entropy = entropy / log_base
pseudo_confidence = 1.0 - entropy
elif alparams["measure"] == "margin":
values, indices = tf.math.top_k(pseudo_prob, k=2)
pseudo_confidence = values[:,:,:,0] - values[:,:,:,1]
elif alparams["measure"] == "confidence":
pseudo_confidence = tf.math.reduce_max(pseudo_prob, axis=-1)
else:
raise NotImplementedError("Uncertainty function not implemented.")
pseudo_mean_confidence = tf.reduce_mean(
tf.cast(pseudo_confidence, tf.float64),
axis=(1,2))
pseudo_mask = tf.where(tf.math.less(pseudo_confidence, alparams["threshold"]),
tf.zeros_like(pseudo_label,
dtype=train_label.dtype),
tf.ones_like(pseudo_label,
dtype=train_label.dtype))
train_label = tf.where(train_labelled, train_label,
pseudo_label, name="MaybeGenLabel")
train_mask = tf.where(train_labelled, train_mask,
pseudo_mask, name="MaybeGenMask")
with tf.device("/device:GPU:1"):
val_logits = val_net(val_image, training=False)
val_pred = tf.math.argmax(val_logits, axis=-1,
name="ValidationPredictions")
with tf.name_scope("Cost"):
with tf.device("/device:GPU:0"):
if hparams["softmax"]["multiscale"]:
loss, loss_weights = \
tt.losses.multiscale_masked_softmax_cross_entropy(
train_label,
train_net.endpoint_outputs[0],
train_mask, dataset.num_classes,
weight=hparams["softmax"]["loginverse_scaling"],
label_smoothing=hparams["softmax"]["label_smoothing"],
scope="XEntropy")
train_net.loss_scale_weights = loss_weights
else:
loss = tt.losses.masked_softmax_cross_entropy(
train_label,
train_logits,
train_mask, dataset.num_classes,
weight=hparams["softmax"]["loginverse_scaling"],
label_smoothing=hparams["softmax"]["label_smoothing"],
scope="XEntropy")
cost = loss
if len(train_net.losses) > 0:
regularization_loss = tf.math.add_n(train_net.losses, name="Regularization")
cost += tf.cast(regularization_loss, dtype=tf.float64)
learning_rate = hparams["learning_rate"]
if hparams["learning_rate_decay"] > 0.0:
learning_rate = tf.train.inverse_time_decay(
learning_rate, local_step,
decay_steps=train_batches,
decay_rate=hparams["learning_rate_decay"])
optimizer = tf.train.AdamOptimizer(learning_rate, **hparams["optimizer"]["kwargs"])
train_op = optimizer.minimize(cost, global_step=local_step,
name="TrainOp")
with tf.name_scope("Summary"):
colormap = tf.constant(dataset.colormap, dtype=tf.uint8,
name="Colormap")
with tf.device("/device:GPU:0"):
with tf.name_scope("TrainMetrics"):
train_metrics = tt.metrics.Metrics(train_pred, train_label,
dataset.num_classes, train_mask)
metric_update_op = train_metrics.get_update_op()
metric_summaries = train_metrics.get_summaries()
train_summary_iter = tf.summary.merge(
[
tf.summary.scalar("CrossEntropyLoss", loss,
family="Losses"),
tf.summary.scalar("TotalCost", cost,
family="Losses"),
tf.summary.scalar("LearningRate", learning_rate,
family="Losses")
], name="IterationSummaries"
)
with tf.control_dependencies([metric_update_op]):
train_summary_epoch = tf.summary.merge(
[
metric_summaries["Metrics"],
metric_summaries["ConfusionMat"]
], name="EpochSummaries"
)
train_image_summary = tf.summary.merge(
[
tf.summary.image(
"PseudoLabel/input",
train_image_raw,
family="PseudoLabel"
),
tf.summary.image(
"PseudoLabel/confidence",
tf.expand_dims(pseudo_confidence, axis=-1),
family="PseudoLabel"
),
tf.summary.image(
"PseudoLabel",
tf.gather(dataset.colormap,
tf.cast(pseudo_label*pseudo_mask \
+ (1 - pseudo_mask)*255,
tf.int32)),
family="PseudoLabel"
)
]
)
with tf.device("/device:GPU:1"):
with tf.name_scope("ValidationTestMetrics"):
val_metrics = tt.metrics.Metrics(val_pred, val_label,
dataset.num_classes, val_mask)
val_metric_update_op = val_metrics.get_update_op()
val_metric_summaries = val_metrics.get_summaries()
with tf.control_dependencies([val_metric_update_op]):
val_metric_summary = tf.summary.merge(
[
val_metric_summaries["Metrics"],
val_metric_summaries["ClassMetrics"],
val_metric_summaries["ConfusionMat"]
], name="EpochSummaries"
)
val_image_summary = tf.summary.merge(
[
tf.summary.image("Input", val_image),
tf.summary.image("Label", tf.gather(
colormap, tf.cast(val_label + 255*(1-val_mask),
tf.int32))),
tf.summary.image("Predictions", tf.gather(
colormap, tf.cast(val_pred, tf.int32)))
]
)
val_summary_epoch = val_metric_summary
test_summary_epoch = tf.summary.merge([
val_metric_summary,
val_image_summary
]
)
conf_summary_ph = tf.placeholder(tf.float64, shape=[None])
conf_summary = tf.summary.histogram("ConfidenceDistribution",
conf_summary_ph)
sess_config = tf.ConfigProto(allow_soft_placement=True)
sess_config.gpu_options.allow_growth = True
with tf.Session(config=sess_config) as sess:
logger.debug("Initializing variables...")
sess.run(tf.global_variables_initializer())
with tf.name_scope("Checkpoint"):
checkpoint = tf.train.Checkpoint(model=train_net,
epoch=epoch_step,
step=global_step,
optimizer=optimizer)
checkpoint_name = os.path.join(args.log_dir, "model")
if args.checkpoint is not None:
ckpt = args.checkpoint
if os.path.isdir(ckpt):
ckpt = tf.train.latest_checkpoint(ckpt)
if ckpt is None:
logger.error("Checkpoint path \"%s\" is invalid.")
return 1
logger.info("Resuming from checkpoint \"%s\"" % ckpt)
status = checkpoint.restore(ckpt)
if tf.__version__ < "1.14.0":
status.assert_existing_objects_matched()
else:
status.expect_partial()
status.initialize_or_restore(sess)
if args.reinitialize_output:
sess.run(train_net.Final.kernel.initializer)
elif state["checkpoint"] != None:
ckpt = state["checkpoint"]
logger.info("Resuming from checkpoint \"%s\"" % ckpt)
status = checkpoint.restore(ckpt)
if tf.__version__ < "1.14.0":
status.assert_existing_objects_matched()
else:
status.expect_partial()
status.initialize_or_restore(sess)
with tf.name_scope("UpdateValidationWeights"):
update_val_op = []
for i in range(len(val_net.layers)):
for j in range(len(val_net.layers[i].variables)):
update_val_op.append(
tf.assign(val_net.layers[i].variables[j],
train_net.layers[i].variables[j]))
update_val_op = tf.group(update_val_op)
ckpt_manager = tt.checkpoint_manager.CheckpointManager(checkpoint,
args.log_dir)
fetches = {
"train" : {
"iteration" : {
"step" : global_step_op,
"summary" : train_summary_iter,
"train_op" : train_op,
"update" : metric_update_op,
"updates" : train_net.updates
},
"epoch" : {
"step" : epoch_step,
"summary" : train_summary_epoch,
"summary/image" : train_image_summary
}
},
"val" : {
"iteration" : {
"update" : val_metric_update_op
},
"epoch" : {
"step" : epoch_step,
"MeanIoU" : val_metrics.metrics["MeanIoU"],
"summary" : val_summary_epoch,
"summary/image" : val_image_summary
}
},
"test" : {
"iteration" : {"update" : val_metric_update_op},
"epoch" : {"summary" : test_summary_epoch}
}
}
def train_loop(summary_writer):
_initial_grace_period = alparams["epochs/warm_up"]
best_ckpt = state["checkpoint"]
best_mean_iou = 0.0
log_subdir = summary_writer.get_logdir()
run_name = os.path.basename(log_subdir)
checkpoint_prefix = os.path.join(log_subdir, "model")
num_iter_per_epoch = np.maximum(train_input.size,
val_input.size)
no_improvement_count = 0
while no_improvement_count < params["epochs"] \
or _initial_grace_period >= 0:
_initial_grace_period -= 1
epoch = sess.run(epoch_step_inc)
_iter = range(0, num_iter_per_epoch, params["batch_size"])
if show_progress:
_iter = tqdm.tqdm(_iter, desc="%s[%d]" % (run_name, epoch),
dynamic_ncols=True,
ascii=True,
postfix={"NIC": no_improvement_count})
train_input_stage.init_iterator(
"train", sess, train_input.feed_dict)
val_input_stage.init_iterator(
"val", sess, val_input.feed_dict)
train_metrics.reset_metrics(sess)
val_metrics.reset_metrics(sess)
_fetches = {
"train" : {"iteration" : fetches["train"]["iteration"]},
"val" : {"iteration" : fetches["val"]["iteration"]}
}
sess.run(update_val_op)
try:
for i in _iter:
if train_input.size-params["batch_size"] <= i < train_input.size:
_fetches["train"]["epoch"] = fetches["train"]["epoch"]
if val_input.size-params["batch_size"] <= i < val_input.size:
_fetches["val"]["epoch"] = fetches["val"]["epoch"]
results = sess.run(_fetches)
if "train" in results.keys():
summary_writer.add_summary(
results["train"]["iteration"]["summary"],
results["train"]["iteration"]["step"])
if "epoch" in results["train"].keys():
summary_writer.add_summary(
results["train"]["epoch"]["summary"],
results["train"]["epoch"]["step"]
)
if results["train"]["epoch"]["step"] % 100 == 0:
summary_writer.add_summary(
results["train"]["epoch"]["summary/image"],
results["train"]["epoch"]["step"]
)
_fetches.pop("train")
if "val" in results.keys() and \
"epoch" in results["val"].keys():
summary_writer.add_summary(
results["val"]["epoch"]["summary"],
results["val"]["epoch"]["step"]
)
if results["val"]["epoch"]["step"] % 100 == 0:
summary_writer.add_summary(
results["val"]["epoch"]["summary/image"],
results["val"]["epoch"]["step"]
)
if results["val"]["epoch"]["MeanIoU"] > best_mean_iou:
best_mean_iou = results["val"]["epoch"]["MeanIoU"]
_ckpt_name = ckpt_manager.commit(
checkpoint_prefix, sess)
if _ckpt_name != "":
best_ckpt = _ckpt_name
no_improvement_count = 0
else:
no_improvement_count += 1
if no_improvement_count >= params["epochs"] and \
_initial_grace_period < 0:
_iter.close()
break
if show_progress:
_iter.set_postfix(NIC=no_improvement_count)
_fetches.pop("val")
except tf.errors.OutOfRangeError:
logger.error("Out of range error. Attempting to continue.")
pass
summary_writer.flush()
ckpt_manager.cache(sess)
return best_ckpt
def test_loop(summary_writer):
_step = len(labelled)
val_input_stage.init_iterator("test", sess, test_input.feed_dict)
_iter = range(0, test_input.size, params["batch_size"])
if show_progress:
_iter = tqdm.tqdm(_iter, desc="test[%d]" % (_step),
ascii=True,
dynamic_ncols=True)
summary_proto = None
val_metrics.reset_metrics(sess)
try:
for i in _iter:
if i < test_input.size - params["batch_size"]:
sess.run(fetches["test"]["iteration"]["update"])
else:
_, summary_proto = sess.run([fetches["test"]["iteration"]["update"],
fetches["test"]["epoch"]["summary"]])
except tf.errors.OutOfRangeError:
pass
summary_writer.add_summary(
summary_proto, _step
)
def rank_confidence():
num_examples = len(state["dataset"]["train"]["filenames"])
confidence = np.zeros(num_examples, dtype=np.float32)
train_input_stage.init_iterator("train", sess,
train_input.feed_dict)
_iter = range(0, train_input.size, params["batch_size"])
if show_progress:
_iter = tqdm.tqdm(_iter, desc="ranking[%d]" % len(labelled),
ascii=True,
dynamic_ncols=True)
try:
for i in _iter:
batch_confidence, batch_indices = sess.run(
[pseudo_mean_confidence, train_index])
confidence[batch_indices] = batch_confidence
except tf.errors.OutOfRangeError:
pass
unlabelled_confidence = confidence[unlabelled]
selection_size = np.minimum(len(unlabelled),
alparams["selection_size"])
example_indices = np.argpartition(unlabelled_confidence,
selection_size)
example_indices = example_indices[:selection_size]
low_conf_examples = unlabelled[example_indices]
return low_conf_examples, unlabelled_confidence
checkpoint_path = state["checkpoint"]
_graph = sess.graph if checkpoint_path == None else None
with tf.summary.FileWriter(args.log_dir, graph=_graph) as test_writer:
iterations = alparams["iterations"]
if iterations < 0:
iterations = np.ceil(len(unlabelled)
/ float(alparams["selection_size"]))
logger.info("Iteration count: %d" % iterations)
while state["iteration"] < iterations:
train_input.set_indices(labelled)
if state["iteration"] == 0:
log_subdir = os.path.join(args.log_dir, "pretrain")
else:
log_subdir = os.path.join(args.log_dir, "iter-%d" %
state["iteration"])
p = alparams["pseudo_labelling_proportion"]
sample_size = int(len(labelled)*p/(1-p))
sample_size = np.minimum(sample_size, len(unlabelled))
train_input.set_sample_size(sample_size)
if not os.path.exists(log_subdir):
os.mkdir(log_subdir)
# Change checkpoint manager directory
ckpt_manager.chdir(log_subdir)
with tf.summary.FileWriter(log_subdir) as train_val_writer:
# Enter train loop
try:
checkpoint_path = train_loop(train_val_writer)
except KeyboardInterrupt as exception:
# Quickly store state
if ckpt_manager.latest_checkpoint != "":
state["checkpoint"] = ckpt_manager.latest_checkpoint
with open(state_filename, "w") as f:
json.dump(state, f, indent=2)
f.truncate()
raise exception
# Reload best checkpoint
status = checkpoint.restore(checkpoint_path)
status.run_restore_ops(sess)
sess.run(update_val_op)
# Step 2: test_loop
if test_input.size > 0:
# This step may be omitted on deployment
test_loop(test_writer)
# Step 3: Find low confidence examples
# Reset train_input to use all examples for ranking
train_input.set_indices()
if alparams["selection_size"] > 0:
low_conf_examples, unlabelled_conf = rank_confidence()
_hist_summary = sess.run(conf_summary,
{conf_summary_ph:
unlabelled_conf})
test_writer.add_summary(_hist_summary, state["iteration"])
else:
# Draw examples randomly
selection_size = np.minimum(alparams["selection_size"],
len(unlabelled.tolist()))
if selection_size != 0:
low_conf_examples = np.random.choice(
unlabelled, np.abs(alparams["selection_size"]))
else:
low_conf_examples = []
# (maybe) Pause for user to annotate
to_annotate_indices = no_label_indices[np.isin(
no_label_indices, low_conf_examples)]
while len(to_annotate_indices) > 0:
to_annotate = train_examples[to_annotate_indices]
# Poll user for filenames of annotated examples
logger.info("Please annotate the following examples:\n%s" %
"\n".join(to_annotate_basename.tolist()))
filenames = tkinter.filedialog.askopenfilename(
multiple=1,
filetypes=(("TFRecord", "*.tfrecord"),))
hit = [] # List of matching filename indices
for filename in filenames:
basename = os.path.basename(filename)
idx = -1
for i in range(len(to_annotate)):
if to_annotate[i].endswith(basename):
idx = i
break
if idx != -1:
# Update state filenames
train_examples[to_annotate_indices[idx]] = filename
hit.append(idx)
else:
logger.info("Unrecognized filepath: %s" % filename)
# Remove matched paths
to_annotate_indices = np.delete(to_annotate_indices, hit)
# Remove annotated examples from unlabelled set
no_label_indices = no_label_indices[np.isin(no_label_indices,
low_conf_examples,
invert=True)]
logger.info(
"Moving following examples to labelled set:\n%s" %
"\n".join(train_examples[low_conf_examples].tolist())
)
# First make the update to input stage before
# commiting state change
train_input_labelled[low_conf_examples] = True
train_input.labelled = train_input_labelled
# Step 4: Update state information
labelled = np.append(labelled, low_conf_examples)
unlabelled = unlabelled[np.isin(unlabelled, low_conf_examples,
assume_unique=True, invert=True)]
state["dataset"]["train"]["filenames"] = train_examples.tolist()
state["dataset"]["train"]["labelled"] = labelled.tolist()
state["dataset"]["train"]["unlabelled"] = unlabelled.tolist()
state["iteration"] += 1
state["checkpoint"] = checkpoint_path
# Dump updated state
with open(state_filename, "w") as f:
json.dump(state, f, indent=2)
f.truncate()
return 0
class HelpfullParser(argparse.ArgumentParser):
# Prints help instead of usage string on error
def error(self, message):
self.print_help()
self.exit(2, "error: %s\n" % message)
def parse_arguments():
# Required arguments
req_parser = argparse.ArgumentParser(add_help=False)
req_group = req_parser.add_argument_group(title="Required arguments")
req_group.add_argument(
"-d", "--data-dir",
required=True,
type=str,
dest="data_dir",
help="Path to dataset root directory"
)
req_group.add_argument(
"-l", "--log-dir",
required=True,
type=str,
dest="log_dir",
metavar="LOG_DIR",
help="Logdirectory for the session."
)
req_group.add_argument(
"-p", "--parameters",
required=True,
type=str,
dest="params",
metavar="PARAM_FILE",
help="Path to parameter configuration file, see conf subdirectory."
)
#Optional arguments
opt_parser = argparse.ArgumentParser(add_help=False)
opt_parser.add_argument(
"-c", "--checkpoint",
type=str,
dest="checkpoint", required=False,
metavar="CHECKPOINT",
help="Path to pretrained checkpoint directory or model."
)
opt_parser.add_argument(
"-r", "--reinitialize-output-layer",
action="store_true",
dest="reinitialize_output", required=False,
help="Reinitialize last layer of model (if checkpoint specified)."
)
opt_parser.add_argument(
"-u", "--unlabelled-dir",
type=str,
default=None,
dest="unlabelled",
metavar="UNLABELLED_GLOB",
help="Path to directory containing only feature data."
)
# Create parser hierarchy
# Top parser
top_parser = argparse.ArgumentParser(
usage="%s {cityscapes,freiburg,vistas} [-h/--help]"
% sys.argv[0])
# Dataset specific parsers inherits required arguments.
data_parsers = top_parser.add_subparsers(parser_class=HelpfullParser)
# Cityscapes dataset
cityscapes = data_parsers.add_parser(
"cityscapes",
usage="%s {cityscapes,freiburg} -d DATA_DIR -l LOG_DIR [options]"
% sys.argv[0],
parents=[req_parser,opt_parser],
conflict_handler="resolve",
help="The Cityscapes dataset.")
cityscapes.set_defaults(dataset="cityscapes")
cityscapes.add_argument("--use-coarse",
action="store_true",
required=False,
dest="coarse")
# Mapillary Vistas dataset
vistas = data_parsers.add_parser(
"vistas",
usage="%s {cityscapes,freiburg,vistas} -d DATA_DIR -l LOG_DIR [options]"
% sys.argv[0],
parents=[req_parser,opt_parser],
conflict_handler="resolve",
help="The Mapillary Vistas dataset.")
vistas.set_defaults(dataset="vistas")
# Freiburg forrest dataset
freiburg = data_parsers.add_parser(
"freiburg",
usage="%s {cityscapes,freiburg} -d DATA_DIR -l LOG_DIR [options]"
% sys.argv[0],
parents=[req_parser,opt_parser],
conflict_handler="resolve",
help="The Freiburg Forest dataset.")
freiburg.set_defaults(dataset="freiburg")
freiburg.add_argument("-m", "--modalities",
type=str,
nargs="+",
required=False,
default=[],
help="Path to Freiburg Forest root directory.")
if not "freiburg" in sys.argv and \
not "cityscapes" in sys.argv and \
not "vistas" in sys.argv:
top_parser.print_help()
sys.exit(0)
args = top_parser.parse_args()
return args
if __name__ == "__main__":
# Get and configure logger
logger = logging.getLogger(__name__)
with open("util/logging.json") as conf:
conf_dict = json.load(conf)
logging.config.dictConfig(conf_dict)
del conf_dict
args = parse_arguments()
# Load parameters
parameters = None
with open(args.params, "r") as f:
parameters = json.load(f)
# Overwrite with parameter dict
args.params = parameters
sys.exit(main(args, logger))
| true | true |
f723a27ec3fd499b54564cfa6d995e4d8b617737 | 3,533 | py | Python | fullwavepy/config/logging.py | kmch/FullwavePy | 3c704b9b6ae2c6c585adb61e57991caf30ab240e | [
"MIT"
] | 2 | 2020-12-24T01:02:16.000Z | 2021-02-17T10:00:58.000Z | fullwavepy/config/logging.py | kmch/FullwavePy | 3c704b9b6ae2c6c585adb61e57991caf30ab240e | [
"MIT"
] | null | null | null | fullwavepy/config/logging.py | kmch/FullwavePy | 3c704b9b6ae2c6c585adb61e57991caf30ab240e | [
"MIT"
] | null | null | null | """
This is a configuration file for logs from FullwavePy modules.
The engine is the 'logging' module which is a part of the Python's
standard library.
Additionally, the 'autologging' module is used as a very convienient wrapper.
It allows to define a function's logger (it contains both the module's and
function's name, as defined in formatter), just by decorating this function
with @logged. It applies also to class methods ('instance methods' of classes,
to be precise) and it's done even more simply, by decorating the class as a whole.
What's more, it provides @traced decorator (works just like @logged)
that allows tracing the execution of the code without a need for
writing your own decorator (and logging from a function inside the
decorator definition is challenging anyway).
Notes
-----
Here we set a default level of a root logger, its two handlers (one for each
type of the standard streams and formatting of all messages.
List of the levels and their
corresponding numerical values:
50 CRITICAL
40 ERROR
30 WARN(ING)
20 INFO
10 DEBUG
1 TRACE
0 NOTSET
"""
from sys import stdout, stderr
from logging import StreamHandler, Formatter, getLogger,\
NOTSET, DEBUG, INFO, WARNING, ERROR, CRITICAL
from autologging import TRACE
# -------------------------------------------------------------------------------
# CONVENIENCE FUNCTIONS
# -------------------------------------------------------------------------------
def log_lvl(lvl):
logger = getLogger()
logger.setLevel(lvl)
def lll(lvl): # alias of above
log_lvl(lvl)
# -------------------------------------------------------------------------------
# FILTERS
# -------------------------------------------------------------------------------
class LevelFilter(object):
"""
Specify a custom logging filter to filter out
records with a level you don't need
Notes
-----
This is the format expected by
handler.addFilter()
Filters are used primarily to filter records
based on more sophisticated criteria than levels
"""
def __init__(self, level):
self.level = level
def filter(self, record):
return record.levelno != self.level
# -------------------------------------------------------------------------------
# FORMATTING OF MESSAGES
# -------------------------------------------------------------------------------
formatter = Formatter("%(levelname)s:%(name)s.%(funcName)s: %(message)s")
# -------------------------------------------------------------------------------
# LOGGERS (ONLY ROOT LOGGER HERE)
# -------------------------------------------------------------------------------
logger = getLogger()
logger.setLevel(INFO)
# -------------------------------------------------------------------------------
# HANDLERS
# -------------------------------------------------------------------------------
# REDIRECT TO STDERR FOR LVL >= WARN
h1 = StreamHandler(stream=stderr)
h1.setLevel(WARNING)
h1.setFormatter(formatter)
# REDIRECT TO STDOUT FOR LVL >= TRACE
h2 = StreamHandler(stream=stdout)
h2.setLevel(TRACE)
h2.setFormatter(formatter)
# EXCLUDE LEVELS HANDLED BY h1 TO PREVENT REDUNDANCY (DOUBLE MESSAGES)
h2.addFilter(LevelFilter(WARNING))
h2.addFilter(LevelFilter(ERROR))
# PUT TOGETHER
logger.handlers = [h1, h2]
# -------------------------------------------------------------------------------
# MUTE CHATTY MATPLOTLIB'S DEBUG. MESSAGES
# -------------------------------------------------------------------------------
mpl_logger = getLogger('matplotlib.pyplot')
mpl_logger.setLevel(WARNING) | 36.42268 | 82 | 0.546278 | from sys import stdout, stderr
from logging import StreamHandler, Formatter, getLogger,\
NOTSET, DEBUG, INFO, WARNING, ERROR, CRITICAL
from autologging import TRACE
def log_lvl(lvl):
logger = getLogger()
logger.setLevel(lvl)
def lll(lvl):
log_lvl(lvl)
class LevelFilter(object):
def __init__(self, level):
self.level = level
def filter(self, record):
return record.levelno != self.level
formatter = Formatter("%(levelname)s:%(name)s.%(funcName)s: %(message)s")
logger = getLogger()
logger.setLevel(INFO)
h1 = StreamHandler(stream=stderr)
h1.setLevel(WARNING)
h1.setFormatter(formatter)
h2 = StreamHandler(stream=stdout)
h2.setLevel(TRACE)
h2.setFormatter(formatter)
h2.addFilter(LevelFilter(WARNING))
h2.addFilter(LevelFilter(ERROR))
logger.handlers = [h1, h2]
# -------------------------------------------------------------------------------
mpl_logger = getLogger('matplotlib.pyplot')
mpl_logger.setLevel(WARNING) | true | true |
f723a2b3b507d5aa59428dd4f44057f7bbe3f655 | 3,368 | py | Python | youtube_dl/extractor/philharmoniedeparis.py | MOODesign/Youtube-videos-Download | 730c0d12a06f349907481570f1f2890251f7a181 | [
"Unlicense"
] | 7 | 2017-06-29T07:00:17.000Z | 2020-10-20T03:55:04.000Z | youtube_dl/extractor/philharmoniedeparis.py | MOODesign/Youtube-videos-Download | 730c0d12a06f349907481570f1f2890251f7a181 | [
"Unlicense"
] | 1 | 2019-01-24T09:33:42.000Z | 2019-01-24T09:33:42.000Z | youtube_dl/extractor/philharmoniedeparis.py | MOODesign/Youtube-videos-Download | 730c0d12a06f349907481570f1f2890251f7a181 | [
"Unlicense"
] | 2 | 2019-01-07T19:00:54.000Z | 2021-02-18T15:51:53.000Z | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
try_get,
urljoin,
)
class PhilharmonieDeParisIE(InfoExtractor):
IE_DESC = 'Philharmonie de Paris'
_VALID_URL = r'''(?x)
https?://
(?:
live\.philharmoniedeparis\.fr/(?:[Cc]oncert/|misc/Playlist\.ashx\?id=)|
pad\.philharmoniedeparis\.fr/doc/CIMU/
)
(?P<id>\d+)
'''
_TESTS = [{
'url': 'http://pad.philharmoniedeparis.fr/doc/CIMU/1086697/jazz-a-la-villette-knower',
'md5': 'a0a4b195f544645073631cbec166a2c2',
'info_dict': {
'id': '1086697',
'ext': 'mp4',
'title': 'Jazz à la Villette : Knower',
},
}, {
'url': 'http://live.philharmoniedeparis.fr/concert/1032066.html',
'info_dict': {
'id': '1032066',
'title': 'md5:0a031b81807b3593cffa3c9a87a167a0',
},
'playlist_mincount': 2,
}, {
'url': 'http://live.philharmoniedeparis.fr/Concert/1030324.html',
'only_matching': True,
}, {
'url': 'http://live.philharmoniedeparis.fr/misc/Playlist.ashx?id=1030324&track=&lang=fr',
'only_matching': True,
}]
_LIVE_URL = 'https://live.philharmoniedeparis.fr'
def _real_extract(self, url):
video_id = self._match_id(url)
config = self._download_json(
'%s/otoPlayer/config.ashx' % self._LIVE_URL, video_id, query={
'id': video_id,
'lang': 'fr-FR',
})
def extract_entry(source):
if not isinstance(source, dict):
return
title = source.get('title')
if not title:
return
files = source.get('files')
if not isinstance(files, dict):
return
format_urls = set()
formats = []
for format_id in ('mobile', 'desktop'):
format_url = try_get(
files, lambda x: x[format_id]['file'], compat_str)
if not format_url or format_url in format_urls:
continue
format_urls.add(format_url)
m3u8_url = urljoin(self._LIVE_URL, format_url)
formats.extend(self._extract_m3u8_formats(
m3u8_url, video_id, 'mp4', entry_protocol='m3u8_native',
m3u8_id='hls', fatal=False))
if not formats:
return
self._sort_formats(formats)
return {
'title': title,
'formats': formats,
}
thumbnail = urljoin(self._LIVE_URL, config.get('image'))
info = extract_entry(config)
if info:
info.update({
'id': video_id,
'thumbnail': thumbnail,
})
return info
entries = []
for num, chapter in enumerate(config['chapters'], start=1):
entry = extract_entry(chapter)
entry['id'] = '%s-%d' % (video_id, num)
entries.append(entry)
return self.playlist_result(entries, video_id, config.get('title'))
| 33.346535 | 99 | 0.509798 |
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
try_get,
urljoin,
)
class PhilharmonieDeParisIE(InfoExtractor):
IE_DESC = 'Philharmonie de Paris'
_VALID_URL = r'''(?x)
https?://
(?:
live\.philharmoniedeparis\.fr/(?:[Cc]oncert/|misc/Playlist\.ashx\?id=)|
pad\.philharmoniedeparis\.fr/doc/CIMU/
)
(?P<id>\d+)
'''
_TESTS = [{
'url': 'http://pad.philharmoniedeparis.fr/doc/CIMU/1086697/jazz-a-la-villette-knower',
'md5': 'a0a4b195f544645073631cbec166a2c2',
'info_dict': {
'id': '1086697',
'ext': 'mp4',
'title': 'Jazz à la Villette : Knower',
},
}, {
'url': 'http://live.philharmoniedeparis.fr/concert/1032066.html',
'info_dict': {
'id': '1032066',
'title': 'md5:0a031b81807b3593cffa3c9a87a167a0',
},
'playlist_mincount': 2,
}, {
'url': 'http://live.philharmoniedeparis.fr/Concert/1030324.html',
'only_matching': True,
}, {
'url': 'http://live.philharmoniedeparis.fr/misc/Playlist.ashx?id=1030324&track=&lang=fr',
'only_matching': True,
}]
_LIVE_URL = 'https://live.philharmoniedeparis.fr'
def _real_extract(self, url):
video_id = self._match_id(url)
config = self._download_json(
'%s/otoPlayer/config.ashx' % self._LIVE_URL, video_id, query={
'id': video_id,
'lang': 'fr-FR',
})
def extract_entry(source):
if not isinstance(source, dict):
return
title = source.get('title')
if not title:
return
files = source.get('files')
if not isinstance(files, dict):
return
format_urls = set()
formats = []
for format_id in ('mobile', 'desktop'):
format_url = try_get(
files, lambda x: x[format_id]['file'], compat_str)
if not format_url or format_url in format_urls:
continue
format_urls.add(format_url)
m3u8_url = urljoin(self._LIVE_URL, format_url)
formats.extend(self._extract_m3u8_formats(
m3u8_url, video_id, 'mp4', entry_protocol='m3u8_native',
m3u8_id='hls', fatal=False))
if not formats:
return
self._sort_formats(formats)
return {
'title': title,
'formats': formats,
}
thumbnail = urljoin(self._LIVE_URL, config.get('image'))
info = extract_entry(config)
if info:
info.update({
'id': video_id,
'thumbnail': thumbnail,
})
return info
entries = []
for num, chapter in enumerate(config['chapters'], start=1):
entry = extract_entry(chapter)
entry['id'] = '%s-%d' % (video_id, num)
entries.append(entry)
return self.playlist_result(entries, video_id, config.get('title'))
| true | true |
f723a2b48a33d76ae84708a264e274a605dbf1d0 | 247 | py | Python | ichor/profiles/serializers.py | AjithRamachandran/Ichor | 7e1ba9215792e3a7a1c07e07f1117d3d429127ee | [
"MIT"
] | null | null | null | ichor/profiles/serializers.py | AjithRamachandran/Ichor | 7e1ba9215792e3a7a1c07e07f1117d3d429127ee | [
"MIT"
] | null | null | null | ichor/profiles/serializers.py | AjithRamachandran/Ichor | 7e1ba9215792e3a7a1c07e07f1117d3d429127ee | [
"MIT"
] | null | null | null | from rest_framework.serializers import ModelSerializer
from profiles.models import Profile
class ProfileSerializer(ModelSerializer):
"""
Serializer for Profile.
"""
class Meta:
model = Profile
exclude = ('user',)
| 20.583333 | 54 | 0.688259 | from rest_framework.serializers import ModelSerializer
from profiles.models import Profile
class ProfileSerializer(ModelSerializer):
class Meta:
model = Profile
exclude = ('user',)
| true | true |
f723a367cba647286e35c63cc2eba00db244a58c | 1,323 | py | Python | tests/modisco/test_modisco_file.py | mlweilert/bpnet | dcc9e8d805f9de774ae9dcc62c20504915be614f | [
"MIT"
] | 93 | 2019-08-15T19:49:19.000Z | 2022-03-04T08:23:44.000Z | tests/modisco/test_modisco_file.py | mlweilert/bpnet | dcc9e8d805f9de774ae9dcc62c20504915be614f | [
"MIT"
] | 29 | 2019-08-15T15:44:44.000Z | 2022-03-28T06:56:07.000Z | tests/modisco/test_modisco_file.py | mlweilert/bpnet | dcc9e8d805f9de774ae9dcc62c20504915be614f | [
"MIT"
] | 24 | 2019-08-29T18:54:36.000Z | 2022-03-23T21:04:46.000Z | """Test ModiscoFile
"""
import pandas as pd
from bpnet.modisco.files import ModiscoFile, ModiscoFileGroup
from bpnet.modisco.core import Pattern, Seqlet
def test_modisco_file(mf, contrib_file):
# contrib_file required for `mf.get_ranges()`
assert len(mf.patterns()) > 0
p = mf.get_pattern("metacluster_0/pattern_0")
assert isinstance(p, Pattern)
assert len(mf.patterns()) > 0
assert isinstance(mf.patterns()[0], Pattern)
assert len(mf.pattern_names()) > 0
assert isinstance(mf.pattern_names()[0], str)
assert mf.tasks() == ['Oct4/profile/wn']
assert 'patterns' in mf.stats()
assert isinstance(mf.seqlet_df_instances(), pd.DataFrame)
assert mf.n_seqlets("metacluster_0/pattern_0") > 0
assert isinstance(mf.load_ranges(), pd.DataFrame)
assert isinstance(mf.seqlets()['metacluster_0/pattern_0'][0], Seqlet)
def test_modisco_file_group(mfg):
p = mfg.get_pattern("Oct4/metacluster_0/pattern_0")
assert isinstance(p, Pattern)
assert len(mfg.patterns()) > 0
assert isinstance(mfg.patterns()[0], Pattern)
assert len(mfg.pattern_names()) > 0
assert isinstance(mfg.pattern_names()[0], str)
assert mfg.tasks() == ['Oct4/profile/wn'] # since we used two times the Oct4 task
assert mfg.n_seqlets("Oct4/metacluster_0/pattern_0") > 0
| 29.4 | 86 | 0.70446 | import pandas as pd
from bpnet.modisco.files import ModiscoFile, ModiscoFileGroup
from bpnet.modisco.core import Pattern, Seqlet
def test_modisco_file(mf, contrib_file):
assert len(mf.patterns()) > 0
p = mf.get_pattern("metacluster_0/pattern_0")
assert isinstance(p, Pattern)
assert len(mf.patterns()) > 0
assert isinstance(mf.patterns()[0], Pattern)
assert len(mf.pattern_names()) > 0
assert isinstance(mf.pattern_names()[0], str)
assert mf.tasks() == ['Oct4/profile/wn']
assert 'patterns' in mf.stats()
assert isinstance(mf.seqlet_df_instances(), pd.DataFrame)
assert mf.n_seqlets("metacluster_0/pattern_0") > 0
assert isinstance(mf.load_ranges(), pd.DataFrame)
assert isinstance(mf.seqlets()['metacluster_0/pattern_0'][0], Seqlet)
def test_modisco_file_group(mfg):
p = mfg.get_pattern("Oct4/metacluster_0/pattern_0")
assert isinstance(p, Pattern)
assert len(mfg.patterns()) > 0
assert isinstance(mfg.patterns()[0], Pattern)
assert len(mfg.pattern_names()) > 0
assert isinstance(mfg.pattern_names()[0], str)
assert mfg.tasks() == ['Oct4/profile/wn']
assert mfg.n_seqlets("Oct4/metacluster_0/pattern_0") > 0
| true | true |
f723a3dd143e7cc78b748e8d9c65d4d8b984a35a | 371 | py | Python | tweet/migrations/0002_alter_tweet_date.py | cannibalcheeseburger/Tweet-Sentiment-Analysis | c53faa5d200ed62be8b127731bf54c4e6575db06 | [
"MIT"
] | null | null | null | tweet/migrations/0002_alter_tweet_date.py | cannibalcheeseburger/Tweet-Sentiment-Analysis | c53faa5d200ed62be8b127731bf54c4e6575db06 | [
"MIT"
] | null | null | null | tweet/migrations/0002_alter_tweet_date.py | cannibalcheeseburger/Tweet-Sentiment-Analysis | c53faa5d200ed62be8b127731bf54c4e6575db06 | [
"MIT"
] | null | null | null | # Generated by Django 3.2.9 on 2021-11-02 04:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tweet', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='tweet',
name='date',
field=models.CharField(max_length=100),
),
]
| 19.526316 | 51 | 0.58221 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tweet', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='tweet',
name='date',
field=models.CharField(max_length=100),
),
]
| true | true |
f723a3ffd6fafcd5ace0293aaf403490962ca8c7 | 2,941 | py | Python | app/models.py | MosesOpiyo/PitchBook | 39b763881b6c5a85c3e4f4d3ecf1ca18c5658f30 | [
"Unlicense"
] | null | null | null | app/models.py | MosesOpiyo/PitchBook | 39b763881b6c5a85c3e4f4d3ecf1ca18c5658f30 | [
"Unlicense"
] | null | null | null | app/models.py | MosesOpiyo/PitchBook | 39b763881b6c5a85c3e4f4d3ecf1ca18c5658f30 | [
"Unlicense"
] | null | null | null | from sqlalchemy.orm import backref
from werkzeug.security import generate_password_hash,check_password_hash
from flask_login import UserMixin,current_user
from app import db
from . import login_manager
@login_manager.user_loader
def load_user(id):
return User.query.get(id)
class Pitch(db.Model):
__tablename__= 'pitches'
id = db.Column(db.Integer,primary_key = True)
description = db.Column(db.String(), index = True)
title = db.Column(db.String())
category = db.Column(db.String(255), nullable=False)
user_id = db.Column(db.Integer,db.ForeignKey('users.id'))
comments_id = db.relationship('Comment',backref='comment',lazy = 'dynamic')
def save_pitches(self):
db.session.add(self)
db.session.commit()
@classmethod
def get_pitches(cls, id):
pitches = Pitch.query.order_by(pitch_id=id).desc().all()
return pitches
def __repr__(self):
return f'Pitch {self.description}'
class Upvote(db.Model):
__tablename__ = 'upvotes'
id = db.Column(db.Integer, primary_key = True)
upvote = db.Column(db.Integer, default = 1)
pitch_id = db.Column(db.Integer, db.ForeignKey('pitches.id'))
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
def save_upvotes(self):
db.session.add(self)
db.session.commit()
def add_upvotes(cls,id):
upvote_pitch = Upvote(user = current_user, pitch_id=id)
upvote_pitch.save_upvotes()
@classmethod
def get_upvotes(cls, id):
upvote = Upvote.query.filter_by(pitch_id=id).all()
return upvote
@classmethod
def get_all_upvotes(cls, pitch_id):
upvotes = Upvote.query.order_by('id').all()
return upvotes
def __repr__(self):
return f'{self.user_id}: {self.pitch_id}'
class User(UserMixin,db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer,primary_key = True)
username = db.Column(db.String(255))
pass_secure = db.Column(db.String(255))
email = db.Column(db.String(255),unique = True,index = True)
bio = db.Column(db.String(255))
profile_pic_path = db.Column(db.String())
pitch = db.relationship('Pitch',backref = 'pitch', lazy = 'dynamic')
@property
def password(self):
raise AttributeError('You cannot read the password attribute')
@password.setter
def password(self, password):
self.pass_secure = generate_password_hash(password)
def verify_password(self,password):
return check_password_hash(self.pass_secure,password)
def __repr__(self):
return f'User {self.username}'
class Comment(db.Model):
__tablename__ = 'comments'
id = db.Column(db.Integer, primary_key = True)
description = db.Column(db.Text)
pitch_id = db.Column(db.Integer,db.ForeignKey('pitches.id'))
def __repr__(self):
return f'Comment : id: {self.id} comment: {self.description}'
| 28.553398 | 79 | 0.6712 | from sqlalchemy.orm import backref
from werkzeug.security import generate_password_hash,check_password_hash
from flask_login import UserMixin,current_user
from app import db
from . import login_manager
@login_manager.user_loader
def load_user(id):
return User.query.get(id)
class Pitch(db.Model):
__tablename__= 'pitches'
id = db.Column(db.Integer,primary_key = True)
description = db.Column(db.String(), index = True)
title = db.Column(db.String())
category = db.Column(db.String(255), nullable=False)
user_id = db.Column(db.Integer,db.ForeignKey('users.id'))
comments_id = db.relationship('Comment',backref='comment',lazy = 'dynamic')
def save_pitches(self):
db.session.add(self)
db.session.commit()
@classmethod
def get_pitches(cls, id):
pitches = Pitch.query.order_by(pitch_id=id).desc().all()
return pitches
def __repr__(self):
return f'Pitch {self.description}'
class Upvote(db.Model):
__tablename__ = 'upvotes'
id = db.Column(db.Integer, primary_key = True)
upvote = db.Column(db.Integer, default = 1)
pitch_id = db.Column(db.Integer, db.ForeignKey('pitches.id'))
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
def save_upvotes(self):
db.session.add(self)
db.session.commit()
def add_upvotes(cls,id):
upvote_pitch = Upvote(user = current_user, pitch_id=id)
upvote_pitch.save_upvotes()
@classmethod
def get_upvotes(cls, id):
upvote = Upvote.query.filter_by(pitch_id=id).all()
return upvote
@classmethod
def get_all_upvotes(cls, pitch_id):
upvotes = Upvote.query.order_by('id').all()
return upvotes
def __repr__(self):
return f'{self.user_id}: {self.pitch_id}'
class User(UserMixin,db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer,primary_key = True)
username = db.Column(db.String(255))
pass_secure = db.Column(db.String(255))
email = db.Column(db.String(255),unique = True,index = True)
bio = db.Column(db.String(255))
profile_pic_path = db.Column(db.String())
pitch = db.relationship('Pitch',backref = 'pitch', lazy = 'dynamic')
@property
def password(self):
raise AttributeError('You cannot read the password attribute')
@password.setter
def password(self, password):
self.pass_secure = generate_password_hash(password)
def verify_password(self,password):
return check_password_hash(self.pass_secure,password)
def __repr__(self):
return f'User {self.username}'
class Comment(db.Model):
__tablename__ = 'comments'
id = db.Column(db.Integer, primary_key = True)
description = db.Column(db.Text)
pitch_id = db.Column(db.Integer,db.ForeignKey('pitches.id'))
def __repr__(self):
return f'Comment : id: {self.id} comment: {self.description}'
| true | true |
f723a519380fc18f05ede2c6042c2a5cae6b4fa6 | 54,000 | py | Python | src/spaceone/inventory/model/applicationgateway/data.py | jean1042/plugin-azure-cloud-services | 3a75a516c9a4d1e8a4962988934ead3fd40e8494 | [
"Apache-2.0"
] | 1 | 2020-12-08T11:59:54.000Z | 2020-12-08T11:59:54.000Z | src/spaceone/inventory/model/applicationgateway/data.py | jean1042/plugin-azure-cloud-services | 3a75a516c9a4d1e8a4962988934ead3fd40e8494 | [
"Apache-2.0"
] | 4 | 2021-01-26T10:43:37.000Z | 2021-12-17T10:13:33.000Z | src/spaceone/inventory/model/applicationgateway/data.py | jean1042/plugin-azure-cloud-services | 3a75a516c9a4d1e8a4962988934ead3fd40e8494 | [
"Apache-2.0"
] | 2 | 2021-01-13T03:24:05.000Z | 2021-01-19T07:25:45.000Z | from schematics import Model
from schematics.types import ModelType, ListType, StringType, IntType, BooleanType, NumberType, DateTimeType, \
TimestampType, UTCDateTimeType, TimedeltaType, FloatType
class Tags(Model):
key = StringType(serialize_when_none=False)
value = StringType(serialize_when_none=False)
class SubResource(Model):
id = StringType()
class ApplicationGatewayAuthenticationCertificate(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
data = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayAutoscaleConfiguration(Model):
max_capacity = IntType(serialize_when_none=False)
min_capacity = IntType(serialize_when_none=False)
class ManagedServiceIdentity(Model):
principal_id = StringType(serialize_when_none=False)
tenant_id = StringType(serialize_when_none=False)
type = StringType(choices=('None', 'SystemAssigned', 'SystemAssigned, UserAssigned', 'UserAssigned'), serialize_when_none=False)
user_assigned_identities = StringType(serialize_when_none=False)
class ApplicationGatewayBackendAddress(Model):
fqdn = StringType(serialize_when_none=False)
ip_address = StringType(serialize_when_none=False)
###### Firewall Classes ######
class AzureFirewallRCAction(Model):
type = StringType(choices=('Allow', 'Deny'), serialize_when_none=False)
class AzureFirewallApplicationRuleProtocol(Model):
port = IntType(serialize_when_none=False)
protocol_type = StringType(choices=('Http', 'Https', 'Mssql'), serialize_when_none=False)
class AzureFirewallApplicationRule(Model):
description = StringType(serialize_when_none=False)
fqdn_tags = ListType(StringType, serialize_when_none=False)
name = StringType(serialize_when_none=False)
protocols = ListType(ModelType(AzureFirewallApplicationRuleProtocol), serialize_when_none=False)
source_addresses = ListType(StringType, serialize_when_none=False)
source_ip_groups = ListType(StringType, serialize_when_none=False)
target_fqdns = ListType(StringType, serialize_when_none=False)
class AzureFirewallApplicationRuleCollection(Model):
etag = StringType()
id = StringType()
name = StringType(serialize_when_none=False)
action = ModelType(AzureFirewallRCAction, serialize_when_none=False)
priority = IntType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
rules = ListType(ModelType(AzureFirewallApplicationRule), serialize_when_none=False)
class AzureFirewallIPConfiguration(Model):
etag = StringType()
id = StringType()
name = StringType(serialize_when_none=False)
private_ip_address = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
public_ip_address = ModelType(SubResource, serialize_when_none=False)
subnet = ModelType(SubResource, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class AzureFirewallPublicIPAddress(Model):
address = StringType(serialize_when_none=False)
class HubPublicIPAddresses(Model):
address = ListType(ModelType(AzureFirewallPublicIPAddress), serialize_when_none=False)
count = IntType(serialize_when_none=False)
class HubIPAddresses(Model):
private_ip_address = StringType(serialize_when_none=False)
public_ips = ModelType(HubPublicIPAddresses, serialize_when_none=False)
class AzureFirewallIpGroups(Model):
change_number = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
class AzureFirewallNatRule(Model):
description = StringType(serialize_when_none=False)
destination_addresses = ListType(StringType, serialize_when_none=False)
destination_ports = ListType(StringType, serialize_when_none=False)
name = StringType(serialize_when_none=False)
protocols = ListType(StringType, serialize_when_none=False)
source_addresses = ListType(StringType, serialize_when_none=False)
source_ip_groups = ListType(StringType, serialize_when_none=False)
translated_address = StringType(serialize_when_none=False)
translated_fqdn = StringType(serialize_when_none=False)
translated_port = StringType(serialize_when_none=False)
class AzureFirewallNetworkRule(Model):
description = StringType(serialize_when_none=False)
destination_addresses = ListType(StringType, serialize_when_none=False)
destination_ports = ListType(StringType, serialize_when_none=False)
destination_fqdns = ListType(StringType, serialize_when_none=False)
destination_ip_groups = ListType(StringType, serialize_when_none=False)
name = StringType(serialize_when_none=False)
protocols = ListType(StringType, serialize_when_none=False)
source_addresses = ListType(StringType, serialize_when_none=False)
source_ip_groups = ListType(StringType, serialize_when_none=False)
translated_address = StringType(serialize_when_none=False)
translated_fqdn = StringType(serialize_when_none=False)
translated_port = StringType(serialize_when_none=False)
class AzureFirewallNatRuleCollection(Model):
etag = StringType()
id = StringType()
name = StringType(serialize_when_none=False)
action = StringType(choices=('Dnat', 'Snat'), serialize_when_none=False)
priority = IntType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
rules = ListType(ModelType(AzureFirewallNatRule), serialize_when_none=False)
class AzureFirewallNetworkRuleCollection(Model):
etag = StringType()
id = StringType()
name = StringType(serialize_when_none=False)
action = ModelType(AzureFirewallRCAction, serialize_when_none=False)
priority = IntType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
rules = ListType(ModelType(AzureFirewallNetworkRule), serialize_when_none=False)
class AzureFirewallSku(Model):
name = StringType(choices=('AZFW_Hub', 'AZFW_VNet'), serialize_when_none=False)
tier = StringType(choices=('Premium', 'Standard'), serialize_when_none=False)
class AzureFirewall(Model):
etag = StringType()
id = StringType()
location = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
subnet = StringType(serialize_when_none=False)
application_rule_collections = ListType(ModelType(AzureFirewallApplicationRuleCollection), serialize_when_none=False)
firewall_policy = ModelType(SubResource, serialize_when_none=False)
hub_ip_addresses = ModelType(HubIPAddresses, serialize_when_none=False)
ip_configurations = ListType(ModelType(AzureFirewallIPConfiguration), serialize_when_none=False)
ip_groups = ListType(ModelType(AzureFirewallIpGroups), serialize_when_none=False)
management_ip_configuration = ModelType(AzureFirewallIPConfiguration, serialize_when_none=False)
nat_rule_collections = ListType(ModelType(AzureFirewallNatRuleCollection), serialize_when_none=False)
network_rule_collections = ListType(ModelType(AzureFirewallNetworkRuleCollection), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
sku = ModelType(AzureFirewallSku, serialize_when_none=False)
threat_intel_mode = StringType(choices=('Alert', 'Deny', 'Off'), serialize_when_none=False)
virtual_hub = ModelType(SubResource, serialize_when_none=False)
tags = ModelType(Tags, serialize_when_none=False)
type = StringType(serialize_when_none=False)
zones = ListType(StringType, serialize_when_none=False)
class ExtendedLocation(Model):
name = StringType(serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationSecurityGroup(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
location = ModelType(ExtendedLocation, serialize_when_none=False)
name = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
resource_guid = StringType(serialize_when_none=False)
tags = ModelType(Tags, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class NetworkInterfaceIPConfigurationPrivateLinkConnectionProperties(Model):
fqdns = ListType(StringType, serialize_when_none=False)
group_id = StringType(serialize_when_none=False)
required_member_name = StringType(serialize_when_none=False)
class DdosSettings(Model):
ddos_custom_policy = ModelType(SubResource, serialize_when_none=False)
protected_ip = BooleanType(serialize_when_none=False)
protection_coverage = StringType(choices=('Basic', 'Standard'), serialize_when_none=False)
class PublicIPAddressDnsSettings(Model):
domain_name_label = StringType(serialize_when_none=False)
fqdn = StringType(serialize_when_none=False)
reverse_fqdn = StringType(serialize_when_none=False)
class IPConfiguration(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
private_ip_address = StringType(serialize_when_none=False)
public_ip_allocation_method = StringType(choices=('Dynamic', 'Static'), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
public_ip_address = StringType(serialize_when_none=False) # Change to PublicIPAddress ID
subnet = StringType(serialize_when_none=False)
class IpTag(Model):
ip_tag_type = StringType(serialize_when_none=False)
tag = StringType(serialize_when_none=False)
class NatGatewaySku(Model):
name = StringType(choices=('Standard', None), serialize_when_none=False)
class NatGateway(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
location = ModelType(ExtendedLocation, serialize_when_none=False)
idle_timeout_in_minutes = IntType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
public_ip_addresses = ListType(ModelType(SubResource), serialize_when_none=False)
public_ip_prefixes = ListType(ModelType(SubResource), serialize_when_none=False)
resource_guid = StringType(serialize_when_none=False)
subnets = ListType(ModelType(SubResource), serialize_when_none=False)
sku = ModelType(NatGatewaySku, serialize_when_none=False)
tags = ModelType(Tags, serialize_when_none=False)
type = StringType(serialize_when_none=False)
zones = ListType(StringType, serialize_when_none=False)
class PublicIPAddressSku(Model):
name = StringType(choices=('Basic', 'Standard'), serialize_when_none=False)
tier = StringType(choices=('Global', 'Regional'), serialize_when_none=False)
class PublicIPAddress(Model):
etag = StringType(serialize_when_none=False)
extended_location = ModelType(ExtendedLocation, serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
location = StringType(serialize_when_none=False)
ddos_settings = ModelType(DdosSettings, serialize_when_none=False)
dns_settings = ModelType(PublicIPAddressDnsSettings, serialize_when_none=False)
idle_timeout_in_minutes = IntType(serialize_when_none=False)
ip_address = StringType(serialize_when_none=False)
ip_configuration = ModelType(IPConfiguration, serialize_when_none=False)
ip_tags = ListType(ModelType(IpTag), serialize_when_none=False)
migration_phase = StringType(choices=('Abort', 'Commit', 'Committed', 'None', 'Prepare'), serialize_when_none=False)
nat_gateway = ModelType(NatGateway, serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
public_ip_address_version = StringType(choices=('IPv4', 'IPv6'), serialize_when_none=False)
public_ip_allocation_method = StringType(choices=('Dynamic', 'Static'), serialize_when_none=False)
public_ip_prefix = ModelType(SubResource, serialize_when_none=False)
resource_guid = StringType(serialize_when_none=False)
sku = ModelType(PublicIPAddressSku, serialize_when_none=False)
tags = ModelType(Tags, serialize_when_none=False)
type = StringType(serialize_when_none=False)
zones = ListType(StringType, serialize_when_none=False)
class Delegation(Model):
etag = StringType(serialize_when_none=False)
id = StringType()
name = StringType(default='-', serialize_when_none=False)
actions = ListType(StringType, serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
service_name = StringType(serialize_when_none=False)
type = StringType(serialize_when_none=False)
class IPConfigurationProfile(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
subnet = StringType(serialize_when_none=False) # Change to Subnet ID
type = StringType(serialize_when_none=False)
class SecurityRule(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
access = StringType(choices=('Allow', 'Deny'), serialize_when_none=False)
description = StringType(serialize_when_none=False)
destination_address_prefix = StringType(serialize_when_none=False)
destination_address_prefixes = ListType(StringType, serialize_when_none=False)
destination_application_security_groups = ListType(ModelType(ApplicationSecurityGroup), serialize_when_none=False)
destination_port_range = StringType(serialize_when_none=False)
destination_port_ranges = ListType(StringType, serialize_when_none=False)
direction = StringType(choices=('Inbound', 'Outbound'), serialize_when_none=False)
priority = IntType(serialize_when_none=False)
protocol = StringType(choices=('*', 'Ah', 'Esp', 'Icmp', 'Tcp', 'Udp'), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
source_address_prefix = StringType(serialize_when_none=False)
source_address_prefixes = ListType(StringType, serialize_when_none=False)
source_application_security_groups = ListType(ModelType(ApplicationSecurityGroup), serialize_when_none=False)
source_port_range = StringType(serialize_when_none=False)
source_port_ranges = ListType(StringType, serialize_when_none=False)
class RetentionPolicyParameters(Model):
days = IntType(serialize_when_none=False)
enabled = BooleanType(serialize_when_none=False)
class TrafficAnalyticsConfigurationProperties(Model):
enabled = BooleanType(serialize_when_none=False)
traffic_analytics_interval = IntType(serialize_when_none=False)
workspace_id = StringType(serialize_when_none=False)
workspace_region = StringType(serialize_when_none=False)
workspace_resource_id = StringType(serialize_when_none=False)
class TrafficAnalyticsProperties(Model):
network_watcher_flow_analytics_configuration = ModelType(TrafficAnalyticsConfigurationProperties,
serialize_when_none=False)
class FlowLogFormatType(Model):
json = StringType(serialize_when_none=False)
class FlowLogFormatParameters(Model):
type = ModelType(FlowLogFormatType, serialize_when_none=False)
version = IntType(serialize_when_none=False)
class FlowLog(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
location = ModelType(ExtendedLocation, serialize_when_none=False)
name = StringType(serialize_when_none=False)
enable = BooleanType(serialize_when_none=False)
flow_analytics_configuration = ModelType(TrafficAnalyticsProperties, serialize_when_none=False)
format = ModelType(FlowLogFormatParameters, serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
retention_policy = ModelType(RetentionPolicyParameters, serialize_when_none=False)
storage_id = StringType(serialize_when_none=False)
target_resource_guid = StringType(serialize_when_none=False)
target_resource_id = StringType(serialize_when_none=False)
tags = ModelType(Tags, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class SecurityRule(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
access = StringType(choices=('Allow', 'Deny'), serialize_when_none=False)
description = StringType(serialize_when_none=False)
destination_address_prefix = StringType(serialize_when_none=False)
destination_address_prefixes = ListType(StringType, serialize_when_none=False)
destination_application_security_groups = ListType(ModelType(ApplicationSecurityGroup), serialize_when_none=False)
destination_port_range = StringType(serialize_when_none=False)
destination_port_ranges = ListType(StringType, serialize_when_none=False)
direction = StringType(choices=('Inbound', 'Outbound'), serialize_when_none=False)
priority = IntType(serialize_when_none=False)
protocol = StringType(choices=('*', 'Ah', 'Esp', 'Icmp', 'Tcp', 'Udp'), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
source_address_prefix = StringType(serialize_when_none=False)
source_address_prefixes = ListType(StringType, serialize_when_none=False)
source_application_security_groups = ListType(ModelType(ApplicationSecurityGroup), serialize_when_none=False)
source_port_range = StringType(serialize_when_none=False)
source_port_ranges = ListType(StringType, serialize_when_none=False)
class NetworkSecurityGroup(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
location = ModelType(ExtendedLocation, serialize_when_none=False)
name = StringType(default='-', serialize_when_none=False)
default_security_rules = ListType(ModelType(SecurityRule), serialize_when_none=False)
flow_logs = ListType(ModelType(FlowLog), serialize_when_none=False)
network_interfaces = StringType(serialize_when_none=False) # Change to Network interfaces' Id
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
resource_guid = StringType(serialize_when_none=False)
security_rules = ListType(ModelType(SecurityRule), serialize_when_none=False)
subnets = ListType(StringType, serialize_when_none=False) # Change to Subnet IDs
tags = ModelType(Tags, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class CustomDnsConfigPropertiesFormat(Model):
fqdn = StringType(serialize_when_none=False)
ip_addresses = ListType(StringType, serialize_when_none=False)
class PrivateLinkServiceConnectionState(Model):
actions_required = StringType(serialize_when_none=False)
description = StringType(serialize_when_none=False)
status = StringType(serialize_when_none=False)
class PrivateLinkServiceConnection(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
group_ids = ListType(StringType, serialize_when_none=False)
private_link_service_connection_state = ModelType(PrivateLinkServiceConnectionState, serialize_when_none=False)
private_link_service_id = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
request_message = StringType(serialize_when_none=False)
type = StringType(serialize_when_none=False)
class PrivateEndpoint(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
location = ModelType(ExtendedLocation, serialize_when_none=False)
extended_location = ModelType(ExtendedLocation, serialize_when_none=False)
name = StringType(serialize_when_none=False)
custom_dns_configs = ListType(ModelType(CustomDnsConfigPropertiesFormat), serialize_when_none=False)
manual_private_link_service_connections = ListType(ModelType(PrivateLinkServiceConnection),
serialize_when_none=False)
network_interfaces = ListType(StringType, serialize_when_none=False) # Change to network interface ids
private_link_service_connections = ListType(ModelType(PrivateLinkServiceConnection), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
subnet = StringType(serialize_when_none=False)
resource_group = StringType(serialize_when_none=False)
tags = ModelType(Tags, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ResourceNavigationLink(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
link = StringType(serialize_when_none=False)
linked_resource_type = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class Route(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
address_prefix = StringType(serialize_when_none=False)
next_hop_ip_address = StringType(serialize_when_none=False)
next_hop_type = StringType(choices=('Internet', 'None', 'VirtualAppliance', 'VirtualNetworkGateway', 'VnetLocal'),
serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
class RouteTable(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
location = ModelType(ExtendedLocation, serialize_when_none=False)
disable_bgp_route_propagation = BooleanType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
routes = ListType(ModelType(Route), serialize_when_none=False)
subnets = ListType(StringType, default=[], serialize_when_none=False)
tags = ModelType(Tags, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ServiceAssociationLink(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
allow_delete = BooleanType(serialize_when_none=False)
link = StringType(serialize_when_none=False)
linked_resource_type = StringType(serialize_when_none=False)
locations = ListType(ModelType(ExtendedLocation), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ServiceEndpointPolicyDefinition(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
description = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
service = StringType(serialize_when_none=False)
service_resources = ListType(StringType)
class ServiceEndpointPolicy(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
location = ModelType(ExtendedLocation, serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
resource_guid = StringType(serialize_when_none=False)
service_endpoint_policy_definitions = ListType(ModelType(ServiceEndpointPolicyDefinition),
serialize_when_none=False)
subnets = ListType(StringType, serialize_when_none=False)
tags = ModelType(Tags, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ServiceEndpointPropertiesFormat(Model):
locations = ListType(StringType, serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
service = StringType(serialize_when_none=False)
subnet = StringType(serialize_when_none=False)
class Subnet(Model):
etag = StringType(serialize_when_none=False)
id = StringType()
name = StringType(serialize_when_none=False)
address_prefix = StringType(serialize_when_none=False)
address_prefixes = ListType(StringType, serialize_when_none=False)
application_gateway_ip_configurations = ListType(StringType, serialize_when_none=False) # Change to ip configurations id
delegations = ListType(ModelType(Delegation), serialize_when_none=False)
ip_allocations = ListType(ModelType(SubResource), serialize_when_none=False)
ip_configuration_profiles = ListType(ModelType(IPConfigurationProfile), serialize_when_none=False)
ip_configurations = ListType(ModelType(IPConfiguration), serialize_when_none=False)
azure_firewall = ListType(ModelType(AzureFirewall), serialize_when_none=False)
nat_gateway = ModelType(SubResource, serialize_when_none=False)
network_security_group = ModelType(NetworkSecurityGroup, serialize_when_none=False)
private_endpoint_network_policies = StringType(choices=('Disabled', 'Enabled'), serialize_when_none=False)
private_endpoints = ListType(ModelType(PrivateEndpoint), serialize_when_none=False)
private_link_service_network_policies = StringType(choices=('Disabled', 'Enabled'), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
purpose = StringType(serialize_when_none=False)
resource_navigation_links = ListType(ModelType(ResourceNavigationLink, serialize_when_none=False))
route_table = ModelType(RouteTable, serialize_when_none=False)
service_association_links = ListType(ModelType(ServiceAssociationLink), serialize_when_none=False)
service_endpoint_policies = ListType(ModelType(ServiceEndpointPolicy), serialize_when_none=False)
service_endpoints = ListType(ModelType(ServiceEndpointPropertiesFormat), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class FrontendIPConfiguration(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
inbound_nat_pools = ListType(ModelType(SubResource), serialize_when_none=False)
inbound_nat_rules = ListType(ModelType(SubResource), serialize_when_none=False)
load_balancing_rules = ListType(ModelType(SubResource), serialize_when_none=False)
outbound_rules = ListType(ModelType(SubResource), serialize_when_none=False)
private_ip_address = StringType(serialize_when_none=False)
private_ip_address_version = StringType(choices=('IPv4', 'IPv6'), serialize_when_none=False)
private_ip_allocation_method = StringType(choices=('Dynamic', 'Static'), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
public_ip_address = ModelType(PublicIPAddress, serialize_when_none=False)
public_ip_prefix = ModelType(SubResource, serialize_when_none=False)
subnet = StringType(serialize_when_none=False) # Change to Subnet ID
type = StringType(serialize_when_none=False)
zones = ListType(StringType, serialize_when_none=False)
class VirtualNetworkTap(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
location = StringType(serialize_when_none=False)
destination_load_balancer_front_end_ip_configuration = ModelType(FrontendIPConfiguration, serialize_when_none=False)
destination_network_interface_ip_configuration = StringType(serialize_when_none=False) # Change to networkinterface ip configuration
destination_port = IntType(serialize_when_none=False)
network_interface_tap_configurations = ListType(StringType,serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
resource_guid = StringType(serialize_when_none=False)
tags = ListType(ModelType(Tags))
type = StringType(serialize_when_none=False)
class NetworkInterfaceIPConfiguration(Model): # ip configuration in a network interface
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
application_gateway_backend_address_pools = ListType(StringType, serialize_when_none=False) # Change to ApplicationGatewayBackendAddressPool's ID
application_security_groups = ListType(ModelType(ApplicationSecurityGroup), serialize_when_none=False)
load_balancer_backend_address_pools = ListType(StringType, serialize_when_none=False) # Change to backend address pools id
load_balancer_inbound_nat_rules = ListType(StringType, serialize_when_none=False) # Change to inbound NAT rules id
primary = BooleanType(serialize_when_none=False)
private_ip_address = StringType(serialize_when_none=False)
private_ip_address_version = StringType(choices=('IPv4', 'IPv6'), serialize_when_none=False)
private_ip_allocation_method = StringType(choices=('Dynamic', 'Static'), serialize_when_none=False)
private_link_connection_properties = ModelType(NetworkInterfaceIPConfigurationPrivateLinkConnectionProperties, serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
public_ip_address = ModelType(PublicIPAddress, serialize_when_none=False)
subnet = ModelType(Subnet, serialize_when_none=False)
virtual_network_taps = ListType(ModelType(VirtualNetworkTap), serialize_when_none=False)
class ApplicationGatewayBackendAddressPool(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
backend_addresses = ListType(ModelType(ApplicationGatewayBackendAddress), serialize_when_none=False)
backend_ip_configurations = ListType(ModelType(NetworkInterfaceIPConfiguration), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
type = StringType(serialize_when_none=False)
associated_rules = ListType(StringType, serialize_when_none=False)
class ApplicationGatewayConnectionDraining(Model):
drain_timeout_in_sec = IntType(serialize_when_none=False)
enabled = BooleanType(serialize_when_none=False)
class ApplicationGatewayBackendHttpSettings(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
affinity_cookie_name = StringType(serialize_when_none=False)
authentication_certificates = ListType(ModelType(SubResource), serialize_when_none=False)
connection_draining = ModelType(ApplicationGatewayConnectionDraining, serialize_when_none=False)
cookie_based_affinity = StringType(choices=('Disabled', 'Enabled'), serialize_when_none=False)
host_name = StringType(serialize_when_none=False)
path = StringType(serialize_when_none=False)
pick_host_name_from_backend_address = BooleanType(serialize_when_none=False)
port = IntType(serialize_when_none=False)
probe = ModelType(SubResource, serialize_when_none=False)
probe_enabled = BooleanType(serialize_when_none=False)
custom_probe = StringType(serialize_when_none=False)
protocol = StringType(choices=('Http', 'Https'), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
request_timeout = IntType(serialize_when_none=False)
trusted_root_certificates = ListType(ModelType(SubResource), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayCustomError(Model):
listener_name = StringType(serialize_when_none=False)
custom_error_page_url = StringType(serialize_when_none=False)
status_code = StringType(choices=('HttpStatus403', 'HttpStatus502'))
class ApplicationGatewayFrontendIPConfiguration(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(default='-', serialize_when_none=False)
type = StringType(serialize_when_none=False)
private_ip_address = StringType(serialize_when_none=False)
private_ip_allocation_method = StringType(choices=('Dynamic', 'Static'), serialize_when_none=False)
private_link_configuration = ModelType(SubResource, serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
public_ip_address = ModelType(SubResource, serialize_when_none=False)
ip_type = StringType(choices=('Public', 'Private'), serialize_when_none=False)
ip_address = StringType(serialize_when_none=False)
associated_listener = StringType(default='-')
subnet = ModelType(SubResource, serialize_when_none=False)
class ApplicationGatewayFrontendPort(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
port = IntType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayIPConfiguration(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
subnet = ModelType(SubResource, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayHttpListener(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
custom_error_configurations = ListType(ModelType(ApplicationGatewayCustomError), serialize_when_none=False)
firewall_policy = ModelType(SubResource)
frontend_ip_configuration = ModelType(SubResource)
frontend_port = ModelType(SubResource)
port = IntType(serialize_when_none=False)
host_name = StringType(default='-')
host_names = ListType(StringType, serialize_when_none=False)
protocol = StringType(choices=('Http', 'Https'), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
port = IntType(serialize_when_none=False)
require_server_name_indication = BooleanType(serialize_when_none=False)
ssl_certificate = ModelType(SubResource, serialize_when_none=False)
ssl_profile = ModelType(SubResource, serialize_when_none=False)
associated_rules = ListType(StringType, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayPrivateEndpointConnection(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
link_identifier = StringType(serialize_when_none=False)
private_endpoint = ModelType(PrivateEndpoint, serialize_when_none=False)
private_link_service_connection_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayPrivateLinkIpConfiguration(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
primary = BooleanType(serialize_when_none=False)
private_ip_address = StringType(serialize_when_none=False)
private_ip_allocation_method = StringType(choices=('Dynamic', 'Static'), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
subnet = ModelType(SubResource, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayPrivateLinkConfiguration(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
ip_configurations = ListType(ModelType(ApplicationGatewayPrivateLinkIpConfiguration), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayProbeHealthResponseMatch(Model):
body = StringType(serialize_when_none=False)
status_codes = ListType(StringType, serialize_when_none=False)
class ApplicationGatewayProbe(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
host = StringType(serialize_when_none=False)
interval = IntType(serialize_when_none=False)
match = ModelType(ApplicationGatewayProbeHealthResponseMatch, serialize_when_none=False)
min_servers = IntType(serialize_when_none=False)
path = StringType(serialize_when_none=False)
pick_host_name_from_backend_http_settings = BooleanType(serialize_when_none=False)
port = IntType(serialize_when_none=False)
protocol = StringType(choices=('Http', 'Https'), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
timeout = IntType(serialize_when_none=False)
unhealthy_threshold = IntType(serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayRedirectConfiguration(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(default='-', serialize_when_none=False)
include_path = BooleanType(serialize_when_none=False)
include_query_string = BooleanType(serialize_when_none=False)
path_rules = ListType(ModelType(SubResource), serialize_when_none=False)
redirect_type = StringType(choices=('Found', 'Permanent', 'SeeOther', 'Temporary'), serialize_when_none=False)
request_routing_rules = ListType(ModelType(SubResource), serialize_when_none=False)
target_listener = ModelType(SubResource, serialize_when_none=False)
target_url = StringType(serialize_when_none=False)
url_path_maps = ListType(ModelType(SubResource), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayRequestRoutingRule(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
backend_address_pool = ModelType(SubResource, serialize_when_none=False)
backend_http_settings = ModelType(SubResource, serialize_when_none=False)
http_listener = ModelType(SubResource, serialize_when_none=False)
http_listener_name = StringType(default='-')
priority = IntType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
redirect_configuration = ModelType(SubResource, serialize_when_none=False)
rewrite_rule_set = ModelType(SubResource, serialize_when_none=False)
rule_type = StringType(choices=('Basic', 'PathBasedRouting'), serialize_when_none=False)
url_path_map = ModelType(SubResource, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayHeaderConfiguration(Model):
header_name = StringType(serialize_when_none=False)
header_value = StringType(serialize_when_none=False)
class ApplicationGatewayUrlConfiguration(Model):
modified_path = StringType(serialize_when_none=False)
modified_query_string = StringType(serialize_when_none=False)
reroute = BooleanType(serialize_when_none=False)
class ApplicationGatewayRewriteRuleActionSet(Model):
request_header_configurations = ListType(ModelType(ApplicationGatewayHeaderConfiguration), serialize_when_none=False)
response_header_configurations = ListType(ModelType(ApplicationGatewayHeaderConfiguration), serialize_when_none=False)
url_configuration = ModelType(ApplicationGatewayUrlConfiguration, serialize_when_none=False)
class ApplicationGatewayRewriteRuleCondition(Model):
ignore_case = BooleanType(serialize_when_none=False)
negate = BooleanType(serialize_when_none=False)
pattern = StringType(serialize_when_none=False)
variable = StringType(serialize_when_none=False)
class ApplicationGatewayRewriteRule(Model):
action_set = ModelType(ApplicationGatewayRewriteRuleActionSet, serialize_when_none=False)
conditions = ListType(ModelType(ApplicationGatewayRewriteRuleCondition), serialize_when_none=False)
name = StringType(serialize_when_none=False)
rule_sequence = IntType(serialize_when_none=False)
class ApplicationGatewayRewriteRuleSet(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
rewrite_rules = ListType(ModelType(ApplicationGatewayRewriteRule), serialize_when_none=False)
rewrite_rules_display = ListType(StringType, serialize_when_none=False)
rules_applied = ListType(StringType, serialize_when_none=False)
class ApplicationGatewaySku(Model):
capacity = IntType(serialize_when_none=False)
name = StringType(choices=('Standard_Large', 'Standard_Medium', 'Standard_Small', 'Standard_v2', 'WAF_Large', 'WAF_Medium', 'WAF_v2'), serialize_when_none=False)
tier = StringType(choices=('Standard', 'Standard_v2', 'WAF', 'WAF_v2'), serialize_when_none=False)
class ApplicationGatewaySslCertificate(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
data = StringType(serialize_when_none=False)
key_vault_secret_id = StringType(serialize_when_none=False)
password = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
public_cert_data = StringType(serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewaySslPolicy(Model):
cipher_suites = ListType(StringType, serialize_when_none=False)
disabled_ssl_protocols = ListType(StringType, serialize_when_none=False)
min_protocol_version = StringType(choices=('TLSv1_0', 'TLSv1_1', 'TLSv1_2'), serialize_when_none=False)
policy_name = StringType(choices=('AppGwSslPolicy20150501', 'AppGwSslPolicy20170401', 'AppGwSslPolicy20170401S'), serialize_when_none=False)
policy_type = StringType(choices=('Custom', 'Predefined'), serialize_when_none=False)
class ApplicationGatewayClientAuthConfiguration(Model):
verify_client_cert_issuer_dn = BooleanType(serialize_when_none=False)
class ApplicationGatewaySslProfile(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
client_auth_configuration = ModelType(ApplicationGatewayClientAuthConfiguration, serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
ssl_policy = ModelType(ApplicationGatewaySslPolicy, serialize_when_none=False)
trusted_client_certificates = ListType(ModelType(SubResource), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayTrustedClientCertificate(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
data = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayTrustedRootCertificate(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
data = StringType(serialize_when_none=False)
key_vault_secret_id = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayPathRule(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
backend_address_pool = ModelType(SubResource, serialize_when_none=False)
backend_http_settings = ModelType(SubResource, serialize_when_none=False)
firewall_policy = ModelType(SubResource, serialize_when_none=False)
paths = ListType(StringType, serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
redirect_configuration = ModelType(SubResource, serialize_when_none=False)
rewrite_rule_set = ModelType(SubResource, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayUrlPathMap(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
default_backend_address_pool = ModelType(SubResource, serialize_when_none=False)
default_backend_http_settings = ModelType(SubResource, serialize_when_none=False)
default_redirect_configuration = ModelType(SubResource, serialize_when_none=False)
default_rewrite_rule_set = ModelType(SubResource, serialize_when_none=False)
path_rules = ListType(ModelType(ApplicationGatewayPathRule), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayFirewallExclusion(Model):
match_variable = StringType(serialize_when_none=False)
selector = StringType(serialize_when_none=False)
selector_match_operator = StringType(serialize_when_none=False)
class ApplicationGatewayFirewallDisabledRuleGroup(Model):
rule_group_name = StringType(serialize_when_none=False)
rules = ListType(IntType, serialize_when_none=False)
class ApplicationGatewayWebApplicationFirewallConfiguration(Model):
disabled_rule_groups = ListType(ModelType(ApplicationGatewayFirewallDisabledRuleGroup), serialize_when_none=False)
enabled = BooleanType(serialize_when_none=False)
exclusions = ListType(ModelType(ApplicationGatewayFirewallExclusion), serialize_when_none=False)
file_upload_limit_in_mb = IntType(serialize_when_none=False)
firewall_mode = StringType(choices=('Detection', 'Prevention'), serialize_when_none=False)
max_request_body_size = IntType(serialize_when_none=False)
max_request_body_size_in_kb = IntType(serialize_when_none=False)
request_body_check = BooleanType(serialize_when_none=False)
rule_set_type = StringType(serialize_when_none=False)
rule_set_version = StringType(serialize_when_none=False)
class ApplicationGateway(Model): # Main Class
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
identity = ModelType(ManagedServiceIdentity, serialize_when_none=False)
location = StringType(serialize_when_none=False)
name = StringType(default='-', serialize_when_none=False)
authentication_certificates = ListType(ModelType(ApplicationGatewayAuthenticationCertificate), serialize_when_none=False)
autoscale_configuration = ModelType(ApplicationGatewayAutoscaleConfiguration, serialize_when_none=False)
backend_address_pools = ListType(ModelType(ApplicationGatewayBackendAddressPool), serialize_when_none=False)
backend_http_settings_collection = ListType(ModelType(ApplicationGatewayBackendHttpSettings), serialize_when_none=False)
custom_error_configurations = ListType(ModelType(ApplicationGatewayCustomError), serialize_when_none=False)
enable_fips = BooleanType(serialize_when_none=False)
enable_http2 = BooleanType(serialize_when_none=False)
firewall_policy = ModelType(SubResource, serialize_when_none=False)
force_firewall_policy_association = BooleanType(serialize_when_none=False)
frontend_ip_configurations = ListType(ModelType(ApplicationGatewayFrontendIPConfiguration), serialize_when_none=False)
frontend_ports = ListType(ModelType(ApplicationGatewayFrontendPort), serialize_when_none=False)
gateway_ip_configurations = ListType(ModelType(ApplicationGatewayIPConfiguration), serialize_when_none=False)
http_listeners = ListType(ModelType(ApplicationGatewayHttpListener), serialize_when_none=False)
operational_state = StringType(choices=('Running', 'Starting', 'Stopped', 'Stopping'), serialize_when_none=False)
private_endpoint_connections = ListType(ModelType(ApplicationGatewayPrivateEndpointConnection), serialize_when_none=False)
private_link_configurations = ListType(ModelType(ApplicationGatewayPrivateLinkConfiguration), serialize_when_none=False)
probes = ListType(ModelType(ApplicationGatewayProbe), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
redirect_configurations = ListType(ModelType(ApplicationGatewayRedirectConfiguration), serialize_when_none=False)
request_routing_rules = ListType(ModelType(ApplicationGatewayRequestRoutingRule), serialize_when_none=False)
resource_guid = StringType(serialize_when_none=False)
rewrite_rule_sets = ListType(ModelType(ApplicationGatewayRewriteRuleSet), serialize_when_none=False)
sku = ModelType(ApplicationGatewaySku, serialize_when_none=False)
ssl_certificates = ListType(ModelType(ApplicationGatewaySslCertificate), serialize_when_none=False)
ssl_policy = ModelType(ApplicationGatewaySslPolicy, serialize_when_none=False)
ssl_profiles = ListType(ModelType(ApplicationGatewaySslProfile), serialize_when_none=False)
trusted_client_certificates = ListType(ModelType(ApplicationGatewayTrustedClientCertificate), serialize_when_none=False)
trusted_root_certificates = ListType(ModelType(ApplicationGatewayTrustedRootCertificate), serialize_when_none=False)
url_path_maps = ListType(ModelType(ApplicationGatewayUrlPathMap), serialize_when_none=False)
web_application_firewall_configuration = ModelType(ApplicationGatewayWebApplicationFirewallConfiguration, serialize_when_none=False)
resource_group = StringType(serialize_when_none=False)
subscription_id = StringType(serialize_when_none=False)
subscription_name = StringType(serialize_when_none=False)
private_ip_address = StringType(serialize_when_none=False)
public_ip_address = ModelType(PublicIPAddress, serialize_when_none=False)
virtual_network = StringType(serialize_when_none=False)
subnet = StringType(serialize_when_none=False)
tags = ModelType(Tags, serialize_when_none=False)
type = StringType(serialize_when_none=False)
zones = ListType(StringType, serialize_when_none=False)
def reference(self):
return {
"resource_id": self.id,
"external_link": f"https://portal.azure.com/#@.onmicrosoft.com/resource{self.id}/overview",
}
| 54.600607 | 165 | 0.797481 | from schematics import Model
from schematics.types import ModelType, ListType, StringType, IntType, BooleanType, NumberType, DateTimeType, \
TimestampType, UTCDateTimeType, TimedeltaType, FloatType
class Tags(Model):
key = StringType(serialize_when_none=False)
value = StringType(serialize_when_none=False)
class SubResource(Model):
id = StringType()
class ApplicationGatewayAuthenticationCertificate(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
data = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayAutoscaleConfiguration(Model):
max_capacity = IntType(serialize_when_none=False)
min_capacity = IntType(serialize_when_none=False)
class ManagedServiceIdentity(Model):
principal_id = StringType(serialize_when_none=False)
tenant_id = StringType(serialize_when_none=False)
type = StringType(choices=('None', 'SystemAssigned', 'SystemAssigned, UserAssigned', 'UserAssigned'), serialize_when_none=False)
user_assigned_identities = StringType(serialize_when_none=False)
class ApplicationGatewayBackendAddress(Model):
fqdn = StringType(serialize_when_none=False)
ip_address = StringType(serialize_when_none=False)
l(Model):
port = IntType(serialize_when_none=False)
protocol_type = StringType(choices=('Http', 'Https', 'Mssql'), serialize_when_none=False)
class AzureFirewallApplicationRule(Model):
description = StringType(serialize_when_none=False)
fqdn_tags = ListType(StringType, serialize_when_none=False)
name = StringType(serialize_when_none=False)
protocols = ListType(ModelType(AzureFirewallApplicationRuleProtocol), serialize_when_none=False)
source_addresses = ListType(StringType, serialize_when_none=False)
source_ip_groups = ListType(StringType, serialize_when_none=False)
target_fqdns = ListType(StringType, serialize_when_none=False)
class AzureFirewallApplicationRuleCollection(Model):
etag = StringType()
id = StringType()
name = StringType(serialize_when_none=False)
action = ModelType(AzureFirewallRCAction, serialize_when_none=False)
priority = IntType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
rules = ListType(ModelType(AzureFirewallApplicationRule), serialize_when_none=False)
class AzureFirewallIPConfiguration(Model):
etag = StringType()
id = StringType()
name = StringType(serialize_when_none=False)
private_ip_address = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
public_ip_address = ModelType(SubResource, serialize_when_none=False)
subnet = ModelType(SubResource, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class AzureFirewallPublicIPAddress(Model):
address = StringType(serialize_when_none=False)
class HubPublicIPAddresses(Model):
address = ListType(ModelType(AzureFirewallPublicIPAddress), serialize_when_none=False)
count = IntType(serialize_when_none=False)
class HubIPAddresses(Model):
private_ip_address = StringType(serialize_when_none=False)
public_ips = ModelType(HubPublicIPAddresses, serialize_when_none=False)
class AzureFirewallIpGroups(Model):
change_number = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
class AzureFirewallNatRule(Model):
description = StringType(serialize_when_none=False)
destination_addresses = ListType(StringType, serialize_when_none=False)
destination_ports = ListType(StringType, serialize_when_none=False)
name = StringType(serialize_when_none=False)
protocols = ListType(StringType, serialize_when_none=False)
source_addresses = ListType(StringType, serialize_when_none=False)
source_ip_groups = ListType(StringType, serialize_when_none=False)
translated_address = StringType(serialize_when_none=False)
translated_fqdn = StringType(serialize_when_none=False)
translated_port = StringType(serialize_when_none=False)
class AzureFirewallNetworkRule(Model):
description = StringType(serialize_when_none=False)
destination_addresses = ListType(StringType, serialize_when_none=False)
destination_ports = ListType(StringType, serialize_when_none=False)
destination_fqdns = ListType(StringType, serialize_when_none=False)
destination_ip_groups = ListType(StringType, serialize_when_none=False)
name = StringType(serialize_when_none=False)
protocols = ListType(StringType, serialize_when_none=False)
source_addresses = ListType(StringType, serialize_when_none=False)
source_ip_groups = ListType(StringType, serialize_when_none=False)
translated_address = StringType(serialize_when_none=False)
translated_fqdn = StringType(serialize_when_none=False)
translated_port = StringType(serialize_when_none=False)
class AzureFirewallNatRuleCollection(Model):
etag = StringType()
id = StringType()
name = StringType(serialize_when_none=False)
action = StringType(choices=('Dnat', 'Snat'), serialize_when_none=False)
priority = IntType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
rules = ListType(ModelType(AzureFirewallNatRule), serialize_when_none=False)
class AzureFirewallNetworkRuleCollection(Model):
etag = StringType()
id = StringType()
name = StringType(serialize_when_none=False)
action = ModelType(AzureFirewallRCAction, serialize_when_none=False)
priority = IntType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
rules = ListType(ModelType(AzureFirewallNetworkRule), serialize_when_none=False)
class AzureFirewallSku(Model):
name = StringType(choices=('AZFW_Hub', 'AZFW_VNet'), serialize_when_none=False)
tier = StringType(choices=('Premium', 'Standard'), serialize_when_none=False)
class AzureFirewall(Model):
etag = StringType()
id = StringType()
location = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
subnet = StringType(serialize_when_none=False)
application_rule_collections = ListType(ModelType(AzureFirewallApplicationRuleCollection), serialize_when_none=False)
firewall_policy = ModelType(SubResource, serialize_when_none=False)
hub_ip_addresses = ModelType(HubIPAddresses, serialize_when_none=False)
ip_configurations = ListType(ModelType(AzureFirewallIPConfiguration), serialize_when_none=False)
ip_groups = ListType(ModelType(AzureFirewallIpGroups), serialize_when_none=False)
management_ip_configuration = ModelType(AzureFirewallIPConfiguration, serialize_when_none=False)
nat_rule_collections = ListType(ModelType(AzureFirewallNatRuleCollection), serialize_when_none=False)
network_rule_collections = ListType(ModelType(AzureFirewallNetworkRuleCollection), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
sku = ModelType(AzureFirewallSku, serialize_when_none=False)
threat_intel_mode = StringType(choices=('Alert', 'Deny', 'Off'), serialize_when_none=False)
virtual_hub = ModelType(SubResource, serialize_when_none=False)
tags = ModelType(Tags, serialize_when_none=False)
type = StringType(serialize_when_none=False)
zones = ListType(StringType, serialize_when_none=False)
class ExtendedLocation(Model):
name = StringType(serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationSecurityGroup(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
location = ModelType(ExtendedLocation, serialize_when_none=False)
name = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
resource_guid = StringType(serialize_when_none=False)
tags = ModelType(Tags, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class NetworkInterfaceIPConfigurationPrivateLinkConnectionProperties(Model):
fqdns = ListType(StringType, serialize_when_none=False)
group_id = StringType(serialize_when_none=False)
required_member_name = StringType(serialize_when_none=False)
class DdosSettings(Model):
ddos_custom_policy = ModelType(SubResource, serialize_when_none=False)
protected_ip = BooleanType(serialize_when_none=False)
protection_coverage = StringType(choices=('Basic', 'Standard'), serialize_when_none=False)
class PublicIPAddressDnsSettings(Model):
domain_name_label = StringType(serialize_when_none=False)
fqdn = StringType(serialize_when_none=False)
reverse_fqdn = StringType(serialize_when_none=False)
class IPConfiguration(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
private_ip_address = StringType(serialize_when_none=False)
public_ip_allocation_method = StringType(choices=('Dynamic', 'Static'), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
public_ip_address = StringType(serialize_when_none=False)
subnet = StringType(serialize_when_none=False)
class IpTag(Model):
ip_tag_type = StringType(serialize_when_none=False)
tag = StringType(serialize_when_none=False)
class NatGatewaySku(Model):
name = StringType(choices=('Standard', None), serialize_when_none=False)
class NatGateway(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
location = ModelType(ExtendedLocation, serialize_when_none=False)
idle_timeout_in_minutes = IntType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
public_ip_addresses = ListType(ModelType(SubResource), serialize_when_none=False)
public_ip_prefixes = ListType(ModelType(SubResource), serialize_when_none=False)
resource_guid = StringType(serialize_when_none=False)
subnets = ListType(ModelType(SubResource), serialize_when_none=False)
sku = ModelType(NatGatewaySku, serialize_when_none=False)
tags = ModelType(Tags, serialize_when_none=False)
type = StringType(serialize_when_none=False)
zones = ListType(StringType, serialize_when_none=False)
class PublicIPAddressSku(Model):
name = StringType(choices=('Basic', 'Standard'), serialize_when_none=False)
tier = StringType(choices=('Global', 'Regional'), serialize_when_none=False)
class PublicIPAddress(Model):
etag = StringType(serialize_when_none=False)
extended_location = ModelType(ExtendedLocation, serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
location = StringType(serialize_when_none=False)
ddos_settings = ModelType(DdosSettings, serialize_when_none=False)
dns_settings = ModelType(PublicIPAddressDnsSettings, serialize_when_none=False)
idle_timeout_in_minutes = IntType(serialize_when_none=False)
ip_address = StringType(serialize_when_none=False)
ip_configuration = ModelType(IPConfiguration, serialize_when_none=False)
ip_tags = ListType(ModelType(IpTag), serialize_when_none=False)
migration_phase = StringType(choices=('Abort', 'Commit', 'Committed', 'None', 'Prepare'), serialize_when_none=False)
nat_gateway = ModelType(NatGateway, serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
public_ip_address_version = StringType(choices=('IPv4', 'IPv6'), serialize_when_none=False)
public_ip_allocation_method = StringType(choices=('Dynamic', 'Static'), serialize_when_none=False)
public_ip_prefix = ModelType(SubResource, serialize_when_none=False)
resource_guid = StringType(serialize_when_none=False)
sku = ModelType(PublicIPAddressSku, serialize_when_none=False)
tags = ModelType(Tags, serialize_when_none=False)
type = StringType(serialize_when_none=False)
zones = ListType(StringType, serialize_when_none=False)
class Delegation(Model):
etag = StringType(serialize_when_none=False)
id = StringType()
name = StringType(default='-', serialize_when_none=False)
actions = ListType(StringType, serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
service_name = StringType(serialize_when_none=False)
type = StringType(serialize_when_none=False)
class IPConfigurationProfile(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
subnet = StringType(serialize_when_none=False)
type = StringType(serialize_when_none=False)
class SecurityRule(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
access = StringType(choices=('Allow', 'Deny'), serialize_when_none=False)
description = StringType(serialize_when_none=False)
destination_address_prefix = StringType(serialize_when_none=False)
destination_address_prefixes = ListType(StringType, serialize_when_none=False)
destination_application_security_groups = ListType(ModelType(ApplicationSecurityGroup), serialize_when_none=False)
destination_port_range = StringType(serialize_when_none=False)
destination_port_ranges = ListType(StringType, serialize_when_none=False)
direction = StringType(choices=('Inbound', 'Outbound'), serialize_when_none=False)
priority = IntType(serialize_when_none=False)
protocol = StringType(choices=('*', 'Ah', 'Esp', 'Icmp', 'Tcp', 'Udp'), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
source_address_prefix = StringType(serialize_when_none=False)
source_address_prefixes = ListType(StringType, serialize_when_none=False)
source_application_security_groups = ListType(ModelType(ApplicationSecurityGroup), serialize_when_none=False)
source_port_range = StringType(serialize_when_none=False)
source_port_ranges = ListType(StringType, serialize_when_none=False)
class RetentionPolicyParameters(Model):
days = IntType(serialize_when_none=False)
enabled = BooleanType(serialize_when_none=False)
class TrafficAnalyticsConfigurationProperties(Model):
enabled = BooleanType(serialize_when_none=False)
traffic_analytics_interval = IntType(serialize_when_none=False)
workspace_id = StringType(serialize_when_none=False)
workspace_region = StringType(serialize_when_none=False)
workspace_resource_id = StringType(serialize_when_none=False)
class TrafficAnalyticsProperties(Model):
network_watcher_flow_analytics_configuration = ModelType(TrafficAnalyticsConfigurationProperties,
serialize_when_none=False)
class FlowLogFormatType(Model):
json = StringType(serialize_when_none=False)
class FlowLogFormatParameters(Model):
type = ModelType(FlowLogFormatType, serialize_when_none=False)
version = IntType(serialize_when_none=False)
class FlowLog(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
location = ModelType(ExtendedLocation, serialize_when_none=False)
name = StringType(serialize_when_none=False)
enable = BooleanType(serialize_when_none=False)
flow_analytics_configuration = ModelType(TrafficAnalyticsProperties, serialize_when_none=False)
format = ModelType(FlowLogFormatParameters, serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
retention_policy = ModelType(RetentionPolicyParameters, serialize_when_none=False)
storage_id = StringType(serialize_when_none=False)
target_resource_guid = StringType(serialize_when_none=False)
target_resource_id = StringType(serialize_when_none=False)
tags = ModelType(Tags, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class SecurityRule(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
access = StringType(choices=('Allow', 'Deny'), serialize_when_none=False)
description = StringType(serialize_when_none=False)
destination_address_prefix = StringType(serialize_when_none=False)
destination_address_prefixes = ListType(StringType, serialize_when_none=False)
destination_application_security_groups = ListType(ModelType(ApplicationSecurityGroup), serialize_when_none=False)
destination_port_range = StringType(serialize_when_none=False)
destination_port_ranges = ListType(StringType, serialize_when_none=False)
direction = StringType(choices=('Inbound', 'Outbound'), serialize_when_none=False)
priority = IntType(serialize_when_none=False)
protocol = StringType(choices=('*', 'Ah', 'Esp', 'Icmp', 'Tcp', 'Udp'), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
source_address_prefix = StringType(serialize_when_none=False)
source_address_prefixes = ListType(StringType, serialize_when_none=False)
source_application_security_groups = ListType(ModelType(ApplicationSecurityGroup), serialize_when_none=False)
source_port_range = StringType(serialize_when_none=False)
source_port_ranges = ListType(StringType, serialize_when_none=False)
class NetworkSecurityGroup(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
location = ModelType(ExtendedLocation, serialize_when_none=False)
name = StringType(default='-', serialize_when_none=False)
default_security_rules = ListType(ModelType(SecurityRule), serialize_when_none=False)
flow_logs = ListType(ModelType(FlowLog), serialize_when_none=False)
network_interfaces = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
resource_guid = StringType(serialize_when_none=False)
security_rules = ListType(ModelType(SecurityRule), serialize_when_none=False)
subnets = ListType(StringType, serialize_when_none=False) # Change to Subnet IDs
tags = ModelType(Tags, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class CustomDnsConfigPropertiesFormat(Model):
fqdn = StringType(serialize_when_none=False)
ip_addresses = ListType(StringType, serialize_when_none=False)
class PrivateLinkServiceConnectionState(Model):
actions_required = StringType(serialize_when_none=False)
description = StringType(serialize_when_none=False)
status = StringType(serialize_when_none=False)
class PrivateLinkServiceConnection(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
group_ids = ListType(StringType, serialize_when_none=False)
private_link_service_connection_state = ModelType(PrivateLinkServiceConnectionState, serialize_when_none=False)
private_link_service_id = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
request_message = StringType(serialize_when_none=False)
type = StringType(serialize_when_none=False)
class PrivateEndpoint(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
location = ModelType(ExtendedLocation, serialize_when_none=False)
extended_location = ModelType(ExtendedLocation, serialize_when_none=False)
name = StringType(serialize_when_none=False)
custom_dns_configs = ListType(ModelType(CustomDnsConfigPropertiesFormat), serialize_when_none=False)
manual_private_link_service_connections = ListType(ModelType(PrivateLinkServiceConnection),
serialize_when_none=False)
network_interfaces = ListType(StringType, serialize_when_none=False) # Change to network interface ids
private_link_service_connections = ListType(ModelType(PrivateLinkServiceConnection), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
subnet = StringType(serialize_when_none=False)
resource_group = StringType(serialize_when_none=False)
tags = ModelType(Tags, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ResourceNavigationLink(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
link = StringType(serialize_when_none=False)
linked_resource_type = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class Route(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
address_prefix = StringType(serialize_when_none=False)
next_hop_ip_address = StringType(serialize_when_none=False)
next_hop_type = StringType(choices=('Internet', 'None', 'VirtualAppliance', 'VirtualNetworkGateway', 'VnetLocal'),
serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
class RouteTable(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
location = ModelType(ExtendedLocation, serialize_when_none=False)
disable_bgp_route_propagation = BooleanType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
routes = ListType(ModelType(Route), serialize_when_none=False)
subnets = ListType(StringType, default=[], serialize_when_none=False)
tags = ModelType(Tags, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ServiceAssociationLink(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
allow_delete = BooleanType(serialize_when_none=False)
link = StringType(serialize_when_none=False)
linked_resource_type = StringType(serialize_when_none=False)
locations = ListType(ModelType(ExtendedLocation), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ServiceEndpointPolicyDefinition(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
description = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
service = StringType(serialize_when_none=False)
service_resources = ListType(StringType)
class ServiceEndpointPolicy(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
location = ModelType(ExtendedLocation, serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
resource_guid = StringType(serialize_when_none=False)
service_endpoint_policy_definitions = ListType(ModelType(ServiceEndpointPolicyDefinition),
serialize_when_none=False)
subnets = ListType(StringType, serialize_when_none=False)
tags = ModelType(Tags, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ServiceEndpointPropertiesFormat(Model):
locations = ListType(StringType, serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
service = StringType(serialize_when_none=False)
subnet = StringType(serialize_when_none=False)
class Subnet(Model):
etag = StringType(serialize_when_none=False)
id = StringType()
name = StringType(serialize_when_none=False)
address_prefix = StringType(serialize_when_none=False)
address_prefixes = ListType(StringType, serialize_when_none=False)
application_gateway_ip_configurations = ListType(StringType, serialize_when_none=False) # Change to ip configurations id
delegations = ListType(ModelType(Delegation), serialize_when_none=False)
ip_allocations = ListType(ModelType(SubResource), serialize_when_none=False)
ip_configuration_profiles = ListType(ModelType(IPConfigurationProfile), serialize_when_none=False)
ip_configurations = ListType(ModelType(IPConfiguration), serialize_when_none=False)
azure_firewall = ListType(ModelType(AzureFirewall), serialize_when_none=False)
nat_gateway = ModelType(SubResource, serialize_when_none=False)
network_security_group = ModelType(NetworkSecurityGroup, serialize_when_none=False)
private_endpoint_network_policies = StringType(choices=('Disabled', 'Enabled'), serialize_when_none=False)
private_endpoints = ListType(ModelType(PrivateEndpoint), serialize_when_none=False)
private_link_service_network_policies = StringType(choices=('Disabled', 'Enabled'), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
purpose = StringType(serialize_when_none=False)
resource_navigation_links = ListType(ModelType(ResourceNavigationLink, serialize_when_none=False))
route_table = ModelType(RouteTable, serialize_when_none=False)
service_association_links = ListType(ModelType(ServiceAssociationLink), serialize_when_none=False)
service_endpoint_policies = ListType(ModelType(ServiceEndpointPolicy), serialize_when_none=False)
service_endpoints = ListType(ModelType(ServiceEndpointPropertiesFormat), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class FrontendIPConfiguration(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
inbound_nat_pools = ListType(ModelType(SubResource), serialize_when_none=False)
inbound_nat_rules = ListType(ModelType(SubResource), serialize_when_none=False)
load_balancing_rules = ListType(ModelType(SubResource), serialize_when_none=False)
outbound_rules = ListType(ModelType(SubResource), serialize_when_none=False)
private_ip_address = StringType(serialize_when_none=False)
private_ip_address_version = StringType(choices=('IPv4', 'IPv6'), serialize_when_none=False)
private_ip_allocation_method = StringType(choices=('Dynamic', 'Static'), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
public_ip_address = ModelType(PublicIPAddress, serialize_when_none=False)
public_ip_prefix = ModelType(SubResource, serialize_when_none=False)
subnet = StringType(serialize_when_none=False) # Change to Subnet ID
type = StringType(serialize_when_none=False)
zones = ListType(StringType, serialize_when_none=False)
class VirtualNetworkTap(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
location = StringType(serialize_when_none=False)
destination_load_balancer_front_end_ip_configuration = ModelType(FrontendIPConfiguration, serialize_when_none=False)
destination_network_interface_ip_configuration = StringType(serialize_when_none=False) # Change to networkinterface ip configuration
destination_port = IntType(serialize_when_none=False)
network_interface_tap_configurations = ListType(StringType,serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
resource_guid = StringType(serialize_when_none=False)
tags = ListType(ModelType(Tags))
type = StringType(serialize_when_none=False)
class NetworkInterfaceIPConfiguration(Model): # ip configuration in a network interface
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
application_gateway_backend_address_pools = ListType(StringType, serialize_when_none=False) # Change to ApplicationGatewayBackendAddressPool's ID
application_security_groups = ListType(ModelType(ApplicationSecurityGroup), serialize_when_none=False)
load_balancer_backend_address_pools = ListType(StringType, serialize_when_none=False)
load_balancer_inbound_nat_rules = ListType(StringType, serialize_when_none=False)
primary = BooleanType(serialize_when_none=False)
private_ip_address = StringType(serialize_when_none=False)
private_ip_address_version = StringType(choices=('IPv4', 'IPv6'), serialize_when_none=False)
private_ip_allocation_method = StringType(choices=('Dynamic', 'Static'), serialize_when_none=False)
private_link_connection_properties = ModelType(NetworkInterfaceIPConfigurationPrivateLinkConnectionProperties, serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
public_ip_address = ModelType(PublicIPAddress, serialize_when_none=False)
subnet = ModelType(Subnet, serialize_when_none=False)
virtual_network_taps = ListType(ModelType(VirtualNetworkTap), serialize_when_none=False)
class ApplicationGatewayBackendAddressPool(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
backend_addresses = ListType(ModelType(ApplicationGatewayBackendAddress), serialize_when_none=False)
backend_ip_configurations = ListType(ModelType(NetworkInterfaceIPConfiguration), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
type = StringType(serialize_when_none=False)
associated_rules = ListType(StringType, serialize_when_none=False)
class ApplicationGatewayConnectionDraining(Model):
drain_timeout_in_sec = IntType(serialize_when_none=False)
enabled = BooleanType(serialize_when_none=False)
class ApplicationGatewayBackendHttpSettings(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
affinity_cookie_name = StringType(serialize_when_none=False)
authentication_certificates = ListType(ModelType(SubResource), serialize_when_none=False)
connection_draining = ModelType(ApplicationGatewayConnectionDraining, serialize_when_none=False)
cookie_based_affinity = StringType(choices=('Disabled', 'Enabled'), serialize_when_none=False)
host_name = StringType(serialize_when_none=False)
path = StringType(serialize_when_none=False)
pick_host_name_from_backend_address = BooleanType(serialize_when_none=False)
port = IntType(serialize_when_none=False)
probe = ModelType(SubResource, serialize_when_none=False)
probe_enabled = BooleanType(serialize_when_none=False)
custom_probe = StringType(serialize_when_none=False)
protocol = StringType(choices=('Http', 'Https'), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
request_timeout = IntType(serialize_when_none=False)
trusted_root_certificates = ListType(ModelType(SubResource), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayCustomError(Model):
listener_name = StringType(serialize_when_none=False)
custom_error_page_url = StringType(serialize_when_none=False)
status_code = StringType(choices=('HttpStatus403', 'HttpStatus502'))
class ApplicationGatewayFrontendIPConfiguration(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(default='-', serialize_when_none=False)
type = StringType(serialize_when_none=False)
private_ip_address = StringType(serialize_when_none=False)
private_ip_allocation_method = StringType(choices=('Dynamic', 'Static'), serialize_when_none=False)
private_link_configuration = ModelType(SubResource, serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
public_ip_address = ModelType(SubResource, serialize_when_none=False)
ip_type = StringType(choices=('Public', 'Private'), serialize_when_none=False)
ip_address = StringType(serialize_when_none=False)
associated_listener = StringType(default='-')
subnet = ModelType(SubResource, serialize_when_none=False)
class ApplicationGatewayFrontendPort(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
port = IntType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayIPConfiguration(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
subnet = ModelType(SubResource, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayHttpListener(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
custom_error_configurations = ListType(ModelType(ApplicationGatewayCustomError), serialize_when_none=False)
firewall_policy = ModelType(SubResource)
frontend_ip_configuration = ModelType(SubResource)
frontend_port = ModelType(SubResource)
port = IntType(serialize_when_none=False)
host_name = StringType(default='-')
host_names = ListType(StringType, serialize_when_none=False)
protocol = StringType(choices=('Http', 'Https'), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
port = IntType(serialize_when_none=False)
require_server_name_indication = BooleanType(serialize_when_none=False)
ssl_certificate = ModelType(SubResource, serialize_when_none=False)
ssl_profile = ModelType(SubResource, serialize_when_none=False)
associated_rules = ListType(StringType, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayPrivateEndpointConnection(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
link_identifier = StringType(serialize_when_none=False)
private_endpoint = ModelType(PrivateEndpoint, serialize_when_none=False)
private_link_service_connection_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayPrivateLinkIpConfiguration(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
primary = BooleanType(serialize_when_none=False)
private_ip_address = StringType(serialize_when_none=False)
private_ip_allocation_method = StringType(choices=('Dynamic', 'Static'), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
subnet = ModelType(SubResource, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayPrivateLinkConfiguration(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
ip_configurations = ListType(ModelType(ApplicationGatewayPrivateLinkIpConfiguration), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayProbeHealthResponseMatch(Model):
body = StringType(serialize_when_none=False)
status_codes = ListType(StringType, serialize_when_none=False)
class ApplicationGatewayProbe(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
host = StringType(serialize_when_none=False)
interval = IntType(serialize_when_none=False)
match = ModelType(ApplicationGatewayProbeHealthResponseMatch, serialize_when_none=False)
min_servers = IntType(serialize_when_none=False)
path = StringType(serialize_when_none=False)
pick_host_name_from_backend_http_settings = BooleanType(serialize_when_none=False)
port = IntType(serialize_when_none=False)
protocol = StringType(choices=('Http', 'Https'), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
timeout = IntType(serialize_when_none=False)
unhealthy_threshold = IntType(serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayRedirectConfiguration(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(default='-', serialize_when_none=False)
include_path = BooleanType(serialize_when_none=False)
include_query_string = BooleanType(serialize_when_none=False)
path_rules = ListType(ModelType(SubResource), serialize_when_none=False)
redirect_type = StringType(choices=('Found', 'Permanent', 'SeeOther', 'Temporary'), serialize_when_none=False)
request_routing_rules = ListType(ModelType(SubResource), serialize_when_none=False)
target_listener = ModelType(SubResource, serialize_when_none=False)
target_url = StringType(serialize_when_none=False)
url_path_maps = ListType(ModelType(SubResource), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayRequestRoutingRule(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
backend_address_pool = ModelType(SubResource, serialize_when_none=False)
backend_http_settings = ModelType(SubResource, serialize_when_none=False)
http_listener = ModelType(SubResource, serialize_when_none=False)
http_listener_name = StringType(default='-')
priority = IntType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
redirect_configuration = ModelType(SubResource, serialize_when_none=False)
rewrite_rule_set = ModelType(SubResource, serialize_when_none=False)
rule_type = StringType(choices=('Basic', 'PathBasedRouting'), serialize_when_none=False)
url_path_map = ModelType(SubResource, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayHeaderConfiguration(Model):
header_name = StringType(serialize_when_none=False)
header_value = StringType(serialize_when_none=False)
class ApplicationGatewayUrlConfiguration(Model):
modified_path = StringType(serialize_when_none=False)
modified_query_string = StringType(serialize_when_none=False)
reroute = BooleanType(serialize_when_none=False)
class ApplicationGatewayRewriteRuleActionSet(Model):
request_header_configurations = ListType(ModelType(ApplicationGatewayHeaderConfiguration), serialize_when_none=False)
response_header_configurations = ListType(ModelType(ApplicationGatewayHeaderConfiguration), serialize_when_none=False)
url_configuration = ModelType(ApplicationGatewayUrlConfiguration, serialize_when_none=False)
class ApplicationGatewayRewriteRuleCondition(Model):
ignore_case = BooleanType(serialize_when_none=False)
negate = BooleanType(serialize_when_none=False)
pattern = StringType(serialize_when_none=False)
variable = StringType(serialize_when_none=False)
class ApplicationGatewayRewriteRule(Model):
action_set = ModelType(ApplicationGatewayRewriteRuleActionSet, serialize_when_none=False)
conditions = ListType(ModelType(ApplicationGatewayRewriteRuleCondition), serialize_when_none=False)
name = StringType(serialize_when_none=False)
rule_sequence = IntType(serialize_when_none=False)
class ApplicationGatewayRewriteRuleSet(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
rewrite_rules = ListType(ModelType(ApplicationGatewayRewriteRule), serialize_when_none=False)
rewrite_rules_display = ListType(StringType, serialize_when_none=False)
rules_applied = ListType(StringType, serialize_when_none=False)
class ApplicationGatewaySku(Model):
capacity = IntType(serialize_when_none=False)
name = StringType(choices=('Standard_Large', 'Standard_Medium', 'Standard_Small', 'Standard_v2', 'WAF_Large', 'WAF_Medium', 'WAF_v2'), serialize_when_none=False)
tier = StringType(choices=('Standard', 'Standard_v2', 'WAF', 'WAF_v2'), serialize_when_none=False)
class ApplicationGatewaySslCertificate(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
data = StringType(serialize_when_none=False)
key_vault_secret_id = StringType(serialize_when_none=False)
password = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
public_cert_data = StringType(serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewaySslPolicy(Model):
cipher_suites = ListType(StringType, serialize_when_none=False)
disabled_ssl_protocols = ListType(StringType, serialize_when_none=False)
min_protocol_version = StringType(choices=('TLSv1_0', 'TLSv1_1', 'TLSv1_2'), serialize_when_none=False)
policy_name = StringType(choices=('AppGwSslPolicy20150501', 'AppGwSslPolicy20170401', 'AppGwSslPolicy20170401S'), serialize_when_none=False)
policy_type = StringType(choices=('Custom', 'Predefined'), serialize_when_none=False)
class ApplicationGatewayClientAuthConfiguration(Model):
verify_client_cert_issuer_dn = BooleanType(serialize_when_none=False)
class ApplicationGatewaySslProfile(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
client_auth_configuration = ModelType(ApplicationGatewayClientAuthConfiguration, serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
ssl_policy = ModelType(ApplicationGatewaySslPolicy, serialize_when_none=False)
trusted_client_certificates = ListType(ModelType(SubResource), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayTrustedClientCertificate(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
data = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayTrustedRootCertificate(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
data = StringType(serialize_when_none=False)
key_vault_secret_id = StringType(serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayPathRule(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
backend_address_pool = ModelType(SubResource, serialize_when_none=False)
backend_http_settings = ModelType(SubResource, serialize_when_none=False)
firewall_policy = ModelType(SubResource, serialize_when_none=False)
paths = ListType(StringType, serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
redirect_configuration = ModelType(SubResource, serialize_when_none=False)
rewrite_rule_set = ModelType(SubResource, serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayUrlPathMap(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
name = StringType(serialize_when_none=False)
default_backend_address_pool = ModelType(SubResource, serialize_when_none=False)
default_backend_http_settings = ModelType(SubResource, serialize_when_none=False)
default_redirect_configuration = ModelType(SubResource, serialize_when_none=False)
default_rewrite_rule_set = ModelType(SubResource, serialize_when_none=False)
path_rules = ListType(ModelType(ApplicationGatewayPathRule), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
type = StringType(serialize_when_none=False)
class ApplicationGatewayFirewallExclusion(Model):
match_variable = StringType(serialize_when_none=False)
selector = StringType(serialize_when_none=False)
selector_match_operator = StringType(serialize_when_none=False)
class ApplicationGatewayFirewallDisabledRuleGroup(Model):
rule_group_name = StringType(serialize_when_none=False)
rules = ListType(IntType, serialize_when_none=False)
class ApplicationGatewayWebApplicationFirewallConfiguration(Model):
disabled_rule_groups = ListType(ModelType(ApplicationGatewayFirewallDisabledRuleGroup), serialize_when_none=False)
enabled = BooleanType(serialize_when_none=False)
exclusions = ListType(ModelType(ApplicationGatewayFirewallExclusion), serialize_when_none=False)
file_upload_limit_in_mb = IntType(serialize_when_none=False)
firewall_mode = StringType(choices=('Detection', 'Prevention'), serialize_when_none=False)
max_request_body_size = IntType(serialize_when_none=False)
max_request_body_size_in_kb = IntType(serialize_when_none=False)
request_body_check = BooleanType(serialize_when_none=False)
rule_set_type = StringType(serialize_when_none=False)
rule_set_version = StringType(serialize_when_none=False)
class ApplicationGateway(Model):
etag = StringType(serialize_when_none=False)
id = StringType(serialize_when_none=False)
identity = ModelType(ManagedServiceIdentity, serialize_when_none=False)
location = StringType(serialize_when_none=False)
name = StringType(default='-', serialize_when_none=False)
authentication_certificates = ListType(ModelType(ApplicationGatewayAuthenticationCertificate), serialize_when_none=False)
autoscale_configuration = ModelType(ApplicationGatewayAutoscaleConfiguration, serialize_when_none=False)
backend_address_pools = ListType(ModelType(ApplicationGatewayBackendAddressPool), serialize_when_none=False)
backend_http_settings_collection = ListType(ModelType(ApplicationGatewayBackendHttpSettings), serialize_when_none=False)
custom_error_configurations = ListType(ModelType(ApplicationGatewayCustomError), serialize_when_none=False)
enable_fips = BooleanType(serialize_when_none=False)
enable_http2 = BooleanType(serialize_when_none=False)
firewall_policy = ModelType(SubResource, serialize_when_none=False)
force_firewall_policy_association = BooleanType(serialize_when_none=False)
frontend_ip_configurations = ListType(ModelType(ApplicationGatewayFrontendIPConfiguration), serialize_when_none=False)
frontend_ports = ListType(ModelType(ApplicationGatewayFrontendPort), serialize_when_none=False)
gateway_ip_configurations = ListType(ModelType(ApplicationGatewayIPConfiguration), serialize_when_none=False)
http_listeners = ListType(ModelType(ApplicationGatewayHttpListener), serialize_when_none=False)
operational_state = StringType(choices=('Running', 'Starting', 'Stopped', 'Stopping'), serialize_when_none=False)
private_endpoint_connections = ListType(ModelType(ApplicationGatewayPrivateEndpointConnection), serialize_when_none=False)
private_link_configurations = ListType(ModelType(ApplicationGatewayPrivateLinkConfiguration), serialize_when_none=False)
probes = ListType(ModelType(ApplicationGatewayProbe), serialize_when_none=False)
provisioning_state = StringType(choices=('Deleting', 'Failed', 'Succeeded', 'Updating'), serialize_when_none=False)
redirect_configurations = ListType(ModelType(ApplicationGatewayRedirectConfiguration), serialize_when_none=False)
request_routing_rules = ListType(ModelType(ApplicationGatewayRequestRoutingRule), serialize_when_none=False)
resource_guid = StringType(serialize_when_none=False)
rewrite_rule_sets = ListType(ModelType(ApplicationGatewayRewriteRuleSet), serialize_when_none=False)
sku = ModelType(ApplicationGatewaySku, serialize_when_none=False)
ssl_certificates = ListType(ModelType(ApplicationGatewaySslCertificate), serialize_when_none=False)
ssl_policy = ModelType(ApplicationGatewaySslPolicy, serialize_when_none=False)
ssl_profiles = ListType(ModelType(ApplicationGatewaySslProfile), serialize_when_none=False)
trusted_client_certificates = ListType(ModelType(ApplicationGatewayTrustedClientCertificate), serialize_when_none=False)
trusted_root_certificates = ListType(ModelType(ApplicationGatewayTrustedRootCertificate), serialize_when_none=False)
url_path_maps = ListType(ModelType(ApplicationGatewayUrlPathMap), serialize_when_none=False)
web_application_firewall_configuration = ModelType(ApplicationGatewayWebApplicationFirewallConfiguration, serialize_when_none=False)
resource_group = StringType(serialize_when_none=False)
subscription_id = StringType(serialize_when_none=False)
subscription_name = StringType(serialize_when_none=False)
private_ip_address = StringType(serialize_when_none=False)
public_ip_address = ModelType(PublicIPAddress, serialize_when_none=False)
virtual_network = StringType(serialize_when_none=False)
subnet = StringType(serialize_when_none=False)
tags = ModelType(Tags, serialize_when_none=False)
type = StringType(serialize_when_none=False)
zones = ListType(StringType, serialize_when_none=False)
def reference(self):
return {
"resource_id": self.id,
"external_link": f"https://portal.azure.com/#@.onmicrosoft.com/resource{self.id}/overview",
}
| true | true |
f723a6b4dc78a8fb71d104e18b609238433e4759 | 1,443 | py | Python | b4sh/__main__.py | Sanix-Darker/b4sh | cef74d10729212bd5cb5d9cc881f75262fdca678 | [
"MIT"
] | 1 | 2020-12-08T22:25:41.000Z | 2020-12-08T22:25:41.000Z | b4sh/__main__.py | Sanix-Darker/b4sh | cef74d10729212bd5cb5d9cc881f75262fdca678 | [
"MIT"
] | null | null | null | b4sh/__main__.py | Sanix-Darker/b4sh | cef74d10729212bd5cb5d9cc881f75262fdca678 | [
"MIT"
] | 1 | 2020-12-08T21:17:21.000Z | 2020-12-08T21:17:21.000Z | from b4sh import *
from sys import argv
from b4sh.utils.create import create_b4sh
if __name__ == "__main__":
if len(argv) > 1:
print("[x] Starting b4sh...")
if "-ls" in argv[1] or "--list" in argv[1]:
list_all()
elif '-c' in argv[1] or '--create' in argv[1]:
create_b4sh(argv[2]) if len(argv) > 2 else create_b4sh()
elif '-h' in argv[1] or '--help' in argv[1]:
paste_help()
else:
# Initialize the arguments
prs = argparse.ArgumentParser('b4sh', add_help=False)
prs.add_argument('-g', '--get',
help='To get a b4sh by key/id, Ex: b4sh -g apache2_eerft',
type=str)
prs.add_argument('-f', '--find',
help='To find a b4sh by name online, Ex: b4sh -f nginx',
type=str)
prs.add_argument('-r', '--run',
help='To run directly with the good key/id, Ex: b4sh -r nginx_eedrf4',
type=str)
prs.add_argument('-v', '--version',
action='version',
help='To get the actual version of b4sh, Ex: b4sh -v',
version="[-] b4sh version {}".format(VERSION))
prs = prs.parse_args()
cmd_parser(prs)
else:
paste_help()
| 37.973684 | 99 | 0.467775 | from b4sh import *
from sys import argv
from b4sh.utils.create import create_b4sh
if __name__ == "__main__":
if len(argv) > 1:
print("[x] Starting b4sh...")
if "-ls" in argv[1] or "--list" in argv[1]:
list_all()
elif '-c' in argv[1] or '--create' in argv[1]:
create_b4sh(argv[2]) if len(argv) > 2 else create_b4sh()
elif '-h' in argv[1] or '--help' in argv[1]:
paste_help()
else:
prs = argparse.ArgumentParser('b4sh', add_help=False)
prs.add_argument('-g', '--get',
help='To get a b4sh by key/id, Ex: b4sh -g apache2_eerft',
type=str)
prs.add_argument('-f', '--find',
help='To find a b4sh by name online, Ex: b4sh -f nginx',
type=str)
prs.add_argument('-r', '--run',
help='To run directly with the good key/id, Ex: b4sh -r nginx_eedrf4',
type=str)
prs.add_argument('-v', '--version',
action='version',
help='To get the actual version of b4sh, Ex: b4sh -v',
version="[-] b4sh version {}".format(VERSION))
prs = prs.parse_args()
cmd_parser(prs)
else:
paste_help()
| true | true |
f723a6b5428de4c2c015ce5d4ab3106bd2ac7104 | 765 | py | Python | faker/providers/phone_number/es_MX/__init__.py | tristanHdez18/faker | 14cb25712e6efcb7bf8d9f30f404a7304722af6d | [
"MIT"
] | 1 | 2022-02-16T23:14:19.000Z | 2022-02-16T23:14:19.000Z | faker/providers/phone_number/es_MX/__init__.py | tristanHdez18/faker | 14cb25712e6efcb7bf8d9f30f404a7304722af6d | [
"MIT"
] | 33 | 2020-12-09T16:49:15.000Z | 2022-01-04T22:03:10.000Z | faker/providers/phone_number/es_MX/__init__.py | tristanHdez18/faker | 14cb25712e6efcb7bf8d9f30f404a7304722af6d | [
"MIT"
] | 3 | 2022-02-07T18:18:54.000Z | 2022-03-11T22:09:01.000Z | from .. import Provider as PhoneNumberProvider
class Provider(PhoneNumberProvider):
formats = (
"+##(#)##########",
"+##(#)##########",
"0##########",
"0##########",
"###-###-####",
"(###)###-####",
"1-###-###-####",
"###.###.####",
"###-###-####",
"(###)###-####",
"1-###-###-####",
"###.###.####",
"###-###-####x###",
"(###)###-####x###",
"1-###-###-####x###",
"###.###.####x###",
"###-###-####x####",
"(###)###-####x####",
"1-###-###-####x####",
"###.###.####x####",
"###-###-####x#####",
"(###)###-####x#####",
"1-###-###-####x#####",
"###.###.####x#####",
)
| 24.677419 | 46 | 0.126797 | from .. import Provider as PhoneNumberProvider
class Provider(PhoneNumberProvider):
formats = (
"+##(#)##########",
"+##(#)##########",
"0##########",
"0##########",
"###-###-####",
"(###)###-####",
"1-###-###-####",
"###.###.####",
"###-###-####",
"(###)###-####",
"1-###-###-####",
"###.###.####",
"###-###-####x###",
"(###)###-####x###",
"1-###-###-####x###",
"###.###.####x###",
"###-###-####x####",
"(###)###-####x####",
"1-###-###-####x####",
"###.###.####x####",
"###-###-####x#####",
"(###)###-####x#####",
"1-###-###-####x#####",
"###.###.####x#####",
)
| true | true |
f723a71c101ccfdacdafab959223007df2b7e9ea | 10,707 | py | Python | executor/cli.py | eyJhb/python-executor | ce71441199613d94441ff31d26f8fd5d48210c6e | [
"MIT"
] | null | null | null | executor/cli.py | eyJhb/python-executor | ce71441199613d94441ff31d26f8fd5d48210c6e | [
"MIT"
] | null | null | null | executor/cli.py | eyJhb/python-executor | ce71441199613d94441ff31d26f8fd5d48210c6e | [
"MIT"
] | null | null | null | # Command line interface for the executor package.
#
# Author: Peter Odding <peter@peterodding.com>
# Last Change: October 7, 2018
# URL: https://executor.readthedocs.io
#
# TODO Expose a clean way to interrupt the fudge factor of other processes.
# TODO Properly document command timeout / lock-timeout / TERM-timeout / KILL-timeout.
# TODO See if there's a way to move command timeout support out of the CLI?
# TODO Find ways to improve the coverage of this module! (multiprocessing?)
"""
Usage: executor [OPTIONS] COMMAND ...
Easy subprocess management on the command line based on the Python package with
the same name. The `executor' program runs external commands with support for
timeouts, dynamic startup delay (fudge factor) and exclusive locking.
You can think of `executor' as a combination of the `flock' and `timelimit'
programs with some additional niceties (namely the dynamic startup delay and
integrated system logging on UNIX platforms).
Supported options:
-t, --timeout=LIMIT
Set the time after which the given command will be aborted. By default
LIMIT is counted in seconds. You can also use one of the suffixes `s'
(seconds), `m' (minutes), `h' (hours) or `d' (days).
-f, --fudge-factor=LIMIT
This option controls the dynamic startup delay (fudge factor) which is
useful when you want a periodic task to run once per given interval but the
exact time is not important. Refer to the --timeout option for acceptable
values of LIMIT, this number specifies the maximum amount of time to sleep
before running the command (the minimum is zero, otherwise you could just
include the command `sleep N && ...' in your command line :-).
-e, --exclusive
Use an interprocess lock file to guarantee that executor will never run
the external command concurrently. Refer to the --lock-timeout option
to customize blocking / non-blocking behavior. To customize the name
of the lock file you can use the --lock-file option.
-T, --lock-timeout=LIMIT
By default executor tries to claim the lock and if it fails it will exit
with a nonzero exit code. This option can be used to enable blocking
behavior. Refer to the --timeout option for acceptable values of LIMIT.
-l, --lock-file=NAME
Customize the name of the lock file. By default this is the base name of
the external command, so if you're running something generic like `bash'
or `python' you might want to change this :-).
-v, --verbose
Increase logging verbosity (can be repeated).
-q, --quiet
Decrease logging verbosity (can be repeated).
-h, --help
Show this message and exit.
"""
# Standard library modules.
import getopt
import logging
import os
import random
import sys
import tempfile
import time
# External dependencies.
import coloredlogs
from fasteners.process_lock import InterProcessLock
from humanfriendly import Timer, format, format_timespan, parse_timespan
from humanfriendly.terminal import usage, warning
from six.moves.urllib.parse import quote as urlencode
# Modules included in our package.
from executor import ExternalCommandFailed, execute, quote, which
LOCKS_DIRECTORY = '/var/lock'
"""
The pathname of the preferred directory for lock files (a string).
Refer to :func:`get_lock_path()` for more details.
"""
INTERRUPT_FILE = 'executor-fudge-factor-interrupt'
"""The base name of the file used to interrupt the fudge factor (a string)."""
# Initialize a logger for this module.
logger = logging.getLogger(__name__)
def main():
"""Command line interface for the ``executor`` program."""
# Enable logging to the terminal and system log.
coloredlogs.install(syslog=True)
# Command line option defaults.
command_timeout = 0
exclusive = False
fudge_factor = 0
lock_name = None
lock_timeout = 0
# Parse the command line options.
try:
options, arguments = getopt.getopt(sys.argv[1:], 'eT:l:t:f:vqh', [
'exclusive', 'lock-timeout=', 'lock-file=', 'timeout=',
'fudge-factor=', 'verbose', 'quiet', 'help',
])
for option, value in options:
if option in ('-e', '--exclusive'):
exclusive = True
elif option in ('-T', '--lock-timeout'):
lock_timeout = parse_timespan(value)
elif option in ('-l', '--lock-file'):
lock_name = value
elif option in ('-t', '--timeout'):
command_timeout = parse_timespan(value)
elif option in ('-f', '--fudge-factor'):
fudge_factor = parse_timespan(value)
elif option in ('-v', '--verbose'):
coloredlogs.increase_verbosity()
elif option in ('-q', '--quiet'):
coloredlogs.decrease_verbosity()
elif option in ('-h', '--help'):
usage(__doc__)
sys.exit(0)
else:
assert False, "Unhandled option!"
# Make sure the operator provided a program to execute.
if not arguments:
usage(__doc__)
sys.exit(0)
# Make sure the program actually exists.
program_name = arguments[0]
if not os.path.isfile(program_name):
# Only search the $PATH if the given program name
# doesn't already include one or more path segments.
if program_name == os.path.basename(program_name):
matching_programs = which(program_name)
if matching_programs:
program_name = matching_programs[0]
# The subprocess.Popen() call later on doesn't search the $PATH so we
# make sure to give it the absolute pathname to the program.
arguments[0] = program_name
except Exception as e:
warning("Failed to parse command line arguments: %s", e)
sys.exit(1)
# Apply the requested fudge factor.
apply_fudge_factor(fudge_factor)
# Run the requested command.
try:
if exclusive:
# Select a default lock file name?
if not lock_name:
lock_name = os.path.basename(arguments[0])
logger.debug("Using base name of command as lock file name (%s).", lock_name)
lock_file = get_lock_path(lock_name)
lock = InterProcessLock(path=lock_file, logger=logger)
logger.debug("Trying to acquire exclusive lock: %s", lock_file)
if lock.acquire(blocking=(lock_timeout > 0), max_delay=lock_timeout):
logger.info("Successfully acquired exclusive lock: %s", lock_file)
run_command(arguments, timeout=command_timeout)
else:
logger.error("Failed to acquire exclusive lock: %s", lock_file)
sys.exit(1)
else:
run_command(arguments, timeout=command_timeout)
except ExternalCommandFailed as e:
logger.error("%s", e.error_message)
sys.exit(e.command.returncode)
def apply_fudge_factor(fudge_factor):
"""
Apply the requested scheduling fudge factor.
:param fudge_factor: The maximum number of seconds to sleep (a number).
Previous implementations of the fudge factor interrupt used UNIX signals
(specifically ``SIGUSR1``) but the use of this signal turned out to be
sensitive to awkward race conditions and it wasn't very cross platform, so
now the creation of a regular file is used to interrupt the fudge factor.
"""
if fudge_factor:
timer = Timer()
logger.debug("Calculating fudge factor based on user defined maximum (%s) ..",
format_timespan(fudge_factor))
fudged_sleep_time = fudge_factor * random.random()
logger.info("Sleeping for %s because of user defined fudge factor ..",
format_timespan(fudged_sleep_time))
interrupt_file = get_lock_path(INTERRUPT_FILE)
while timer.elapsed_time < fudged_sleep_time:
if os.path.isfile(interrupt_file):
logger.info("Fudge factor sleep was interrupted! (%s exists)",
interrupt_file)
break
time_to_sleep = min(1, fudged_sleep_time - timer.elapsed_time)
if time_to_sleep > 0:
time.sleep(time_to_sleep)
else:
logger.info("Finished sleeping because of fudge factor (took %s).", timer)
def get_lock_path(lock_name):
"""
Get a pathname that can be used for an interprocess lock.
:param lock_name: The base name for the lock file (a string).
:returns: An absolute pathname (a string).
"""
lock_file = '%s.lock' % urlencode(lock_name, safe='')
if os.path.isdir(LOCKS_DIRECTORY) and os.access(LOCKS_DIRECTORY, os.W_OK):
return os.path.join(LOCKS_DIRECTORY, lock_file)
else:
return os.path.join(tempfile.gettempdir(), lock_file)
def run_command(arguments, timeout=None):
"""
Run the specified command (with an optional timeout).
:param arguments: The command line for the external command (a list of
strings).
:param timeout: The optional command timeout (a number or :data:`None`).
:raises: :exc:`CommandTimedOut` if the command times out.
"""
timer = Timer()
logger.info("Running command: %s", quote(arguments))
with execute(*arguments, asynchronous=True) as command:
# Wait for the command to finish or exceed the given timeout.
while command.is_running:
if timeout and timer.elapsed_time > timeout:
raise CommandTimedOut(command, timeout)
# Sleep between 0.1 and 1 second, waiting for
# the external command to finish its execution.
time_to_sleep = min(1, max(0.1, timeout - timer.elapsed_time))
if time_to_sleep > 0:
time.sleep(time_to_sleep)
if command.succeeded:
logger.info("Command completed successfully in %s.", timer)
class CommandTimedOut(ExternalCommandFailed):
"""Raised when a command exceeds the given timeout."""
def __init__(self, command, timeout):
"""
Initialize a :class:`CommandTimedOut` object.
:param command: The command that timed out (an
:class:`~executor.ExternalCommand` object).
:param timeout: The timeout that was exceeded (a number).
"""
super(CommandTimedOut, self).__init__(
command=command,
error_message=format(
"External command exceeded timeout of %s: %s",
format_timespan(timeout),
quote(command.command_line),
),
)
| 38.934545 | 93 | 0.653124 |
# TODO Find ways to improve the coverage of this module! (multiprocessing?)
# Standard library modules.
import getopt
import logging
import os
import random
import sys
import tempfile
import time
# External dependencies.
import coloredlogs
from fasteners.process_lock import InterProcessLock
from humanfriendly import Timer, format, format_timespan, parse_timespan
from humanfriendly.terminal import usage, warning
from six.moves.urllib.parse import quote as urlencode
# Modules included in our package.
from executor import ExternalCommandFailed, execute, quote, which
LOCKS_DIRECTORY = '/var/lock'
INTERRUPT_FILE = 'executor-fudge-factor-interrupt'
# Initialize a logger for this module.
logger = logging.getLogger(__name__)
def main():
# Enable logging to the terminal and system log.
coloredlogs.install(syslog=True)
# Command line option defaults.
command_timeout = 0
exclusive = False
fudge_factor = 0
lock_name = None
lock_timeout = 0
# Parse the command line options.
try:
options, arguments = getopt.getopt(sys.argv[1:], 'eT:l:t:f:vqh', [
'exclusive', 'lock-timeout=', 'lock-file=', 'timeout=',
'fudge-factor=', 'verbose', 'quiet', 'help',
])
for option, value in options:
if option in ('-e', '--exclusive'):
exclusive = True
elif option in ('-T', '--lock-timeout'):
lock_timeout = parse_timespan(value)
elif option in ('-l', '--lock-file'):
lock_name = value
elif option in ('-t', '--timeout'):
command_timeout = parse_timespan(value)
elif option in ('-f', '--fudge-factor'):
fudge_factor = parse_timespan(value)
elif option in ('-v', '--verbose'):
coloredlogs.increase_verbosity()
elif option in ('-q', '--quiet'):
coloredlogs.decrease_verbosity()
elif option in ('-h', '--help'):
usage(__doc__)
sys.exit(0)
else:
assert False, "Unhandled option!"
# Make sure the operator provided a program to execute.
if not arguments:
usage(__doc__)
sys.exit(0)
# Make sure the program actually exists.
program_name = arguments[0]
if not os.path.isfile(program_name):
# Only search the $PATH if the given program name
# doesn't already include one or more path segments.
if program_name == os.path.basename(program_name):
matching_programs = which(program_name)
if matching_programs:
program_name = matching_programs[0]
# make sure to give it the absolute pathname to the program.
arguments[0] = program_name
except Exception as e:
warning("Failed to parse command line arguments: %s", e)
sys.exit(1)
# Apply the requested fudge factor.
apply_fudge_factor(fudge_factor)
# Run the requested command.
try:
if exclusive:
# Select a default lock file name?
if not lock_name:
lock_name = os.path.basename(arguments[0])
logger.debug("Using base name of command as lock file name (%s).", lock_name)
lock_file = get_lock_path(lock_name)
lock = InterProcessLock(path=lock_file, logger=logger)
logger.debug("Trying to acquire exclusive lock: %s", lock_file)
if lock.acquire(blocking=(lock_timeout > 0), max_delay=lock_timeout):
logger.info("Successfully acquired exclusive lock: %s", lock_file)
run_command(arguments, timeout=command_timeout)
else:
logger.error("Failed to acquire exclusive lock: %s", lock_file)
sys.exit(1)
else:
run_command(arguments, timeout=command_timeout)
except ExternalCommandFailed as e:
logger.error("%s", e.error_message)
sys.exit(e.command.returncode)
def apply_fudge_factor(fudge_factor):
if fudge_factor:
timer = Timer()
logger.debug("Calculating fudge factor based on user defined maximum (%s) ..",
format_timespan(fudge_factor))
fudged_sleep_time = fudge_factor * random.random()
logger.info("Sleeping for %s because of user defined fudge factor ..",
format_timespan(fudged_sleep_time))
interrupt_file = get_lock_path(INTERRUPT_FILE)
while timer.elapsed_time < fudged_sleep_time:
if os.path.isfile(interrupt_file):
logger.info("Fudge factor sleep was interrupted! (%s exists)",
interrupt_file)
break
time_to_sleep = min(1, fudged_sleep_time - timer.elapsed_time)
if time_to_sleep > 0:
time.sleep(time_to_sleep)
else:
logger.info("Finished sleeping because of fudge factor (took %s).", timer)
def get_lock_path(lock_name):
lock_file = '%s.lock' % urlencode(lock_name, safe='')
if os.path.isdir(LOCKS_DIRECTORY) and os.access(LOCKS_DIRECTORY, os.W_OK):
return os.path.join(LOCKS_DIRECTORY, lock_file)
else:
return os.path.join(tempfile.gettempdir(), lock_file)
def run_command(arguments, timeout=None):
timer = Timer()
logger.info("Running command: %s", quote(arguments))
with execute(*arguments, asynchronous=True) as command:
# Wait for the command to finish or exceed the given timeout.
while command.is_running:
if timeout and timer.elapsed_time > timeout:
raise CommandTimedOut(command, timeout)
# Sleep between 0.1 and 1 second, waiting for
# the external command to finish its execution.
time_to_sleep = min(1, max(0.1, timeout - timer.elapsed_time))
if time_to_sleep > 0:
time.sleep(time_to_sleep)
if command.succeeded:
logger.info("Command completed successfully in %s.", timer)
class CommandTimedOut(ExternalCommandFailed):
def __init__(self, command, timeout):
super(CommandTimedOut, self).__init__(
command=command,
error_message=format(
"External command exceeded timeout of %s: %s",
format_timespan(timeout),
quote(command.command_line),
),
)
| true | true |
f723a7e316f05dd510c09ac774ab6103a90f49f4 | 6,252 | py | Python | libs/yowsup/yowsup/yowsup/common/http/warequest.py | akshitpradhan/TomHack | 837226e7b38de1140c19bc2d478eeb9e379ed1fd | [
"MIT"
] | null | null | null | libs/yowsup/yowsup/yowsup/common/http/warequest.py | akshitpradhan/TomHack | 837226e7b38de1140c19bc2d478eeb9e379ed1fd | [
"MIT"
] | null | null | null | libs/yowsup/yowsup/yowsup/common/http/warequest.py | akshitpradhan/TomHack | 837226e7b38de1140c19bc2d478eeb9e379ed1fd | [
"MIT"
] | null | null | null | import urllib,sys, os, logging
import hashlib
from .waresponseparser import ResponseParser
from yowsup.env import YowsupEnv
from .httpproxy import HttpProxy
if sys.version_info < (3, 0):
import httplib
from urllib import urlencode
if sys.version_info >= (2, 7, 9):
#see https://github.com/tgalal/yowsup/issues/677
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
else:
from http import client as httplib
from urllib.parse import urlencode
logger = logging.getLogger(__name__)
class WARequest(object):
OK = 200
def __init__(self):
self.pvars = []
self.port = 443
self.type = "GET"
self.parser = None
self.params = []
self.headers = {}
self.sent = False
self.response = None
def setParsableVariables(self, pvars):
self.pvars = pvars
def onResponse(self, name, value):
if name == "status":
self.status = value
elif name == "result":
self.result = value
def addParam(self,name,value):
self.params.append((name,value))
def removeParam(self, name):
for i in range(0, len(self.params)):
if self.params[i][0] == name:
del self.params[i]
def addHeaderField(self, name, value):
self.headers[name] = value
def clearParams(self):
self.params = []
def getUserAgent(self):
return YowsupEnv.getCurrent().getUserAgent()
def send(self, parser = None):
if self.type == "POST":
return self.sendPostRequest(parser)
return self.sendGetRequest(parser)
def setParser(self, parser):
if isinstance(parser, ResponseParser):
self.parser = parser
else:
logger.error("Invalid parser")
def getConnectionParameters(self):
if not self.url:
return "", "", self.port
try:
url = self.url.split("://", 1)
url = url[0] if len(url) == 1 else url[1]
host, path = url.split('/', 1)
except ValueError:
host = url
path = ""
path = "/" + path
return host, self.port, path
def sendGetRequest(self, parser = None):
self.response = None
params = self.params#[param.items()[0] for param in self.params];
parser = parser or self.parser or ResponseParser()
headers = dict(list({"User-Agent":self.getUserAgent(),
"Accept": parser.getMeta()
}.items()) + list(self.headers.items()));
host,port,path = self.getConnectionParameters()
proxy = HttpProxy.getFromEnviron()
if proxy is None:
self.response = WARequest.sendRequest(host, port, path, headers, params, "GET")
if not self.response.status == WARequest.OK:
logger.error("Request not success, status was %s"%self.response.status)
return {}
data = self.response.read()
logger.info(data)
self.sent = True
return parser.parse(data.decode(), self.pvars)
else:
logger.info("Request with proxy")
self.response = WARequest.sendRequestWithProxy(host, port,path,headers, params, proxy)
logger.info(self.response)
return self.response
def sendPostRequest(self, parser = None):
self.response = None
params = self.params #[param.items()[0] for param in self.params];
parser = parser or self.parser or ResponseParser()
headers = dict(list({"User-Agent":self.getUserAgent(),
"Accept": parser.getMeta(),
"Content-Type":"application/x-www-form-urlencoded"
}.items()) + list(self.headers.items()))
host,port,path = self.getConnectionParameters()
self.response = WARequest.sendRequest(host, port, path, headers, params, "POST")
if not self.response.status == WARequest.OK:
logger.error("Request not success, status was %s" % self.response.status)
return {}
data = self.response.read()
logger.info(data)
self.sent = True
return parser.parse(data.decode(), self.pvars)
@staticmethod
def sendRequest(host, port, path, headers, params, reqType="GET"):
params = urlencode(params)
path = path + "?"+ params if reqType == "GET" and params else path
if len(headers):
logger.debug(headers)
if len(params):
logger.debug(params)
logger.debug("Opening connection to %s" % host);
conn = httplib.HTTPSConnection(host ,port) if port == 443 else httplib.HTTPConnection(host ,port)
logger.debug("Sending %s request to %s" % (reqType, path))
conn.request(reqType, path, params, headers);
response = conn.getresponse()
return response
def sendRequestWithProxy(host,port,path,headers,params,proxy):
import pycurl
import json
from io import BytesIO
logger.info("SENDING PROXY REQUEST WITH %s"%proxy.getHost())
bytes_buffer = BytesIO()
c = pycurl.Curl()
c.setopt(pycurl.URL, WARequest.build_get_url(host,path,params))
c.setopt(pycurl.PROXY,proxy.getHost())
c.setopt(pycurl.PROXYPORT,proxy.getPort())
if proxy.getUserName() is not None:
c.setopt(pycurl.PROXYUSERPWD, "%s:%s" % (proxy.getUser(), proxy.getPassword()))
c.setopt(pycurl.PORT, port)
c.setopt(pycurl.HTTPHEADER,WARequest.build_headers(headers))
c.setopt(pycurl.WRITEDATA, bytes_buffer)
c.perform()
c.close()
data = bytes_buffer.getvalue().decode('utf-8')
return json.loads(data)
@staticmethod
def build_get_url(host, path, params):
params = urlencode(params)
url = 'https://'+host+path+"?"+params
print(url)
return url
@staticmethod
def build_headers(headers_tuple):
headers_array = []
for idx in headers_tuple:
headers_array.append(idx + ":"+headers_tuple[idx])
print(headers_array)
return headers_array
| 29.490566 | 105 | 0.59453 | import urllib,sys, os, logging
import hashlib
from .waresponseparser import ResponseParser
from yowsup.env import YowsupEnv
from .httpproxy import HttpProxy
if sys.version_info < (3, 0):
import httplib
from urllib import urlencode
if sys.version_info >= (2, 7, 9):
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
else:
from http import client as httplib
from urllib.parse import urlencode
logger = logging.getLogger(__name__)
class WARequest(object):
OK = 200
def __init__(self):
self.pvars = []
self.port = 443
self.type = "GET"
self.parser = None
self.params = []
self.headers = {}
self.sent = False
self.response = None
def setParsableVariables(self, pvars):
self.pvars = pvars
def onResponse(self, name, value):
if name == "status":
self.status = value
elif name == "result":
self.result = value
def addParam(self,name,value):
self.params.append((name,value))
def removeParam(self, name):
for i in range(0, len(self.params)):
if self.params[i][0] == name:
del self.params[i]
def addHeaderField(self, name, value):
self.headers[name] = value
def clearParams(self):
self.params = []
def getUserAgent(self):
return YowsupEnv.getCurrent().getUserAgent()
def send(self, parser = None):
if self.type == "POST":
return self.sendPostRequest(parser)
return self.sendGetRequest(parser)
def setParser(self, parser):
if isinstance(parser, ResponseParser):
self.parser = parser
else:
logger.error("Invalid parser")
def getConnectionParameters(self):
if not self.url:
return "", "", self.port
try:
url = self.url.split("://", 1)
url = url[0] if len(url) == 1 else url[1]
host, path = url.split('/', 1)
except ValueError:
host = url
path = ""
path = "/" + path
return host, self.port, path
def sendGetRequest(self, parser = None):
self.response = None
params = self.params
parser = parser or self.parser or ResponseParser()
headers = dict(list({"User-Agent":self.getUserAgent(),
"Accept": parser.getMeta()
}.items()) + list(self.headers.items()));
host,port,path = self.getConnectionParameters()
proxy = HttpProxy.getFromEnviron()
if proxy is None:
self.response = WARequest.sendRequest(host, port, path, headers, params, "GET")
if not self.response.status == WARequest.OK:
logger.error("Request not success, status was %s"%self.response.status)
return {}
data = self.response.read()
logger.info(data)
self.sent = True
return parser.parse(data.decode(), self.pvars)
else:
logger.info("Request with proxy")
self.response = WARequest.sendRequestWithProxy(host, port,path,headers, params, proxy)
logger.info(self.response)
return self.response
def sendPostRequest(self, parser = None):
self.response = None
params = self.params
parser = parser or self.parser or ResponseParser()
headers = dict(list({"User-Agent":self.getUserAgent(),
"Accept": parser.getMeta(),
"Content-Type":"application/x-www-form-urlencoded"
}.items()) + list(self.headers.items()))
host,port,path = self.getConnectionParameters()
self.response = WARequest.sendRequest(host, port, path, headers, params, "POST")
if not self.response.status == WARequest.OK:
logger.error("Request not success, status was %s" % self.response.status)
return {}
data = self.response.read()
logger.info(data)
self.sent = True
return parser.parse(data.decode(), self.pvars)
@staticmethod
def sendRequest(host, port, path, headers, params, reqType="GET"):
params = urlencode(params)
path = path + "?"+ params if reqType == "GET" and params else path
if len(headers):
logger.debug(headers)
if len(params):
logger.debug(params)
logger.debug("Opening connection to %s" % host);
conn = httplib.HTTPSConnection(host ,port) if port == 443 else httplib.HTTPConnection(host ,port)
logger.debug("Sending %s request to %s" % (reqType, path))
conn.request(reqType, path, params, headers);
response = conn.getresponse()
return response
def sendRequestWithProxy(host,port,path,headers,params,proxy):
import pycurl
import json
from io import BytesIO
logger.info("SENDING PROXY REQUEST WITH %s"%proxy.getHost())
bytes_buffer = BytesIO()
c = pycurl.Curl()
c.setopt(pycurl.URL, WARequest.build_get_url(host,path,params))
c.setopt(pycurl.PROXY,proxy.getHost())
c.setopt(pycurl.PROXYPORT,proxy.getPort())
if proxy.getUserName() is not None:
c.setopt(pycurl.PROXYUSERPWD, "%s:%s" % (proxy.getUser(), proxy.getPassword()))
c.setopt(pycurl.PORT, port)
c.setopt(pycurl.HTTPHEADER,WARequest.build_headers(headers))
c.setopt(pycurl.WRITEDATA, bytes_buffer)
c.perform()
c.close()
data = bytes_buffer.getvalue().decode('utf-8')
return json.loads(data)
@staticmethod
def build_get_url(host, path, params):
params = urlencode(params)
url = 'https://'+host+path+"?"+params
print(url)
return url
@staticmethod
def build_headers(headers_tuple):
headers_array = []
for idx in headers_tuple:
headers_array.append(idx + ":"+headers_tuple[idx])
print(headers_array)
return headers_array
| true | true |
f723a8b910c26396af2b76ef90aa5780ae4ad126 | 13,646 | py | Python | utils/sparse_molecular_dataset.py | naveenarun/MolGAN | c304707144ec9a4870390011aa73cdc7078a0e9d | [
"MIT"
] | 1 | 2022-01-08T13:47:02.000Z | 2022-01-08T13:47:02.000Z | utils/sparse_molecular_dataset.py | shiyu-wangbyte/MolGAN | c304707144ec9a4870390011aa73cdc7078a0e9d | [
"MIT"
] | null | null | null | utils/sparse_molecular_dataset.py | shiyu-wangbyte/MolGAN | c304707144ec9a4870390011aa73cdc7078a0e9d | [
"MIT"
] | null | null | null | import pickle
import numpy as np
from rdkit import Chem
if __name__ == '__main__':
from progress_bar import ProgressBar
else:
from utils.progress_bar import ProgressBar
from datetime import datetime
class SparseMolecularDataset():
def load(self, filename, subset=1):
with open(filename, 'rb') as f:
self.__dict__.update(pickle.load(f))
self.train_idx = np.random.choice(self.train_idx, int(len(self.train_idx) * subset), replace=False)
self.validation_idx = np.random.choice(self.validation_idx, int(len(self.validation_idx) * subset),
replace=False)
self.test_idx = np.random.choice(self.test_idx, int(len(self.test_idx) * subset), replace=False)
self.train_count = len(self.train_idx)
self.validation_count = len(self.validation_idx)
self.test_count = len(self.test_idx)
self.__len = self.train_count + self.validation_count + self.test_count
def save(self, filename):
with open(filename, 'wb') as f:
pickle.dump(self.__dict__, f)
def generate(self, filename, add_h=False, filters=lambda x: True, size=None, validation=0.1, test=0.1):
self.log('Extracting {}..'.format(filename))
if filename.endswith('.sdf'):
self.data = list(filter(lambda x: x is not None, Chem.SDMolSupplier(filename)))
elif filename.endswith('.smi'):
self.data = [Chem.MolFromSmiles(line) for line in open(filename, 'r').readlines()]
self.data = list(map(Chem.AddHs, self.data)) if add_h else self.data
self.data = list(filter(filters, self.data))
self.data = self.data[:size]
self.log('Extracted {} out of {} molecules {}adding Hydrogen!'.format(len(self.data),
len(Chem.SDMolSupplier(filename)),
'' if add_h else 'not '))
self._generate_encoders_decoders()
self._generate_AX()
# it contains the all the molecules stored as rdkit.Chem objects
self.data = np.array(self.data)
# it contains the all the molecules stored as SMILES strings
self.smiles = np.array(self.smiles)
# a (N, L) matrix where N is the length of the dataset and each L-dim vector contains the
# indices corresponding to a SMILE sequences with padding wrt the max length of the longest
# SMILES sequence in the dataset (see self._genS)
self.data_S = np.stack(self.data_S)
# a (N, 9, 9) tensor where N is the length of the dataset and each 9x9 matrix contains the
# indices of the positions of the ones in the one-hot representation of the adjacency tensor
# (see self._genA)
self.data_A = np.stack(self.data_A)
# a (N, 9) matrix where N is the length of the dataset and each 9-dim vector contains the
# indices of the positions of the ones in the one-hot representation of the annotation matrix
# (see self._genX)
self.data_X = np.stack(self.data_X)
# a (N, 9) matrix where N is the length of the dataset and each 9-dim vector contains the
# diagonal of the correspondent adjacency matrix
self.data_D = np.stack(self.data_D)
# a (N, F) matrix where N is the length of the dataset and each F vector contains features
# of the correspondent molecule (see self._genF)
self.data_F = np.stack(self.data_F)
# a (N, 9) matrix where N is the length of the dataset and each 9-dim vector contains the
# eigenvalues of the correspondent Laplacian matrix
self.data_Le = np.stack(self.data_Le)
# a (N, 9, 9) matrix where N is the length of the dataset and each 9x9 matrix contains the
# eigenvectors of the correspondent Laplacian matrix
self.data_Lv = np.stack(self.data_Lv)
self.vertexes = self.data_F.shape[-2]
self.features = self.data_F.shape[-1]
self._generate_train_validation_test(validation, test)
def _generate_encoders_decoders(self):
self.log('Creating atoms encoder and decoder..')
atom_labels = sorted(set([atom.GetAtomicNum() for mol in self.data for atom in mol.GetAtoms()] + [0]))
self.atom_encoder_m = {l: i for i, l in enumerate(atom_labels)}
self.atom_decoder_m = {i: l for i, l in enumerate(atom_labels)}
self.atom_num_types = len(atom_labels)
self.log('Created atoms encoder and decoder with {} atom types and 1 PAD symbol!'.format(
self.atom_num_types - 1))
self.log('Creating bonds encoder and decoder..')
bond_labels = [Chem.rdchem.BondType.ZERO] + list(sorted(set(bond.GetBondType()
for mol in self.data
for bond in mol.GetBonds())))
self.bond_encoder_m = {l: i for i, l in enumerate(bond_labels)}
self.bond_decoder_m = {i: l for i, l in enumerate(bond_labels)}
self.bond_num_types = len(bond_labels)
self.log('Created bonds encoder and decoder with {} bond types and 1 PAD symbol!'.format(
self.bond_num_types - 1))
self.log('Creating SMILES encoder and decoder..')
smiles_labels = ['E'] + list(set(c for mol in self.data for c in Chem.MolToSmiles(mol)))
self.smiles_encoder_m = {l: i for i, l in enumerate(smiles_labels)}
self.smiles_decoder_m = {i: l for i, l in enumerate(smiles_labels)}
self.smiles_num_types = len(smiles_labels)
self.log('Created SMILES encoder and decoder with {} types and 1 PAD symbol!'.format(
self.smiles_num_types - 1))
def _generate_AX(self):
self.log('Creating features and adjacency matrices..')
pr = ProgressBar(60, len(self.data))
data = []
smiles = []
data_S = []
data_A = []
data_X = []
data_D = []
data_F = []
data_Le = []
data_Lv = []
max_length = max(mol.GetNumAtoms() for mol in self.data)
max_length_s = max(len(Chem.MolToSmiles(mol)) for mol in self.data)
for i, mol in enumerate(self.data):
A = self._genA(mol, connected=True, max_length=max_length)
D = np.count_nonzero(A, -1)
if A is not None:
data.append(mol)
smiles.append(Chem.MolToSmiles(mol))
data_S.append(self._genS(mol, max_length=max_length_s))
data_A.append(A)
data_X.append(self._genX(mol, max_length=max_length))
data_D.append(D)
data_F.append(self._genF(mol, max_length=max_length))
L = D - A
Le, Lv = np.linalg.eigh(L)
data_Le.append(Le)
data_Lv.append(Lv)
pr.update(i + 1)
self.log(date=False)
self.log('Created {} features and adjacency matrices out of {} molecules!'.format(len(data),
len(self.data)))
self.data = data
self.smiles = smiles
self.data_S = data_S
self.data_A = data_A
self.data_X = data_X
self.data_D = data_D
self.data_F = data_F
self.data_Le = data_Le
self.data_Lv = data_Lv
self.__len = len(self.data)
def _genA(self, mol, connected=True, max_length=None):
max_length = max_length if max_length is not None else mol.GetNumAtoms()
A = np.zeros(shape=(max_length, max_length), dtype=np.int32)
begin, end = [b.GetBeginAtomIdx() for b in mol.GetBonds()], [b.GetEndAtomIdx() for b in mol.GetBonds()]
bond_type = [self.bond_encoder_m[b.GetBondType()] for b in mol.GetBonds()]
A[begin, end] = bond_type
A[end, begin] = bond_type
degree = np.sum(A[:mol.GetNumAtoms(), :mol.GetNumAtoms()], axis=-1)
return A if connected and (degree > 0).all() else None
def _genX(self, mol, max_length=None):
max_length = max_length if max_length is not None else mol.GetNumAtoms()
return np.array([self.atom_encoder_m[atom.GetAtomicNum()] for atom in mol.GetAtoms()] + [0] * (
max_length - mol.GetNumAtoms()), dtype=np.int32)
def _genS(self, mol, max_length=None):
max_length = max_length if max_length is not None else len(Chem.MolToSmiles(mol))
return np.array([self.smiles_encoder_m[c] for c in Chem.MolToSmiles(mol)] + [self.smiles_encoder_m['E']] * (
max_length - len(Chem.MolToSmiles(mol))), dtype=np.int32)
def _genF(self, mol, max_length=None):
max_length = max_length if max_length is not None else mol.GetNumAtoms()
features = np.array([[*[a.GetDegree() == i for i in range(5)],
*[a.GetExplicitValence() == i for i in range(9)],
*[int(a.GetHybridization()) == i for i in range(1, 7)],
*[a.GetImplicitValence() == i for i in range(9)],
a.GetIsAromatic(),
a.GetNoImplicit(),
*[a.GetNumExplicitHs() == i for i in range(5)],
*[a.GetNumImplicitHs() == i for i in range(5)],
*[a.GetNumRadicalElectrons() == i for i in range(5)],
a.IsInRing(),
*[a.IsInRingSize(i) for i in range(2, 9)]] for a in mol.GetAtoms()], dtype=np.int32)
return np.vstack((features, np.zeros((max_length - features.shape[0], features.shape[1]))))
def matrices2mol(self, node_labels, edge_labels, strict=False):
mol = Chem.RWMol()
for node_label in node_labels:
mol.AddAtom(Chem.Atom(self.atom_decoder_m[node_label]))
for start, end in zip(*np.nonzero(edge_labels)):
if start > end:
mol.AddBond(int(start), int(end), self.bond_decoder_m[edge_labels[start, end]])
if strict:
try:
Chem.SanitizeMol(mol)
except:
mol = None
return mol
def seq2mol(self, seq, strict=False):
mol = Chem.MolFromSmiles(''.join([self.smiles_decoder_m[e] for e in seq if e != 0]))
if strict:
try:
Chem.SanitizeMol(mol)
except:
mol = None
return mol
def _generate_train_validation_test(self, validation, test):
self.log('Creating train, validation and test sets..')
validation = int(validation * len(self))
test = int(test * len(self))
train = len(self) - validation - test
self.all_idx = np.random.permutation(len(self))
self.train_idx = self.all_idx[0:train]
self.validation_idx = self.all_idx[train:train + validation]
self.test_idx = self.all_idx[train + validation:]
self.train_counter = 0
self.validation_counter = 0
self.test_counter = 0
self.train_count = train
self.validation_count = validation
self.test_count = test
self.log('Created train ({} items), validation ({} items) and test ({} items) sets!'.format(
train, validation, test))
def _next_batch(self, counter, count, idx, batch_size):
if batch_size is not None:
if counter + batch_size >= count:
counter = 0
np.random.shuffle(idx)
output = [obj[idx[counter:counter + batch_size]]
for obj in (self.data, self.smiles, self.data_S, self.data_A, self.data_X,
self.data_D, self.data_F, self.data_Le, self.data_Lv)]
counter += batch_size
else:
output = [obj[idx] for obj in (self.data, self.smiles, self.data_S, self.data_A, self.data_X,
self.data_D, self.data_F, self.data_Le, self.data_Lv)]
return [counter] + output
def next_train_batch(self, batch_size=None):
out = self._next_batch(counter=self.train_counter, count=self.train_count,
idx=self.train_idx, batch_size=batch_size)
self.train_counter = out[0]
return out[1:]
def next_validation_batch(self, batch_size=None):
out = self._next_batch(counter=self.validation_counter, count=self.validation_count,
idx=self.validation_idx, batch_size=batch_size)
self.validation_counter = out[0]
return out[1:]
def next_test_batch(self, batch_size=None):
out = self._next_batch(counter=self.test_counter, count=self.test_count,
idx=self.test_idx, batch_size=batch_size)
self.test_counter = out[0]
return out[1:]
@staticmethod
def log(msg='', date=True):
print(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')) + ' ' + str(msg) if date else str(msg))
def __len__(self):
return self.__len
if __name__ == '__main__':
data = SparseMolecularDataset()
data.generate('data/gdb9.sdf', filters=lambda x: x.GetNumAtoms() <= 9)
data.save('data/gdb9_9nodes.sparsedataset')
# data = SparseMolecularDataset()
# data.generate('data/qm9_5k.smi', validation=0.00021, test=0.00021) # , filters=lambda x: x.GetNumAtoms() <= 9)
# data.save('data/qm9_5k.sparsedataset')
| 41.10241 | 117 | 0.590136 | import pickle
import numpy as np
from rdkit import Chem
if __name__ == '__main__':
from progress_bar import ProgressBar
else:
from utils.progress_bar import ProgressBar
from datetime import datetime
class SparseMolecularDataset():
def load(self, filename, subset=1):
with open(filename, 'rb') as f:
self.__dict__.update(pickle.load(f))
self.train_idx = np.random.choice(self.train_idx, int(len(self.train_idx) * subset), replace=False)
self.validation_idx = np.random.choice(self.validation_idx, int(len(self.validation_idx) * subset),
replace=False)
self.test_idx = np.random.choice(self.test_idx, int(len(self.test_idx) * subset), replace=False)
self.train_count = len(self.train_idx)
self.validation_count = len(self.validation_idx)
self.test_count = len(self.test_idx)
self.__len = self.train_count + self.validation_count + self.test_count
def save(self, filename):
with open(filename, 'wb') as f:
pickle.dump(self.__dict__, f)
def generate(self, filename, add_h=False, filters=lambda x: True, size=None, validation=0.1, test=0.1):
self.log('Extracting {}..'.format(filename))
if filename.endswith('.sdf'):
self.data = list(filter(lambda x: x is not None, Chem.SDMolSupplier(filename)))
elif filename.endswith('.smi'):
self.data = [Chem.MolFromSmiles(line) for line in open(filename, 'r').readlines()]
self.data = list(map(Chem.AddHs, self.data)) if add_h else self.data
self.data = list(filter(filters, self.data))
self.data = self.data[:size]
self.log('Extracted {} out of {} molecules {}adding Hydrogen!'.format(len(self.data),
len(Chem.SDMolSupplier(filename)),
'' if add_h else 'not '))
self._generate_encoders_decoders()
self._generate_AX()
self.data = np.array(self.data)
self.smiles = np.array(self.smiles)
self.data_S = np.stack(self.data_S)
self.data_A = np.stack(self.data_A)
self.data_X = np.stack(self.data_X)
self.data_D = np.stack(self.data_D)
self.data_F = np.stack(self.data_F)
self.data_Le = np.stack(self.data_Le)
self.data_Lv = np.stack(self.data_Lv)
self.vertexes = self.data_F.shape[-2]
self.features = self.data_F.shape[-1]
self._generate_train_validation_test(validation, test)
def _generate_encoders_decoders(self):
self.log('Creating atoms encoder and decoder..')
atom_labels = sorted(set([atom.GetAtomicNum() for mol in self.data for atom in mol.GetAtoms()] + [0]))
self.atom_encoder_m = {l: i for i, l in enumerate(atom_labels)}
self.atom_decoder_m = {i: l for i, l in enumerate(atom_labels)}
self.atom_num_types = len(atom_labels)
self.log('Created atoms encoder and decoder with {} atom types and 1 PAD symbol!'.format(
self.atom_num_types - 1))
self.log('Creating bonds encoder and decoder..')
bond_labels = [Chem.rdchem.BondType.ZERO] + list(sorted(set(bond.GetBondType()
for mol in self.data
for bond in mol.GetBonds())))
self.bond_encoder_m = {l: i for i, l in enumerate(bond_labels)}
self.bond_decoder_m = {i: l for i, l in enumerate(bond_labels)}
self.bond_num_types = len(bond_labels)
self.log('Created bonds encoder and decoder with {} bond types and 1 PAD symbol!'.format(
self.bond_num_types - 1))
self.log('Creating SMILES encoder and decoder..')
smiles_labels = ['E'] + list(set(c for mol in self.data for c in Chem.MolToSmiles(mol)))
self.smiles_encoder_m = {l: i for i, l in enumerate(smiles_labels)}
self.smiles_decoder_m = {i: l for i, l in enumerate(smiles_labels)}
self.smiles_num_types = len(smiles_labels)
self.log('Created SMILES encoder and decoder with {} types and 1 PAD symbol!'.format(
self.smiles_num_types - 1))
def _generate_AX(self):
self.log('Creating features and adjacency matrices..')
pr = ProgressBar(60, len(self.data))
data = []
smiles = []
data_S = []
data_A = []
data_X = []
data_D = []
data_F = []
data_Le = []
data_Lv = []
max_length = max(mol.GetNumAtoms() for mol in self.data)
max_length_s = max(len(Chem.MolToSmiles(mol)) for mol in self.data)
for i, mol in enumerate(self.data):
A = self._genA(mol, connected=True, max_length=max_length)
D = np.count_nonzero(A, -1)
if A is not None:
data.append(mol)
smiles.append(Chem.MolToSmiles(mol))
data_S.append(self._genS(mol, max_length=max_length_s))
data_A.append(A)
data_X.append(self._genX(mol, max_length=max_length))
data_D.append(D)
data_F.append(self._genF(mol, max_length=max_length))
L = D - A
Le, Lv = np.linalg.eigh(L)
data_Le.append(Le)
data_Lv.append(Lv)
pr.update(i + 1)
self.log(date=False)
self.log('Created {} features and adjacency matrices out of {} molecules!'.format(len(data),
len(self.data)))
self.data = data
self.smiles = smiles
self.data_S = data_S
self.data_A = data_A
self.data_X = data_X
self.data_D = data_D
self.data_F = data_F
self.data_Le = data_Le
self.data_Lv = data_Lv
self.__len = len(self.data)
def _genA(self, mol, connected=True, max_length=None):
max_length = max_length if max_length is not None else mol.GetNumAtoms()
A = np.zeros(shape=(max_length, max_length), dtype=np.int32)
begin, end = [b.GetBeginAtomIdx() for b in mol.GetBonds()], [b.GetEndAtomIdx() for b in mol.GetBonds()]
bond_type = [self.bond_encoder_m[b.GetBondType()] for b in mol.GetBonds()]
A[begin, end] = bond_type
A[end, begin] = bond_type
degree = np.sum(A[:mol.GetNumAtoms(), :mol.GetNumAtoms()], axis=-1)
return A if connected and (degree > 0).all() else None
def _genX(self, mol, max_length=None):
max_length = max_length if max_length is not None else mol.GetNumAtoms()
return np.array([self.atom_encoder_m[atom.GetAtomicNum()] for atom in mol.GetAtoms()] + [0] * (
max_length - mol.GetNumAtoms()), dtype=np.int32)
def _genS(self, mol, max_length=None):
max_length = max_length if max_length is not None else len(Chem.MolToSmiles(mol))
return np.array([self.smiles_encoder_m[c] for c in Chem.MolToSmiles(mol)] + [self.smiles_encoder_m['E']] * (
max_length - len(Chem.MolToSmiles(mol))), dtype=np.int32)
def _genF(self, mol, max_length=None):
max_length = max_length if max_length is not None else mol.GetNumAtoms()
features = np.array([[*[a.GetDegree() == i for i in range(5)],
*[a.GetExplicitValence() == i for i in range(9)],
*[int(a.GetHybridization()) == i for i in range(1, 7)],
*[a.GetImplicitValence() == i for i in range(9)],
a.GetIsAromatic(),
a.GetNoImplicit(),
*[a.GetNumExplicitHs() == i for i in range(5)],
*[a.GetNumImplicitHs() == i for i in range(5)],
*[a.GetNumRadicalElectrons() == i for i in range(5)],
a.IsInRing(),
*[a.IsInRingSize(i) for i in range(2, 9)]] for a in mol.GetAtoms()], dtype=np.int32)
return np.vstack((features, np.zeros((max_length - features.shape[0], features.shape[1]))))
def matrices2mol(self, node_labels, edge_labels, strict=False):
mol = Chem.RWMol()
for node_label in node_labels:
mol.AddAtom(Chem.Atom(self.atom_decoder_m[node_label]))
for start, end in zip(*np.nonzero(edge_labels)):
if start > end:
mol.AddBond(int(start), int(end), self.bond_decoder_m[edge_labels[start, end]])
if strict:
try:
Chem.SanitizeMol(mol)
except:
mol = None
return mol
def seq2mol(self, seq, strict=False):
mol = Chem.MolFromSmiles(''.join([self.smiles_decoder_m[e] for e in seq if e != 0]))
if strict:
try:
Chem.SanitizeMol(mol)
except:
mol = None
return mol
def _generate_train_validation_test(self, validation, test):
self.log('Creating train, validation and test sets..')
validation = int(validation * len(self))
test = int(test * len(self))
train = len(self) - validation - test
self.all_idx = np.random.permutation(len(self))
self.train_idx = self.all_idx[0:train]
self.validation_idx = self.all_idx[train:train + validation]
self.test_idx = self.all_idx[train + validation:]
self.train_counter = 0
self.validation_counter = 0
self.test_counter = 0
self.train_count = train
self.validation_count = validation
self.test_count = test
self.log('Created train ({} items), validation ({} items) and test ({} items) sets!'.format(
train, validation, test))
def _next_batch(self, counter, count, idx, batch_size):
if batch_size is not None:
if counter + batch_size >= count:
counter = 0
np.random.shuffle(idx)
output = [obj[idx[counter:counter + batch_size]]
for obj in (self.data, self.smiles, self.data_S, self.data_A, self.data_X,
self.data_D, self.data_F, self.data_Le, self.data_Lv)]
counter += batch_size
else:
output = [obj[idx] for obj in (self.data, self.smiles, self.data_S, self.data_A, self.data_X,
self.data_D, self.data_F, self.data_Le, self.data_Lv)]
return [counter] + output
def next_train_batch(self, batch_size=None):
out = self._next_batch(counter=self.train_counter, count=self.train_count,
idx=self.train_idx, batch_size=batch_size)
self.train_counter = out[0]
return out[1:]
def next_validation_batch(self, batch_size=None):
out = self._next_batch(counter=self.validation_counter, count=self.validation_count,
idx=self.validation_idx, batch_size=batch_size)
self.validation_counter = out[0]
return out[1:]
def next_test_batch(self, batch_size=None):
out = self._next_batch(counter=self.test_counter, count=self.test_count,
idx=self.test_idx, batch_size=batch_size)
self.test_counter = out[0]
return out[1:]
@staticmethod
def log(msg='', date=True):
print(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')) + ' ' + str(msg) if date else str(msg))
def __len__(self):
return self.__len
if __name__ == '__main__':
data = SparseMolecularDataset()
data.generate('data/gdb9.sdf', filters=lambda x: x.GetNumAtoms() <= 9)
data.save('data/gdb9_9nodes.sparsedataset')
| true | true |
f723a8c66e2d3e4cfcb597ee5e6413d95dd99dce | 4,557 | py | Python | scvi/dataset/csv.py | YufengChenK/scVI-1 | bf26369b0a2edd1bb16c3d90524d1e5cf0138bbb | [
"MIT"
] | 1 | 2019-06-04T07:56:26.000Z | 2019-06-04T07:56:26.000Z | scvi/dataset/csv.py | davek44/scVI | c05237c384c59f1fd783ee1f45e75d108bcabf4e | [
"MIT"
] | null | null | null | scvi/dataset/csv.py | davek44/scVI | c05237c384c59f1fd783ee1f45e75d108bcabf4e | [
"MIT"
] | null | null | null | from .dataset import GeneExpressionDataset
import pandas as pd
import numpy as np
import os
class CsvDataset(GeneExpressionDataset):
r""" Loads a `.csv` file.
Args:
:filename: Name of the `.csv` file.
:save_path: Save path of the dataset. Default: ``'data/'``.
:url: Url of the remote dataset. Default: ``None``.
:new_n_genes: Number of subsampled genes. Default: ``600``.
:subset_genes: List of genes for subsampling. Default: ``None``.
:compression: For on-the-fly decompression of on-disk data. If ‘infer’ and filepath_or_buffer
is path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, or ‘.xz’
(otherwise no decompression). If using ‘zip’, the ZIP file must contain only one data file to be read in.
Default: ``None``.
:batch_ids_file: Name of the `.csv` file with batch indices.
File contains two columns. The first holds gene names and second
holds batch indices - type int. The first row of the file is header.
Examples:
>>> # Loading a remote dataset
>>> remote_url = "https://www.ncbi.nlm.nih.gov/geo/download/?acc=GSE100866&format=file&file=" \
... "GSE100866%5FCBMC%5F8K%5F13AB%5F10X%2DRNA%5Fumi%2Ecsv%2Egz")
>>> remote_csv_dataset = CsvDataset("GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz", save_path='data/',
... compression='gzip', url=remote_url)
>>> # Loading a local dataset
>>> local_csv_dataset = CsvDataset("GSE100866_CBMC_8K_13AB_10X-RNA_umi.csv.gz",
... save_path='data/', compression='gzip')
"""
def __init__(self, filename, save_path='data/', url=None, new_n_genes=600, subset_genes=None,
compression=None, sep=',', gene_by_cell=True, labels_file=None,
batch_ids_file=None):
self.download_name = filename # The given csv file is
self.save_path = save_path
self.url = url
self.compression = compression
self.sep = sep
self.gene_by_cell = gene_by_cell # Whether the original dataset is genes by cells
self.labels_file = labels_file
self.batch_ids_file = batch_ids_file
data, gene_names, labels, cell_types, batch_ids = self.download_and_preprocess()
super().__init__(
*GeneExpressionDataset.get_attributes_from_matrix(
data, labels=labels,
batch_indices=batch_ids if batch_ids is not None else 0),
gene_names=gene_names, cell_types=cell_types)
self.subsample_genes(new_n_genes, subset_genes)
def preprocess(self):
print("Preprocessing dataset")
if self.gene_by_cell:
data = pd.read_csv(os.path.join(self.save_path, self.download_name),
sep=self.sep, index_col=0, compression=self.compression).T
else:
data = pd.read_csv(os.path.join(self.save_path, self.download_name),
sep=self.sep, index_col=0, compression=self.compression)
gene_names = np.array(data.columns, dtype=str)
labels, cell_types, batch_ids = None, None, None
if self.labels_file is not None:
labels = pd.read_csv(os.path.join(self.save_path, self.labels_file), header=0, index_col=0)
labels = labels.values
cell_types = np.unique(labels)
if self.batch_ids_file is not None:
batch_ids = pd.read_csv(
os.path.join(
self.save_path, self.batch_ids_file), header=0, index_col=0)
batch_ids = batch_ids.values
data = data.values
print("Finished preprocessing dataset")
return data, gene_names, labels, cell_types, batch_ids
class BreastCancerDataset(CsvDataset):
def __init__(self, save_path='data/'):
super().__init__("Layer2_BC_count_matrix-1.tsv", save_path=save_path,
url="http://www.spatialtranscriptomicsresearch.org/wp-content/"
"uploads/2016/07/Layer2_BC_count_matrix-1.tsv",
sep='\t', gene_by_cell=False)
class MouseOBDataset(CsvDataset):
def __init__(self, save_path='data/'):
super().__init__("Rep11_MOB_count_matrix-1.tsv", save_path=save_path,
url="http://www.spatialtranscriptomicsresearch.org/wp-content/uploads/"
"2016/07/Rep11_MOB_count_matrix-1.tsv",
sep='\t', gene_by_cell=False)
| 45.57 | 117 | 0.631117 | from .dataset import GeneExpressionDataset
import pandas as pd
import numpy as np
import os
class CsvDataset(GeneExpressionDataset):
def __init__(self, filename, save_path='data/', url=None, new_n_genes=600, subset_genes=None,
compression=None, sep=',', gene_by_cell=True, labels_file=None,
batch_ids_file=None):
self.download_name = filename
self.save_path = save_path
self.url = url
self.compression = compression
self.sep = sep
self.gene_by_cell = gene_by_cell
self.labels_file = labels_file
self.batch_ids_file = batch_ids_file
data, gene_names, labels, cell_types, batch_ids = self.download_and_preprocess()
super().__init__(
*GeneExpressionDataset.get_attributes_from_matrix(
data, labels=labels,
batch_indices=batch_ids if batch_ids is not None else 0),
gene_names=gene_names, cell_types=cell_types)
self.subsample_genes(new_n_genes, subset_genes)
def preprocess(self):
print("Preprocessing dataset")
if self.gene_by_cell:
data = pd.read_csv(os.path.join(self.save_path, self.download_name),
sep=self.sep, index_col=0, compression=self.compression).T
else:
data = pd.read_csv(os.path.join(self.save_path, self.download_name),
sep=self.sep, index_col=0, compression=self.compression)
gene_names = np.array(data.columns, dtype=str)
labels, cell_types, batch_ids = None, None, None
if self.labels_file is not None:
labels = pd.read_csv(os.path.join(self.save_path, self.labels_file), header=0, index_col=0)
labels = labels.values
cell_types = np.unique(labels)
if self.batch_ids_file is not None:
batch_ids = pd.read_csv(
os.path.join(
self.save_path, self.batch_ids_file), header=0, index_col=0)
batch_ids = batch_ids.values
data = data.values
print("Finished preprocessing dataset")
return data, gene_names, labels, cell_types, batch_ids
class BreastCancerDataset(CsvDataset):
def __init__(self, save_path='data/'):
super().__init__("Layer2_BC_count_matrix-1.tsv", save_path=save_path,
url="http://www.spatialtranscriptomicsresearch.org/wp-content/"
"uploads/2016/07/Layer2_BC_count_matrix-1.tsv",
sep='\t', gene_by_cell=False)
class MouseOBDataset(CsvDataset):
def __init__(self, save_path='data/'):
super().__init__("Rep11_MOB_count_matrix-1.tsv", save_path=save_path,
url="http://www.spatialtranscriptomicsresearch.org/wp-content/uploads/"
"2016/07/Rep11_MOB_count_matrix-1.tsv",
sep='\t', gene_by_cell=False)
| true | true |
f723a8d72374f0697752634c01e9ae24d90b88d0 | 4,463 | py | Python | tests/test_trigger.py | Lujeni/mongoop | 787222437d7de126c019cc546525cac65209ff9c | [
"BSD-3-Clause"
] | 41 | 2015-07-23T12:47:15.000Z | 2020-09-16T00:13:25.000Z | tests/test_trigger.py | yutiansut/mongoop | 787222437d7de126c019cc546525cac65209ff9c | [
"BSD-3-Clause"
] | 10 | 2015-12-28T10:30:49.000Z | 2016-06-06T18:32:50.000Z | tests/test_trigger.py | yutiansut/mongoop | 787222437d7de126c019cc546525cac65209ff9c | [
"BSD-3-Clause"
] | 3 | 2015-10-18T16:30:35.000Z | 2017-08-28T07:31:16.000Z | # -*- coding: utf-8 -*-
import sys
import pytest
@pytest.fixture
def base_mongoop_arguments():
return {
'mongodb_host': 'localhost',
'mongodb_port': 27017,
}
@pytest.fixture
def base_mongoop_trigger_arguments():
return {
'name': 'pytest',
'params': {'threshold': 10},
'category': 'op'
}
@pytest.fixture
def base_mongoop(base_mongoop_arguments):
from mongoop.core import Mongoop
return Mongoop(**base_mongoop_arguments)
@pytest.fixture
def base_mongoop_trigger(base_mongoop, base_mongoop_trigger_arguments):
from mongoop.triggers import BaseTrigger
trigger_params = base_mongoop_trigger_arguments
trigger_params['params']['type'] = 'base'
trigger_params['mongoop'] = base_mongoop
return BaseTrigger(**trigger_params)
@pytest.fixture
def email_mongoop_trigger(base_mongoop, base_mongoop_trigger_arguments):
from mongoop.triggers.email import MongoopTrigger
trigger_params = base_mongoop_trigger_arguments
trigger_params['params']['type'] = 'email'
trigger_params['mongoop'] = base_mongoop
return MongoopTrigger(**trigger_params)
@pytest.fixture
def killer_mongoop_trigger(base_mongoop, base_mongoop_trigger_arguments):
from mongoop.triggers.killer import MongoopTrigger
trigger_params = base_mongoop_trigger_arguments
trigger_params['params']['type'] = 'killer'
trigger_params['mongoop'] = base_mongoop
return MongoopTrigger(**trigger_params)
@pytest.fixture
def mongodb_mongoop_trigger(base_mongoop, base_mongoop_trigger_arguments):
from mongoop.triggers.mongodb import MongoopTrigger
trigger_params = base_mongoop_trigger_arguments
trigger_params['params']['type'] = 'mongodb'
trigger_params['mongoop'] = base_mongoop
return MongoopTrigger(**trigger_params)
def test_base_trigger_public_api(base_mongoop_trigger):
assert hasattr(base_mongoop_trigger, 'name')
assert hasattr(base_mongoop_trigger, 'mongoop')
assert hasattr(base_mongoop_trigger, 'type')
assert hasattr(base_mongoop_trigger, 'threshold')
assert hasattr(base_mongoop_trigger, 'state')
assert hasattr(base_mongoop_trigger, 'params')
assert hasattr(base_mongoop_trigger, 'trigger_history')
def test_base_mongoop_public_api(base_mongoop):
assert hasattr(base_mongoop, '_frequency')
assert hasattr(base_mongoop, '_mongodb_credentials')
assert hasattr(base_mongoop, '_mongodb_host')
assert hasattr(base_mongoop, '_mongodb_options')
assert hasattr(base_mongoop, '_mongodb_port')
assert hasattr(base_mongoop, '_query')
assert hasattr(base_mongoop, '_base_op_query')
assert hasattr(base_mongoop, '_threshold_timeout')
assert hasattr(base_mongoop, '_query')
assert hasattr(base_mongoop, 'conn')
assert hasattr(base_mongoop, 'db')
assert hasattr(base_mongoop, 'op_triggers')
assert hasattr(base_mongoop, 'balancer_triggers')
def test_email_trigger_public_api(email_mongoop_trigger):
assert hasattr(email_mongoop_trigger, 'name')
assert hasattr(email_mongoop_trigger, 'mongoop')
assert hasattr(email_mongoop_trigger, 'type')
assert hasattr(email_mongoop_trigger, 'category')
assert hasattr(email_mongoop_trigger, 'threshold')
assert hasattr(email_mongoop_trigger, 'state')
assert hasattr(email_mongoop_trigger, 'params')
def test_killer_trigger_public_api(killer_mongoop_trigger):
assert hasattr(killer_mongoop_trigger, 'name')
assert hasattr(killer_mongoop_trigger, 'mongoop')
assert hasattr(killer_mongoop_trigger, 'type')
assert hasattr(killer_mongoop_trigger, 'category')
assert hasattr(killer_mongoop_trigger, 'threshold')
assert hasattr(killer_mongoop_trigger, 'state')
assert hasattr(killer_mongoop_trigger, 'params')
@pytest.mark.skipif(True, reason='need mongodb instance')
def test_mongodb_trigger_public_api(mongodb_mongoop_trigger):
assert hasattr(mongodb_mongoop_trigger, 'name')
assert hasattr(mongodb_mongoop_trigger, 'mongoop')
assert hasattr(mongodb_mongoop_trigger, 'type')
assert hasattr(mongodb_mongoop_trigger, 'category')
assert hasattr(mongodb_mongoop_trigger, 'threshold')
assert hasattr(mongodb_mongoop_trigger, 'state')
assert hasattr(mongodb_mongoop_trigger, 'params')
assert hasattr(mongodb_mongoop_trigger, 'operations')
assert hasattr(mongodb_mongoop_trigger, 'db')
assert hasattr(mongodb_mongoop_trigger, 'collection')
| 33.810606 | 74 | 0.765629 |
import sys
import pytest
@pytest.fixture
def base_mongoop_arguments():
return {
'mongodb_host': 'localhost',
'mongodb_port': 27017,
}
@pytest.fixture
def base_mongoop_trigger_arguments():
return {
'name': 'pytest',
'params': {'threshold': 10},
'category': 'op'
}
@pytest.fixture
def base_mongoop(base_mongoop_arguments):
from mongoop.core import Mongoop
return Mongoop(**base_mongoop_arguments)
@pytest.fixture
def base_mongoop_trigger(base_mongoop, base_mongoop_trigger_arguments):
from mongoop.triggers import BaseTrigger
trigger_params = base_mongoop_trigger_arguments
trigger_params['params']['type'] = 'base'
trigger_params['mongoop'] = base_mongoop
return BaseTrigger(**trigger_params)
@pytest.fixture
def email_mongoop_trigger(base_mongoop, base_mongoop_trigger_arguments):
from mongoop.triggers.email import MongoopTrigger
trigger_params = base_mongoop_trigger_arguments
trigger_params['params']['type'] = 'email'
trigger_params['mongoop'] = base_mongoop
return MongoopTrigger(**trigger_params)
@pytest.fixture
def killer_mongoop_trigger(base_mongoop, base_mongoop_trigger_arguments):
from mongoop.triggers.killer import MongoopTrigger
trigger_params = base_mongoop_trigger_arguments
trigger_params['params']['type'] = 'killer'
trigger_params['mongoop'] = base_mongoop
return MongoopTrigger(**trigger_params)
@pytest.fixture
def mongodb_mongoop_trigger(base_mongoop, base_mongoop_trigger_arguments):
from mongoop.triggers.mongodb import MongoopTrigger
trigger_params = base_mongoop_trigger_arguments
trigger_params['params']['type'] = 'mongodb'
trigger_params['mongoop'] = base_mongoop
return MongoopTrigger(**trigger_params)
def test_base_trigger_public_api(base_mongoop_trigger):
assert hasattr(base_mongoop_trigger, 'name')
assert hasattr(base_mongoop_trigger, 'mongoop')
assert hasattr(base_mongoop_trigger, 'type')
assert hasattr(base_mongoop_trigger, 'threshold')
assert hasattr(base_mongoop_trigger, 'state')
assert hasattr(base_mongoop_trigger, 'params')
assert hasattr(base_mongoop_trigger, 'trigger_history')
def test_base_mongoop_public_api(base_mongoop):
assert hasattr(base_mongoop, '_frequency')
assert hasattr(base_mongoop, '_mongodb_credentials')
assert hasattr(base_mongoop, '_mongodb_host')
assert hasattr(base_mongoop, '_mongodb_options')
assert hasattr(base_mongoop, '_mongodb_port')
assert hasattr(base_mongoop, '_query')
assert hasattr(base_mongoop, '_base_op_query')
assert hasattr(base_mongoop, '_threshold_timeout')
assert hasattr(base_mongoop, '_query')
assert hasattr(base_mongoop, 'conn')
assert hasattr(base_mongoop, 'db')
assert hasattr(base_mongoop, 'op_triggers')
assert hasattr(base_mongoop, 'balancer_triggers')
def test_email_trigger_public_api(email_mongoop_trigger):
assert hasattr(email_mongoop_trigger, 'name')
assert hasattr(email_mongoop_trigger, 'mongoop')
assert hasattr(email_mongoop_trigger, 'type')
assert hasattr(email_mongoop_trigger, 'category')
assert hasattr(email_mongoop_trigger, 'threshold')
assert hasattr(email_mongoop_trigger, 'state')
assert hasattr(email_mongoop_trigger, 'params')
def test_killer_trigger_public_api(killer_mongoop_trigger):
assert hasattr(killer_mongoop_trigger, 'name')
assert hasattr(killer_mongoop_trigger, 'mongoop')
assert hasattr(killer_mongoop_trigger, 'type')
assert hasattr(killer_mongoop_trigger, 'category')
assert hasattr(killer_mongoop_trigger, 'threshold')
assert hasattr(killer_mongoop_trigger, 'state')
assert hasattr(killer_mongoop_trigger, 'params')
@pytest.mark.skipif(True, reason='need mongodb instance')
def test_mongodb_trigger_public_api(mongodb_mongoop_trigger):
assert hasattr(mongodb_mongoop_trigger, 'name')
assert hasattr(mongodb_mongoop_trigger, 'mongoop')
assert hasattr(mongodb_mongoop_trigger, 'type')
assert hasattr(mongodb_mongoop_trigger, 'category')
assert hasattr(mongodb_mongoop_trigger, 'threshold')
assert hasattr(mongodb_mongoop_trigger, 'state')
assert hasattr(mongodb_mongoop_trigger, 'params')
assert hasattr(mongodb_mongoop_trigger, 'operations')
assert hasattr(mongodb_mongoop_trigger, 'db')
assert hasattr(mongodb_mongoop_trigger, 'collection')
| true | true |
f723aafd7aa89cd123249c2670712ff1e3b4e9cb | 715 | py | Python | transformer/hooks/noam_hook.py | chainer/models | 33fd51dfef2ae50fd615bfa28a3d7e62e0b56c22 | [
"MIT"
] | 112 | 2018-04-18T07:13:03.000Z | 2022-03-11T03:36:34.000Z | transformer/hooks/noam_hook.py | 167rgc911/models | 33fd51dfef2ae50fd615bfa28a3d7e62e0b56c22 | [
"MIT"
] | 16 | 2018-05-11T11:41:08.000Z | 2021-04-24T03:50:54.000Z | transformer/hooks/noam_hook.py | 167rgc911/models | 33fd51dfef2ae50fd615bfa28a3d7e62e0b56c22 | [
"MIT"
] | 45 | 2018-04-18T07:13:06.000Z | 2021-12-22T03:46:18.000Z |
class NoamOptimizer:
"""
This Hook implements the optimization strategy presented in the "Attention is all you need" paper
Section 5.3.
"""
timing = "pre"
name = "NoamOptimizerHook"
call_for_each_param = False
def __init__(self, num_warmup_steps, factor, model_size):
self.num_warmup_steps = num_warmup_steps
self.factor = factor
self.model_size = model_size
self.iteration = 0
def __call__(self, optimizer):
self.iteration += 1
warmup_vs_step_num = min(self.iteration ** (-0.5), self.iteration * self.num_warmup_steps ** (-1.5))
optimizer.alpha = self.factor * self.model_size ** (-0.5) * warmup_vs_step_num
| 29.791667 | 108 | 0.651748 |
class NoamOptimizer:
timing = "pre"
name = "NoamOptimizerHook"
call_for_each_param = False
def __init__(self, num_warmup_steps, factor, model_size):
self.num_warmup_steps = num_warmup_steps
self.factor = factor
self.model_size = model_size
self.iteration = 0
def __call__(self, optimizer):
self.iteration += 1
warmup_vs_step_num = min(self.iteration ** (-0.5), self.iteration * self.num_warmup_steps ** (-1.5))
optimizer.alpha = self.factor * self.model_size ** (-0.5) * warmup_vs_step_num
| true | true |
f723ab2cc5b45559d0f1053cc8e4fccc4be4e6b1 | 820 | py | Python | texar/modules/policies/policy_nets_test.py | Holmeswww/Text_Infilling | f63cd24bee5c62d7dedd8fb35c4e52aee20c39f3 | [
"Apache-2.0"
] | 25 | 2019-01-03T09:15:20.000Z | 2022-02-12T04:20:59.000Z | texar/modules/policies/policy_nets_test.py | Holmeswww/Text_Infilling | f63cd24bee5c62d7dedd8fb35c4e52aee20c39f3 | [
"Apache-2.0"
] | 4 | 2019-03-28T11:02:20.000Z | 2022-02-15T04:57:33.000Z | texar/modules/policies/policy_nets_test.py | Holmeswww/Text_Infilling | f63cd24bee5c62d7dedd8fb35c4e52aee20c39f3 | [
"Apache-2.0"
] | 9 | 2019-01-03T02:20:37.000Z | 2022-02-12T04:20:50.000Z | #
"""
Tests policy nets.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import tensorflow as tf
from texar.modules.policies.policy_nets import CategoricalPolicyNet
class CategoricalPolicyNetTest(tf.test.TestCase):
"""Tests :class:`texar.modules.CategoricalPolicyNet`.
"""
def test_categorical_policy(self):
"""Tests logics.
"""
policy = CategoricalPolicyNet()
inputs = tf.random_uniform(shape=[64, 4])
outputs = policy(inputs=inputs)
self.assertEqual(outputs['action'].shape, outputs['log_prob'].shape)
self.assertIsInstance(
outputs['distribution'], tf.distributions.Categorical)
if __name__ == "__main__":
tf.test.main()
| 25.625 | 76 | 0.709756 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import tensorflow as tf
from texar.modules.policies.policy_nets import CategoricalPolicyNet
class CategoricalPolicyNetTest(tf.test.TestCase):
def test_categorical_policy(self):
policy = CategoricalPolicyNet()
inputs = tf.random_uniform(shape=[64, 4])
outputs = policy(inputs=inputs)
self.assertEqual(outputs['action'].shape, outputs['log_prob'].shape)
self.assertIsInstance(
outputs['distribution'], tf.distributions.Categorical)
if __name__ == "__main__":
tf.test.main()
| true | true |
f723ab8786fc51f0667051874a0f83750245a60c | 20,572 | py | Python | sources/image_colorization/datasets/quantized_colors/utils.py | tramtran2/prlab_image_colorization | 3ec7f3ad60d6235c5bb232713f1b3ec5f06f4d67 | [
"Apache-2.0"
] | null | null | null | sources/image_colorization/datasets/quantized_colors/utils.py | tramtran2/prlab_image_colorization | 3ec7f3ad60d6235c5bb232713f1b3ec5f06f4d67 | [
"Apache-2.0"
] | null | null | null | sources/image_colorization/datasets/quantized_colors/utils.py | tramtran2/prlab_image_colorization | 3ec7f3ad60d6235c5bb232713f1b3ec5f06f4d67 | [
"Apache-2.0"
] | null | null | null | """
Functions:
def read_image(img_path, is_resize = True, width = 224, height = 224, interpolation = cv2.INTER_AREA)
def cielab_color_space()
def view_db_info(db_root, db_files, db_name)
def compute_prior_prob(image_files, width, height, do_plot, pts_in_hull_path, prior_prob_path)
def compute_prior_prob_v1(image_files, is_resize, width, height, do_plot, pts_in_hull_path, prior_prob_path, ab_hist_path):
def compute_prior_prob_smoothed(prior_prob_path, prior_prob_smoothed_path, sigma, do_plot = True, verbose = 1)
def compute_prior_factor(prior_prob_path, prior_prob_smoothed_path, prior_prob_factor_path, gamma = 0.5, alpha = 1, do_plot = True, verbose = 1)
Main:
def compute_prior_prob_export(db_root, db_file, db_name, column_image = "image", column_type = "type", process_types = ["train"],
pts_in_hull_path = os.path.join(module_dir, "data", "prior_prob_train_div2k.npy").replace("\\", "/"),
export_prior_prob_path = None,
export_ab_hist_path = None,
is_resize = False, width = 112, height = 112,
do_plot = True, verbose = 1, )
def main()
def main_index_data(**input_params)
def main_compute_prior_prob(**input_params)
def main_compute_prior_prob_smoothed(**input_params)
def main_cielab_color_space()
"""
from __future__ import absolute_import, division, print_function
import click, os, pandas as pd, glob, tqdm, cv2, numpy as np, sys
import matplotlib.gridspec as gridspec
import matplotlib.pylab as plt
from matplotlib.colors import LogNorm
import time
from skimage import color
from console_progressbar import ProgressBar
import sklearn.neighbors as nn
from scipy.interpolate import interp1d
from scipy.signal import gaussian, convolve
def read_image(img_path, is_resize = True, width = 224, height = 224, interpolation = cv2.INTER_AREA):
"""
Load img with opencv and reshape
"""
result = {}
org_img_color = cv2.imread(img_path)
if len(org_img_color.shape)==2: # grayscale
org_img_color = np.dstack([org_img_color, org_img_color, org_img_color])
else:
org_img_color = org_img_color[:, :, ::-1] # RGB convert
# if
org_img_gray = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
org_img_Lab = cv2.cvtColor(org_img_color, cv2.COLOR_RGB2Lab)
result.update(dict(org_img_color=org_img_color, org_img_gray=org_img_gray, org_img_Lab=org_img_Lab))
if is_resize == True:
res_img_color = cv2.resize(org_img_color, (width, height), interpolation=interpolation)
res_img_gray = cv2.resize(org_img_gray, (width, height), interpolation=interpolation)
res_img_Lab = cv2.cvtColor(res_img_color, cv2.COLOR_RGB2Lab)
result.update(dict(res_img_color=res_img_color, res_img_gray=res_img_gray, res_img_Lab=res_img_Lab))
# if
return result
# read_image
def compute_prior_prob(image_files, width, height, do_plot, pts_in_hull_path, prior_prob_path):
"""
Compute color prior probabilities for pts in hull
Reference: https://github.com/foamliu/Colorful-Image-Colorization/blob/master/class_rebal.py
Usage:
df_data = pd.read_hdf(os.path.join(data_dir, "preprocessing", "DIV2K", "div2k.hdf5"), "data")
list_types = ["'train'"]
df_select_data = df_data.query("type in [" + ",".join(list_types) + "]")
image_dir = os.path.join(dataset_dir, "DIV2K").replace("\\", "/")
image_files = image_dir + "/" + df_select_data["path"].values
image_files[0:3], len(image_files)
info = dict(
image_files = image_files,
pts_in_hull_path = os.path.join(data_dir, "colorization_richard_zhang", "pts_in_hull.npy"),
prior_prob_path = os.path.join(data_dir, "preprocessing", "DIV2K", "prior_prob_train_div2k.npy"),
width = 112,
height = 112,
do_plot = True
)
locals().update(**info)
prior_prob = compute_prior_prob(**info)
"""
# Load ab image
X_ab = []
for image_path in tqdm.tqdm(image_files):
result = read_image(image_path, is_resize = True, width = width, height = height)
X_ab.append(result["res_img_Lab"][:, :, 1:])
# for
X_ab = np.array(X_ab)
X_ab = X_ab - 128.0
# Load the gamut points location
q_ab = np.load(pts_in_hull_path)
if do_plot:
plt.figure(figsize=(8, 8))
plt.title("ab quantize")
gs = gridspec.GridSpec(1, 1)
ax = plt.subplot(gs[0])
for i in range(q_ab.shape[0]):
ax.scatter(q_ab[:, 0], q_ab[:, 1])
ax.annotate(str(i), (q_ab[i, 0], q_ab[i, 1]), fontsize=6)
ax.set_xlim([-110, 110])
ax.set_ylim([-110, 110])
# for
# if
npts, c, h, w = X_ab.shape
X_a_ravel = np.ravel(X_ab[:, :, :, 0])
X_b_ravel = np.ravel(X_ab[:, :, :, 1])
X_ab_ravel = np.vstack((X_a_ravel, X_b_ravel)).T
if do_plot:
plt.title("Prior Distribution in ab space\n", fontsize=16)
plt.hist2d(X_ab_ravel[:, 0], X_ab_ravel[:, 1], bins=100, density=True, norm=LogNorm(), cmap=plt.cm.jet)
plt.xlim([-120, 120])
plt.ylim([-120, 120])
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
plt.xlabel("b channel", fontsize = 14)
plt.ylabel("a channel", fontsize = 14)
plt.colorbar()
plt.show()
plt.clf()
plt.close()
# if
# Create nearest neighbord instance with index = q_ab
NN = 1
nearest = nn.NearestNeighbors(n_neighbors=NN, algorithm='ball_tree').fit(q_ab)
# Find index of nearest neighbor for X_ab
dists, ind = nearest.kneighbors(X_ab_ravel)
# We now count the number of occurrences of each color
ind = np.ravel(ind)
counts = np.bincount(ind)
idxs = np.nonzero(counts)[0]
prior_prob = np.zeros((q_ab.shape[0]))
prior_prob[idxs] = counts[idxs]
# We turn this into a color probability
prior_prob = prior_prob / (1.0 * np.sum(prior_prob))
# Save
if prior_prob_path is not None:
save_dir = os.path.dirname(prior_prob_path)
if save_dir != "" and os.path.exists(save_dir) == False: os.makedirs(save_dir)
pts_in_hull_name = os.path.basename(pts_in_hull_path)
safe_copy(pts_in_hull_path, os.path.join(save_dir, pts_in_hull_name))
np.save(prior_prob_path, prior_prob)
# if
if do_plot:
plt.hist(prior_prob, bins=100)
plt.xlabel("Prior probability")
plt.ylabel("Frequency")
plt.yscale("log")
plt.show()
# if
return prior_prob
pass
# compute_prior_prob
def compute_prior_prob_v1(image_files, is_resize, width, height, do_plot, pts_in_hull_path, prior_prob_path, ab_hist_path):
"""
Compute color prior probabilities for pts in hull
Reference: https://github.com/foamliu/Colorful-Image-Colorization/blob/master/class_rebal.py
Usage:
df_data = pd.read_hdf(os.path.join(dataset_dir, "DIV2K", "div2k.hdf5"), "data")
list_types = ["'train'"]
df_select_data = df_data.query("type in [" + ",".join(list_types) + "]")
image_dir = os.path.join(dataset_dir, "DIV2K").replace("\\", "/")
image_files = image_dir + "/" + df_select_data["path"].values
image_files[0:3], len(image_files)
info = dict(
image_files = image_files,
pts_in_hull_path = os.path.join(module_dir, "data", "pts_in_hull.npy"),
prior_prob_path = os.path.join(module_dir, "data", "prior_prob_train_div2k.npy"),
ab_hist_path = os.path.join(data_dir, "preprocessing", "DIV2K", "ab_hist_train_div2k.npy"),
is_resize = False,
width = 112,
height = 112,
do_plot = True
)
locals().update(**info)
prior_prob = compute_prior_prob(**info)
"""
# Load ab image
ab_hist = np.zeros((256, 256), dtype = np.uint64)
for image_path in tqdm.tqdm(image_files):
result = read_image(image_path, is_resize = is_resize,
width = width, height = height)
I_ab = result["res_img_Lab"][:, :, 1:] if is_resize==True else result["org_img_Lab"][:, :, 1:]
I_ab = I_ab.reshape(-1, 2).astype(np.uint)
(ab_vals, ab_cnts) = np.unique(I_ab, return_counts = True, axis=0)
ab_hist[ab_vals[:, 0], ab_vals[:, 1]] += ab_cnts.astype(np.uint64)
# for
# Load the gamut points location
q_ab = np.load(pts_in_hull_path)
if do_plot:
plt.figure(figsize=(8, 8))
gs = gridspec.GridSpec(1, 1)
ax = plt.subplot(gs[0])
for i in range(q_ab.shape[0]):
ax.scatter(q_ab[:, 0], q_ab[:, 1])
ax.annotate(str(i), (q_ab[i, 0], q_ab[i, 1]), fontsize=6)
ax.set_xlim([-110, 110])
ax.set_ylim([-110, 110])
# for
plt.title("Prior Distribution in ab space\n", fontsize=16)
plt.imshow(ab_hist.transpose(), norm=LogNorm(), cmap=plt.cm.jet, extent = (-128, 127, -128, 127), origin = "uper")
plt.xlim([-120, 120])
plt.ylim([-120, 120])
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
plt.xlabel("b channel", fontsize = 14)
plt.ylabel("a channel", fontsize = 14)
plt.colorbar()
plt.show()
plt.clf()
plt.close()
# if
X_ab_ravel_h = np.vstack(np.nonzero(ab_hist)).T
X_ab_ravel_h = X_ab_ravel_h - 128
# Create nearest neighbord instance with index = q_ab
NN = 1
nearest = nn.NearestNeighbors(n_neighbors=NN, algorithm='ball_tree').fit(q_ab)
# Find index of nearest neighbor for X_ab
dists, ind = nearest.kneighbors(X_ab_ravel_h)
# We now count the number of occurrences of each color
ind = np.ravel(ind)
counts = np.zeros(np.max(ind) + 1, np.uint64)
for idx, (a,b) in enumerate(X_ab_ravel_h):
counts[ind[idx]] = counts[ind[idx]] + ab_hist[(a + 128,b + 128)]
pass
# for
idxs = np.nonzero(counts)[0]
prior_prob = np.zeros((q_ab.shape[0]))
prior_prob[idxs] = counts[idxs]
# We turn this into a color probability
prior_prob = prior_prob / (1.0 * np.sum(prior_prob))
# Save
if prior_prob_path is not None:
save_dir = os.path.dirname(prior_prob_path)
if save_dir != "" and os.path.exists(save_dir) == False: os.makedirs(save_dir)
np.save(prior_prob_path, prior_prob)
# if
# Save
if ab_hist_path is not None:
save_dir = os.path.dirname(ab_hist_path)
if save_dir != "" and os.path.exists(save_dir) == False: os.makedirs(save_dir)
np.save(ab_hist_path, ab_hist)
# if
if do_plot:
plt.hist(prior_prob, bins=100)
plt.xlabel("Prior probability")
plt.ylabel("Frequency")
plt.yscale("log")
plt.show()
# if
return prior_prob, ab_hist
pass
# compute_prior_prob_v1
def compute_prior_prob_smoothed(prior_prob_path, prior_prob_smoothed_path, sigma = 5, do_plot = True, verbose = 1):
"""
Interpolation on prior prob, next using interpolation to smoothness path, and normalize again
Reference: https://github.com/foamliu/Colorful-Image-Colorization/blob/master/class_rebal.py
Usage:
info = dict(
prior_prob_path = os.path.join(module_dir, "data", "prior_prob_train_div2k.npy"),
prior_prob_smoothed_path = os.path.join(module_dir, "data", "prior_prob_smoothed_train_div2k.npy"),
sigma = 5,
do_plot = True,
verbose = True,
)
locals().update(**info)
prior_prob_smoothed = compute_prior_prob_smoothed(**info)
"""
# load prior probability
if verbose==1: print("\n=== Compute Prior Probability Smoothed === ")
prior_prob = np.load(prior_prob_path)
# add an epsilon to prior prob to avoid 0 vakues and possible NaN
prior_prob += 1E-3 * np.min(prior_prob)
# renormalize
prior_prob = prior_prob / (1.0 * np.sum(prior_prob))
# Smooth with gaussian
f = interp1d(np.arange(prior_prob.shape[0]), prior_prob)
xx = np.linspace(0, prior_prob.shape[0] - 1, 1000)
yy = f(xx)
window = gaussian(2000, sigma) # 2000 pts in the window, sigma=5
smoothed = convolve(yy, window / window.sum(), mode='same')
fout = interp1d(xx, smoothed)
prior_prob_smoothed = np.array([fout(i) for i in range(prior_prob.shape[0])])
prior_prob_smoothed = prior_prob_smoothed / np.sum(prior_prob_smoothed)
# Save
if prior_prob_smoothed_path is not None:
save_dir = os.path.dirname(prior_prob_smoothed_path)
if save_dir != "" and os.path.exists(save_dir) == False: os.makedirs(save_dir)
np.save(prior_prob_smoothed_path, prior_prob_smoothed)
# if
if do_plot:
plt.figure(figsize=(20, 10))
plt.subplot(2, 2, 1)
plt.plot(prior_prob, label="prior_prob")
plt.plot(prior_prob_smoothed, "g--", label="prior_prob_smoothed")
plt.yscale("log")
plt.legend()
plt.subplot(2, 2, 2)
plt.plot(prior_prob, label="prior_prob")
plt.plot(xx, smoothed, "r-", label="smoothed")
plt.yscale("log")
plt.legend()
plt.subplot(2, 2, 3)
plt.hist(prior_prob, bins=100)
plt.xlabel("Prior probability")
plt.ylabel("Frequency")
plt.yscale("log")
plt.subplot(2, 2, 4)
plt.hist(prior_prob_smoothed, bins=100)
plt.xlabel("Prior probability smoothed")
plt.ylabel("Frequency")
plt.yscale("log")
plt.show()
# if
return prior_prob_smoothed
# compute_prior_prob_smoothed
def compute_prior_factor(prior_prob_path, prior_prob_smoothed_path, prior_prob_factor_path, gamma = 0.5, alpha = 1, do_plot = True, verbose = 1):
"""
Calculate prior probability factorization
Reference: https://github.com/foamliu/Colorful-Image-Colorization/blob/master/class_rebal.py
Usage:
info = dict(
prior_prob_path = os.path.join(data_dir, "preprocessing", "DIV2K", "prior_prob_train_div2k.npy"),
prior_prob_smoothed_path = os.path.join(data_dir, "preprocessing", "DIV2K", "prior_prob_smoothed_train_div2k.npy"),
prior_prob_factor_path = os.path.join(data_dir, "preprocessing", "DIV2K", "prior_prob_factor_train_div2k.npy"),
gamma = 0.5,
alpha = 1,
do_plot = True,
verbose = 1,
)
locals().update(**info)
prior_factor = compute_prior_factor(**info)
"""
if verbose==1: print("\n=== Compute Prior Factor === ")
prior_prob = np.load(prior_prob_path)
prior_prob_smoothed = np.load(prior_prob_smoothed_path)
u = np.ones_like(prior_prob_smoothed)
u = u / np.sum(1.0 * u)
prior_factor = (1 - gamma) * prior_prob_smoothed + gamma * u
prior_factor = np.power(prior_factor, -alpha)
# renormalize
prior_factor = prior_factor / (np.sum(prior_factor * prior_prob_smoothed))
# Save
if prior_prob_factor_path is not None:
save_dir = os.path.dirname(prior_prob_factor_path)
if save_dir != "" and os.path.exists(save_dir) == False: os.makedirs(save_dir)
np.save(prior_prob_factor_path, prior_factor)
# if
if do_plot:
plt.figure(figsize=(20, 10))
plt.subplot(1, 3, 1)
plt.hist(prior_prob)
plt.xlabel("Prior probability")
plt.ylabel("Frequency")
plt.yscale("log")
plt.subplot(1, 3, 2)
plt.hist(prior_prob_smoothed)
plt.xlabel("Prior probability smoothed")
plt.ylabel("Frequency")
plt.yscale("log")
plt.subplot(1, 3, 3)
plt.hist(prior_factor)
plt.xlabel("Prior probability smoothed factor")
plt.ylabel("Frequency")
plt.yscale("log")
plt.show()
# if
return prior_factor
# def
def cielab_color_space():
print('SkImage:')
start = time.time()
L = [0] * 256 ** 3
a = [0] * 256 ** 3
b = [0] * 256 ** 3
i = 0
pb = ProgressBar(total=256, prefix='SkImage converting images', suffix='', decimals=3, length=50, fill='=')
for r in range(256):
for g in range(256):
for bb in range(256):
im = np.array((bb, g, r), np.uint8).reshape(1, 1, 3)
color.rgb2lab(im) # transform it to LAB
L[i] = im[0, 0, 0]
a[i] = im[0, 0, 1]
b[i] = im[0, 0, 2]
i += 1
# for
# for
pb.print_progress_bar(r)
# for
print("")
print(min(L), '<=L<=', max(L))
print(min(a), '<=a<=', max(a))
print(min(b), '<=b<=', max(b))
end = time.time()
elapsed = end - start
print('elapsed: {} seconds.'.format(elapsed))
##############################################
print('OpenCV:')
start = time.time()
L = [0] * 256 ** 3
a = [0] * 256 ** 3
b = [0] * 256 ** 3
i = 0
pb = ProgressBar(total=256, prefix='OpenCV converting images', suffix='', decimals=3, length=50, fill='=')
for r in range(256):
for g in range(256):
for bb in range(256):
im = np.array((bb, g, r), np.uint8).reshape(1, 1, 3)
cv2.cvtColor(im, cv2.COLOR_BGR2LAB, im) # transform it to LAB
L[i] = im[0, 0, 0]
a[i] = im[0, 0, 1]
b[i] = im[0, 0, 2]
i += 1
# for
# for
pb.print_progress_bar(r)
# for
print("")
print(min(L), '<=L<=', max(L))
print(min(a), '<=a<=', max(a))
print(min(b), '<=b<=', max(b))
end = time.time()
elapsed = end - start
print('elapsed: {} seconds.'.format(elapsed))
# cielab_color_space
def view_db_info(db_root, db_files, db_name):
df_data = pd.read_hdf(db_files, key = db_name)
print("Dataset info: ")
print("+ Image Path: ", db_root)
print("+ Index Path: ", db_files)
print("+ Columns: ", df_data.keys())
print("+ Rows: ", len(df_data))
info_types = df_data.groupby("type").count().reset_index()[["type", "image"]].values
print("+ Types: \n", info_types)
print()
# view_db_info
def compute_prior_prob_export(db_root, db_file, db_name, column_image = "image", column_type = "type", process_types = ["train"],
pts_in_hull_path = "prior_prob_train_div2k.npy",
export_prior_prob_path = None,
export_ab_hist_path = None,
is_resize = False, width = 112, height = 112,
do_plot = True, verbose = 1, ):
print("\n=== Compute Prior Probability === ")
df_data = pd.read_hdf(db_file, key = db_name)
select_expr = f'{column_type} in ["%s"]'%('", "'.join(list(process_types)))
df_select_data = df_data.query(select_expr)
image_files = db_root + "/" + df_select_data[column_image].values
if verbose==1:
view_db_info(db_root, db_file, db_name)
print(f'Select_expr: {select_expr}')
print(f'Rows after select: {len(df_select_data)}')
print()
print("Images: ", image_files[0:5], " ... ")
print()
print("Caluculate prior probability")
# if
prior_prob, ab_hist = compute_prior_prob_v1(image_files = image_files,
pts_in_hull_path = pts_in_hull_path,
prior_prob_path = export_prior_prob_path,
ab_hist_path = export_ab_hist_path,
is_resize = is_resize,
width = width, height = height,
do_plot = do_plot)
if verbose==1:
print()
print(f'prior_prob: shape={prior_prob.shape}')
print(prior_prob)
print()
print(f'ab_hist: shape={ab_hist.shape}')
print(ab_hist)
# if
return prior_prob, ab_hist
# compute_prior_prob_export | 37.540146 | 148 | 0.593768 | from __future__ import absolute_import, division, print_function
import click, os, pandas as pd, glob, tqdm, cv2, numpy as np, sys
import matplotlib.gridspec as gridspec
import matplotlib.pylab as plt
from matplotlib.colors import LogNorm
import time
from skimage import color
from console_progressbar import ProgressBar
import sklearn.neighbors as nn
from scipy.interpolate import interp1d
from scipy.signal import gaussian, convolve
def read_image(img_path, is_resize = True, width = 224, height = 224, interpolation = cv2.INTER_AREA):
result = {}
org_img_color = cv2.imread(img_path)
if len(org_img_color.shape)==2:
org_img_color = np.dstack([org_img_color, org_img_color, org_img_color])
else:
org_img_color = org_img_color[:, :, ::-1]
org_img_gray = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
org_img_Lab = cv2.cvtColor(org_img_color, cv2.COLOR_RGB2Lab)
result.update(dict(org_img_color=org_img_color, org_img_gray=org_img_gray, org_img_Lab=org_img_Lab))
if is_resize == True:
res_img_color = cv2.resize(org_img_color, (width, height), interpolation=interpolation)
res_img_gray = cv2.resize(org_img_gray, (width, height), interpolation=interpolation)
res_img_Lab = cv2.cvtColor(res_img_color, cv2.COLOR_RGB2Lab)
result.update(dict(res_img_color=res_img_color, res_img_gray=res_img_gray, res_img_Lab=res_img_Lab))
return result
def compute_prior_prob(image_files, width, height, do_plot, pts_in_hull_path, prior_prob_path):
X_ab = []
for image_path in tqdm.tqdm(image_files):
result = read_image(image_path, is_resize = True, width = width, height = height)
X_ab.append(result["res_img_Lab"][:, :, 1:])
X_ab = np.array(X_ab)
X_ab = X_ab - 128.0
q_ab = np.load(pts_in_hull_path)
if do_plot:
plt.figure(figsize=(8, 8))
plt.title("ab quantize")
gs = gridspec.GridSpec(1, 1)
ax = plt.subplot(gs[0])
for i in range(q_ab.shape[0]):
ax.scatter(q_ab[:, 0], q_ab[:, 1])
ax.annotate(str(i), (q_ab[i, 0], q_ab[i, 1]), fontsize=6)
ax.set_xlim([-110, 110])
ax.set_ylim([-110, 110])
npts, c, h, w = X_ab.shape
X_a_ravel = np.ravel(X_ab[:, :, :, 0])
X_b_ravel = np.ravel(X_ab[:, :, :, 1])
X_ab_ravel = np.vstack((X_a_ravel, X_b_ravel)).T
if do_plot:
plt.title("Prior Distribution in ab space\n", fontsize=16)
plt.hist2d(X_ab_ravel[:, 0], X_ab_ravel[:, 1], bins=100, density=True, norm=LogNorm(), cmap=plt.cm.jet)
plt.xlim([-120, 120])
plt.ylim([-120, 120])
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
plt.xlabel("b channel", fontsize = 14)
plt.ylabel("a channel", fontsize = 14)
plt.colorbar()
plt.show()
plt.clf()
plt.close()
NN = 1
nearest = nn.NearestNeighbors(n_neighbors=NN, algorithm='ball_tree').fit(q_ab)
dists, ind = nearest.kneighbors(X_ab_ravel)
ind = np.ravel(ind)
counts = np.bincount(ind)
idxs = np.nonzero(counts)[0]
prior_prob = np.zeros((q_ab.shape[0]))
prior_prob[idxs] = counts[idxs]
prior_prob = prior_prob / (1.0 * np.sum(prior_prob))
if prior_prob_path is not None:
save_dir = os.path.dirname(prior_prob_path)
if save_dir != "" and os.path.exists(save_dir) == False: os.makedirs(save_dir)
pts_in_hull_name = os.path.basename(pts_in_hull_path)
safe_copy(pts_in_hull_path, os.path.join(save_dir, pts_in_hull_name))
np.save(prior_prob_path, prior_prob)
if do_plot:
plt.hist(prior_prob, bins=100)
plt.xlabel("Prior probability")
plt.ylabel("Frequency")
plt.yscale("log")
plt.show()
return prior_prob
pass
def compute_prior_prob_v1(image_files, is_resize, width, height, do_plot, pts_in_hull_path, prior_prob_path, ab_hist_path):
ab_hist = np.zeros((256, 256), dtype = np.uint64)
for image_path in tqdm.tqdm(image_files):
result = read_image(image_path, is_resize = is_resize,
width = width, height = height)
I_ab = result["res_img_Lab"][:, :, 1:] if is_resize==True else result["org_img_Lab"][:, :, 1:]
I_ab = I_ab.reshape(-1, 2).astype(np.uint)
(ab_vals, ab_cnts) = np.unique(I_ab, return_counts = True, axis=0)
ab_hist[ab_vals[:, 0], ab_vals[:, 1]] += ab_cnts.astype(np.uint64)
q_ab = np.load(pts_in_hull_path)
if do_plot:
plt.figure(figsize=(8, 8))
gs = gridspec.GridSpec(1, 1)
ax = plt.subplot(gs[0])
for i in range(q_ab.shape[0]):
ax.scatter(q_ab[:, 0], q_ab[:, 1])
ax.annotate(str(i), (q_ab[i, 0], q_ab[i, 1]), fontsize=6)
ax.set_xlim([-110, 110])
ax.set_ylim([-110, 110])
plt.title("Prior Distribution in ab space\n", fontsize=16)
plt.imshow(ab_hist.transpose(), norm=LogNorm(), cmap=plt.cm.jet, extent = (-128, 127, -128, 127), origin = "uper")
plt.xlim([-120, 120])
plt.ylim([-120, 120])
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
plt.xlabel("b channel", fontsize = 14)
plt.ylabel("a channel", fontsize = 14)
plt.colorbar()
plt.show()
plt.clf()
plt.close()
X_ab_ravel_h = np.vstack(np.nonzero(ab_hist)).T
X_ab_ravel_h = X_ab_ravel_h - 128
NN = 1
nearest = nn.NearestNeighbors(n_neighbors=NN, algorithm='ball_tree').fit(q_ab)
dists, ind = nearest.kneighbors(X_ab_ravel_h)
ind = np.ravel(ind)
counts = np.zeros(np.max(ind) + 1, np.uint64)
for idx, (a,b) in enumerate(X_ab_ravel_h):
counts[ind[idx]] = counts[ind[idx]] + ab_hist[(a + 128,b + 128)]
pass
idxs = np.nonzero(counts)[0]
prior_prob = np.zeros((q_ab.shape[0]))
prior_prob[idxs] = counts[idxs]
prior_prob = prior_prob / (1.0 * np.sum(prior_prob))
if prior_prob_path is not None:
save_dir = os.path.dirname(prior_prob_path)
if save_dir != "" and os.path.exists(save_dir) == False: os.makedirs(save_dir)
np.save(prior_prob_path, prior_prob)
if ab_hist_path is not None:
save_dir = os.path.dirname(ab_hist_path)
if save_dir != "" and os.path.exists(save_dir) == False: os.makedirs(save_dir)
np.save(ab_hist_path, ab_hist)
if do_plot:
plt.hist(prior_prob, bins=100)
plt.xlabel("Prior probability")
plt.ylabel("Frequency")
plt.yscale("log")
plt.show()
return prior_prob, ab_hist
pass
def compute_prior_prob_smoothed(prior_prob_path, prior_prob_smoothed_path, sigma = 5, do_plot = True, verbose = 1):
if verbose==1: print("\n=== Compute Prior Probability Smoothed === ")
prior_prob = np.load(prior_prob_path)
prior_prob += 1E-3 * np.min(prior_prob)
prior_prob = prior_prob / (1.0 * np.sum(prior_prob))
f = interp1d(np.arange(prior_prob.shape[0]), prior_prob)
xx = np.linspace(0, prior_prob.shape[0] - 1, 1000)
yy = f(xx)
window = gaussian(2000, sigma)
smoothed = convolve(yy, window / window.sum(), mode='same')
fout = interp1d(xx, smoothed)
prior_prob_smoothed = np.array([fout(i) for i in range(prior_prob.shape[0])])
prior_prob_smoothed = prior_prob_smoothed / np.sum(prior_prob_smoothed)
if prior_prob_smoothed_path is not None:
save_dir = os.path.dirname(prior_prob_smoothed_path)
if save_dir != "" and os.path.exists(save_dir) == False: os.makedirs(save_dir)
np.save(prior_prob_smoothed_path, prior_prob_smoothed)
if do_plot:
plt.figure(figsize=(20, 10))
plt.subplot(2, 2, 1)
plt.plot(prior_prob, label="prior_prob")
plt.plot(prior_prob_smoothed, "g--", label="prior_prob_smoothed")
plt.yscale("log")
plt.legend()
plt.subplot(2, 2, 2)
plt.plot(prior_prob, label="prior_prob")
plt.plot(xx, smoothed, "r-", label="smoothed")
plt.yscale("log")
plt.legend()
plt.subplot(2, 2, 3)
plt.hist(prior_prob, bins=100)
plt.xlabel("Prior probability")
plt.ylabel("Frequency")
plt.yscale("log")
plt.subplot(2, 2, 4)
plt.hist(prior_prob_smoothed, bins=100)
plt.xlabel("Prior probability smoothed")
plt.ylabel("Frequency")
plt.yscale("log")
plt.show()
return prior_prob_smoothed
def compute_prior_factor(prior_prob_path, prior_prob_smoothed_path, prior_prob_factor_path, gamma = 0.5, alpha = 1, do_plot = True, verbose = 1):
if verbose==1: print("\n=== Compute Prior Factor === ")
prior_prob = np.load(prior_prob_path)
prior_prob_smoothed = np.load(prior_prob_smoothed_path)
u = np.ones_like(prior_prob_smoothed)
u = u / np.sum(1.0 * u)
prior_factor = (1 - gamma) * prior_prob_smoothed + gamma * u
prior_factor = np.power(prior_factor, -alpha)
prior_factor = prior_factor / (np.sum(prior_factor * prior_prob_smoothed))
if prior_prob_factor_path is not None:
save_dir = os.path.dirname(prior_prob_factor_path)
if save_dir != "" and os.path.exists(save_dir) == False: os.makedirs(save_dir)
np.save(prior_prob_factor_path, prior_factor)
if do_plot:
plt.figure(figsize=(20, 10))
plt.subplot(1, 3, 1)
plt.hist(prior_prob)
plt.xlabel("Prior probability")
plt.ylabel("Frequency")
plt.yscale("log")
plt.subplot(1, 3, 2)
plt.hist(prior_prob_smoothed)
plt.xlabel("Prior probability smoothed")
plt.ylabel("Frequency")
plt.yscale("log")
plt.subplot(1, 3, 3)
plt.hist(prior_factor)
plt.xlabel("Prior probability smoothed factor")
plt.ylabel("Frequency")
plt.yscale("log")
plt.show()
return prior_factor
def cielab_color_space():
print('SkImage:')
start = time.time()
L = [0] * 256 ** 3
a = [0] * 256 ** 3
b = [0] * 256 ** 3
i = 0
pb = ProgressBar(total=256, prefix='SkImage converting images', suffix='', decimals=3, length=50, fill='=')
for r in range(256):
for g in range(256):
for bb in range(256):
im = np.array((bb, g, r), np.uint8).reshape(1, 1, 3)
color.rgb2lab(im)
L[i] = im[0, 0, 0]
a[i] = im[0, 0, 1]
b[i] = im[0, 0, 2]
i += 1
pb.print_progress_bar(r)
print("")
print(min(L), '<=L<=', max(L))
print(min(a), '<=a<=', max(a))
print(min(b), '<=b<=', max(b))
end = time.time()
elapsed = end - start
print('elapsed: {} seconds.'.format(elapsed))
t("+ Index Path: ", db_files)
print("+ Columns: ", df_data.keys())
print("+ Rows: ", len(df_data))
info_types = df_data.groupby("type").count().reset_index()[["type", "image"]].values
print("+ Types: \n", info_types)
print()
def compute_prior_prob_export(db_root, db_file, db_name, column_image = "image", column_type = "type", process_types = ["train"],
pts_in_hull_path = "prior_prob_train_div2k.npy",
export_prior_prob_path = None,
export_ab_hist_path = None,
is_resize = False, width = 112, height = 112,
do_plot = True, verbose = 1, ):
print("\n=== Compute Prior Probability === ")
df_data = pd.read_hdf(db_file, key = db_name)
select_expr = f'{column_type} in ["%s"]'%('", "'.join(list(process_types)))
df_select_data = df_data.query(select_expr)
image_files = db_root + "/" + df_select_data[column_image].values
if verbose==1:
view_db_info(db_root, db_file, db_name)
print(f'Select_expr: {select_expr}')
print(f'Rows after select: {len(df_select_data)}')
print()
print("Images: ", image_files[0:5], " ... ")
print()
print("Caluculate prior probability")
prior_prob, ab_hist = compute_prior_prob_v1(image_files = image_files,
pts_in_hull_path = pts_in_hull_path,
prior_prob_path = export_prior_prob_path,
ab_hist_path = export_ab_hist_path,
is_resize = is_resize,
width = width, height = height,
do_plot = do_plot)
if verbose==1:
print()
print(f'prior_prob: shape={prior_prob.shape}')
print(prior_prob)
print()
print(f'ab_hist: shape={ab_hist.shape}')
print(ab_hist)
return prior_prob, ab_hist
| true | true |
f723ac9e30e75faf4cd6dde9b90036c5374a00df | 10,566 | py | Python | mars/tensor/linalg/cholesky.py | HarshCasper/mars | 4c12c968414d666c7a10f497bc22de90376b1932 | [
"Apache-2.0"
] | 2 | 2019-03-29T04:11:10.000Z | 2020-07-08T10:19:54.000Z | mars/tensor/linalg/cholesky.py | HarshCasper/mars | 4c12c968414d666c7a10f497bc22de90376b1932 | [
"Apache-2.0"
] | null | null | null | mars/tensor/linalg/cholesky.py | HarshCasper/mars | 4c12c968414d666c7a10f497bc22de90376b1932 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2020 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
from numpy.linalg import LinAlgError
from ...serialize import KeyField, BoolField
from ... import opcodes as OperandDef
from ...utils import check_chunks_unknown_shape
from ...tiles import TilesError
from ..operands import TensorHasInput, TensorOperand, TensorOperandMixin
from ..datasource import tensor as astensor
from ..core import TensorOrder
from ..array_utils import as_same_device, device
class TensorCholesky(TensorHasInput, TensorOperandMixin):
_op_type_ = OperandDef.CHOLESKY
_input = KeyField('input')
_lower = BoolField('lower')
def __init__(self, lower=None, dtype=None, **kw):
super().__init__(_lower=lower, _dtype=dtype, **kw)
@property
def lower(self):
return self._lower
def _set_inputs(self, inputs):
super()._set_inputs(inputs)
self._input = self._inputs[0]
def __call__(self, a):
return self.new_tensor([a], a.shape, order=TensorOrder.C_ORDER)
@classmethod
def tile(cls, op):
from ..datasource.zeros import TensorZeros
from ..base import TensorTranspose
from ..utils import reverse_order
from .dot import TensorDot
from .solve_triangular import TensorSolveTriangular
tensor = op.outputs[0]
in_tensor = op.input
check_chunks_unknown_shape([in_tensor], TilesError)
if in_tensor.nsplits[0] != in_tensor.nsplits[1]:
# all chunks on diagonal should be square
nsplits = in_tensor.nsplits[0]
in_tensor = in_tensor.rechunk([nsplits, nsplits])._inplace_tile()
lower_chunks, upper_chunks = {}, {}
for i in range(in_tensor.chunk_shape[0]):
for j in range(in_tensor.chunk_shape[1]):
if i < j:
lower_chunk = TensorZeros(dtype=tensor.dtype).new_chunk(
None, shape=(in_tensor.nsplits[0][i], in_tensor.nsplits[1][j]),
index=(i, j), order=tensor.order)
upper_chunk = TensorZeros(dtype=tensor.dtype).new_chunk(
None, shape=(in_tensor.nsplits[1][j], in_tensor.nsplits[0][i]),
index=(j, i), order=tensor.order)
lower_chunks[lower_chunk.index] = lower_chunk
upper_chunks[upper_chunk.index] = upper_chunk
elif i == j:
target = in_tensor.cix[i, j]
if i > 0:
prev_chunks = []
for p in range(i):
a, b = lower_chunks[i, p], upper_chunks[p, j]
prev_chunk = TensorDot(dtype=tensor.dtype).new_chunk(
[a, b], shape=(a.shape[0], b.shape[1]), order=tensor.order)
prev_chunks.append(prev_chunk)
cholesky_fuse_op = TensorCholeskyFuse()
lower_chunk = cholesky_fuse_op.new_chunk([target] + prev_chunks,
shape=target.shape, index=(i, j),
order=tensor.order)
else:
lower_chunk = TensorCholesky(lower=True, dtype=tensor.dtype).new_chunk(
[target], shape=target.shape, index=(i, j), order=tensor.order)
upper_chunk = TensorTranspose(dtype=lower_chunk.dtype).new_chunk(
[lower_chunk], shape=lower_chunk.shape[::-1],
index=lower_chunk.index[::-1], order=reverse_order(lower_chunk.order))
lower_chunks[lower_chunk.index] = lower_chunk
upper_chunks[upper_chunk.index] = upper_chunk
else:
target = in_tensor.cix[j, i]
if j > 0:
prev_chunks = []
for p in range(j):
a, b = lower_chunks[j, p], upper_chunks[p, i]
prev_chunk = TensorDot(dtype=tensor.dtype).new_chunk(
[a, b], shape=(a.shape[0], b.shape[1]), order=tensor.order)
prev_chunks.append(prev_chunk)
cholesky_fuse_op = TensorCholeskyFuse(by_solve_triangular=True)
upper_chunk = cholesky_fuse_op.new_chunk([target] + [lower_chunks[j, j]] + prev_chunks,
shape=target.shape, index=(j, i),
order=tensor.order)
else:
upper_chunk = TensorSolveTriangular(lower=True, dtype=tensor.dtype).new_chunk(
[lower_chunks[j, j], target], shape=target.shape,
index=(j, i), order=tensor.order)
lower_chunk = TensorTranspose(dtype=upper_chunk.dtype).new_chunk(
[upper_chunk], shape=upper_chunk.shape[::-1],
index=upper_chunk.index[::-1], order=reverse_order(upper_chunk.order))
lower_chunks[lower_chunk.index] = lower_chunk
upper_chunks[upper_chunk.index] = upper_chunk
new_op = op.copy()
if op.lower:
return new_op.new_tensors(op.inputs, tensor.shape, order=tensor.order,
chunks=list(lower_chunks.values()), nsplits=in_tensor.nsplits)
else:
return new_op.new_tensors(op.inputs, tensor.shape, order=tensor.order,
chunks=list(upper_chunks.values()), nsplits=in_tensor.nsplits)
@classmethod
def execute(cls, ctx, op):
chunk = op.outputs[0]
(a,), device_id, xp = as_same_device(
[ctx[c.key] for c in op.inputs], device=op.device, ret_extra=True)
with device(device_id):
if xp is np:
try:
import scipy.linalg
ctx[chunk.key] = scipy.linalg.cholesky(a, lower=op.lower)
return
except ImportError: # pragma: no cover
pass
r = xp.linalg.cholesky(a)
if not chunk.op.lower:
r = r.T.conj()
ctx[chunk.key] = r
class TensorCholeskyFuse(TensorOperand, TensorOperandMixin):
_op_type_ = OperandDef.CHOLESKY_FUSE
_by_solve_triangular = BoolField('by_solve_triangular')
def __init__(self, by_solve_triangular=None, **kw):
super().__init__(_by_solve_triangular=by_solve_triangular, **kw)
@property
def by_solve_triangular(self):
return self._by_solve_triangular
@classmethod
def _execute_by_cholesky(cls, inputs):
import scipy.linalg
target = inputs[0]
return scipy.linalg.cholesky((target - sum(inputs[1:])), lower=True)
@classmethod
def _execute_by_solve_striangular(cls, inputs):
import scipy.linalg
target = inputs[0]
lower = inputs[1]
return scipy.linalg.solve_triangular(lower, (target - sum(inputs[2:])), lower=True)
@classmethod
def execute(cls, ctx, op):
inputs = [ctx[c.key] for c in op.inputs]
if op.by_solve_triangular:
ret = cls._execute_by_solve_striangular(inputs)
else:
ret = cls._execute_by_cholesky(inputs)
ctx[op.outputs[0].key] = ret
def cholesky(a, lower=False):
"""
Cholesky decomposition.
Return the Cholesky decomposition, `L * L.H`, of the square matrix `a`,
where `L` is lower-triangular and .H is the conjugate transpose operator
(which is the ordinary transpose if `a` is real-valued). `a` must be
Hermitian (symmetric if real-valued) and positive-definite. Only `L` is
actually returned.
Parameters
----------
a : (..., M, M) array_like
Hermitian (symmetric if all elements are real), positive-definite
input matrix.
lower : bool
Whether to compute the upper or lower triangular Cholesky
factorization. Default is upper-triangular.
Returns
-------
L : (..., M, M) array_like
Upper or lower-triangular Cholesky factor of `a`.
Raises
------
LinAlgError
If the decomposition fails, for example, if `a` is not
positive-definite.
Notes
-----
Broadcasting rules apply, see the `mt.linalg` documentation for
details.
The Cholesky decomposition is often used as a fast way of solving
.. math:: A \\mathbf{x} = \\mathbf{b}
(when `A` is both Hermitian/symmetric and positive-definite).
First, we solve for :math:`\\mathbf{y}` in
.. math:: L \\mathbf{y} = \\mathbf{b},
and then for :math:`\\mathbf{x}` in
.. math:: L.H \\mathbf{x} = \\mathbf{y}.
Examples
--------
>>> import mars.tensor as mt
>>> A = mt.array([[1,-2j],[2j,5]])
>>> A.execute()
array([[ 1.+0.j, 0.-2.j],
[ 0.+2.j, 5.+0.j]])
>>> L = mt.linalg.cholesky(A, lower=True)
>>> L.execute()
array([[ 1.+0.j, 0.+0.j],
[ 0.+2.j, 1.+0.j]])
>>> mt.dot(L, L.T.conj()).execute() # verify that L * L.H = A
array([[ 1.+0.j, 0.-2.j],
[ 0.+2.j, 5.+0.j]])
>>> A = [[1,-2j],[2j,5]] # what happens if A is only array_like?
>>> mt.linalg.cholesky(A, lower=True).execute()
array([[ 1.+0.j, 0.+0.j],
[ 0.+2.j, 1.+0.j]])
"""
a = astensor(a)
if a.ndim != 2:
raise LinAlgError(f'{a.ndim}-dimensional array given. '
'Tensor must be two-dimensional')
if a.shape[0] != a.shape[1]:
raise LinAlgError('Input must be square')
cho = np.linalg.cholesky(np.array([[1, 2], [2, 5]], dtype=a.dtype))
op = TensorCholesky(lower=lower, dtype=cho.dtype)
return op(a)
| 38.421818 | 111 | 0.565777 |
import numpy as np
from numpy.linalg import LinAlgError
from ...serialize import KeyField, BoolField
from ... import opcodes as OperandDef
from ...utils import check_chunks_unknown_shape
from ...tiles import TilesError
from ..operands import TensorHasInput, TensorOperand, TensorOperandMixin
from ..datasource import tensor as astensor
from ..core import TensorOrder
from ..array_utils import as_same_device, device
class TensorCholesky(TensorHasInput, TensorOperandMixin):
_op_type_ = OperandDef.CHOLESKY
_input = KeyField('input')
_lower = BoolField('lower')
def __init__(self, lower=None, dtype=None, **kw):
super().__init__(_lower=lower, _dtype=dtype, **kw)
@property
def lower(self):
return self._lower
def _set_inputs(self, inputs):
super()._set_inputs(inputs)
self._input = self._inputs[0]
def __call__(self, a):
return self.new_tensor([a], a.shape, order=TensorOrder.C_ORDER)
@classmethod
def tile(cls, op):
from ..datasource.zeros import TensorZeros
from ..base import TensorTranspose
from ..utils import reverse_order
from .dot import TensorDot
from .solve_triangular import TensorSolveTriangular
tensor = op.outputs[0]
in_tensor = op.input
check_chunks_unknown_shape([in_tensor], TilesError)
if in_tensor.nsplits[0] != in_tensor.nsplits[1]:
nsplits = in_tensor.nsplits[0]
in_tensor = in_tensor.rechunk([nsplits, nsplits])._inplace_tile()
lower_chunks, upper_chunks = {}, {}
for i in range(in_tensor.chunk_shape[0]):
for j in range(in_tensor.chunk_shape[1]):
if i < j:
lower_chunk = TensorZeros(dtype=tensor.dtype).new_chunk(
None, shape=(in_tensor.nsplits[0][i], in_tensor.nsplits[1][j]),
index=(i, j), order=tensor.order)
upper_chunk = TensorZeros(dtype=tensor.dtype).new_chunk(
None, shape=(in_tensor.nsplits[1][j], in_tensor.nsplits[0][i]),
index=(j, i), order=tensor.order)
lower_chunks[lower_chunk.index] = lower_chunk
upper_chunks[upper_chunk.index] = upper_chunk
elif i == j:
target = in_tensor.cix[i, j]
if i > 0:
prev_chunks = []
for p in range(i):
a, b = lower_chunks[i, p], upper_chunks[p, j]
prev_chunk = TensorDot(dtype=tensor.dtype).new_chunk(
[a, b], shape=(a.shape[0], b.shape[1]), order=tensor.order)
prev_chunks.append(prev_chunk)
cholesky_fuse_op = TensorCholeskyFuse()
lower_chunk = cholesky_fuse_op.new_chunk([target] + prev_chunks,
shape=target.shape, index=(i, j),
order=tensor.order)
else:
lower_chunk = TensorCholesky(lower=True, dtype=tensor.dtype).new_chunk(
[target], shape=target.shape, index=(i, j), order=tensor.order)
upper_chunk = TensorTranspose(dtype=lower_chunk.dtype).new_chunk(
[lower_chunk], shape=lower_chunk.shape[::-1],
index=lower_chunk.index[::-1], order=reverse_order(lower_chunk.order))
lower_chunks[lower_chunk.index] = lower_chunk
upper_chunks[upper_chunk.index] = upper_chunk
else:
target = in_tensor.cix[j, i]
if j > 0:
prev_chunks = []
for p in range(j):
a, b = lower_chunks[j, p], upper_chunks[p, i]
prev_chunk = TensorDot(dtype=tensor.dtype).new_chunk(
[a, b], shape=(a.shape[0], b.shape[1]), order=tensor.order)
prev_chunks.append(prev_chunk)
cholesky_fuse_op = TensorCholeskyFuse(by_solve_triangular=True)
upper_chunk = cholesky_fuse_op.new_chunk([target] + [lower_chunks[j, j]] + prev_chunks,
shape=target.shape, index=(j, i),
order=tensor.order)
else:
upper_chunk = TensorSolveTriangular(lower=True, dtype=tensor.dtype).new_chunk(
[lower_chunks[j, j], target], shape=target.shape,
index=(j, i), order=tensor.order)
lower_chunk = TensorTranspose(dtype=upper_chunk.dtype).new_chunk(
[upper_chunk], shape=upper_chunk.shape[::-1],
index=upper_chunk.index[::-1], order=reverse_order(upper_chunk.order))
lower_chunks[lower_chunk.index] = lower_chunk
upper_chunks[upper_chunk.index] = upper_chunk
new_op = op.copy()
if op.lower:
return new_op.new_tensors(op.inputs, tensor.shape, order=tensor.order,
chunks=list(lower_chunks.values()), nsplits=in_tensor.nsplits)
else:
return new_op.new_tensors(op.inputs, tensor.shape, order=tensor.order,
chunks=list(upper_chunks.values()), nsplits=in_tensor.nsplits)
@classmethod
def execute(cls, ctx, op):
chunk = op.outputs[0]
(a,), device_id, xp = as_same_device(
[ctx[c.key] for c in op.inputs], device=op.device, ret_extra=True)
with device(device_id):
if xp is np:
try:
import scipy.linalg
ctx[chunk.key] = scipy.linalg.cholesky(a, lower=op.lower)
return
except ImportError:
pass
r = xp.linalg.cholesky(a)
if not chunk.op.lower:
r = r.T.conj()
ctx[chunk.key] = r
class TensorCholeskyFuse(TensorOperand, TensorOperandMixin):
_op_type_ = OperandDef.CHOLESKY_FUSE
_by_solve_triangular = BoolField('by_solve_triangular')
def __init__(self, by_solve_triangular=None, **kw):
super().__init__(_by_solve_triangular=by_solve_triangular, **kw)
@property
def by_solve_triangular(self):
return self._by_solve_triangular
@classmethod
def _execute_by_cholesky(cls, inputs):
import scipy.linalg
target = inputs[0]
return scipy.linalg.cholesky((target - sum(inputs[1:])), lower=True)
@classmethod
def _execute_by_solve_striangular(cls, inputs):
import scipy.linalg
target = inputs[0]
lower = inputs[1]
return scipy.linalg.solve_triangular(lower, (target - sum(inputs[2:])), lower=True)
@classmethod
def execute(cls, ctx, op):
inputs = [ctx[c.key] for c in op.inputs]
if op.by_solve_triangular:
ret = cls._execute_by_solve_striangular(inputs)
else:
ret = cls._execute_by_cholesky(inputs)
ctx[op.outputs[0].key] = ret
def cholesky(a, lower=False):
a = astensor(a)
if a.ndim != 2:
raise LinAlgError(f'{a.ndim}-dimensional array given. '
'Tensor must be two-dimensional')
if a.shape[0] != a.shape[1]:
raise LinAlgError('Input must be square')
cho = np.linalg.cholesky(np.array([[1, 2], [2, 5]], dtype=a.dtype))
op = TensorCholesky(lower=lower, dtype=cho.dtype)
return op(a)
| true | true |
f723adcd52513b64e1355d73342ebd48142ef31e | 6,813 | py | Python | artificial_bias_experiments/noisy_prop_scores/sar_two_subject_groups/experiment_running/run_dataset.py | ML-KULeuven/KBC-as-PU-Learning | a00f606bd40ca06af0a5627e65a4582859976918 | [
"Apache-2.0"
] | 4 | 2021-12-14T16:13:47.000Z | 2022-01-21T13:14:14.000Z | artificial_bias_experiments/noisy_prop_scores/sar_two_subject_groups/experiment_running/run_dataset.py | ML-KULeuven/KBC-as-PU-Learning | a00f606bd40ca06af0a5627e65a4582859976918 | [
"Apache-2.0"
] | null | null | null | artificial_bias_experiments/noisy_prop_scores/sar_two_subject_groups/experiment_running/run_dataset.py | ML-KULeuven/KBC-as-PU-Learning | a00f606bd40ca06af0a5627e65a4582859976918 | [
"Apache-2.0"
] | null | null | null | import os
from typing import List, Tuple, Dict, Optional, Any
from dask.delayed import Delayed, delayed
from distributed import Client
from artificial_bias_experiments.evaluation.sar_group_finding_relation_overlap import \
get_target_relation_to_filter_relation_list_map_and_create_if_non_existent
from dask_utils.computations import compute_delayed_functions
from dask_utils.dask_initialization import reconnect_client_to_ssh_cluster
from kbc_pul.project_info import data_dir as kbc_pul_data_dir
from artificial_bias_experiments.amie_rule_learning import get_amie_rule_tsv_filename
from artificial_bias_experiments.noisy_prop_scores.sar_two_subject_groups.experiment_running.run_exp_multiple_settings import \
run_per_target_relation_experiment_noisy_prop_scores_sar_two_subject_groups
from artificial_bias_experiments.known_prop_scores.sar_two_subject_groups.experiment_info import \
TargetFilterOverlapSettings
from artificial_bias_experiments.noisy_prop_scores.sar_two_subject_groups.noisy_prop_scores_sar_two_groups_file_naming import \
NoisyPropScoresSARTwoGroupsFileNamer
from kbc_pul.observed_data_generation.sar_two_subject_groups.sar_two_subject_groups_prop_scores import \
PropScoresTwoSARGroups
def run_noisy_prop_scores_sar_two_groups_both_pca_and_non_pca_for_dataset(
dataset_name: str, dask_scheduler_host: str) -> None:
# true_prop_score_in_filter = 1.0
# true_prop_score_other = 0.5
true_prop_score_in_filter = 0.5
true_prop_score_other_list = [0.3, .7]
# true_prop_scores = PropScoresTwoSARGroups(
# in_filter=true_prop_score_in_filter,
# other=true_prop_score_other
# )
noisy_prop_score_in_filter: float = true_prop_score_in_filter
noisy_prop_score_not_in_filter_list: List[float] = [0.1, 0.2, .3, .4, .5, .6, .7, .8, .9, 1]
random_seed: int = 3
verbose = False
use_pca_list: List[bool] = [False, True]
target_filter_overlap_settings = TargetFilterOverlapSettings(
fraction_lower_bound=0.1,
fraction_upper_bound=0.9,
intersection_absolute_lower_bound=10
)
n_random_trials: int = 10
amie_min_std_confidence: float = 0.1
filename_ground_truth_dataset: str = os.path.join(
kbc_pul_data_dir, dataset_name, 'cleaned_csv', 'train.csv'
)
separator_ground_truth_dataset = "\t"
# df_ground_truth: pd.DataFrame = get_df_ground_truth(filename_ground_truth_dataset, separator_ground_truth_dataset)
# target_relation_list: List[str] = list(sorted(df_ground_truth["Rel"].unique()))
amie_rule_tsv_filename = get_amie_rule_tsv_filename(
filename_ground_truth_dataset=filename_ground_truth_dataset,
dataset_name=dataset_name,
min_std_confidence=amie_min_std_confidence
)
use_dask: bool = True
list_of_computations: List[Tuple[Delayed, Dict]] = []
if use_dask:
scheduler_host: str = dask_scheduler_host
client: Optional[Client] = reconnect_client_to_ssh_cluster(scheduler_host)
else:
client = None
for use_pca in use_pca_list:
target_to_filter_relation_list_map: Dict[
str,
List[str]
] = get_target_relation_to_filter_relation_list_map_and_create_if_non_existent(
filename_ground_truth_dataset=filename_ground_truth_dataset,
separator_ground_truth_dataset=separator_ground_truth_dataset,
dataset_name=dataset_name,
target_filter_overlap_settings=target_filter_overlap_settings,
is_pca_version=use_pca
)
for true_prop_score_other in true_prop_score_other_list:
true_prop_scores = PropScoresTwoSARGroups(
in_filter=true_prop_score_in_filter,
other=true_prop_score_other
)
target_relation: str
filter_relation_list: List[str]
for target_relation, filter_relation_list in target_to_filter_relation_list_map.items():
if use_dask:
func_args: Dict[str, Any] = dict(
filename_ground_truth_dataset=filename_ground_truth_dataset,
separator_ground_truth_dataset="\t",
amie_rule_tsv_filename=amie_rule_tsv_filename,
dataset_name=dataset_name,
target_relation=target_relation,
filter_relation_list=filter_relation_list,
true_prop_scores=true_prop_scores,
noisy_prop_score_in_filter=noisy_prop_score_in_filter,
noisy_prop_score_not_in_filter_list=noisy_prop_score_not_in_filter_list,
is_pca_version=use_pca,
random_seed=random_seed,
n_random_trials=n_random_trials,
verbose=verbose,
)
delayed_func = delayed(run_per_target_relation_experiment_noisy_prop_scores_sar_two_subject_groups)(
**func_args
)
list_of_computations.append((delayed_func, func_args))
else:
run_per_target_relation_experiment_noisy_prop_scores_sar_two_subject_groups(
filename_ground_truth_dataset=filename_ground_truth_dataset,
separator_ground_truth_dataset="\t",
amie_rule_tsv_filename=amie_rule_tsv_filename,
dataset_name=dataset_name,
target_relation=target_relation,
filter_relation_list=filter_relation_list,
true_prop_scores=true_prop_scores,
noisy_prop_score_in_filter=noisy_prop_score_in_filter,
noisy_prop_score_not_in_filter_list=noisy_prop_score_not_in_filter_list,
is_pca_version=use_pca,
random_seed=random_seed,
n_random_trials=n_random_trials,
verbose=verbose,
)
if use_dask:
dir_log_file: str = NoisyPropScoresSARTwoGroupsFileNamer.get_filename_log_file_dir(
dataset_name=dataset_name
)
if not os.path.exists(dir_log_file):
os.makedirs(dir_log_file)
logger_name: str = 'ERROR_LOGGER_noisy_prop_scores_sar_for_' + dataset_name
logger_file_name: str = os.path.join(
dir_log_file,
logger_name
)
compute_delayed_functions(
list_of_computations=list_of_computations,
client=client,
nb_of_retries_if_erred=5,
error_logger_name=logger_name,
error_logger_file_name=logger_file_name,
)
| 43.394904 | 127 | 0.691032 | import os
from typing import List, Tuple, Dict, Optional, Any
from dask.delayed import Delayed, delayed
from distributed import Client
from artificial_bias_experiments.evaluation.sar_group_finding_relation_overlap import \
get_target_relation_to_filter_relation_list_map_and_create_if_non_existent
from dask_utils.computations import compute_delayed_functions
from dask_utils.dask_initialization import reconnect_client_to_ssh_cluster
from kbc_pul.project_info import data_dir as kbc_pul_data_dir
from artificial_bias_experiments.amie_rule_learning import get_amie_rule_tsv_filename
from artificial_bias_experiments.noisy_prop_scores.sar_two_subject_groups.experiment_running.run_exp_multiple_settings import \
run_per_target_relation_experiment_noisy_prop_scores_sar_two_subject_groups
from artificial_bias_experiments.known_prop_scores.sar_two_subject_groups.experiment_info import \
TargetFilterOverlapSettings
from artificial_bias_experiments.noisy_prop_scores.sar_two_subject_groups.noisy_prop_scores_sar_two_groups_file_naming import \
NoisyPropScoresSARTwoGroupsFileNamer
from kbc_pul.observed_data_generation.sar_two_subject_groups.sar_two_subject_groups_prop_scores import \
PropScoresTwoSARGroups
def run_noisy_prop_scores_sar_two_groups_both_pca_and_non_pca_for_dataset(
dataset_name: str, dask_scheduler_host: str) -> None:
true_prop_score_in_filter = 0.5
true_prop_score_other_list = [0.3, .7]
noisy_prop_score_in_filter: float = true_prop_score_in_filter
noisy_prop_score_not_in_filter_list: List[float] = [0.1, 0.2, .3, .4, .5, .6, .7, .8, .9, 1]
random_seed: int = 3
verbose = False
use_pca_list: List[bool] = [False, True]
target_filter_overlap_settings = TargetFilterOverlapSettings(
fraction_lower_bound=0.1,
fraction_upper_bound=0.9,
intersection_absolute_lower_bound=10
)
n_random_trials: int = 10
amie_min_std_confidence: float = 0.1
filename_ground_truth_dataset: str = os.path.join(
kbc_pul_data_dir, dataset_name, 'cleaned_csv', 'train.csv'
)
separator_ground_truth_dataset = "\t"
amie_rule_tsv_filename = get_amie_rule_tsv_filename(
filename_ground_truth_dataset=filename_ground_truth_dataset,
dataset_name=dataset_name,
min_std_confidence=amie_min_std_confidence
)
use_dask: bool = True
list_of_computations: List[Tuple[Delayed, Dict]] = []
if use_dask:
scheduler_host: str = dask_scheduler_host
client: Optional[Client] = reconnect_client_to_ssh_cluster(scheduler_host)
else:
client = None
for use_pca in use_pca_list:
target_to_filter_relation_list_map: Dict[
str,
List[str]
] = get_target_relation_to_filter_relation_list_map_and_create_if_non_existent(
filename_ground_truth_dataset=filename_ground_truth_dataset,
separator_ground_truth_dataset=separator_ground_truth_dataset,
dataset_name=dataset_name,
target_filter_overlap_settings=target_filter_overlap_settings,
is_pca_version=use_pca
)
for true_prop_score_other in true_prop_score_other_list:
true_prop_scores = PropScoresTwoSARGroups(
in_filter=true_prop_score_in_filter,
other=true_prop_score_other
)
target_relation: str
filter_relation_list: List[str]
for target_relation, filter_relation_list in target_to_filter_relation_list_map.items():
if use_dask:
func_args: Dict[str, Any] = dict(
filename_ground_truth_dataset=filename_ground_truth_dataset,
separator_ground_truth_dataset="\t",
amie_rule_tsv_filename=amie_rule_tsv_filename,
dataset_name=dataset_name,
target_relation=target_relation,
filter_relation_list=filter_relation_list,
true_prop_scores=true_prop_scores,
noisy_prop_score_in_filter=noisy_prop_score_in_filter,
noisy_prop_score_not_in_filter_list=noisy_prop_score_not_in_filter_list,
is_pca_version=use_pca,
random_seed=random_seed,
n_random_trials=n_random_trials,
verbose=verbose,
)
delayed_func = delayed(run_per_target_relation_experiment_noisy_prop_scores_sar_two_subject_groups)(
**func_args
)
list_of_computations.append((delayed_func, func_args))
else:
run_per_target_relation_experiment_noisy_prop_scores_sar_two_subject_groups(
filename_ground_truth_dataset=filename_ground_truth_dataset,
separator_ground_truth_dataset="\t",
amie_rule_tsv_filename=amie_rule_tsv_filename,
dataset_name=dataset_name,
target_relation=target_relation,
filter_relation_list=filter_relation_list,
true_prop_scores=true_prop_scores,
noisy_prop_score_in_filter=noisy_prop_score_in_filter,
noisy_prop_score_not_in_filter_list=noisy_prop_score_not_in_filter_list,
is_pca_version=use_pca,
random_seed=random_seed,
n_random_trials=n_random_trials,
verbose=verbose,
)
if use_dask:
dir_log_file: str = NoisyPropScoresSARTwoGroupsFileNamer.get_filename_log_file_dir(
dataset_name=dataset_name
)
if not os.path.exists(dir_log_file):
os.makedirs(dir_log_file)
logger_name: str = 'ERROR_LOGGER_noisy_prop_scores_sar_for_' + dataset_name
logger_file_name: str = os.path.join(
dir_log_file,
logger_name
)
compute_delayed_functions(
list_of_computations=list_of_computations,
client=client,
nb_of_retries_if_erred=5,
error_logger_name=logger_name,
error_logger_file_name=logger_file_name,
)
| true | true |
f723aeb2aeac1a32beb23fffa80507823230fb32 | 366 | py | Python | jp.atcoder/abc068/arc079_a/8266792.py | kagemeka/atcoder-submissions | 91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e | [
"MIT"
] | 1 | 2022-02-09T03:06:25.000Z | 2022-02-09T03:06:25.000Z | jp.atcoder/abc068/arc079_a/8266792.py | kagemeka/atcoder-submissions | 91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e | [
"MIT"
] | 1 | 2022-02-05T22:53:18.000Z | 2022-02-09T01:29:30.000Z | jp.atcoder/abc068/arc079_a/8266792.py | kagemeka/atcoder-submissions | 91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e | [
"MIT"
] | null | null | null | import sys
from collections import deque
l = deque(sys.stdin.readlines())
n, m = (int(x) for x in l[0].split())
l.popleft()
from_1, to_n = set(), set()
for a, b in deque((int(x) for x in l[i].split()) for i in range(m)):
if a == 1:
from_1.add(b)
elif b == n:
to_n.add(a)
print("POSSIBLE" if from_1 & to_n else "IMPOSSIBLE")
| 22.875 | 69 | 0.571038 | import sys
from collections import deque
l = deque(sys.stdin.readlines())
n, m = (int(x) for x in l[0].split())
l.popleft()
from_1, to_n = set(), set()
for a, b in deque((int(x) for x in l[i].split()) for i in range(m)):
if a == 1:
from_1.add(b)
elif b == n:
to_n.add(a)
print("POSSIBLE" if from_1 & to_n else "IMPOSSIBLE")
| true | true |
f723af36ad4e0a686b6bf06f93aabd8e0e1d70aa | 640 | py | Python | setup.py | bradfordleak/Units | 585f30c60cd0958d61ebd465bb1328a459e078b2 | [
"BSD-3-Clause"
] | null | null | null | setup.py | bradfordleak/Units | 585f30c60cd0958d61ebd465bb1328a459e078b2 | [
"BSD-3-Clause"
] | null | null | null | setup.py | bradfordleak/Units | 585f30c60cd0958d61ebd465bb1328a459e078b2 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
github_url = ("https://guthub.com/bradfordleak/Units/bradfordleak/"
"Units")
try:
with open('README.md') as f:
readme = f.read()
except:
readme = "Please see the README.md file at {}.".format(github_url)
setup(
name='units',
version='0.0.1',
description='it does something interesting, I'm sure',
long_description=readme,
author='Bradford Leak',
author_email='bradfordleak@gmail.com',
url=github_url,
license='License :: Other/Proprietary License',
packages=find_packages(exclude=('tests', 'docs'))
)
| 24.615385 | 70 | 0.654688 |
from setuptools import setup, find_packages
github_url = ("https://guthub.com/bradfordleak/Units/bradfordleak/"
"Units")
try:
with open('README.md') as f:
readme = f.read()
except:
readme = "Please see the README.md file at {}.".format(github_url)
setup(
name='units',
version='0.0.1',
description='it does something interesting, I'm sure',
long_description=readme,
author='Bradford Leak',
author_email='bradfordleak@gmail.com',
url=github_url,
license='License :: Other/Proprietary License',
packages=find_packages(exclude=('tests', 'docs'))
)
| false | true |
f723afcdd58b39429c1e28d0944d4253ee87ed6f | 5,475 | py | Python | objectdetection/user_interface.py | JunlinLi30/ObjectDetectionApplication | 1dbd6760f54e143c5f3476fd29cb4c5646b6f3c6 | [
"MIT"
] | null | null | null | objectdetection/user_interface.py | JunlinLi30/ObjectDetectionApplication | 1dbd6760f54e143c5f3476fd29cb4c5646b6f3c6 | [
"MIT"
] | null | null | null | objectdetection/user_interface.py | JunlinLi30/ObjectDetectionApplication | 1dbd6760f54e143c5f3476fd29cb4c5646b6f3c6 | [
"MIT"
] | null | null | null | import submodule.appfunction as af
import tkinter.filedialog
from tkinter import *
import tkinter as tk
import numpy as np
import PIL.ImageTk
import PIL.Image
from PIL import *
import cv2
import os
class ObjectDetection_ui(tk.Tk):
def __init__(self):
self.window = tk.Tk()
self.window.title("Object Detection")
af.tf_version_check();
self.modelPath = ""
self.labelMapPath = ""
# Open a file dialog asking for the input image file
def askopenimgfile(self):
path = filedialog.askopenfilename()
# got back the detected image
img_processed = af.input_image(path, self.modelPath, self.labelMapPath)
img = img_processed.resize((800, 600))
photo = PIL.ImageTk.PhotoImage(img)
# open the image in a new window
self.new_window = tk.Toplevel()
self.new_window.title("Image")
self.img_import = Label(self.new_window, image=photo, height=600, width=800)
self.img_import.pack(fill=BOTH, expand=YES)
self.img_import.bind("<Configure>", lambda event, arg=img: self.resize_image(event, arg))
self.img_import.pack(fill=BOTH, expand=YES)
self.new_window.mainloop()
# image resize related to the window size
def resize_image(self, event, img):
w, h = event.width, event.height
img_copy = img.copy()
resize_img = img_copy.resize((w,h))
photo = PIL.ImageTk.PhotoImage(resize_img)
self.img_import.config(image=photo)
self.img_import.image=photo #avoid garbage collection
# Open a file dialog asking for the input video file
def askopenvideofile(self):
path = filedialog.askopenfilename()
stop = af.input_video(path, self.modelPath, self.labelMapPath)
if stop == True:
return
# Open the webcam of the user's laptop
def askcam(self):
stop = af.input_cam(self.modelPath, self.labelMapPath);
# stop streaming and release the camera
# if window close or "q" is pressed
if (stop == True):
return
# Delete the placeholder when new input is indicated
def delete_placeholder(self, entry):
entry.delete(0, END)
# Open a file dialog asking for the model file
def askmodelfile(self, entry):
path = filedialog.askopenfilename()
if not af.file_is_exist(path) or not os.access(path, os.R_OK):
raise Exception("Model file doesn't exist or is unreadable!")
self.delete_placeholder(entry)
entry.insert(0, path)
self.modelPath = path
# Open a file dialog asking for the label map file
def asklabelfile(self, entry):
path = filedialog.askopenfilename()
if not af.file_is_exist(path) or not os.access(path, os.R_OK):
raise Exception("Label map file doesn't exist or is unreadable!")
self.delete_placeholder(entry)
entry.insert(0, path)
self.labelMapPath = path
# main function where the ui runs
def main(self):
self.group_1 = Frame(self.window)
self.group_1.pack()
self.modelGroup = Frame(self.group_1)
self.modelGroup.pack(fill=X, expand=YES)
self.labelGroup = Frame(self.group_1)
self.labelGroup.pack(fill=X, expand=YES)
# display the path of model used and label map data file
custPath = StringVar(None)
pretext_model = "Please indicate the path to your detection model (*.pbtxt)"
self.model_path = Entry(self.modelGroup, width=54, textvariable=custPath)
self.model_path.insert(0, pretext_model)
self.model_path.pack(side=LEFT)
self.model_path.bind("<Button-1>", lambda event, arg=self.model_path: self.delete_placeholder(arg))
# browse for a model
self.model_input = Button(self.modelGroup, text = "Browse", command = lambda: self.askmodelfile(self.model_path))
self.model_input.pack(side=LEFT)
# label map data file
custPath_label = StringVar(None)
pretext_label = "Please indicate the path to your label map file (*.pb)"
self.label_path = Entry(self.labelGroup, width=54, textvariable=custPath_label)
self.label_path.insert(0, pretext_label)
self.label_path.pack(side=LEFT)
self.label_path.bind("<Button-1>", lambda event, arg=self.label_path: self.delete_placeholder(arg))
# browse for a label map file
self.label_input = Button(self.labelGroup, text = "Browse", command = lambda: self.asklabelfile(self.label_path))
self.label_input.pack(side=LEFT)
# Buttons of 3 input-type options and Quit
self.group_2 = Frame(self.window)
self.group_2.pack(fill=X, expand=YES)
self.group_btn = Frame(self.group_2)
self.group_btn.pack()
# define all buttons
image_input = Button(self.group_btn, text = "Image", command = self.askopenimgfile)
image_input.pack(side=LEFT)
video_input = Button(self.group_btn, text = "Video", command = self.askopenvideofile)
video_input.pack(side=LEFT)
cam_input = Button(self.group_btn, text = "Camera", command = self.askcam)
cam_input.pack(side=LEFT)
quitBtn = Button(self.group_btn, text="Quit", command = quit)
quitBtn.pack(side=LEFT)
self.window.mainloop()
# start the user interface
start = ObjectDetection_ui()
start.main()
if __name__ == "__main__":
ObjectDetection_ui().main()
| 40.555556 | 121 | 0.661735 | import submodule.appfunction as af
import tkinter.filedialog
from tkinter import *
import tkinter as tk
import numpy as np
import PIL.ImageTk
import PIL.Image
from PIL import *
import cv2
import os
class ObjectDetection_ui(tk.Tk):
def __init__(self):
self.window = tk.Tk()
self.window.title("Object Detection")
af.tf_version_check();
self.modelPath = ""
self.labelMapPath = ""
def askopenimgfile(self):
path = filedialog.askopenfilename()
img_processed = af.input_image(path, self.modelPath, self.labelMapPath)
img = img_processed.resize((800, 600))
photo = PIL.ImageTk.PhotoImage(img)
self.new_window = tk.Toplevel()
self.new_window.title("Image")
self.img_import = Label(self.new_window, image=photo, height=600, width=800)
self.img_import.pack(fill=BOTH, expand=YES)
self.img_import.bind("<Configure>", lambda event, arg=img: self.resize_image(event, arg))
self.img_import.pack(fill=BOTH, expand=YES)
self.new_window.mainloop()
def resize_image(self, event, img):
w, h = event.width, event.height
img_copy = img.copy()
resize_img = img_copy.resize((w,h))
photo = PIL.ImageTk.PhotoImage(resize_img)
self.img_import.config(image=photo)
self.img_import.image=photo
def askopenvideofile(self):
path = filedialog.askopenfilename()
stop = af.input_video(path, self.modelPath, self.labelMapPath)
if stop == True:
return
def askcam(self):
stop = af.input_cam(self.modelPath, self.labelMapPath);
# stop streaming and release the camera
# if window close or "q" is pressed
if (stop == True):
return
# Delete the placeholder when new input is indicated
def delete_placeholder(self, entry):
entry.delete(0, END)
# Open a file dialog asking for the model file
def askmodelfile(self, entry):
path = filedialog.askopenfilename()
if not af.file_is_exist(path) or not os.access(path, os.R_OK):
raise Exception("Model file doesn't exist or is unreadable!")
self.delete_placeholder(entry)
entry.insert(0, path)
self.modelPath = path
def asklabelfile(self, entry):
path = filedialog.askopenfilename()
if not af.file_is_exist(path) or not os.access(path, os.R_OK):
raise Exception("Label map file doesn't exist or is unreadable!")
self.delete_placeholder(entry)
entry.insert(0, path)
self.labelMapPath = path
# main function where the ui runs
def main(self):
self.group_1 = Frame(self.window)
self.group_1.pack()
self.modelGroup = Frame(self.group_1)
self.modelGroup.pack(fill=X, expand=YES)
self.labelGroup = Frame(self.group_1)
self.labelGroup.pack(fill=X, expand=YES)
# display the path of model used and label map data file
custPath = StringVar(None)
pretext_model = "Please indicate the path to your detection model (*.pbtxt)"
self.model_path = Entry(self.modelGroup, width=54, textvariable=custPath)
self.model_path.insert(0, pretext_model)
self.model_path.pack(side=LEFT)
self.model_path.bind("<Button-1>", lambda event, arg=self.model_path: self.delete_placeholder(arg))
# browse for a model
self.model_input = Button(self.modelGroup, text = "Browse", command = lambda: self.askmodelfile(self.model_path))
self.model_input.pack(side=LEFT)
# label map data file
custPath_label = StringVar(None)
pretext_label = "Please indicate the path to your label map file (*.pb)"
self.label_path = Entry(self.labelGroup, width=54, textvariable=custPath_label)
self.label_path.insert(0, pretext_label)
self.label_path.pack(side=LEFT)
self.label_path.bind("<Button-1>", lambda event, arg=self.label_path: self.delete_placeholder(arg))
# browse for a label map file
self.label_input = Button(self.labelGroup, text = "Browse", command = lambda: self.asklabelfile(self.label_path))
self.label_input.pack(side=LEFT)
# Buttons of 3 input-type options and Quit
self.group_2 = Frame(self.window)
self.group_2.pack(fill=X, expand=YES)
self.group_btn = Frame(self.group_2)
self.group_btn.pack()
# define all buttons
image_input = Button(self.group_btn, text = "Image", command = self.askopenimgfile)
image_input.pack(side=LEFT)
video_input = Button(self.group_btn, text = "Video", command = self.askopenvideofile)
video_input.pack(side=LEFT)
cam_input = Button(self.group_btn, text = "Camera", command = self.askcam)
cam_input.pack(side=LEFT)
quitBtn = Button(self.group_btn, text="Quit", command = quit)
quitBtn.pack(side=LEFT)
self.window.mainloop()
# start the user interface
start = ObjectDetection_ui()
start.main()
if __name__ == "__main__":
ObjectDetection_ui().main()
| true | true |
f723afd8001413518d42ccf2a8cf98aeaed860c8 | 256 | py | Python | checkov/common/version_manager.py | kylelaker/checkov | 6eada26030a87f397a6bf1831827b3dc6c5dad2d | [
"Apache-2.0"
] | 4,013 | 2019-12-09T13:16:54.000Z | 2022-03-31T14:31:01.000Z | checkov/common/version_manager.py | kylelaker/checkov | 6eada26030a87f397a6bf1831827b3dc6c5dad2d | [
"Apache-2.0"
] | 1,258 | 2019-12-17T09:55:51.000Z | 2022-03-31T19:17:17.000Z | checkov/common/version_manager.py | kylelaker/checkov | 6eada26030a87f397a6bf1831827b3dc6c5dad2d | [
"Apache-2.0"
] | 638 | 2019-12-19T08:57:38.000Z | 2022-03-30T21:38:37.000Z | from update_checker import UpdateChecker
def check_for_update(package, version):
try:
checker = UpdateChecker()
result = checker.check(package, version)
return result.available_version
except: # nosec
return None
| 23.272727 | 48 | 0.683594 | from update_checker import UpdateChecker
def check_for_update(package, version):
try:
checker = UpdateChecker()
result = checker.check(package, version)
return result.available_version
except:
return None
| true | true |
f723b0f4485a13205bef9f26c46a1ba70d2ed257 | 46,585 | py | Python | electrum/util.py | mi6gan/electrum | 7a6ec23b6ecfe48e28e16d2a9cd1bb255ead75c8 | [
"MIT"
] | null | null | null | electrum/util.py | mi6gan/electrum | 7a6ec23b6ecfe48e28e16d2a9cd1bb255ead75c8 | [
"MIT"
] | null | null | null | electrum/util.py | mi6gan/electrum | 7a6ec23b6ecfe48e28e16d2a9cd1bb255ead75c8 | [
"MIT"
] | null | null | null | # Electrum - lightweight Bitcoin client
# Copyright (C) 2011 Thomas Voegtlin
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import binascii
import os, sys, re, json
from collections import defaultdict, OrderedDict
from typing import (NamedTuple, Union, TYPE_CHECKING, Tuple, Optional, Callable, Any,
Sequence, Dict, Generic, TypeVar, List, Iterable)
from datetime import datetime
import decimal
from decimal import Decimal
import traceback
import urllib
import threading
import hmac
import stat
from locale import localeconv
import asyncio
import urllib.request, urllib.parse, urllib.error
import builtins
import json
import time
from typing import NamedTuple, Optional
import ssl
import ipaddress
from ipaddress import IPv4Address, IPv6Address
import random
import attr
import aiohttp
from aiohttp_socks import ProxyConnector, ProxyType
import aiorpcx
from aiorpcx import TaskGroup
import certifi
import dns.resolver
import ecdsa
from .i18n import _
from .logging import get_logger, Logger
if TYPE_CHECKING:
from .network import Network
from .interface import Interface
from .simple_config import SimpleConfig
_logger = get_logger(__name__)
def inv_dict(d):
return {v: k for k, v in d.items()}
ca_path = certifi.where()
base_units = {'BTC':8, 'mBTC':5, 'bits':2, 'sat':0}
base_units_inverse = inv_dict(base_units)
base_units_list = ['BTC', 'mBTC', 'bits', 'sat'] # list(dict) does not guarantee order
DECIMAL_POINT_DEFAULT = 5 # mBTC
class UnknownBaseUnit(Exception): pass
def decimal_point_to_base_unit_name(dp: int) -> str:
# e.g. 8 -> "BTC"
try:
return base_units_inverse[dp]
except KeyError:
raise UnknownBaseUnit(dp) from None
def base_unit_name_to_decimal_point(unit_name: str) -> int:
# e.g. "BTC" -> 8
try:
return base_units[unit_name]
except KeyError:
raise UnknownBaseUnit(unit_name) from None
class NotEnoughFunds(Exception):
def __str__(self):
return _("Insufficient funds")
class NoDynamicFeeEstimates(Exception):
def __str__(self):
return _('Dynamic fee estimates not available')
class MultipleSpendMaxTxOutputs(Exception):
def __str__(self):
return _('At most one output can be set to spend max')
class InvalidPassword(Exception):
def __str__(self):
return _("Incorrect password")
class FileImportFailed(Exception):
def __init__(self, message=''):
self.message = str(message)
def __str__(self):
return _("Failed to import from file.") + "\n" + self.message
class FileExportFailed(Exception):
def __init__(self, message=''):
self.message = str(message)
def __str__(self):
return _("Failed to export to file.") + "\n" + self.message
class WalletFileException(Exception): pass
class BitcoinException(Exception): pass
class UserFacingException(Exception):
"""Exception that contains information intended to be shown to the user."""
class InvoiceError(UserFacingException): pass
# Throw this exception to unwind the stack like when an error occurs.
# However unlike other exceptions the user won't be informed.
class UserCancelled(Exception):
'''An exception that is suppressed from the user'''
pass
# note: this is not a NamedTuple as then its json encoding cannot be customized
class Satoshis(object):
__slots__ = ('value',)
def __new__(cls, value):
self = super(Satoshis, cls).__new__(cls)
# note: 'value' sometimes has msat precision
self.value = value
return self
def __repr__(self):
return f'Satoshis({self.value})'
def __str__(self):
# note: precision is truncated to satoshis here
return format_satoshis(self.value)
def __eq__(self, other):
return self.value == other.value
def __ne__(self, other):
return not (self == other)
def __add__(self, other):
return Satoshis(self.value + other.value)
# note: this is not a NamedTuple as then its json encoding cannot be customized
class Fiat(object):
__slots__ = ('value', 'ccy')
def __new__(cls, value: Optional[Decimal], ccy: str):
self = super(Fiat, cls).__new__(cls)
self.ccy = ccy
if not isinstance(value, (Decimal, type(None))):
raise TypeError(f"value should be Decimal or None, not {type(value)}")
self.value = value
return self
def __repr__(self):
return 'Fiat(%s)'% self.__str__()
def __str__(self):
if self.value is None or self.value.is_nan():
return _('No Data')
else:
return "{:.2f}".format(self.value)
def to_ui_string(self):
if self.value is None or self.value.is_nan():
return _('No Data')
else:
return "{:.2f}".format(self.value) + ' ' + self.ccy
def __eq__(self, other):
if self.ccy != other.ccy:
return False
if isinstance(self.value, Decimal) and isinstance(other.value, Decimal) \
and self.value.is_nan() and other.value.is_nan():
return True
return self.value == other.value
def __ne__(self, other):
return not (self == other)
def __add__(self, other):
assert self.ccy == other.ccy
return Fiat(self.value + other.value, self.ccy)
class MyEncoder(json.JSONEncoder):
def default(self, obj):
# note: this does not get called for namedtuples :( https://bugs.python.org/issue30343
from .transaction import Transaction, TxOutput
from .lnutil import UpdateAddHtlc
if isinstance(obj, UpdateAddHtlc):
return obj.to_tuple()
if isinstance(obj, Transaction):
return obj.serialize()
if isinstance(obj, TxOutput):
return obj.to_legacy_tuple()
if isinstance(obj, Satoshis):
return str(obj)
if isinstance(obj, Fiat):
return str(obj)
if isinstance(obj, Decimal):
return str(obj)
if isinstance(obj, datetime):
return obj.isoformat(' ')[:-3]
if isinstance(obj, set):
return list(obj)
if isinstance(obj, bytes): # for nametuples in lnchannel
return obj.hex()
if hasattr(obj, 'to_json') and callable(obj.to_json):
return obj.to_json()
return super(MyEncoder, self).default(obj)
class ThreadJob(Logger):
"""A job that is run periodically from a thread's main loop. run() is
called from that thread's context.
"""
def __init__(self):
Logger.__init__(self)
def run(self):
"""Called periodically from the thread"""
pass
class DebugMem(ThreadJob):
'''A handy class for debugging GC memory leaks'''
def __init__(self, classes, interval=30):
ThreadJob.__init__(self)
self.next_time = 0
self.classes = classes
self.interval = interval
def mem_stats(self):
import gc
self.logger.info("Start memscan")
gc.collect()
objmap = defaultdict(list)
for obj in gc.get_objects():
for class_ in self.classes:
if isinstance(obj, class_):
objmap[class_].append(obj)
for class_, objs in objmap.items():
self.logger.info(f"{class_.__name__}: {len(objs)}")
self.logger.info("Finish memscan")
def run(self):
if time.time() > self.next_time:
self.mem_stats()
self.next_time = time.time() + self.interval
class DaemonThread(threading.Thread, Logger):
""" daemon thread that terminates cleanly """
LOGGING_SHORTCUT = 'd'
def __init__(self):
threading.Thread.__init__(self)
Logger.__init__(self)
self.parent_thread = threading.currentThread()
self.running = False
self.running_lock = threading.Lock()
self.job_lock = threading.Lock()
self.jobs = []
def add_jobs(self, jobs):
with self.job_lock:
self.jobs.extend(jobs)
def run_jobs(self):
# Don't let a throwing job disrupt the thread, future runs of
# itself, or other jobs. This is useful protection against
# malformed or malicious server responses
with self.job_lock:
for job in self.jobs:
try:
job.run()
except Exception as e:
self.logger.exception('')
def remove_jobs(self, jobs):
with self.job_lock:
for job in jobs:
self.jobs.remove(job)
def start(self):
with self.running_lock:
self.running = True
return threading.Thread.start(self)
def is_running(self):
with self.running_lock:
return self.running and self.parent_thread.is_alive()
def stop(self):
with self.running_lock:
self.running = False
def on_stop(self):
if 'ANDROID_DATA' in os.environ:
import jnius
jnius.detach()
self.logger.info("jnius detach")
self.logger.info("stopped")
def print_stderr(*args):
args = [str(item) for item in args]
sys.stderr.write(" ".join(args) + "\n")
sys.stderr.flush()
def print_msg(*args):
# Stringify args
args = [str(item) for item in args]
sys.stdout.write(" ".join(args) + "\n")
sys.stdout.flush()
def json_encode(obj):
try:
s = json.dumps(obj, sort_keys = True, indent = 4, cls=MyEncoder)
except TypeError:
s = repr(obj)
return s
def json_decode(x):
try:
return json.loads(x, parse_float=Decimal)
except:
return x
# taken from Django Source Code
def constant_time_compare(val1, val2):
"""Return True if the two strings are equal, False otherwise."""
return hmac.compare_digest(to_bytes(val1, 'utf8'), to_bytes(val2, 'utf8'))
# decorator that prints execution time
_profiler_logger = _logger.getChild('profiler')
def profiler(func):
def do_profile(args, kw_args):
name = func.__qualname__
t0 = time.time()
o = func(*args, **kw_args)
t = time.time() - t0
_profiler_logger.debug(f"{name} {t:,.4f}")
return o
return lambda *args, **kw_args: do_profile(args, kw_args)
def android_ext_dir():
from android.storage import primary_external_storage_path
return primary_external_storage_path()
def android_backup_dir():
d = os.path.join(android_ext_dir(), 'org.electrum.electrum')
if not os.path.exists(d):
os.mkdir(d)
return d
def android_data_dir():
import jnius
PythonActivity = jnius.autoclass('org.kivy.android.PythonActivity')
return PythonActivity.mActivity.getFilesDir().getPath() + '/data'
def get_backup_dir(config):
if 'ANDROID_DATA' in os.environ:
return android_backup_dir() if config.get('android_backups') else None
else:
return config.get('backup_dir')
def ensure_sparse_file(filename):
# On modern Linux, no need to do anything.
# On Windows, need to explicitly mark file.
if os.name == "nt":
try:
os.system('fsutil sparse setflag "{}" 1'.format(filename))
except Exception as e:
_logger.info(f'error marking file {filename} as sparse: {e}')
def get_headers_dir(config):
return config.path
def assert_datadir_available(config_path):
path = config_path
if os.path.exists(path):
return
else:
raise FileNotFoundError(
'Electrum datadir does not exist. Was it deleted while running?' + '\n' +
'Should be at {}'.format(path))
def assert_file_in_datadir_available(path, config_path):
if os.path.exists(path):
return
else:
assert_datadir_available(config_path)
raise FileNotFoundError(
'Cannot find file but datadir is there.' + '\n' +
'Should be at {}'.format(path))
def standardize_path(path):
return os.path.normcase(
os.path.realpath(
os.path.abspath(
os.path.expanduser(
path
))))
def get_new_wallet_name(wallet_folder: str) -> str:
i = 1
while True:
filename = "wallet_%d" % i
if filename in os.listdir(wallet_folder):
i += 1
else:
break
return filename
def assert_bytes(*args):
"""
porting helper, assert args type
"""
try:
for x in args:
assert isinstance(x, (bytes, bytearray))
except:
print('assert bytes failed', list(map(type, args)))
raise
def assert_str(*args):
"""
porting helper, assert args type
"""
for x in args:
assert isinstance(x, str)
def to_string(x, enc) -> str:
if isinstance(x, (bytes, bytearray)):
return x.decode(enc)
if isinstance(x, str):
return x
else:
raise TypeError("Not a string or bytes like object")
def to_bytes(something, encoding='utf8') -> bytes:
"""
cast string to bytes() like object, but for python2 support it's bytearray copy
"""
if isinstance(something, bytes):
return something
if isinstance(something, str):
return something.encode(encoding)
elif isinstance(something, bytearray):
return bytes(something)
else:
raise TypeError("Not a string or bytes like object")
bfh = bytes.fromhex
def bh2u(x: bytes) -> str:
"""
str with hex representation of a bytes-like object
>>> x = bytes((1, 2, 10))
>>> bh2u(x)
'01020A'
"""
return x.hex()
def xor_bytes(a: bytes, b: bytes) -> bytes:
size = min(len(a), len(b))
return ((int.from_bytes(a[:size], "big") ^ int.from_bytes(b[:size], "big"))
.to_bytes(size, "big"))
def user_dir():
if "ELECTRUMDIR" in os.environ:
return os.environ["ELECTRUMDIR"]
elif 'ANDROID_DATA' in os.environ:
return android_data_dir()
elif os.name == 'posix':
return os.path.join(os.environ["HOME"], ".electrum")
elif "APPDATA" in os.environ:
return os.path.join(os.environ["APPDATA"], "Electrum")
elif "LOCALAPPDATA" in os.environ:
return os.path.join(os.environ["LOCALAPPDATA"], "Electrum")
else:
#raise Exception("No home directory found in environment variables.")
return
def resource_path(*parts):
return os.path.join(pkg_dir, *parts)
# absolute path to python package folder of electrum ("lib")
pkg_dir = os.path.split(os.path.realpath(__file__))[0]
def is_valid_email(s):
regexp = r"[^@]+@[^@]+\.[^@]+"
return re.match(regexp, s) is not None
def is_hash256_str(text: Any) -> bool:
if not isinstance(text, str): return False
if len(text) != 64: return False
return is_hex_str(text)
def is_hex_str(text: Any) -> bool:
if not isinstance(text, str): return False
try:
bytes.fromhex(text)
except:
return False
return True
def is_non_negative_integer(val) -> bool:
try:
val = int(val)
if val >= 0:
return True
except:
pass
return False
def chunks(items, size: int):
"""Break up items, an iterable, into chunks of length size."""
if size < 1:
raise ValueError(f"size must be positive, not {repr(size)}")
for i in range(0, len(items), size):
yield items[i: i + size]
def format_satoshis_plain(x, *, decimal_point=8) -> str:
"""Display a satoshi amount scaled. Always uses a '.' as a decimal
point and has no thousands separator"""
if x == '!':
return 'max'
scale_factor = pow(10, decimal_point)
return "{:.8f}".format(Decimal(x) / scale_factor).rstrip('0').rstrip('.')
DECIMAL_POINT = localeconv()['decimal_point'] # type: str
def format_satoshis(
x, # in satoshis
*,
num_zeros=0,
decimal_point=8,
precision=None,
is_diff=False,
whitespaces=False,
) -> str:
if x is None:
return 'unknown'
if x == '!':
return 'max'
if precision is None:
precision = decimal_point
# format string
decimal_format = "." + str(precision) if precision > 0 else ""
if is_diff:
decimal_format = '+' + decimal_format
# initial result
scale_factor = pow(10, decimal_point)
if not isinstance(x, Decimal):
x = Decimal(x).quantize(Decimal('1E-8'))
result = ("{:" + decimal_format + "f}").format(x / scale_factor)
if "." not in result: result += "."
result = result.rstrip('0')
# extra decimal places
integer_part, fract_part = result.split(".")
if len(fract_part) < num_zeros:
fract_part += "0" * (num_zeros - len(fract_part))
result = integer_part + DECIMAL_POINT + fract_part
# leading/trailing whitespaces
if whitespaces:
result += " " * (decimal_point - len(fract_part))
result = " " * (15 - len(result)) + result
return result
FEERATE_PRECISION = 1 # num fractional decimal places for sat/byte fee rates
_feerate_quanta = Decimal(10) ** (-FEERATE_PRECISION)
def format_fee_satoshis(fee, *, num_zeros=0, precision=None):
if precision is None:
precision = FEERATE_PRECISION
num_zeros = min(num_zeros, FEERATE_PRECISION) # no more zeroes than available prec
return format_satoshis(fee, num_zeros=num_zeros, decimal_point=0, precision=precision)
def quantize_feerate(fee) -> Union[None, Decimal, int]:
"""Strip sat/byte fee rate of excess precision."""
if fee is None:
return None
return Decimal(fee).quantize(_feerate_quanta, rounding=decimal.ROUND_HALF_DOWN)
def timestamp_to_datetime(timestamp):
if timestamp is None:
return None
return datetime.fromtimestamp(timestamp)
def format_time(timestamp):
date = timestamp_to_datetime(timestamp)
return date.isoformat(' ')[:-3] if date else _("Unknown")
# Takes a timestamp and returns a string with the approximation of the age
def age(from_date, since_date = None, target_tz=None, include_seconds=False):
if from_date is None:
return "Unknown"
from_date = datetime.fromtimestamp(from_date)
if since_date is None:
since_date = datetime.now(target_tz)
td = time_difference(from_date - since_date, include_seconds)
return td + " ago" if from_date < since_date else "in " + td
def time_difference(distance_in_time, include_seconds):
#distance_in_time = since_date - from_date
distance_in_seconds = int(round(abs(distance_in_time.days * 86400 + distance_in_time.seconds)))
distance_in_minutes = int(round(distance_in_seconds/60))
if distance_in_minutes == 0:
if include_seconds:
return "%s seconds" % distance_in_seconds
else:
return "less than a minute"
elif distance_in_minutes < 45:
return "%s minutes" % distance_in_minutes
elif distance_in_minutes < 90:
return "about 1 hour"
elif distance_in_minutes < 1440:
return "about %d hours" % (round(distance_in_minutes / 60.0))
elif distance_in_minutes < 2880:
return "1 day"
elif distance_in_minutes < 43220:
return "%d days" % (round(distance_in_minutes / 1440))
elif distance_in_minutes < 86400:
return "about 1 month"
elif distance_in_minutes < 525600:
return "%d months" % (round(distance_in_minutes / 43200))
elif distance_in_minutes < 1051200:
return "about 1 year"
else:
return "over %d years" % (round(distance_in_minutes / 525600))
mainnet_block_explorers = {
'Bitupper Explorer': ('https://bitupper.com/en/explorer/bitcoin/',
{'tx': 'transactions/', 'addr': 'addresses/'}),
'Bitflyer.jp': ('https://chainflyer.bitflyer.jp/',
{'tx': 'Transaction/', 'addr': 'Address/'}),
'Blockchain.info': ('https://blockchain.com/btc/',
{'tx': 'tx/', 'addr': 'address/'}),
'blockchainbdgpzk.onion': ('https://blockchainbdgpzk.onion/',
{'tx': 'tx/', 'addr': 'address/'}),
'Blockstream.info': ('https://blockstream.info/',
{'tx': 'tx/', 'addr': 'address/'}),
'Bitaps.com': ('https://btc.bitaps.com/',
{'tx': '', 'addr': ''}),
'BTC.com': ('https://btc.com/',
{'tx': '', 'addr': ''}),
'Chain.so': ('https://www.chain.so/',
{'tx': 'tx/BTC/', 'addr': 'address/BTC/'}),
'Insight.is': ('https://insight.bitpay.com/',
{'tx': 'tx/', 'addr': 'address/'}),
'TradeBlock.com': ('https://tradeblock.com/blockchain/',
{'tx': 'tx/', 'addr': 'address/'}),
'BlockCypher.com': ('https://live.blockcypher.com/btc/',
{'tx': 'tx/', 'addr': 'address/'}),
'Blockchair.com': ('https://blockchair.com/bitcoin/',
{'tx': 'transaction/', 'addr': 'address/'}),
'blockonomics.co': ('https://www.blockonomics.co/',
{'tx': 'api/tx?txid=', 'addr': '#/search?q='}),
'mempool.space': ('https://mempool.space/',
{'tx': 'tx/', 'addr': 'address/'}),
'OXT.me': ('https://oxt.me/',
{'tx': 'transaction/', 'addr': 'address/'}),
'smartbit.com.au': ('https://www.smartbit.com.au/',
{'tx': 'tx/', 'addr': 'address/'}),
'mynode.local': ('http://mynode.local:3002/',
{'tx': 'tx/', 'addr': 'address/'}),
'system default': ('blockchain:/',
{'tx': 'tx/', 'addr': 'address/'}),
}
testnet_block_explorers = {
'Bitaps.com': ('https://tbtc.bitaps.com/',
{'tx': '', 'addr': ''}),
'BlockCypher.com': ('https://live.blockcypher.com/btc-testnet/',
{'tx': 'tx/', 'addr': 'address/'}),
'Blockchain.info': ('https://www.blockchain.com/btctest/',
{'tx': 'tx/', 'addr': 'address/'}),
'Blockstream.info': ('https://blockstream.info/testnet/',
{'tx': 'tx/', 'addr': 'address/'}),
'mempool.space': ('https://mempool.space/testnet/',
{'tx': 'tx/', 'addr': 'address/'}),
'smartbit.com.au': ('https://testnet.smartbit.com.au/',
{'tx': 'tx/', 'addr': 'address/'}),
'system default': ('blockchain://000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943/',
{'tx': 'tx/', 'addr': 'address/'}),
}
def block_explorer_info():
from . import constants
return mainnet_block_explorers if not constants.net.TESTNET else testnet_block_explorers
def block_explorer(config: 'SimpleConfig') -> str:
from . import constants
default_ = 'Blockstream.info'
be_key = config.get('block_explorer', default_)
be = block_explorer_info().get(be_key)
return be_key if be is not None else default_
def block_explorer_tuple(config: 'SimpleConfig') -> Optional[Tuple[str, dict]]:
return block_explorer_info().get(block_explorer(config))
def block_explorer_URL(config: 'SimpleConfig', kind: str, item: str) -> Optional[str]:
be_tuple = block_explorer_tuple(config)
if not be_tuple:
return
explorer_url, explorer_dict = be_tuple
kind_str = explorer_dict.get(kind)
if kind_str is None:
return
url_parts = [explorer_url, kind_str, item]
return ''.join(url_parts)
# URL decode
#_ud = re.compile('%([0-9a-hA-H]{2})', re.MULTILINE)
#urldecode = lambda x: _ud.sub(lambda m: chr(int(m.group(1), 16)), x)
class InvalidBitcoinURI(Exception): pass
# TODO rename to parse_bip21_uri or similar
def parse_URI(uri: str, on_pr: Callable = None, *, loop=None) -> dict:
"""Raises InvalidBitcoinURI on malformed URI."""
from . import bitcoin
from .bitcoin import COIN
if not isinstance(uri, str):
raise InvalidBitcoinURI(f"expected string, not {repr(uri)}")
if ':' not in uri:
if not bitcoin.is_address(uri):
raise InvalidBitcoinURI("Not a bitcoin address")
return {'address': uri}
u = urllib.parse.urlparse(uri)
if u.scheme != 'bitcoin':
raise InvalidBitcoinURI("Not a bitcoin URI")
address = u.path
# python for android fails to parse query
if address.find('?') > 0:
address, query = u.path.split('?')
pq = urllib.parse.parse_qs(query)
else:
pq = urllib.parse.parse_qs(u.query)
for k, v in pq.items():
if len(v) != 1:
raise InvalidBitcoinURI(f'Duplicate Key: {repr(k)}')
out = {k: v[0] for k, v in pq.items()}
if address:
if not bitcoin.is_address(address):
raise InvalidBitcoinURI(f"Invalid bitcoin address: {address}")
out['address'] = address
if 'amount' in out:
am = out['amount']
try:
m = re.match(r'([0-9.]+)X([0-9])', am)
if m:
k = int(m.group(2)) - 8
amount = Decimal(m.group(1)) * pow( Decimal(10) , k)
else:
amount = Decimal(am) * COIN
out['amount'] = int(amount)
except Exception as e:
raise InvalidBitcoinURI(f"failed to parse 'amount' field: {repr(e)}") from e
if 'message' in out:
out['message'] = out['message']
out['memo'] = out['message']
if 'time' in out:
try:
out['time'] = int(out['time'])
except Exception as e:
raise InvalidBitcoinURI(f"failed to parse 'time' field: {repr(e)}") from e
if 'exp' in out:
try:
out['exp'] = int(out['exp'])
except Exception as e:
raise InvalidBitcoinURI(f"failed to parse 'exp' field: {repr(e)}") from e
if 'sig' in out:
try:
out['sig'] = bh2u(bitcoin.base_decode(out['sig'], base=58))
except Exception as e:
raise InvalidBitcoinURI(f"failed to parse 'sig' field: {repr(e)}") from e
r = out.get('r')
sig = out.get('sig')
name = out.get('name')
if on_pr and (r or (name and sig)):
@log_exceptions
async def get_payment_request():
from . import paymentrequest as pr
if name and sig:
s = pr.serialize_request(out).SerializeToString()
request = pr.PaymentRequest(s)
else:
request = await pr.get_payment_request(r)
if on_pr:
on_pr(request)
loop = loop or asyncio.get_event_loop()
asyncio.run_coroutine_threadsafe(get_payment_request(), loop)
return out
def create_bip21_uri(addr, amount_sat: Optional[int], message: Optional[str],
*, extra_query_params: Optional[dict] = None) -> str:
from . import bitcoin
if not bitcoin.is_address(addr):
return ""
if extra_query_params is None:
extra_query_params = {}
query = []
if amount_sat:
query.append('amount=%s'%format_satoshis_plain(amount_sat))
if message:
query.append('message=%s'%urllib.parse.quote(message))
for k, v in extra_query_params.items():
if not isinstance(k, str) or k != urllib.parse.quote(k):
raise Exception(f"illegal key for URI: {repr(k)}")
v = urllib.parse.quote(v)
query.append(f"{k}={v}")
p = urllib.parse.ParseResult(scheme='bitcoin', netloc='', path=addr, params='', query='&'.join(query), fragment='')
return str(urllib.parse.urlunparse(p))
def maybe_extract_bolt11_invoice(data: str) -> Optional[str]:
data = data.strip() # whitespaces
data = data.lower()
if data.startswith('lightning:ln'):
data = data[10:]
if data.startswith('ln'):
return data
return None
# Python bug (http://bugs.python.org/issue1927) causes raw_input
# to be redirected improperly between stdin/stderr on Unix systems
#TODO: py3
def raw_input(prompt=None):
if prompt:
sys.stdout.write(prompt)
return builtin_raw_input()
builtin_raw_input = builtins.input
builtins.input = raw_input
def parse_json(message):
# TODO: check \r\n pattern
n = message.find(b'\n')
if n==-1:
return None, message
try:
j = json.loads(message[0:n].decode('utf8'))
except:
j = None
return j, message[n+1:]
def setup_thread_excepthook():
"""
Workaround for `sys.excepthook` thread bug from:
http://bugs.python.org/issue1230540
Call once from the main thread before creating any threads.
"""
init_original = threading.Thread.__init__
def init(self, *args, **kwargs):
init_original(self, *args, **kwargs)
run_original = self.run
def run_with_except_hook(*args2, **kwargs2):
try:
run_original(*args2, **kwargs2)
except Exception:
sys.excepthook(*sys.exc_info())
self.run = run_with_except_hook
threading.Thread.__init__ = init
def send_exception_to_crash_reporter(e: BaseException):
sys.excepthook(type(e), e, e.__traceback__)
def versiontuple(v):
return tuple(map(int, (v.split("."))))
def read_json_file(path):
try:
with open(path, 'r', encoding='utf-8') as f:
data = json.loads(f.read())
#backwards compatibility for JSONDecodeError
except ValueError:
_logger.exception('')
raise FileImportFailed(_("Invalid JSON code."))
except BaseException as e:
_logger.exception('')
raise FileImportFailed(e)
return data
def write_json_file(path, data):
try:
with open(path, 'w+', encoding='utf-8') as f:
json.dump(data, f, indent=4, sort_keys=True, cls=MyEncoder)
except (IOError, os.error) as e:
_logger.exception('')
raise FileExportFailed(e)
def make_dir(path, allow_symlink=True):
"""Make directory if it does not yet exist."""
if not os.path.exists(path):
if not allow_symlink and os.path.islink(path):
raise Exception('Dangling link: ' + path)
os.mkdir(path)
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
def log_exceptions(func):
"""Decorator to log AND re-raise exceptions."""
assert asyncio.iscoroutinefunction(func), 'func needs to be a coroutine'
async def wrapper(*args, **kwargs):
self = args[0] if len(args) > 0 else None
try:
return await func(*args, **kwargs)
except asyncio.CancelledError as e:
raise
except BaseException as e:
mylogger = self.logger if hasattr(self, 'logger') else _logger
try:
mylogger.exception(f"Exception in {func.__name__}: {repr(e)}")
except BaseException as e2:
print(f"logging exception raised: {repr(e2)}... orig exc: {repr(e)} in {func.__name__}")
raise
return wrapper
def ignore_exceptions(func):
"""Decorator to silently swallow all exceptions."""
assert asyncio.iscoroutinefunction(func), 'func needs to be a coroutine'
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except asyncio.CancelledError:
# note: with python 3.8, CancelledError no longer inherits Exception, so this catch is redundant
raise
except Exception as e:
pass
return wrapper
class TxMinedInfo(NamedTuple):
height: int # height of block that mined tx
conf: Optional[int] = None # number of confirmations, SPV verified (None means unknown)
timestamp: Optional[int] = None # timestamp of block that mined tx
txpos: Optional[int] = None # position of tx in serialized block
header_hash: Optional[str] = None # hash of block that mined tx
def make_aiohttp_session(proxy: Optional[dict], headers=None, timeout=None):
if headers is None:
headers = {'User-Agent': 'Electrum'}
if timeout is None:
# The default timeout is high intentionally.
# DNS on some systems can be really slow, see e.g. #5337
timeout = aiohttp.ClientTimeout(total=45)
elif isinstance(timeout, (int, float)):
timeout = aiohttp.ClientTimeout(total=timeout)
ssl_context = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH, cafile=ca_path)
if proxy:
connector = ProxyConnector(
proxy_type=ProxyType.SOCKS5 if proxy['mode'] == 'socks5' else ProxyType.SOCKS4,
host=proxy['host'],
port=int(proxy['port']),
username=proxy.get('user', None),
password=proxy.get('password', None),
rdns=True,
ssl=ssl_context,
)
else:
connector = aiohttp.TCPConnector(ssl=ssl_context)
return aiohttp.ClientSession(headers=headers, timeout=timeout, connector=connector)
class SilentTaskGroup(TaskGroup):
def spawn(self, *args, **kwargs):
# don't complain if group is already closed.
if self._closed:
raise asyncio.CancelledError()
return super().spawn(*args, **kwargs)
class NetworkJobOnDefaultServer(Logger):
"""An abstract base class for a job that runs on the main network
interface. Every time the main interface changes, the job is
restarted, and some of its internals are reset.
"""
def __init__(self, network: 'Network'):
Logger.__init__(self)
asyncio.set_event_loop(network.asyncio_loop)
self.network = network
self.interface = None # type: Interface
self._restart_lock = asyncio.Lock()
self._reset()
asyncio.run_coroutine_threadsafe(self._restart(), network.asyncio_loop)
register_callback(self._restart, ['default_server_changed'])
def _reset(self):
"""Initialise fields. Called every time the underlying
server connection changes.
"""
self.taskgroup = SilentTaskGroup()
async def _start(self, interface: 'Interface'):
self.interface = interface
await interface.taskgroup.spawn(self._start_tasks)
async def _start_tasks(self):
"""Start tasks in self.taskgroup. Called every time the underlying
server connection changes.
"""
raise NotImplementedError() # implemented by subclasses
async def stop(self):
unregister_callback(self._restart)
await self._stop()
async def _stop(self):
await self.taskgroup.cancel_remaining()
@log_exceptions
async def _restart(self, *args):
interface = self.network.interface
if interface is None:
return # we should get called again soon
async with self._restart_lock:
await self._stop()
self._reset()
await self._start(interface)
@property
def session(self):
s = self.interface.session
assert s is not None
return s
def create_and_start_event_loop() -> Tuple[asyncio.AbstractEventLoop,
asyncio.Future,
threading.Thread]:
def on_exception(loop, context):
"""Suppress spurious messages it appears we cannot control."""
SUPPRESS_MESSAGE_REGEX = re.compile('SSL handshake|Fatal read error on|'
'SSL error in data received')
message = context.get('message')
if message and SUPPRESS_MESSAGE_REGEX.match(message):
return
loop.default_exception_handler(context)
loop = asyncio.get_event_loop()
loop.set_exception_handler(on_exception)
# loop.set_debug(1)
stopping_fut = asyncio.Future()
loop_thread = threading.Thread(target=loop.run_until_complete,
args=(stopping_fut,),
name='EventLoop')
loop_thread.start()
return loop, stopping_fut, loop_thread
class OrderedDictWithIndex(OrderedDict):
"""An OrderedDict that keeps track of the positions of keys.
Note: very inefficient to modify contents, except to add new items.
"""
def __init__(self):
super().__init__()
self._key_to_pos = {}
self._pos_to_key = {}
def _recalc_index(self):
self._key_to_pos = {key: pos for (pos, key) in enumerate(self.keys())}
self._pos_to_key = {pos: key for (pos, key) in enumerate(self.keys())}
def pos_from_key(self, key):
return self._key_to_pos[key]
def value_from_pos(self, pos):
key = self._pos_to_key[pos]
return self[key]
def popitem(self, *args, **kwargs):
ret = super().popitem(*args, **kwargs)
self._recalc_index()
return ret
def move_to_end(self, *args, **kwargs):
ret = super().move_to_end(*args, **kwargs)
self._recalc_index()
return ret
def clear(self):
ret = super().clear()
self._recalc_index()
return ret
def pop(self, *args, **kwargs):
ret = super().pop(*args, **kwargs)
self._recalc_index()
return ret
def update(self, *args, **kwargs):
ret = super().update(*args, **kwargs)
self._recalc_index()
return ret
def __delitem__(self, *args, **kwargs):
ret = super().__delitem__(*args, **kwargs)
self._recalc_index()
return ret
def __setitem__(self, key, *args, **kwargs):
is_new_key = key not in self
ret = super().__setitem__(key, *args, **kwargs)
if is_new_key:
pos = len(self) - 1
self._key_to_pos[key] = pos
self._pos_to_key[pos] = key
return ret
def multisig_type(wallet_type):
'''If wallet_type is mofn multi-sig, return [m, n],
otherwise return None.'''
if not wallet_type:
return None
match = re.match(r'(\d+)of(\d+)', wallet_type)
if match:
match = [int(x) for x in match.group(1, 2)]
return match
def is_ip_address(x: Union[str, bytes]) -> bool:
if isinstance(x, bytes):
x = x.decode("utf-8")
try:
ipaddress.ip_address(x)
return True
except ValueError:
return False
def is_private_netaddress(host: str) -> bool:
if str(host) in ('localhost', 'localhost.',):
return True
if host[0] == '[' and host[-1] == ']': # IPv6
host = host[1:-1]
try:
ip_addr = ipaddress.ip_address(host) # type: Union[IPv4Address, IPv6Address]
return ip_addr.is_private
except ValueError:
pass # not an IP
return False
def list_enabled_bits(x: int) -> Sequence[int]:
"""e.g. 77 (0b1001101) --> (0, 2, 3, 6)"""
binary = bin(x)[2:]
rev_bin = reversed(binary)
return tuple(i for i, b in enumerate(rev_bin) if b == '1')
def resolve_dns_srv(host: str):
srv_records = dns.resolver.query(host, 'SRV')
# priority: prefer lower
# weight: tie breaker; prefer higher
srv_records = sorted(srv_records, key=lambda x: (x.priority, -x.weight))
def dict_from_srv_record(srv):
return {
'host': str(srv.target),
'port': srv.port,
}
return [dict_from_srv_record(srv) for srv in srv_records]
def randrange(bound: int) -> int:
"""Return a random integer k such that 1 <= k < bound, uniformly
distributed across that range."""
return ecdsa.util.randrange(bound)
class CallbackManager:
# callbacks set by the GUI
def __init__(self):
self.callback_lock = threading.Lock()
self.callbacks = defaultdict(list) # note: needs self.callback_lock
self.asyncio_loop = None
def register_callback(self, callback, events):
with self.callback_lock:
for event in events:
self.callbacks[event].append(callback)
def unregister_callback(self, callback):
with self.callback_lock:
for callbacks in self.callbacks.values():
if callback in callbacks:
callbacks.remove(callback)
def trigger_callback(self, event, *args):
if self.asyncio_loop is None:
self.asyncio_loop = asyncio.get_event_loop()
assert self.asyncio_loop.is_running(), "event loop not running"
with self.callback_lock:
callbacks = self.callbacks[event][:]
for callback in callbacks:
# FIXME: if callback throws, we will lose the traceback
if asyncio.iscoroutinefunction(callback):
asyncio.run_coroutine_threadsafe(callback(event, *args), self.asyncio_loop)
else:
self.asyncio_loop.call_soon_threadsafe(callback, event, *args)
callback_mgr = CallbackManager()
trigger_callback = callback_mgr.trigger_callback
register_callback = callback_mgr.register_callback
unregister_callback = callback_mgr.unregister_callback
_NetAddrType = TypeVar("_NetAddrType")
class NetworkRetryManager(Generic[_NetAddrType]):
"""Truncated Exponential Backoff for network connections."""
def __init__(
self, *,
max_retry_delay_normal: float,
init_retry_delay_normal: float,
max_retry_delay_urgent: float = None,
init_retry_delay_urgent: float = None,
):
self._last_tried_addr = {} # type: Dict[_NetAddrType, Tuple[float, int]] # (unix ts, num_attempts)
# note: these all use "seconds" as unit
if max_retry_delay_urgent is None:
max_retry_delay_urgent = max_retry_delay_normal
if init_retry_delay_urgent is None:
init_retry_delay_urgent = init_retry_delay_normal
self._max_retry_delay_normal = max_retry_delay_normal
self._init_retry_delay_normal = init_retry_delay_normal
self._max_retry_delay_urgent = max_retry_delay_urgent
self._init_retry_delay_urgent = init_retry_delay_urgent
def _trying_addr_now(self, addr: _NetAddrType) -> None:
last_time, num_attempts = self._last_tried_addr.get(addr, (0, 0))
# we add up to 1 second of noise to the time, so that clients are less likely
# to get synchronised and bombard the remote in connection waves:
cur_time = time.time() + random.random()
self._last_tried_addr[addr] = cur_time, num_attempts + 1
def _on_connection_successfully_established(self, addr: _NetAddrType) -> None:
self._last_tried_addr[addr] = time.time(), 0
def _can_retry_addr(self, peer: _NetAddrType, *,
now: float = None, urgent: bool = False) -> bool:
if now is None:
now = time.time()
last_time, num_attempts = self._last_tried_addr.get(peer, (0, 0))
if urgent:
delay = min(self._max_retry_delay_urgent,
self._init_retry_delay_urgent * 2 ** num_attempts)
else:
delay = min(self._max_retry_delay_normal,
self._init_retry_delay_normal * 2 ** num_attempts)
next_time = last_time + delay
return next_time < now
def _clear_addr_retry_times(self) -> None:
self._last_tried_addr.clear()
class MySocksProxy(aiorpcx.SOCKSProxy):
async def open_connection(self, host=None, port=None, **kwargs):
loop = asyncio.get_event_loop()
reader = asyncio.StreamReader(loop=loop)
protocol = asyncio.StreamReaderProtocol(reader, loop=loop)
transport, _ = await self.create_connection(
lambda: protocol, host, port, **kwargs)
writer = asyncio.StreamWriter(transport, protocol, reader, loop)
return reader, writer
@classmethod
def from_proxy_dict(cls, proxy: dict = None) -> Optional['MySocksProxy']:
if not proxy:
return None
username, pw = proxy.get('user'), proxy.get('password')
if not username or not pw:
auth = None
else:
auth = aiorpcx.socks.SOCKSUserAuth(username, pw)
addr = aiorpcx.NetAddress(proxy['host'], proxy['port'])
if proxy['mode'] == "socks4":
ret = cls(addr, aiorpcx.socks.SOCKS4a, auth)
elif proxy['mode'] == "socks5":
ret = cls(addr, aiorpcx.socks.SOCKS5, auth)
else:
raise NotImplementedError # http proxy not available with aiorpcx
return ret
class JsonRPCClient:
def __init__(self, session: aiohttp.ClientSession, url: str):
self.session = session
self.url = url
self._id = 0
async def request(self, endpoint, *args):
self._id += 1
data = ('{"jsonrpc": "2.0", "id":"%d", "method": "%s", "params": %s }'
% (self._id, endpoint, json.dumps(args)))
async with self.session.post(self.url, data=data) as resp:
if resp.status == 200:
r = await resp.json()
result = r.get('result')
error = r.get('error')
if error:
return 'Error: ' + str(error)
else:
return result
else:
text = await resp.text()
return 'Error: ' + str(text)
def add_method(self, endpoint):
async def coro(*args):
return await self.request(endpoint, *args)
setattr(self, endpoint, coro)
T = TypeVar('T')
def random_shuffled_copy(x: Iterable[T]) -> List[T]:
"""Returns a shuffled copy of the input."""
x_copy = list(x) # copy
random.shuffle(x_copy) # shuffle in-place
return x_copy
| 32.26108 | 119 | 0.618504 |
import binascii
import os, sys, re, json
from collections import defaultdict, OrderedDict
from typing import (NamedTuple, Union, TYPE_CHECKING, Tuple, Optional, Callable, Any,
Sequence, Dict, Generic, TypeVar, List, Iterable)
from datetime import datetime
import decimal
from decimal import Decimal
import traceback
import urllib
import threading
import hmac
import stat
from locale import localeconv
import asyncio
import urllib.request, urllib.parse, urllib.error
import builtins
import json
import time
from typing import NamedTuple, Optional
import ssl
import ipaddress
from ipaddress import IPv4Address, IPv6Address
import random
import attr
import aiohttp
from aiohttp_socks import ProxyConnector, ProxyType
import aiorpcx
from aiorpcx import TaskGroup
import certifi
import dns.resolver
import ecdsa
from .i18n import _
from .logging import get_logger, Logger
if TYPE_CHECKING:
from .network import Network
from .interface import Interface
from .simple_config import SimpleConfig
_logger = get_logger(__name__)
def inv_dict(d):
return {v: k for k, v in d.items()}
ca_path = certifi.where()
base_units = {'BTC':8, 'mBTC':5, 'bits':2, 'sat':0}
base_units_inverse = inv_dict(base_units)
base_units_list = ['BTC', 'mBTC', 'bits', 'sat']
DECIMAL_POINT_DEFAULT = 5
class UnknownBaseUnit(Exception): pass
def decimal_point_to_base_unit_name(dp: int) -> str:
try:
return base_units_inverse[dp]
except KeyError:
raise UnknownBaseUnit(dp) from None
def base_unit_name_to_decimal_point(unit_name: str) -> int:
try:
return base_units[unit_name]
except KeyError:
raise UnknownBaseUnit(unit_name) from None
class NotEnoughFunds(Exception):
def __str__(self):
return _("Insufficient funds")
class NoDynamicFeeEstimates(Exception):
def __str__(self):
return _('Dynamic fee estimates not available')
class MultipleSpendMaxTxOutputs(Exception):
def __str__(self):
return _('At most one output can be set to spend max')
class InvalidPassword(Exception):
def __str__(self):
return _("Incorrect password")
class FileImportFailed(Exception):
def __init__(self, message=''):
self.message = str(message)
def __str__(self):
return _("Failed to import from file.") + "\n" + self.message
class FileExportFailed(Exception):
def __init__(self, message=''):
self.message = str(message)
def __str__(self):
return _("Failed to export to file.") + "\n" + self.message
class WalletFileException(Exception): pass
class BitcoinException(Exception): pass
class UserFacingException(Exception):
class InvoiceError(UserFacingException): pass
class UserCancelled(Exception):
pass
# note: this is not a NamedTuple as then its json encoding cannot be customized
class Satoshis(object):
__slots__ = ('value',)
def __new__(cls, value):
self = super(Satoshis, cls).__new__(cls)
# note: 'value' sometimes has msat precision
self.value = value
return self
def __repr__(self):
return f'Satoshis({self.value})'
def __str__(self):
# note: precision is truncated to satoshis here
return format_satoshis(self.value)
def __eq__(self, other):
return self.value == other.value
def __ne__(self, other):
return not (self == other)
def __add__(self, other):
return Satoshis(self.value + other.value)
# note: this is not a NamedTuple as then its json encoding cannot be customized
class Fiat(object):
__slots__ = ('value', 'ccy')
def __new__(cls, value: Optional[Decimal], ccy: str):
self = super(Fiat, cls).__new__(cls)
self.ccy = ccy
if not isinstance(value, (Decimal, type(None))):
raise TypeError(f"value should be Decimal or None, not {type(value)}")
self.value = value
return self
def __repr__(self):
return 'Fiat(%s)'% self.__str__()
def __str__(self):
if self.value is None or self.value.is_nan():
return _('No Data')
else:
return "{:.2f}".format(self.value)
def to_ui_string(self):
if self.value is None or self.value.is_nan():
return _('No Data')
else:
return "{:.2f}".format(self.value) + ' ' + self.ccy
def __eq__(self, other):
if self.ccy != other.ccy:
return False
if isinstance(self.value, Decimal) and isinstance(other.value, Decimal) \
and self.value.is_nan() and other.value.is_nan():
return True
return self.value == other.value
def __ne__(self, other):
return not (self == other)
def __add__(self, other):
assert self.ccy == other.ccy
return Fiat(self.value + other.value, self.ccy)
class MyEncoder(json.JSONEncoder):
def default(self, obj):
# note: this does not get called for namedtuples :( https://bugs.python.org/issue30343
from .transaction import Transaction, TxOutput
from .lnutil import UpdateAddHtlc
if isinstance(obj, UpdateAddHtlc):
return obj.to_tuple()
if isinstance(obj, Transaction):
return obj.serialize()
if isinstance(obj, TxOutput):
return obj.to_legacy_tuple()
if isinstance(obj, Satoshis):
return str(obj)
if isinstance(obj, Fiat):
return str(obj)
if isinstance(obj, Decimal):
return str(obj)
if isinstance(obj, datetime):
return obj.isoformat(' ')[:-3]
if isinstance(obj, set):
return list(obj)
if isinstance(obj, bytes): # for nametuples in lnchannel
return obj.hex()
if hasattr(obj, 'to_json') and callable(obj.to_json):
return obj.to_json()
return super(MyEncoder, self).default(obj)
class ThreadJob(Logger):
def __init__(self):
Logger.__init__(self)
def run(self):
pass
class DebugMem(ThreadJob):
def __init__(self, classes, interval=30):
ThreadJob.__init__(self)
self.next_time = 0
self.classes = classes
self.interval = interval
def mem_stats(self):
import gc
self.logger.info("Start memscan")
gc.collect()
objmap = defaultdict(list)
for obj in gc.get_objects():
for class_ in self.classes:
if isinstance(obj, class_):
objmap[class_].append(obj)
for class_, objs in objmap.items():
self.logger.info(f"{class_.__name__}: {len(objs)}")
self.logger.info("Finish memscan")
def run(self):
if time.time() > self.next_time:
self.mem_stats()
self.next_time = time.time() + self.interval
class DaemonThread(threading.Thread, Logger):
LOGGING_SHORTCUT = 'd'
def __init__(self):
threading.Thread.__init__(self)
Logger.__init__(self)
self.parent_thread = threading.currentThread()
self.running = False
self.running_lock = threading.Lock()
self.job_lock = threading.Lock()
self.jobs = []
def add_jobs(self, jobs):
with self.job_lock:
self.jobs.extend(jobs)
def run_jobs(self):
# Don't let a throwing job disrupt the thread, future runs of
with self.job_lock:
for job in self.jobs:
try:
job.run()
except Exception as e:
self.logger.exception('')
def remove_jobs(self, jobs):
with self.job_lock:
for job in jobs:
self.jobs.remove(job)
def start(self):
with self.running_lock:
self.running = True
return threading.Thread.start(self)
def is_running(self):
with self.running_lock:
return self.running and self.parent_thread.is_alive()
def stop(self):
with self.running_lock:
self.running = False
def on_stop(self):
if 'ANDROID_DATA' in os.environ:
import jnius
jnius.detach()
self.logger.info("jnius detach")
self.logger.info("stopped")
def print_stderr(*args):
args = [str(item) for item in args]
sys.stderr.write(" ".join(args) + "\n")
sys.stderr.flush()
def print_msg(*args):
args = [str(item) for item in args]
sys.stdout.write(" ".join(args) + "\n")
sys.stdout.flush()
def json_encode(obj):
try:
s = json.dumps(obj, sort_keys = True, indent = 4, cls=MyEncoder)
except TypeError:
s = repr(obj)
return s
def json_decode(x):
try:
return json.loads(x, parse_float=Decimal)
except:
return x
def constant_time_compare(val1, val2):
return hmac.compare_digest(to_bytes(val1, 'utf8'), to_bytes(val2, 'utf8'))
_profiler_logger = _logger.getChild('profiler')
def profiler(func):
def do_profile(args, kw_args):
name = func.__qualname__
t0 = time.time()
o = func(*args, **kw_args)
t = time.time() - t0
_profiler_logger.debug(f"{name} {t:,.4f}")
return o
return lambda *args, **kw_args: do_profile(args, kw_args)
def android_ext_dir():
from android.storage import primary_external_storage_path
return primary_external_storage_path()
def android_backup_dir():
d = os.path.join(android_ext_dir(), 'org.electrum.electrum')
if not os.path.exists(d):
os.mkdir(d)
return d
def android_data_dir():
import jnius
PythonActivity = jnius.autoclass('org.kivy.android.PythonActivity')
return PythonActivity.mActivity.getFilesDir().getPath() + '/data'
def get_backup_dir(config):
if 'ANDROID_DATA' in os.environ:
return android_backup_dir() if config.get('android_backups') else None
else:
return config.get('backup_dir')
def ensure_sparse_file(filename):
if os.name == "nt":
try:
os.system('fsutil sparse setflag "{}" 1'.format(filename))
except Exception as e:
_logger.info(f'error marking file {filename} as sparse: {e}')
def get_headers_dir(config):
return config.path
def assert_datadir_available(config_path):
path = config_path
if os.path.exists(path):
return
else:
raise FileNotFoundError(
'Electrum datadir does not exist. Was it deleted while running?' + '\n' +
'Should be at {}'.format(path))
def assert_file_in_datadir_available(path, config_path):
if os.path.exists(path):
return
else:
assert_datadir_available(config_path)
raise FileNotFoundError(
'Cannot find file but datadir is there.' + '\n' +
'Should be at {}'.format(path))
def standardize_path(path):
return os.path.normcase(
os.path.realpath(
os.path.abspath(
os.path.expanduser(
path
))))
def get_new_wallet_name(wallet_folder: str) -> str:
i = 1
while True:
filename = "wallet_%d" % i
if filename in os.listdir(wallet_folder):
i += 1
else:
break
return filename
def assert_bytes(*args):
try:
for x in args:
assert isinstance(x, (bytes, bytearray))
except:
print('assert bytes failed', list(map(type, args)))
raise
def assert_str(*args):
for x in args:
assert isinstance(x, str)
def to_string(x, enc) -> str:
if isinstance(x, (bytes, bytearray)):
return x.decode(enc)
if isinstance(x, str):
return x
else:
raise TypeError("Not a string or bytes like object")
def to_bytes(something, encoding='utf8') -> bytes:
if isinstance(something, bytes):
return something
if isinstance(something, str):
return something.encode(encoding)
elif isinstance(something, bytearray):
return bytes(something)
else:
raise TypeError("Not a string or bytes like object")
bfh = bytes.fromhex
def bh2u(x: bytes) -> str:
return x.hex()
def xor_bytes(a: bytes, b: bytes) -> bytes:
size = min(len(a), len(b))
return ((int.from_bytes(a[:size], "big") ^ int.from_bytes(b[:size], "big"))
.to_bytes(size, "big"))
def user_dir():
if "ELECTRUMDIR" in os.environ:
return os.environ["ELECTRUMDIR"]
elif 'ANDROID_DATA' in os.environ:
return android_data_dir()
elif os.name == 'posix':
return os.path.join(os.environ["HOME"], ".electrum")
elif "APPDATA" in os.environ:
return os.path.join(os.environ["APPDATA"], "Electrum")
elif "LOCALAPPDATA" in os.environ:
return os.path.join(os.environ["LOCALAPPDATA"], "Electrum")
else:
return
def resource_path(*parts):
return os.path.join(pkg_dir, *parts)
pkg_dir = os.path.split(os.path.realpath(__file__))[0]
def is_valid_email(s):
regexp = r"[^@]+@[^@]+\.[^@]+"
return re.match(regexp, s) is not None
def is_hash256_str(text: Any) -> bool:
if not isinstance(text, str): return False
if len(text) != 64: return False
return is_hex_str(text)
def is_hex_str(text: Any) -> bool:
if not isinstance(text, str): return False
try:
bytes.fromhex(text)
except:
return False
return True
def is_non_negative_integer(val) -> bool:
try:
val = int(val)
if val >= 0:
return True
except:
pass
return False
def chunks(items, size: int):
if size < 1:
raise ValueError(f"size must be positive, not {repr(size)}")
for i in range(0, len(items), size):
yield items[i: i + size]
def format_satoshis_plain(x, *, decimal_point=8) -> str:
if x == '!':
return 'max'
scale_factor = pow(10, decimal_point)
return "{:.8f}".format(Decimal(x) / scale_factor).rstrip('0').rstrip('.')
DECIMAL_POINT = localeconv()['decimal_point']
def format_satoshis(
x,
*,
num_zeros=0,
decimal_point=8,
precision=None,
is_diff=False,
whitespaces=False,
) -> str:
if x is None:
return 'unknown'
if x == '!':
return 'max'
if precision is None:
precision = decimal_point
decimal_format = "." + str(precision) if precision > 0 else ""
if is_diff:
decimal_format = '+' + decimal_format
scale_factor = pow(10, decimal_point)
if not isinstance(x, Decimal):
x = Decimal(x).quantize(Decimal('1E-8'))
result = ("{:" + decimal_format + "f}").format(x / scale_factor)
if "." not in result: result += "."
result = result.rstrip('0')
integer_part, fract_part = result.split(".")
if len(fract_part) < num_zeros:
fract_part += "0" * (num_zeros - len(fract_part))
result = integer_part + DECIMAL_POINT + fract_part
if whitespaces:
result += " " * (decimal_point - len(fract_part))
result = " " * (15 - len(result)) + result
return result
FEERATE_PRECISION = 1
_feerate_quanta = Decimal(10) ** (-FEERATE_PRECISION)
def format_fee_satoshis(fee, *, num_zeros=0, precision=None):
if precision is None:
precision = FEERATE_PRECISION
num_zeros = min(num_zeros, FEERATE_PRECISION)
return format_satoshis(fee, num_zeros=num_zeros, decimal_point=0, precision=precision)
def quantize_feerate(fee) -> Union[None, Decimal, int]:
if fee is None:
return None
return Decimal(fee).quantize(_feerate_quanta, rounding=decimal.ROUND_HALF_DOWN)
def timestamp_to_datetime(timestamp):
if timestamp is None:
return None
return datetime.fromtimestamp(timestamp)
def format_time(timestamp):
date = timestamp_to_datetime(timestamp)
return date.isoformat(' ')[:-3] if date else _("Unknown")
def age(from_date, since_date = None, target_tz=None, include_seconds=False):
if from_date is None:
return "Unknown"
from_date = datetime.fromtimestamp(from_date)
if since_date is None:
since_date = datetime.now(target_tz)
td = time_difference(from_date - since_date, include_seconds)
return td + " ago" if from_date < since_date else "in " + td
def time_difference(distance_in_time, include_seconds):
distance_in_seconds = int(round(abs(distance_in_time.days * 86400 + distance_in_time.seconds)))
distance_in_minutes = int(round(distance_in_seconds/60))
if distance_in_minutes == 0:
if include_seconds:
return "%s seconds" % distance_in_seconds
else:
return "less than a minute"
elif distance_in_minutes < 45:
return "%s minutes" % distance_in_minutes
elif distance_in_minutes < 90:
return "about 1 hour"
elif distance_in_minutes < 1440:
return "about %d hours" % (round(distance_in_minutes / 60.0))
elif distance_in_minutes < 2880:
return "1 day"
elif distance_in_minutes < 43220:
return "%d days" % (round(distance_in_minutes / 1440))
elif distance_in_minutes < 86400:
return "about 1 month"
elif distance_in_minutes < 525600:
return "%d months" % (round(distance_in_minutes / 43200))
elif distance_in_minutes < 1051200:
return "about 1 year"
else:
return "over %d years" % (round(distance_in_minutes / 525600))
mainnet_block_explorers = {
'Bitupper Explorer': ('https://bitupper.com/en/explorer/bitcoin/',
{'tx': 'transactions/', 'addr': 'addresses/'}),
'Bitflyer.jp': ('https://chainflyer.bitflyer.jp/',
{'tx': 'Transaction/', 'addr': 'Address/'}),
'Blockchain.info': ('https://blockchain.com/btc/',
{'tx': 'tx/', 'addr': 'address/'}),
'blockchainbdgpzk.onion': ('https://blockchainbdgpzk.onion/',
{'tx': 'tx/', 'addr': 'address/'}),
'Blockstream.info': ('https://blockstream.info/',
{'tx': 'tx/', 'addr': 'address/'}),
'Bitaps.com': ('https://btc.bitaps.com/',
{'tx': '', 'addr': ''}),
'BTC.com': ('https://btc.com/',
{'tx': '', 'addr': ''}),
'Chain.so': ('https://www.chain.so/',
{'tx': 'tx/BTC/', 'addr': 'address/BTC/'}),
'Insight.is': ('https://insight.bitpay.com/',
{'tx': 'tx/', 'addr': 'address/'}),
'TradeBlock.com': ('https://tradeblock.com/blockchain/',
{'tx': 'tx/', 'addr': 'address/'}),
'BlockCypher.com': ('https://live.blockcypher.com/btc/',
{'tx': 'tx/', 'addr': 'address/'}),
'Blockchair.com': ('https://blockchair.com/bitcoin/',
{'tx': 'transaction/', 'addr': 'address/'}),
'blockonomics.co': ('https://www.blockonomics.co/',
{'tx': 'api/tx?txid=', 'addr': '#/search?q='}),
'mempool.space': ('https://mempool.space/',
{'tx': 'tx/', 'addr': 'address/'}),
'OXT.me': ('https://oxt.me/',
{'tx': 'transaction/', 'addr': 'address/'}),
'smartbit.com.au': ('https://www.smartbit.com.au/',
{'tx': 'tx/', 'addr': 'address/'}),
'mynode.local': ('http://mynode.local:3002/',
{'tx': 'tx/', 'addr': 'address/'}),
'system default': ('blockchain:/',
{'tx': 'tx/', 'addr': 'address/'}),
}
testnet_block_explorers = {
'Bitaps.com': ('https://tbtc.bitaps.com/',
{'tx': '', 'addr': ''}),
'BlockCypher.com': ('https://live.blockcypher.com/btc-testnet/',
{'tx': 'tx/', 'addr': 'address/'}),
'Blockchain.info': ('https://www.blockchain.com/btctest/',
{'tx': 'tx/', 'addr': 'address/'}),
'Blockstream.info': ('https://blockstream.info/testnet/',
{'tx': 'tx/', 'addr': 'address/'}),
'mempool.space': ('https://mempool.space/testnet/',
{'tx': 'tx/', 'addr': 'address/'}),
'smartbit.com.au': ('https://testnet.smartbit.com.au/',
{'tx': 'tx/', 'addr': 'address/'}),
'system default': ('blockchain://000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943/',
{'tx': 'tx/', 'addr': 'address/'}),
}
def block_explorer_info():
from . import constants
return mainnet_block_explorers if not constants.net.TESTNET else testnet_block_explorers
def block_explorer(config: 'SimpleConfig') -> str:
from . import constants
default_ = 'Blockstream.info'
be_key = config.get('block_explorer', default_)
be = block_explorer_info().get(be_key)
return be_key if be is not None else default_
def block_explorer_tuple(config: 'SimpleConfig') -> Optional[Tuple[str, dict]]:
return block_explorer_info().get(block_explorer(config))
def block_explorer_URL(config: 'SimpleConfig', kind: str, item: str) -> Optional[str]:
be_tuple = block_explorer_tuple(config)
if not be_tuple:
return
explorer_url, explorer_dict = be_tuple
kind_str = explorer_dict.get(kind)
if kind_str is None:
return
url_parts = [explorer_url, kind_str, item]
return ''.join(url_parts)
class InvalidBitcoinURI(Exception): pass
def parse_URI(uri: str, on_pr: Callable = None, *, loop=None) -> dict:
from . import bitcoin
from .bitcoin import COIN
if not isinstance(uri, str):
raise InvalidBitcoinURI(f"expected string, not {repr(uri)}")
if ':' not in uri:
if not bitcoin.is_address(uri):
raise InvalidBitcoinURI("Not a bitcoin address")
return {'address': uri}
u = urllib.parse.urlparse(uri)
if u.scheme != 'bitcoin':
raise InvalidBitcoinURI("Not a bitcoin URI")
address = u.path
if address.find('?') > 0:
address, query = u.path.split('?')
pq = urllib.parse.parse_qs(query)
else:
pq = urllib.parse.parse_qs(u.query)
for k, v in pq.items():
if len(v) != 1:
raise InvalidBitcoinURI(f'Duplicate Key: {repr(k)}')
out = {k: v[0] for k, v in pq.items()}
if address:
if not bitcoin.is_address(address):
raise InvalidBitcoinURI(f"Invalid bitcoin address: {address}")
out['address'] = address
if 'amount' in out:
am = out['amount']
try:
m = re.match(r'([0-9.]+)X([0-9])', am)
if m:
k = int(m.group(2)) - 8
amount = Decimal(m.group(1)) * pow( Decimal(10) , k)
else:
amount = Decimal(am) * COIN
out['amount'] = int(amount)
except Exception as e:
raise InvalidBitcoinURI(f"failed to parse 'amount' field: {repr(e)}") from e
if 'message' in out:
out['message'] = out['message']
out['memo'] = out['message']
if 'time' in out:
try:
out['time'] = int(out['time'])
except Exception as e:
raise InvalidBitcoinURI(f"failed to parse 'time' field: {repr(e)}") from e
if 'exp' in out:
try:
out['exp'] = int(out['exp'])
except Exception as e:
raise InvalidBitcoinURI(f"failed to parse 'exp' field: {repr(e)}") from e
if 'sig' in out:
try:
out['sig'] = bh2u(bitcoin.base_decode(out['sig'], base=58))
except Exception as e:
raise InvalidBitcoinURI(f"failed to parse 'sig' field: {repr(e)}") from e
r = out.get('r')
sig = out.get('sig')
name = out.get('name')
if on_pr and (r or (name and sig)):
@log_exceptions
async def get_payment_request():
from . import paymentrequest as pr
if name and sig:
s = pr.serialize_request(out).SerializeToString()
request = pr.PaymentRequest(s)
else:
request = await pr.get_payment_request(r)
if on_pr:
on_pr(request)
loop = loop or asyncio.get_event_loop()
asyncio.run_coroutine_threadsafe(get_payment_request(), loop)
return out
def create_bip21_uri(addr, amount_sat: Optional[int], message: Optional[str],
*, extra_query_params: Optional[dict] = None) -> str:
from . import bitcoin
if not bitcoin.is_address(addr):
return ""
if extra_query_params is None:
extra_query_params = {}
query = []
if amount_sat:
query.append('amount=%s'%format_satoshis_plain(amount_sat))
if message:
query.append('message=%s'%urllib.parse.quote(message))
for k, v in extra_query_params.items():
if not isinstance(k, str) or k != urllib.parse.quote(k):
raise Exception(f"illegal key for URI: {repr(k)}")
v = urllib.parse.quote(v)
query.append(f"{k}={v}")
p = urllib.parse.ParseResult(scheme='bitcoin', netloc='', path=addr, params='', query='&'.join(query), fragment='')
return str(urllib.parse.urlunparse(p))
def maybe_extract_bolt11_invoice(data: str) -> Optional[str]:
data = data.strip()
data = data.lower()
if data.startswith('lightning:ln'):
data = data[10:]
if data.startswith('ln'):
return data
return None
def raw_input(prompt=None):
if prompt:
sys.stdout.write(prompt)
return builtin_raw_input()
builtin_raw_input = builtins.input
builtins.input = raw_input
def parse_json(message):
n = message.find(b'\n')
if n==-1:
return None, message
try:
j = json.loads(message[0:n].decode('utf8'))
except:
j = None
return j, message[n+1:]
def setup_thread_excepthook():
init_original = threading.Thread.__init__
def init(self, *args, **kwargs):
init_original(self, *args, **kwargs)
run_original = self.run
def run_with_except_hook(*args2, **kwargs2):
try:
run_original(*args2, **kwargs2)
except Exception:
sys.excepthook(*sys.exc_info())
self.run = run_with_except_hook
threading.Thread.__init__ = init
def send_exception_to_crash_reporter(e: BaseException):
sys.excepthook(type(e), e, e.__traceback__)
def versiontuple(v):
return tuple(map(int, (v.split("."))))
def read_json_file(path):
try:
with open(path, 'r', encoding='utf-8') as f:
data = json.loads(f.read())
except ValueError:
_logger.exception('')
raise FileImportFailed(_("Invalid JSON code."))
except BaseException as e:
_logger.exception('')
raise FileImportFailed(e)
return data
def write_json_file(path, data):
try:
with open(path, 'w+', encoding='utf-8') as f:
json.dump(data, f, indent=4, sort_keys=True, cls=MyEncoder)
except (IOError, os.error) as e:
_logger.exception('')
raise FileExportFailed(e)
def make_dir(path, allow_symlink=True):
if not os.path.exists(path):
if not allow_symlink and os.path.islink(path):
raise Exception('Dangling link: ' + path)
os.mkdir(path)
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
def log_exceptions(func):
assert asyncio.iscoroutinefunction(func), 'func needs to be a coroutine'
async def wrapper(*args, **kwargs):
self = args[0] if len(args) > 0 else None
try:
return await func(*args, **kwargs)
except asyncio.CancelledError as e:
raise
except BaseException as e:
mylogger = self.logger if hasattr(self, 'logger') else _logger
try:
mylogger.exception(f"Exception in {func.__name__}: {repr(e)}")
except BaseException as e2:
print(f"logging exception raised: {repr(e2)}... orig exc: {repr(e)} in {func.__name__}")
raise
return wrapper
def ignore_exceptions(func):
assert asyncio.iscoroutinefunction(func), 'func needs to be a coroutine'
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except asyncio.CancelledError:
raise
except Exception as e:
pass
return wrapper
class TxMinedInfo(NamedTuple):
height: int
conf: Optional[int] = None
timestamp: Optional[int] = None
txpos: Optional[int] = None
header_hash: Optional[str] = None
def make_aiohttp_session(proxy: Optional[dict], headers=None, timeout=None):
if headers is None:
headers = {'User-Agent': 'Electrum'}
if timeout is None:
timeout = aiohttp.ClientTimeout(total=45)
elif isinstance(timeout, (int, float)):
timeout = aiohttp.ClientTimeout(total=timeout)
ssl_context = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH, cafile=ca_path)
if proxy:
connector = ProxyConnector(
proxy_type=ProxyType.SOCKS5 if proxy['mode'] == 'socks5' else ProxyType.SOCKS4,
host=proxy['host'],
port=int(proxy['port']),
username=proxy.get('user', None),
password=proxy.get('password', None),
rdns=True,
ssl=ssl_context,
)
else:
connector = aiohttp.TCPConnector(ssl=ssl_context)
return aiohttp.ClientSession(headers=headers, timeout=timeout, connector=connector)
class SilentTaskGroup(TaskGroup):
def spawn(self, *args, **kwargs):
if self._closed:
raise asyncio.CancelledError()
return super().spawn(*args, **kwargs)
class NetworkJobOnDefaultServer(Logger):
def __init__(self, network: 'Network'):
Logger.__init__(self)
asyncio.set_event_loop(network.asyncio_loop)
self.network = network
self.interface = None # type: Interface
self._restart_lock = asyncio.Lock()
self._reset()
asyncio.run_coroutine_threadsafe(self._restart(), network.asyncio_loop)
register_callback(self._restart, ['default_server_changed'])
def _reset(self):
self.taskgroup = SilentTaskGroup()
async def _start(self, interface: 'Interface'):
self.interface = interface
await interface.taskgroup.spawn(self._start_tasks)
async def _start_tasks(self):
raise NotImplementedError() # implemented by subclasses
async def stop(self):
unregister_callback(self._restart)
await self._stop()
async def _stop(self):
await self.taskgroup.cancel_remaining()
@log_exceptions
async def _restart(self, *args):
interface = self.network.interface
if interface is None:
return # we should get called again soon
async with self._restart_lock:
await self._stop()
self._reset()
await self._start(interface)
@property
def session(self):
s = self.interface.session
assert s is not None
return s
def create_and_start_event_loop() -> Tuple[asyncio.AbstractEventLoop,
asyncio.Future,
threading.Thread]:
def on_exception(loop, context):
SUPPRESS_MESSAGE_REGEX = re.compile('SSL handshake|Fatal read error on|'
'SSL error in data received')
message = context.get('message')
if message and SUPPRESS_MESSAGE_REGEX.match(message):
return
loop.default_exception_handler(context)
loop = asyncio.get_event_loop()
loop.set_exception_handler(on_exception)
# loop.set_debug(1)
stopping_fut = asyncio.Future()
loop_thread = threading.Thread(target=loop.run_until_complete,
args=(stopping_fut,),
name='EventLoop')
loop_thread.start()
return loop, stopping_fut, loop_thread
class OrderedDictWithIndex(OrderedDict):
def __init__(self):
super().__init__()
self._key_to_pos = {}
self._pos_to_key = {}
def _recalc_index(self):
self._key_to_pos = {key: pos for (pos, key) in enumerate(self.keys())}
self._pos_to_key = {pos: key for (pos, key) in enumerate(self.keys())}
def pos_from_key(self, key):
return self._key_to_pos[key]
def value_from_pos(self, pos):
key = self._pos_to_key[pos]
return self[key]
def popitem(self, *args, **kwargs):
ret = super().popitem(*args, **kwargs)
self._recalc_index()
return ret
def move_to_end(self, *args, **kwargs):
ret = super().move_to_end(*args, **kwargs)
self._recalc_index()
return ret
def clear(self):
ret = super().clear()
self._recalc_index()
return ret
def pop(self, *args, **kwargs):
ret = super().pop(*args, **kwargs)
self._recalc_index()
return ret
def update(self, *args, **kwargs):
ret = super().update(*args, **kwargs)
self._recalc_index()
return ret
def __delitem__(self, *args, **kwargs):
ret = super().__delitem__(*args, **kwargs)
self._recalc_index()
return ret
def __setitem__(self, key, *args, **kwargs):
is_new_key = key not in self
ret = super().__setitem__(key, *args, **kwargs)
if is_new_key:
pos = len(self) - 1
self._key_to_pos[key] = pos
self._pos_to_key[pos] = key
return ret
def multisig_type(wallet_type):
if not wallet_type:
return None
match = re.match(r'(\d+)of(\d+)', wallet_type)
if match:
match = [int(x) for x in match.group(1, 2)]
return match
def is_ip_address(x: Union[str, bytes]) -> bool:
if isinstance(x, bytes):
x = x.decode("utf-8")
try:
ipaddress.ip_address(x)
return True
except ValueError:
return False
def is_private_netaddress(host: str) -> bool:
if str(host) in ('localhost', 'localhost.',):
return True
if host[0] == '[' and host[-1] == ']': # IPv6
host = host[1:-1]
try:
ip_addr = ipaddress.ip_address(host) # type: Union[IPv4Address, IPv6Address]
return ip_addr.is_private
except ValueError:
pass # not an IP
return False
def list_enabled_bits(x: int) -> Sequence[int]:
binary = bin(x)[2:]
rev_bin = reversed(binary)
return tuple(i for i, b in enumerate(rev_bin) if b == '1')
def resolve_dns_srv(host: str):
srv_records = dns.resolver.query(host, 'SRV')
# priority: prefer lower
# weight: tie breaker; prefer higher
srv_records = sorted(srv_records, key=lambda x: (x.priority, -x.weight))
def dict_from_srv_record(srv):
return {
'host': str(srv.target),
'port': srv.port,
}
return [dict_from_srv_record(srv) for srv in srv_records]
def randrange(bound: int) -> int:
return ecdsa.util.randrange(bound)
class CallbackManager:
# callbacks set by the GUI
def __init__(self):
self.callback_lock = threading.Lock()
self.callbacks = defaultdict(list) # note: needs self.callback_lock
self.asyncio_loop = None
def register_callback(self, callback, events):
with self.callback_lock:
for event in events:
self.callbacks[event].append(callback)
def unregister_callback(self, callback):
with self.callback_lock:
for callbacks in self.callbacks.values():
if callback in callbacks:
callbacks.remove(callback)
def trigger_callback(self, event, *args):
if self.asyncio_loop is None:
self.asyncio_loop = asyncio.get_event_loop()
assert self.asyncio_loop.is_running(), "event loop not running"
with self.callback_lock:
callbacks = self.callbacks[event][:]
for callback in callbacks:
# FIXME: if callback throws, we will lose the traceback
if asyncio.iscoroutinefunction(callback):
asyncio.run_coroutine_threadsafe(callback(event, *args), self.asyncio_loop)
else:
self.asyncio_loop.call_soon_threadsafe(callback, event, *args)
callback_mgr = CallbackManager()
trigger_callback = callback_mgr.trigger_callback
register_callback = callback_mgr.register_callback
unregister_callback = callback_mgr.unregister_callback
_NetAddrType = TypeVar("_NetAddrType")
class NetworkRetryManager(Generic[_NetAddrType]):
def __init__(
self, *,
max_retry_delay_normal: float,
init_retry_delay_normal: float,
max_retry_delay_urgent: float = None,
init_retry_delay_urgent: float = None,
):
self._last_tried_addr = {} # type: Dict[_NetAddrType, Tuple[float, int]] # (unix ts, num_attempts)
# note: these all use "seconds" as unit
if max_retry_delay_urgent is None:
max_retry_delay_urgent = max_retry_delay_normal
if init_retry_delay_urgent is None:
init_retry_delay_urgent = init_retry_delay_normal
self._max_retry_delay_normal = max_retry_delay_normal
self._init_retry_delay_normal = init_retry_delay_normal
self._max_retry_delay_urgent = max_retry_delay_urgent
self._init_retry_delay_urgent = init_retry_delay_urgent
def _trying_addr_now(self, addr: _NetAddrType) -> None:
last_time, num_attempts = self._last_tried_addr.get(addr, (0, 0))
# we add up to 1 second of noise to the time, so that clients are less likely
# to get synchronised and bombard the remote in connection waves:
cur_time = time.time() + random.random()
self._last_tried_addr[addr] = cur_time, num_attempts + 1
def _on_connection_successfully_established(self, addr: _NetAddrType) -> None:
self._last_tried_addr[addr] = time.time(), 0
def _can_retry_addr(self, peer: _NetAddrType, *,
now: float = None, urgent: bool = False) -> bool:
if now is None:
now = time.time()
last_time, num_attempts = self._last_tried_addr.get(peer, (0, 0))
if urgent:
delay = min(self._max_retry_delay_urgent,
self._init_retry_delay_urgent * 2 ** num_attempts)
else:
delay = min(self._max_retry_delay_normal,
self._init_retry_delay_normal * 2 ** num_attempts)
next_time = last_time + delay
return next_time < now
def _clear_addr_retry_times(self) -> None:
self._last_tried_addr.clear()
class MySocksProxy(aiorpcx.SOCKSProxy):
async def open_connection(self, host=None, port=None, **kwargs):
loop = asyncio.get_event_loop()
reader = asyncio.StreamReader(loop=loop)
protocol = asyncio.StreamReaderProtocol(reader, loop=loop)
transport, _ = await self.create_connection(
lambda: protocol, host, port, **kwargs)
writer = asyncio.StreamWriter(transport, protocol, reader, loop)
return reader, writer
@classmethod
def from_proxy_dict(cls, proxy: dict = None) -> Optional['MySocksProxy']:
if not proxy:
return None
username, pw = proxy.get('user'), proxy.get('password')
if not username or not pw:
auth = None
else:
auth = aiorpcx.socks.SOCKSUserAuth(username, pw)
addr = aiorpcx.NetAddress(proxy['host'], proxy['port'])
if proxy['mode'] == "socks4":
ret = cls(addr, aiorpcx.socks.SOCKS4a, auth)
elif proxy['mode'] == "socks5":
ret = cls(addr, aiorpcx.socks.SOCKS5, auth)
else:
raise NotImplementedError # http proxy not available with aiorpcx
return ret
class JsonRPCClient:
def __init__(self, session: aiohttp.ClientSession, url: str):
self.session = session
self.url = url
self._id = 0
async def request(self, endpoint, *args):
self._id += 1
data = ('{"jsonrpc": "2.0", "id":"%d", "method": "%s", "params": %s }'
% (self._id, endpoint, json.dumps(args)))
async with self.session.post(self.url, data=data) as resp:
if resp.status == 200:
r = await resp.json()
result = r.get('result')
error = r.get('error')
if error:
return 'Error: ' + str(error)
else:
return result
else:
text = await resp.text()
return 'Error: ' + str(text)
def add_method(self, endpoint):
async def coro(*args):
return await self.request(endpoint, *args)
setattr(self, endpoint, coro)
T = TypeVar('T')
def random_shuffled_copy(x: Iterable[T]) -> List[T]:
x_copy = list(x) # copy
random.shuffle(x_copy) # shuffle in-place
return x_copy
| true | true |
f723b19e6f28b0a672a93781a73545812f9126e2 | 7,613 | py | Python | python/tensorflow/lib/ner/embeddings_resolver.py | hatrungduc/spark-nlp | b38260543524507e34cbcb7fa2006923091634ad | [
"Apache-2.0"
] | 2,731 | 2017-09-25T08:26:31.000Z | 2022-03-30T10:57:32.000Z | python/tensorflow/lib/ner/embeddings_resolver.py | hatrungduc/spark-nlp | b38260543524507e34cbcb7fa2006923091634ad | [
"Apache-2.0"
] | 957 | 2017-10-03T20:47:51.000Z | 2022-03-31T14:58:52.000Z | python/tensorflow/lib/ner/embeddings_resolver.py | hatrungduc/spark-nlp | b38260543524507e34cbcb7fa2006923091634ad | [
"Apache-2.0"
] | 600 | 2017-10-08T11:35:58.000Z | 2022-03-31T11:19:50.000Z | import shutil
import numpy as np
import plyvel
import os.path
import sys
sys.path.append('../')
from bert.modeling import *
from bert.tokenization import *
import json
import os.path
import numpy as np
class TokenEmbeddings:
def __init__(self, piece, is_word_start, vector):
self.piece = piece
self.is_word_start = is_word_start
self.vector = vector
@staticmethod
def create_sentence(pieces, is_word_starts, embeddings):
# Array of TokenEmbeddings
return [TokenEmbeddings(piece, is_start, vector)
for (piece, is_start, vector) in zip(pieces, is_word_starts, embeddings)]
def __str__(self):
return 'TokenEmbeddings({}, {}, [{}])'.format(self.piece, self.is_word_start, np.shape(self.vector))
def __repr__(self):
return self.__str__()
class EmbeddingsDbResolver:
@staticmethod
def get_index_name(prefix, dim):
return prefix + '-' + str(dim)
@staticmethod
def read_from_file(glove_file, dim, index_file = 'embeddings_index',
lowercase=False, clear_if_exists = False):
full_index_file = EmbeddingsDbResolver.get_index_name(index_file, dim)
try:
resolver = None
index_existed = os.path.exists(full_index_file) and not clear_if_exists
resolver = EmbeddingsDbResolver(dim, index_file, lowercase, clear_if_exists)
if not index_existed:
resolver.read_glove(glove_file)
return resolver
except:
if resolver and resolver.db:
resolver.close()
raise()
def read_glove(self, glove_file):
portion = 500000
print('reading file: ', glove_file)
wb = None
with open(glove_file, encoding='utf-8') as f:
for num, line in enumerate(f):
items = line.split(' ')
word = items[0]
vector = [float(x) for x in items[1:]]
if num % portion == portion - 1:
print('read lines: {}'.format(num))
wb.write()
wb = None
if not wb:
wb = self.db.write_batch()
self.add_vector(word, vector, wb)
if wb:
wb.write()
def __init__(self, dim, index_file = 'embeddings_index', lowercase = False, clear_if_exists=False):
full_index_file = EmbeddingsDbResolver.get_index_name(index_file, dim)
if clear_if_exists and os.path.exists(full_index_file):
shutil.rmtree(db_index)
dummy_added = False
self.db = plyvel.DB(full_index_file, create_if_missing=True)
self.add_vector("__oov__", [0.] * dim)
self.lowercase = lowercase
def get_embeddings(self, word):
word = word.strip()
if self.lowercase:
word = word.lower()
result = self.db.get(word.encode()) or self.db.get('__oov__'.encode())
return np.frombuffer(result)
def resolve_sentence(self, sentence):
"""
sentence - array of words
"""
embeddings = list([self.get_embeddings(word) for word in sentence])
is_word_start = [True] * len(sentence)
return TokenEmbeddings.create_sentence(sentence, is_word_start, embeddings)
def add_vector(self, word, vector, wb = None):
array = np.array(vector)
if wb:
wb.put(word.encode(), array.tobytes())
else:
self.db.put(word.encode(), array.tobytes())
def close(self):
self.db.close()
class BertEmbeddingsResolver:
def __init__(self, model_folder, max_length = 256, lowercase = True):
# 1. Create tokenizer
self.max_length = max_length
vocab_file = os.path.join(model_folder, 'vocab.txt')
self.tokenizer = FullTokenizer(vocab_file, do_lower_case = lowercase)
# 2. Read Config
config_file = os.path.join(model_folder, 'bert_config.json')
self.config = BertConfig.from_json_file(config_file)
# 3. Create Model
self.session = tf.Session()
self.token_ids_op = tf.placeholder(tf.int32, shape=(None, max_length), name='token_ids')
self.model = BertModel(config = self.config,
is_training = False,
input_ids = self.token_ids_op,
use_one_hot_embeddings = False)
# 4. Restore Trained Model
self.saver = tf.train.Saver()
ckpt_file = os.path.join(model_folder, 'bert_model.ckpt')
self.saver.restore(self.session, ckpt_file)
hidden_layers = self.config.num_hidden_layers
self.embeddings_op = tf.get_default_graph().get_tensor_by_name(
"bert/encoder/Reshape_{}:0".format(hidden_layers + 1))
def tokenize_sentence(self, tokens, add_service_tokens = True):
result = []
is_word_start = []
for token in tokens:
pieces = self.tokenizer.tokenize(token)
result.extend(pieces)
starts = [False] * len(pieces)
starts[0] = True
is_word_start.extend(starts)
if add_service_tokens:
if len(result) > self.max_length - 2:
result = result[:self.max_length -2]
is_word_start = is_word_start[:self.max_length -2]
result = ['[CLS]'] + result + ['[SEP]']
is_word_start = [False] + is_word_start + [False]
else:
if len(result) > self.max_length:
result = result[:self.max_length]
is_word_start = is_word_start[:self.max_length]
return (result, is_word_start)
def resolve_sentences(self, sentences):
batch_is_word_start = []
batch_token_ids = []
batch_tokens = []
for sentence in sentences:
tokens, is_word_start = self.tokenize_sentence(sentence)
token_ids = self.tokenizer.convert_tokens_to_ids(tokens)
to_input = np.pad(token_ids, [(0, self.max_length - len(token_ids))], mode='constant')
batch_token_ids.append(to_input)
batch_tokens.append(tokens)
batch_is_word_start.append(is_word_start)
embeddings = self.session.run(self.embeddings_op, feed_dict = {self.token_ids_op: batch_token_ids})
result = []
for i in range(len(sentences)):
tokens = batch_tokens[i]
is_word_start = batch_is_word_start[i]
item_embeddings = embeddings[i, :len(tokens), :]
resolved = TokenEmbeddings.create_sentence(tokens, is_word_start, item_embeddings)
result.append(resolved)
return result
def resolve_sentence(self, sentence):
tokens, is_word_start = self.tokenize_sentence(sentence)
token_ids = self.tokenizer.convert_tokens_to_ids(tokens)
to_input = np.pad(token_ids, [(0, self.max_length - len(token_ids))], mode='constant')
to_input = to_input.reshape((1, self.max_length))
embeddings = self.session.run(self.embeddings_op, feed_dict = {self.token_ids_op: to_input})
embeddings = np.squeeze(embeddings)
embeddings = embeddings[:len(token_ids), :]
return TokenEmbeddings.create_sentence(tokens, is_word_start, embeddings)
| 35.574766 | 111 | 0.590569 | import shutil
import numpy as np
import plyvel
import os.path
import sys
sys.path.append('../')
from bert.modeling import *
from bert.tokenization import *
import json
import os.path
import numpy as np
class TokenEmbeddings:
def __init__(self, piece, is_word_start, vector):
self.piece = piece
self.is_word_start = is_word_start
self.vector = vector
@staticmethod
def create_sentence(pieces, is_word_starts, embeddings):
return [TokenEmbeddings(piece, is_start, vector)
for (piece, is_start, vector) in zip(pieces, is_word_starts, embeddings)]
def __str__(self):
return 'TokenEmbeddings({}, {}, [{}])'.format(self.piece, self.is_word_start, np.shape(self.vector))
def __repr__(self):
return self.__str__()
class EmbeddingsDbResolver:
@staticmethod
def get_index_name(prefix, dim):
return prefix + '-' + str(dim)
@staticmethod
def read_from_file(glove_file, dim, index_file = 'embeddings_index',
lowercase=False, clear_if_exists = False):
full_index_file = EmbeddingsDbResolver.get_index_name(index_file, dim)
try:
resolver = None
index_existed = os.path.exists(full_index_file) and not clear_if_exists
resolver = EmbeddingsDbResolver(dim, index_file, lowercase, clear_if_exists)
if not index_existed:
resolver.read_glove(glove_file)
return resolver
except:
if resolver and resolver.db:
resolver.close()
raise()
def read_glove(self, glove_file):
portion = 500000
print('reading file: ', glove_file)
wb = None
with open(glove_file, encoding='utf-8') as f:
for num, line in enumerate(f):
items = line.split(' ')
word = items[0]
vector = [float(x) for x in items[1:]]
if num % portion == portion - 1:
print('read lines: {}'.format(num))
wb.write()
wb = None
if not wb:
wb = self.db.write_batch()
self.add_vector(word, vector, wb)
if wb:
wb.write()
def __init__(self, dim, index_file = 'embeddings_index', lowercase = False, clear_if_exists=False):
full_index_file = EmbeddingsDbResolver.get_index_name(index_file, dim)
if clear_if_exists and os.path.exists(full_index_file):
shutil.rmtree(db_index)
dummy_added = False
self.db = plyvel.DB(full_index_file, create_if_missing=True)
self.add_vector("__oov__", [0.] * dim)
self.lowercase = lowercase
def get_embeddings(self, word):
word = word.strip()
if self.lowercase:
word = word.lower()
result = self.db.get(word.encode()) or self.db.get('__oov__'.encode())
return np.frombuffer(result)
def resolve_sentence(self, sentence):
embeddings = list([self.get_embeddings(word) for word in sentence])
is_word_start = [True] * len(sentence)
return TokenEmbeddings.create_sentence(sentence, is_word_start, embeddings)
def add_vector(self, word, vector, wb = None):
array = np.array(vector)
if wb:
wb.put(word.encode(), array.tobytes())
else:
self.db.put(word.encode(), array.tobytes())
def close(self):
self.db.close()
class BertEmbeddingsResolver:
def __init__(self, model_folder, max_length = 256, lowercase = True):
self.max_length = max_length
vocab_file = os.path.join(model_folder, 'vocab.txt')
self.tokenizer = FullTokenizer(vocab_file, do_lower_case = lowercase)
config_file = os.path.join(model_folder, 'bert_config.json')
self.config = BertConfig.from_json_file(config_file)
self.session = tf.Session()
self.token_ids_op = tf.placeholder(tf.int32, shape=(None, max_length), name='token_ids')
self.model = BertModel(config = self.config,
is_training = False,
input_ids = self.token_ids_op,
use_one_hot_embeddings = False)
self.saver = tf.train.Saver()
ckpt_file = os.path.join(model_folder, 'bert_model.ckpt')
self.saver.restore(self.session, ckpt_file)
hidden_layers = self.config.num_hidden_layers
self.embeddings_op = tf.get_default_graph().get_tensor_by_name(
"bert/encoder/Reshape_{}:0".format(hidden_layers + 1))
def tokenize_sentence(self, tokens, add_service_tokens = True):
result = []
is_word_start = []
for token in tokens:
pieces = self.tokenizer.tokenize(token)
result.extend(pieces)
starts = [False] * len(pieces)
starts[0] = True
is_word_start.extend(starts)
if add_service_tokens:
if len(result) > self.max_length - 2:
result = result[:self.max_length -2]
is_word_start = is_word_start[:self.max_length -2]
result = ['[CLS]'] + result + ['[SEP]']
is_word_start = [False] + is_word_start + [False]
else:
if len(result) > self.max_length:
result = result[:self.max_length]
is_word_start = is_word_start[:self.max_length]
return (result, is_word_start)
def resolve_sentences(self, sentences):
batch_is_word_start = []
batch_token_ids = []
batch_tokens = []
for sentence in sentences:
tokens, is_word_start = self.tokenize_sentence(sentence)
token_ids = self.tokenizer.convert_tokens_to_ids(tokens)
to_input = np.pad(token_ids, [(0, self.max_length - len(token_ids))], mode='constant')
batch_token_ids.append(to_input)
batch_tokens.append(tokens)
batch_is_word_start.append(is_word_start)
embeddings = self.session.run(self.embeddings_op, feed_dict = {self.token_ids_op: batch_token_ids})
result = []
for i in range(len(sentences)):
tokens = batch_tokens[i]
is_word_start = batch_is_word_start[i]
item_embeddings = embeddings[i, :len(tokens), :]
resolved = TokenEmbeddings.create_sentence(tokens, is_word_start, item_embeddings)
result.append(resolved)
return result
def resolve_sentence(self, sentence):
tokens, is_word_start = self.tokenize_sentence(sentence)
token_ids = self.tokenizer.convert_tokens_to_ids(tokens)
to_input = np.pad(token_ids, [(0, self.max_length - len(token_ids))], mode='constant')
to_input = to_input.reshape((1, self.max_length))
embeddings = self.session.run(self.embeddings_op, feed_dict = {self.token_ids_op: to_input})
embeddings = np.squeeze(embeddings)
embeddings = embeddings[:len(token_ids), :]
return TokenEmbeddings.create_sentence(tokens, is_word_start, embeddings)
| true | true |
f723b1ca60f09e7b6c6efbcd402f29ce0f674af3 | 560 | py | Python | bdm/__init__.py | algorithmic-dynamics-lab/pybdm | a46cd2129dae8322047bb7dc2f9aad982c9b8687 | [
"MIT"
] | 1 | 2019-05-10T10:04:23.000Z | 2019-05-10T10:04:23.000Z | bdm/__init__.py | algorithmic-dynamics-lab/pybdm | a46cd2129dae8322047bb7dc2f9aad982c9b8687 | [
"MIT"
] | null | null | null | bdm/__init__.py | algorithmic-dynamics-lab/pybdm | a46cd2129dae8322047bb7dc2f9aad982c9b8687 | [
"MIT"
] | 1 | 2019-05-10T10:04:25.000Z | 2019-05-10T10:04:25.000Z | """Approximation of algorithmic complexity by Block Decomposition Method.
This package provides the :py:class:`bdm.BDM` class for computing approximated
algorithmic complexity of arbitrary binary 1D and 2D arrays based
on the *Block Decomposition Method* (**BDM**). The method is descibed
`in this paper <https://www.mdpi.com/1099-4300/20/8/605>`__.
"""
from .base import BDMIgnore, BDMRecursive
from .algorithms import PerturbationExperiment
BDM = BDMIgnore
__author__ = 'AlgoDyn Development Team'
__email__ = 'stalaga@protonmail.com'
__version__ = '0.0.0'
| 37.333333 | 78 | 0.783929 | from .base import BDMIgnore, BDMRecursive
from .algorithms import PerturbationExperiment
BDM = BDMIgnore
__author__ = 'AlgoDyn Development Team'
__email__ = 'stalaga@protonmail.com'
__version__ = '0.0.0'
| true | true |
f723b2b061d2c4c4046b6ac43e2de915d6e58e51 | 91,533 | py | Python | pygsti/algorithms/germselection.py | colibri-coruscans/pyGSTi | da54f4abf668a28476030528f81afa46a1fbba33 | [
"Apache-2.0"
] | null | null | null | pygsti/algorithms/germselection.py | colibri-coruscans/pyGSTi | da54f4abf668a28476030528f81afa46a1fbba33 | [
"Apache-2.0"
] | null | null | null | pygsti/algorithms/germselection.py | colibri-coruscans/pyGSTi | da54f4abf668a28476030528f81afa46a1fbba33 | [
"Apache-2.0"
] | null | null | null | """
Functions for selecting a complete set of germs for a GST analysis.
"""
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights
# in this software.
# 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 or in the LICENSE file in the root pyGSTi directory.
#***************************************************************************************************
import warnings as _warnings
import numpy as _np
import numpy.linalg as _nla
from pygsti.algorithms import grasp as _grasp
from pygsti.algorithms import scoring as _scoring
from pygsti import circuits as _circuits
from pygsti import baseobjs as _baseobjs
from pygsti.tools import mpitools as _mpit
FLOATSIZE = 8 # in bytes: TODO: a better way
def find_germs(target_model, randomize=True, randomization_strength=1e-2,
num_gs_copies=5, seed=None, candidate_germ_counts=None,
candidate_seed=None, force="singletons", algorithm='greedy',
algorithm_kwargs=None, mem_limit=None, comm=None,
profiler=None, verbosity=1):
"""
Generate a germ set for doing GST with a given target model.
This function provides a streamlined interface to a variety of germ
selection algorithms. It's goal is to provide a method that typical users
can run by simply providing a target model and leaving all other settings
at their default values, while providing flexibility for users desiring
more control to fine tune some of the general and algorithm-specific
details.
Currently, to break troublesome degeneracies and provide some confidence
that the chosen germ set is amplificationally complete (AC) for all
models in a neighborhood of the target model (rather than only the
target model), an ensemble of models with random unitary perturbations
to their gates must be provided or generated.
Parameters
----------
target_model : Model or list of Model
The model you are aiming to implement, or a list of models that are
copies of the model you are trying to implement (either with or
without random unitary perturbations applied to the models).
randomize : bool, optional
Whether or not to add random unitary perturbations to the model(s)
provided.
randomization_strength : float, optional
The size of the random unitary perturbations applied to gates in the
model. See :meth:`~pygsti.objects.Model.randomize_with_unitary`
for more details.
num_gs_copies : int, optional
The number of copies of the original model that should be used.
seed : int, optional
Seed for generating random unitary perturbations to models. Also
passed along to stochastic germ-selection algorithms.
candidate_germ_counts : dict, optional
A dictionary of *germ_length* : *count* key-value pairs, specifying
the germ "candidate list" - a list of potential germs to draw from.
*count* is either an integer specifying the number of random germs
considered at the given *germ_length* or the special values `"all upto"`
that considers all of the of all non-equivalent germs of length up to
the corresponding *germ_length*. If None, all germs of up to length
6 are used, the equivalent of `{6: 'all upto'}`.
candidate_seed : int, optional
A seed value used when randomly selecting candidate germs. For each
germ length being randomly selected, the germ length is added to
the value of `candidate_seed` to get the actual seed used.
force : str or list, optional
A list of Circuits which *must* be included in the final germ set.
If set to the special string "singletons" then all length-1 strings will
be included. Seting to None is the same as an empty list.
algorithm : {'greedy', 'grasp', 'slack'}, optional
Specifies the algorithm to use to generate the germ set. Current
options are:
'greedy'
Add germs one-at-a-time until the set is AC, picking the germ that
improves the germ-set score by the largest amount at each step. See
:func:`find_germs_breadthfirst` for more details.
'grasp'
Use GRASP to generate random greedy germ sets and then locally
optimize them. See :func:`find_germs_grasp` for more
details.
'slack'
From a initial set of germs, add or remove a germ at each step in
an attempt to improve the germ-set score. Will allow moves that
degrade the score in an attempt to escape local optima as long as
the degredation is within some specified amount of "slack". See
:func:`find_germs_integer_slack` for more details.
algorithm_kwargs : dict
Dictionary of ``{'keyword': keyword_arg}`` pairs providing keyword
arguments for the specified `algorithm` function. See the documentation
for functions referred to in the `algorithm` keyword documentation for
what options are available for each algorithm.
mem_limit : int, optional
A rough memory limit in bytes which restricts the amount of intermediate
values that are computed and stored.
comm : mpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation
across multiple processors.
profiler : Profiler, optional
A profiler object used for to track timing and memory usage.
verbosity : int, optional
The verbosity level of the :class:`~pygsti.objects.VerbosityPrinter`
used to print log messages.
Returns
-------
list of Circuit
A list containing the germs making up the germ set.
"""
printer = _baseobjs.VerbosityPrinter.create_printer(verbosity, comm)
modelList = _setup_model_list(target_model, randomize,
randomization_strength, num_gs_copies, seed)
gates = list(target_model.operations.keys())
availableGermsList = []
if candidate_germ_counts is None: candidate_germ_counts = {6: 'all upto'}
for germLength, count in candidate_germ_counts.items():
if count == "all upto":
availableGermsList.extend(_circuits.list_all_circuits_without_powers_and_cycles(
gates, max_length=germLength))
else:
seed = None if candidate_seed is None else candidate_seed + germLength
availableGermsList.extend(_circuits.list_random_circuits_onelen(
gates, germLength, count, seed=seed))
if algorithm_kwargs is None:
# Avoid danger of using empty dict for default value.
algorithm_kwargs = {}
if algorithm == 'greedy':
printer.log('Using greedy algorithm.', 1)
# Define defaults for parameters that currently have no default or
# whose default we want to change.
default_kwargs = {
'germs_list': availableGermsList,
'randomize': False,
'seed': seed,
'verbosity': max(0, verbosity - 1),
'force': force,
'score_func': 'all',
'comm': comm,
'mem_limit': mem_limit,
'profiler': profiler
}
for key in default_kwargs:
if key not in algorithm_kwargs:
algorithm_kwargs[key] = default_kwargs[key]
germList = find_germs_breadthfirst(model_list=modelList,
**algorithm_kwargs)
if germList is not None:
germsetScore = compute_germ_set_score(
germList, neighborhood=modelList,
score_func=algorithm_kwargs['score_func'])
printer.log('Constructed germ set:', 1)
printer.log(str([germ.str for germ in germList]), 1)
printer.log('Score: {}'.format(germsetScore), 1)
elif algorithm == 'grasp':
printer.log('Using GRASP algorithm.', 1)
# Define defaults for parameters that currently have no default or
# whose default we want to change.
default_kwargs = {
'alpha': 0.1, # No real reason for setting this value of alpha.
'germs_list': availableGermsList,
'randomize': False,
'seed': seed,
'verbosity': max(0, verbosity - 1),
'force': force,
'return_all': False,
'score_func': 'all',
}
for key in default_kwargs:
if key not in algorithm_kwargs:
algorithm_kwargs[key] = default_kwargs[key]
germList = find_germs_grasp(model_list=modelList,
**algorithm_kwargs)
printer.log('Constructed germ set:', 1)
if algorithm_kwargs['return_all'] and germList[0] is not None:
germsetScore = compute_germ_set_score(
germList[0], neighborhood=modelList,
score_func=algorithm_kwargs['score_func'])
printer.log(str([germ.str for germ in germList[0]]), 1)
printer.log('Score: {}'.format(germsetScore))
elif not algorithm_kwargs['return_all'] and germList is not None:
germsetScore = compute_germ_set_score(germList,
neighborhood=modelList)
printer.log(str([germ.str for germ in germList]), 1)
printer.log('Score: {}'.format(germsetScore), 1)
elif algorithm == 'slack':
printer.log('Using slack algorithm.', 1)
# Define defaults for parameters that currently have no default or
# whose default we want to change.
default_kwargs = {
'germs_list': availableGermsList,
'randomize': False,
'seed': seed,
'verbosity': max(0, verbosity - 1),
'force': force,
'score_func': 'all',
}
if ('slack_frac' not in algorithm_kwargs
and 'fixed_slack' not in algorithm_kwargs):
algorithm_kwargs['slack_frac'] = 0.1
for key in default_kwargs:
if key not in algorithm_kwargs:
algorithm_kwargs[key] = default_kwargs[key]
germList = find_germs_integer_slack(modelList,
**algorithm_kwargs)
if germList is not None:
germsetScore = compute_germ_set_score(
germList, neighborhood=modelList,
score_func=algorithm_kwargs['score_func'])
printer.log('Constructed germ set:', 1)
printer.log(str([germ.str for germ in germList]), 1)
printer.log('Score: {}'.format(germsetScore), 1)
else:
raise ValueError("'{}' is not a valid algorithm "
"identifier.".format(algorithm))
return germList
def compute_germ_set_score(germs, target_model=None, neighborhood=None,
neighborhood_size=5,
randomization_strength=1e-2, score_func='all',
op_penalty=0.0, l1_penalty=0.0):
"""
Calculate the score of a germ set with respect to a model.
More precisely, this function computes the maximum score (roughly equal
to the number of amplified parameters) for a cloud of models.
If `target_model` is given, it serves as the center of the cloud,
otherwise the cloud must be supplied directly via `neighborhood`.
Parameters
----------
germs : list
The germ set
target_model : Model, optional
The target model, used to generate a neighborhood of randomized models.
neighborhood : list of Models, optional
The "cloud" of models for which scores are computed. If not None, this
overrides `target_model`, `neighborhood_size`, and `randomization_strength`.
neighborhood_size : int, optional
Number of randomized models to construct around `target_model`.
randomization_strength : float, optional
Strength of unitary randomizations, as passed to :method:`target_model.randomize_with_unitary`.
score_func : {'all', 'worst'}
Sets the objective function for scoring the eigenvalues. If 'all',
score is ``sum(1/input_array)``. If 'worst', score is ``1/min(input_array)``.
op_penalty : float, optional
Coefficient for a penalty linear in the sum of the germ lengths.
l1_penalty : float, optional
Coefficient for a penalty linear in the number of germs.
Returns
-------
CompositeScore
The maximum score for `germs`, indicating how many parameters it amplifies.
"""
def score_fn(x): return _scoring.list_score(x, score_func=score_func)
if neighborhood is None:
neighborhood = [target_model.randomize_with_unitary(randomization_strength)
for n in range(neighborhood_size)]
scores = [compute_composite_germ_set_score(score_fn, model=model,
partial_germs_list=germs,
op_penalty=op_penalty,
l1_penalty=l1_penalty)
for model in neighborhood]
return max(scores)
def _get_model_params(model_list):
"""
Get the number of gates and gauge parameters of the models in a list.
Also verifies all models have the same number of gates and gauge parameters.
Parameters
----------
model_list : list of Model
A list of models for which you want an AC germ set.
Returns
-------
reducedModelList : list of Model
The original list of models with SPAM removed
numGaugeParams : int
The number of non-SPAM gauge parameters for all models.
numNonGaugeParams : int
The number of non-SPAM non-gauge parameters for all models.
numOps : int
The number of gates for all models.
Raises
------
ValueError
If the number of gauge parameters or gates varies among the models.
"""
# We don't care about SPAM, since it can't be amplified.
reducedModelList = [_remove_spam_vectors(model)
for model in model_list]
# All the models should have the same number of parameters and gates, but
# let's be paranoid here for the time being and make sure.
numGaugeParamsList = [reducedModel.num_gauge_params
for reducedModel in reducedModelList]
numGaugeParams = numGaugeParamsList[0]
if not all([numGaugeParams == otherNumGaugeParams
for otherNumGaugeParams in numGaugeParamsList[1:]]):
raise ValueError("All models must have the same number of gauge "
"parameters!")
numNonGaugeParamsList = [reducedModel.num_nongauge_params
for reducedModel in reducedModelList]
numNonGaugeParams = numNonGaugeParamsList[0]
if not all([numNonGaugeParams == otherNumNonGaugeParams
for otherNumNonGaugeParams in numNonGaugeParamsList[1:]]):
raise ValueError("All models must have the same number of non-gauge "
"parameters!")
numOpsList = [len(reducedModel.operations)
for reducedModel in reducedModelList]
numOps = numOpsList[0]
if not all([numOps == otherNumOps
for otherNumOps in numOpsList[1:]]):
raise ValueError("All models must have the same number of gates!")
return reducedModelList, numGaugeParams, numNonGaugeParams, numOps
def _setup_model_list(model_list, randomize, randomization_strength,
num_copies, seed):
"""
Sets up a list of randomize models (helper function).
"""
if not isinstance(model_list, (list, tuple)):
model_list = [model_list]
if len(model_list) > 1 and num_copies is not None:
_warnings.warn("Ignoring num_copies={} since multiple models were "
"supplied.".format(num_copies))
if randomize:
model_list = randomize_model_list(model_list, randomization_strength,
num_copies, seed)
return model_list
def compute_composite_germ_set_score(score_fn, threshold_ac=1e6, init_n=1,
partial_deriv_dagger_deriv=None, model=None,
partial_germs_list=None, eps=None, num_gauge_params=None,
op_penalty=0.0, germ_lengths=None, l1_penalty=0.0):
"""
Compute the score for a germ set when it is not AC against a model.
Normally scores computed for germ sets against models for which they are
not AC will simply be astronomically large. This is fine if AC is all you
care about, but not so useful if you want to compare partial germ sets
against one another to see which is closer to being AC. This function
will see if the germ set is AC for the parameters corresponding to the
largest `N` eigenvalues for increasing `N` until it finds a value of `N`
for which the germ set is not AC or all the non gauge parameters are
accounted for and report the value of `N` as well as the score.
This allows partial germ set scores to be compared against one-another
sensibly, where a larger value of `N` always beats a smaller value of `N`,
and ties in the value of `N` are broken by the score for that value of `N`.
Parameters
----------
score_fn : callable
A function that takes as input a list of sorted eigenvalues and returns
a score for the partial germ set based on those eigenvalues, with lower
scores indicating better germ sets. Usually some flavor of
:func:`~pygsti.algorithms.scoring.list_score`.
threshold_ac : float, optional
Value which the score (before penalties are applied) must be lower than
for the germ set to be considered AC.
init_n : int
The number of largest eigenvalues to begin with checking.
partial_deriv_dagger_deriv : numpy.array, optional
Array with three axes, where the first axis indexes individual germs
within the partial germ set and the remaining axes index entries in the
positive square of the Jacobian of each individual germ's parameters
with respect to the model parameters.
If this array is not supplied it will need to be computed from
`germs_list` and `model`, which will take longer, so it is recommended
to precompute this array if this routine will be called multiple times.
model : Model, optional
The model against which the germ set is to be scored. Not needed if
`partial_deriv_dagger_deriv` is provided.
partial_germs_list : list of Circuit, optional
The list of germs in the partial germ set to be evaluated. Not needed
if `partial_deriv_dagger_deriv` (and `germ_lengths` when
``op_penalty > 0``) are provided.
eps : float, optional
Used when calculating `partial_deriv_dagger_deriv` to determine if two
eigenvalues are equal (see :func:`_bulk_twirled_deriv` for details). Not
used if `partial_deriv_dagger_deriv` is provided.
num_gauge_params : int
The number of gauge parameters of the model. Not needed if `model`
is provided.
op_penalty : float, optional
Coefficient for a penalty linear in the sum of the germ lengths.
germ_lengths : numpy.array, optional
The length of each germ. Not needed if `op_penalty` is ``0.0`` or
`partial_germs_list` is provided.
l1_penalty : float, optional
Coefficient for a penalty linear in the number of germs.
Returns
-------
CompositeScore
The score for the germ set indicating how many parameters it amplifies
and its numerical score restricted to those parameters.
"""
if partial_deriv_dagger_deriv is None:
if model is None or partial_germs_list is None:
raise ValueError("Must provide either partial_deriv_dagger_deriv or "
"(model, partial_germs_list)!")
else:
pDDD_kwargs = {'model': model, 'germs_list': partial_germs_list}
if eps is not None:
pDDD_kwargs['eps'] = eps
if germ_lengths is not None:
pDDD_kwargs['germ_lengths'] = germ_lengths
partial_deriv_dagger_deriv = _compute_bulk_twirled_ddd(**pDDD_kwargs)
if num_gauge_params is None:
if model is None:
raise ValueError("Must provide either num_gauge_params or model!")
else:
num_gauge_params = _remove_spam_vectors(model).num_gauge_params
# Calculate penalty scores
numGerms = partial_deriv_dagger_deriv.shape[0]
l1Score = l1_penalty * numGerms
opScore = 0.0
if op_penalty != 0.0:
if germ_lengths is None:
if partial_germs_list is None:
raise ValueError("Must provide either germ_lengths or "
"partial_germs_list when op_penalty != 0.0!")
else:
germ_lengths = _np.array([len(germ)
for germ in partial_germs_list])
opScore = op_penalty * _np.sum(germ_lengths)
combinedDDD = _np.sum(partial_deriv_dagger_deriv, axis=0)
sortedEigenvals = _np.sort(_np.real(_nla.eigvalsh(combinedDDD)))
observableEigenvals = sortedEigenvals[num_gauge_params:]
N_AC = 0
AC_score = _np.inf
for N in range(init_n, len(observableEigenvals) + 1):
scoredEigenvals = observableEigenvals[-N:]
candidate_AC_score = score_fn(scoredEigenvals)
if candidate_AC_score > threshold_ac:
break # We've found a set of parameters for which the germ set
# is not AC.
else:
AC_score = candidate_AC_score
N_AC = N
# OLD Apply penalties to the minor score; major part is just #amplified
#major_score = N_AC
#minor_score = AC_score + l1Score + opScore
# Apply penalties to the major score
major_score = -N_AC + opScore + l1Score
minor_score = AC_score
ret = _scoring.CompositeScore(major_score, minor_score, N_AC)
#DEBUG: ret.extra = {'opScore': opScore,
# 'sum(germ_lengths)': _np.sum(germ_lengths), 'l1': l1Score}
return ret
def _compute_bulk_twirled_ddd(model, germs_list, eps=1e-6, check=False,
germ_lengths=None, comm=None):
"""
Calculate the positive squares of the germ Jacobians.
twirledDerivDaggerDeriv == array J.H*J contributions from each germ
(J=Jacobian) indexed by (iGerm, iModelParam1, iModelParam2)
size (nGerms, vec_model_dim, vec_model_dim)
Parameters
----------
model : Model
The model defining the parameters to differentiate with respect to.
germs_list : list
The germ set
eps : float, optional
Tolerance used for testing whether two eigenvectors are degenerate
(i.e. abs(eval1 - eval2) < eps ? )
check : bool, optional
Whether to perform internal consistency checks, at the expense of
making the function slower.
germ_lengths : numpy.ndarray, optional
A pre-computed array of the length (depth) of each germ.
comm : mpi4py.MPI.Comm, optional
When not ``None``, an MPI communicator for distributing the computation
across multiple processors.
Returns
-------
twirledDerivDaggerDeriv : numpy.ndarray
A complex array of shape `(len(germs), model.num_params, model.num_params)`.
"""
if germ_lengths is None:
germ_lengths = _np.array([len(germ) for germ in germs_list])
twirledDeriv = _bulk_twirled_deriv(model, germs_list, eps, check, comm) / germ_lengths[:, None, None]
#OLD: slow, I think because conjugate *copies* a large tensor, causing a memory bottleneck
#twirledDerivDaggerDeriv = _np.einsum('ijk,ijl->ikl',
# _np.conjugate(twirledDeriv),
# twirledDeriv)
#NEW: faster, one-germ-at-a-time computation requires less memory.
nGerms, _, vec_model_dim = twirledDeriv.shape
twirledDerivDaggerDeriv = _np.empty((nGerms, vec_model_dim, vec_model_dim),
dtype=_np.complex)
for i in range(nGerms):
twirledDerivDaggerDeriv[i, :, :] = _np.dot(
twirledDeriv[i, :, :].conjugate().T, twirledDeriv[i, :, :])
return twirledDerivDaggerDeriv
def _compute_twirled_ddd(model, germ, eps=1e-6):
"""
Calculate the positive squares of the germ Jacobian.
twirledDerivDaggerDeriv == array J.H*J contributions from `germ`
(J=Jacobian) indexed by (iModelParam1, iModelParam2)
size (vec_model_dim, vec_model_dim)
Parameters
----------
model : Model
The model defining the parameters to differentiate with respect to.
germ : Circuit
The (single) germ circuit to consider. `J` above is the twirled
derivative of this circuit's action (process matrix).
eps : float, optional
Tolerance used for testing whether two eigenvectors are degenerate
(i.e. abs(eval1 - eval2) < eps ? )
Returns
-------
numpy.ndarray
"""
twirledDeriv = _twirled_deriv(model, germ, eps) / len(germ)
#twirledDerivDaggerDeriv = _np.einsum('jk,jl->kl',
# _np.conjugate(twirledDeriv),
# twirledDeriv)
twirledDerivDaggerDeriv = _np.tensordot(_np.conjugate(twirledDeriv),
twirledDeriv, (0, 0))
return twirledDerivDaggerDeriv
def _germ_set_score_slack(weights, model_num, score_func, deriv_dagger_deriv_list,
force_indices, force_score,
n_gauge_params, op_penalty, germ_lengths, l1_penalty=1e-2,
score_dict=None):
"""
Returns a germ set "score" in which smaller is better.
Also returns intentionally bad score (`force_score`) if `weights` is zero on any of
the "forced" germs (i.e. at any index in `forcedIndices`).
This function is included for use by :func:`find_germs_integer_slack`,
but is not convenient for just computing the score of a germ set. For that,
use :func:`compute_germ_set_score`.
Parameters
----------
weights : list
The per-germ "selection weight", indicating whether the germ
is present in the selected germ set or not.
model_num : int
index into `deriv_dagger_deriv_list` indicating which model (typically in
a neighborhood) we're computing scores for.
score_func : {'all', 'worst'}
Sets the objective function for scoring the eigenvalues. If 'all',
score is ``sum(1/input_array)``. If 'worst', score is ``1/min(input_array)``.
deriv_dagger_deriv_list : numpy.ndarray
Array of J.T * J contributions for each model.
force_indices : list of ints
Indices marking the germs that *must* be in the final set (or else `force_score`
will be returned).
force_score : float
The score that is returned when any of the germs indexed by `force_indices` are
not present (i.e. their weights are <= 0).
n_gauge_params : int
The number of gauge (not amplifiable) parameters in the model.
op_penalty : float
Coefficient for a penalty linear in the sum of the germ lengths.
germ_lengths : numpy.ndarray
A pre-computed array of the length (depth) of each germ.
l1_penalty : float
Coefficient for a penalty linear in the number of germs.
score_dict : dict, optional
A dictionary to cache the score valies for the given `model_num` and
`weights`, i.e. `score_dict[model_num, tuple(weights)]` is set to the
returned value.
Returns
-------
float
"""
if force_indices is not None and _np.any(weights[force_indices] <= 0):
score = force_score
else:
#combinedDDD = _np.einsum('i,ijk', weights,
# deriv_dagger_deriv_list[model_num])
combinedDDD = _np.squeeze(
_np.tensordot(_np.expand_dims(weights, 1),
deriv_dagger_deriv_list[model_num], (0, 0)))
assert len(combinedDDD.shape) == 2
sortedEigenvals = _np.sort(_np.real(_nla.eigvalsh(combinedDDD)))
observableEigenvals = sortedEigenvals[n_gauge_params:]
score = (_scoring.list_score(observableEigenvals, score_func)
+ l1_penalty * _np.sum(weights)
+ op_penalty * _np.dot(germ_lengths, weights))
if score_dict is not None:
# Side effect: calling _germ_set_score_slack caches result in score_dict
score_dict[model_num, tuple(weights)] = score
return score
def randomize_model_list(model_list, randomization_strength, num_copies,
seed=None):
"""
Applies random unitary perturbations to a model or list of models.
If `model_list` is a length-1 list, then `num_copies` determines how
many randomizations to create. If `model_list` containes multiple
models, then `num_copies` must be `None` and each model is
randomized once to create the corresponding returned model.
Parameters
----------
model_list : Model or list
A list of Model objects.
randomization_strength : float, optional
Strength of unitary randomizations, as passed to :method:`Model.randomize_with_unitary`.
num_copies : int
The number of random perturbations of `model_list[0]` to generate when
`len(model_list) == 1`. A value of `None` will result in 1 copy. If
`len(model_list) > 1` then `num_copies` must be set to None.
seed : int, optional
Starting seed for randomization. Successive randomizations receive
successive seeds. `None` results in random seeds.
Returns
-------
list
A list of the randomized Models.
"""
if len(model_list) > 1 and num_copies is not None:
raise ValueError("Input multiple models XOR request multiple "
"copies only!")
newmodelList = []
if len(model_list) > 1:
for modelnum, model in enumerate(model_list):
newmodelList.append(model.randomize_with_unitary(
randomization_strength,
seed=None if seed is None else seed + modelnum))
else:
for modelnum in range(num_copies if num_copies is not None else 1):
newmodelList.append(model_list[0].randomize_with_unitary(
randomization_strength,
seed=None if seed is None else seed + modelnum))
return newmodelList
def test_germs_list_completeness(model_list, germs_list, score_func, threshold):
"""
Check to see if the germs_list is amplificationally complete (AC).
Checks for AC with respect to all the Models in `model_list`, returning
the index of the first Model for which it is not AC or `-1` if it is AC
for all Models.
Parameters
----------
model_list : list
A list of models to test. Often this list is a neighborhood ("cloud") of
models around a model of interest.
germs_list : list
A list of the germ :class:`Circuit`s (the "germ set") to test for completeness.
score_func : {'all', 'worst'}
Sets the objective function for scoring the eigenvalues. If 'all',
score is ``sum(1/eigval_array)``. If 'worst', score is ``1/min(eigval_array)``.
threshold : float, optional
An eigenvalue of jacobian^T*jacobian is considered zero and thus a
parameter un-amplified when its reciprocal is greater than threshold.
Also used for eigenvector degeneracy testing in twirling operation.
Returns
-------
int
The index of the first model in `model_list` to fail the amplficational
completeness test.
"""
for modelNum, model in enumerate(model_list):
initial_test = test_germ_set_infl(model, germs_list,
score_func=score_func,
threshold=threshold)
if not initial_test:
return modelNum
# If the germs_list is complete for all models, return -1
return -1
def _remove_spam_vectors(model):
"""
Returns a copy of `model` with state preparations and effects removed.
Parameters
----------
model : Model
The model to act on.
Returns
-------
Model
"""
reducedModel = model.copy()
for prepLabel in list(reducedModel.preps.keys()):
del reducedModel.preps[prepLabel]
for povmLabel in list(reducedModel.povms.keys()):
del reducedModel.povms[povmLabel]
return reducedModel
def _num_non_spam_gauge_params(model):
"""
Return the number of non-gauge, non-SPAM parameters in `model`.
Equivalent to `_remove_spam_vectors(model).num_gauge_params`.
Parameters
---------
model : Model
Parameters
----------
model : Model
The model to act on.
Returns
-------
int
"""
return _remove_spam_vectors(model).num_gauge_params
# wrt is op_dim x op_dim, so is M, Minv, Proj
# so SOP is op_dim^2 x op_dim^2 and acts on vectorized *gates*
# Recall vectorizing identity (when vec(.) concats rows as flatten does):
# vec( A * X * B ) = A tensor B^T * vec( X )
def _super_op_for_perfect_twirl(wrt, eps):
"""Return super operator for doing a perfect twirl with respect to wrt.
"""
assert wrt.shape[0] == wrt.shape[1] # only square matrices allowed
dim = wrt.shape[0]
SuperOp = _np.zeros((dim**2, dim**2), 'complex')
# Get spectrum and eigenvectors of wrt
wrtEvals, wrtEvecs = _np.linalg.eig(wrt)
wrtEvecsInv = _np.linalg.inv(wrtEvecs)
# We want to project X -> M * (Proj_i * (Minv * X * M) * Proj_i) * Minv,
# where M = wrtEvecs. So A = B = M * Proj_i * Minv and so
# superop = A tensor B^T == A tensor A^T
# NOTE: this == (A^T tensor A)^T while *Maple* germ functions seem to just
# use A^T tensor A -> ^T difference
for i in range(dim):
# Create projector onto i-th eigenspace (spanned by i-th eigenvector
# and other degenerate eigenvectors)
Proj_i = _np.diag([(1 if (abs(wrtEvals[i] - wrtEvals[j]) <= eps)
else 0) for j in range(dim)])
A = _np.dot(wrtEvecs, _np.dot(Proj_i, wrtEvecsInv))
#if _np.linalg.norm(A.imag) > 1e-6:
# print("DB: imag = ",_np.linalg.norm(A.imag))
#assert(_np.linalg.norm(A.imag) < 1e-6)
#A = _np.real(A)
# Need to normalize, because we are overcounting projectors onto
# subspaces of dimension d > 1, giving us d * Proj_i tensor Proj_i^T.
# We can fix this with a division by tr(Proj_i) = d.
SuperOp += _np.kron(A, A.T) / _np.trace(Proj_i)
# SuperOp += _np.kron(A.T,A) # Mimic Maple version (but I think this is
# wrong... or it doesn't matter?)
return SuperOp # a op_dim^2 x op_dim^2 matrix
def _sq_sing_vals_from_deriv(deriv, weights=None):
"""
Calculate the squared singular values of the Jacobian of the germ set.
Parameters
----------
deriv : numpy.array
Array of shape ``(nGerms, flattened_op_dim, vec_model_dim)``. Each
sub-array corresponding to an individual germ is the Jacobian of the
vectorized gate representation of that germ raised to some power with
respect to the model parameters, normalized by dividing by the length
of each germ after repetition.
weights : numpy.array
Array of length ``nGerms``, giving the relative contributions of each
individual germ's Jacobian to the combined Jacobian (which is calculated
as a convex combination of the individual Jacobians).
Returns
-------
numpy.array
The sorted squared singular values of the combined Jacobian of the germ
set.
"""
# shape (nGerms, vec_model_dim, vec_model_dim)
derivDaggerDeriv = _np.einsum('ijk,ijl->ikl', _np.conjugate(deriv), deriv)
# awkward to convert to tensordot, so leave as einsum
# Take the average of the D^dagger*D/L^2 matrices associated with each germ
# with optional weights.
combinedDDD = _np.average(derivDaggerDeriv, weights=weights, axis=0)
sortedEigenvals = _np.sort(_np.real(_nla.eigvalsh(combinedDDD)))
return sortedEigenvals
def _twirled_deriv(model, circuit, eps=1e-6):
"""
Compute the "Twirled Derivative" of a circuit.
The twirled derivative is obtained by acting on the standard derivative of
a circuit with the twirling superoperator.
Parameters
----------
model : Model object
The Model which associates operation labels with operators.
circuit : Circuit object
A twirled derivative of this circuit's action (process matrix) is taken.
eps : float, optional
Tolerance used for testing whether two eigenvectors are degenerate
(i.e. abs(eval1 - eval2) < eps ? )
Returns
-------
numpy array
An array of shape (op_dim^2, num_model_params)
"""
prod = model.sim.product(circuit)
# flattened_op_dim x vec_model_dim
dProd = model.sim.dproduct(circuit, flat=True)
# flattened_op_dim x flattened_op_dim
twirler = _super_op_for_perfect_twirl(prod, eps)
# flattened_op_dim x vec_model_dim
return _np.dot(twirler, dProd)
def _bulk_twirled_deriv(model, circuits, eps=1e-6, check=False, comm=None):
"""
Compute the "Twirled Derivative" of a set of circuits.
The twirled derivative is obtained by acting on the standard derivative of
a circuit with the twirling superoperator.
Parameters
----------
model : Model object
The Model which associates operation labels with operators.
circuits : list of Circuit objects
A twirled derivative of this circuit's action (process matrix) is taken.
eps : float, optional
Tolerance used for testing whether two eigenvectors are degenerate
(i.e. abs(eval1 - eval2) < eps ? )
check : bool, optional
Whether to perform internal consistency checks, at the expense of
making the function slower.
comm : mpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation
across multiple processors.
Returns
-------
numpy array
An array of shape (num_simplified_circuits, op_dim^2, num_model_params)
"""
if len(model.preps) > 0 or len(model.povms) > 0:
model = _remove_spam_vectors(model)
# This function assumes model has no spam elements so `lookup` below
# gives indexes into products computed by evalTree.
resource_alloc = _baseobjs.ResourceAllocation(comm=comm)
dProds, prods = model.sim.bulk_dproduct(circuits, flat=True, return_prods=True, resource_alloc=resource_alloc)
op_dim = model.dim
fd = op_dim**2 # flattened gate dimension
nCircuits = len(circuits)
ret = _np.empty((nCircuits, fd, dProds.shape[1]), 'complex')
for i in range(nCircuits):
# flattened_op_dim x flattened_op_dim
twirler = _super_op_for_perfect_twirl(prods[i], eps)
# flattened_op_dim x vec_model_dim
ret[i] = _np.dot(twirler, dProds[i * fd:(i + 1) * fd])
if check:
for i, circuit in enumerate(circuits):
chk_ret = _twirled_deriv(model, circuit, eps)
if _nla.norm(ret[i] - chk_ret) > 1e-6:
_warnings.warn("bulk twirled derivative norm mismatch = "
"%g - %g = %g"
% (_nla.norm(ret[i]), _nla.norm(chk_ret),
_nla.norm(ret[i] - chk_ret))) # pragma: no cover
return ret # nSimplifiedCircuits x flattened_op_dim x vec_model_dim
def test_germ_set_finitel(model, germs_to_test, length, weights=None,
return_spectrum=False, tol=1e-6):
"""
Test whether a set of germs is able to amplify all non-gauge parameters.
Parameters
----------
model : Model
The Model (associates operation matrices with operation labels).
germs_to_test : list of Circuits
List of germ circuits to test for completeness.
length : int
The finite length to use in amplification testing. Larger
values take longer to compute but give more robust results.
weights : numpy array, optional
A 1-D array of weights with length equal len(germs_to_test),
which multiply the contribution of each germ to the total
jacobian matrix determining parameter amplification. If
None, a uniform weighting of 1.0/len(germs_to_test) is applied.
return_spectrum : bool, optional
If True, return the jacobian^T*jacobian spectrum in addition
to the success flag.
tol : float, optional
Tolerance: an eigenvalue of jacobian^T*jacobian is considered
zero and thus a parameter un-amplified when it is less than tol.
Returns
-------
success : bool
Whether all non-gauge parameters were amplified.
spectrum : numpy array
Only returned when `return_spectrum` is ``True``. Sorted array of
eigenvalues (from small to large) of the jacobian^T * jacobian
matrix used to determine parameter amplification.
"""
# Remove any SPAM vectors from model since we only want
# to consider the set of *gate* parameters for amplification
# and this makes sure our parameter counting is correct
model = _remove_spam_vectors(model)
nGerms = len(germs_to_test)
germToPowL = [germ * length for germ in germs_to_test]
op_dim = model.dim
dprods = model.sim.bulk_dproduct(germToPowL, flat=True) # shape (nGerms*flattened_op_dim, vec_model_dim)
dprods.shape = (nGerms, op_dim**2, dprods.shape[1])
germLengths = _np.array([len(germ) for germ in germs_to_test], 'd')
normalizedDeriv = dprods / (length * germLengths[:, None, None])
sortedEigenvals = _sq_sing_vals_from_deriv(normalizedDeriv, weights)
nGaugeParams = model.num_gauge_params
observableEigenvals = sortedEigenvals[nGaugeParams:]
bSuccess = bool(_scoring.list_score(observableEigenvals, 'worst') < 1 / tol)
return (bSuccess, sortedEigenvals) if return_spectrum else bSuccess
def test_germ_set_infl(model, germs_to_test, score_func='all', weights=None,
return_spectrum=False, threshold=1e6, check=False):
"""
Test whether a set of germs is able to amplify all non-gauge parameters.
Parameters
----------
model : Model
The Model (associates operation matrices with operation labels).
germs_to_test : list of Circuit
List of germ circuits to test for completeness.
score_func : string
Label to indicate how a germ set is scored. See
:func:`~pygsti.algorithms.scoring.list_score` for details.
weights : numpy array, optional
A 1-D array of weights with length equal len(germs_to_test),
which multiply the contribution of each germ to the total
jacobian matrix determining parameter amplification. If
None, a uniform weighting of 1.0/len(germs_to_test) is applied.
return_spectrum : bool, optional
If ``True``, return the jacobian^T*jacobian spectrum in addition
to the success flag.
threshold : float, optional
An eigenvalue of jacobian^T*jacobian is considered zero and thus a
parameter un-amplified when its reciprocal is greater than threshold.
Also used for eigenvector degeneracy testing in twirling operation.
check : bool, optional
Whether to perform internal consistency checks, at the
expense of making the function slower.
Returns
-------
success : bool
Whether all non-gauge parameters were amplified.
spectrum : numpy array
Only returned when `return_spectrum` is ``True``. Sorted array of
eigenvalues (from small to large) of the jacobian^T * jacobian
matrix used to determine parameter amplification.
"""
# Remove any SPAM vectors from model since we only want
# to consider the set of *gate* parameters for amplification
# and this makes sure our parameter counting is correct
model = _remove_spam_vectors(model)
germLengths = _np.array([len(germ) for germ in germs_to_test], _np.int64)
twirledDerivDaggerDeriv = _compute_bulk_twirled_ddd(model, germs_to_test,
1. / threshold, check,
germLengths)
# result[i] = _np.dot( twirledDeriv[i].H, twirledDeriv[i] ) i.e. matrix
# product
# result[i,k,l] = sum_j twirledDerivH[i,k,j] * twirledDeriv(i,j,l)
# result[i,k,l] = sum_j twirledDeriv_conj[i,j,k] * twirledDeriv(i,j,l)
if weights is None:
nGerms = len(germs_to_test)
# weights = _np.array( [1.0/nGerms]*nGerms, 'd')
weights = _np.array([1.0] * nGerms, 'd')
#combinedTDDD = _np.einsum('i,ijk->jk', weights, twirledDerivDaggerDeriv)
combinedTDDD = _np.tensordot(weights, twirledDerivDaggerDeriv, (0, 0))
sortedEigenvals = _np.sort(_np.real(_np.linalg.eigvalsh(combinedTDDD)))
nGaugeParams = model.num_gauge_params
observableEigenvals = sortedEigenvals[nGaugeParams:]
bSuccess = bool(_scoring.list_score(observableEigenvals, score_func)
< threshold)
return (bSuccess, sortedEigenvals) if return_spectrum else bSuccess
def find_germs_depthfirst(model_list, germs_list, randomize=True,
randomization_strength=1e-3, num_copies=None, seed=0, op_penalty=0,
score_func='all', tol=1e-6, threshold=1e6, check=False,
force="singletons", verbosity=0):
"""
Greedy germ selection algorithm starting with 0 germs.
Tries to minimize the number of germs needed to achieve amplificational
completeness (AC). Begins with 0 germs and adds the germ that increases the
score used to check for AC by the largest amount at each step, stopping when
the threshold for AC is achieved.
Parameters
----------
model_list : Model or list
The model or list of `Model`s to select germs for.
germs_list : list of Circuit
The list of germs to contruct a germ set from.
randomize : bool, optional
Whether or not to randomize `model_list` (usually just a single
`Model`) with small (see `randomizationStrengh`) unitary maps
in order to avoid "accidental" symmetries which could allow for
fewer germs but *only* for that particular model. Setting this
to `True` will increase the run time by a factor equal to the
numer of randomized copies (`num_copies`).
randomization_strength : float, optional
The strength of the unitary noise used to randomize input Model(s);
is passed to :func:`~pygsti.objects.Model.randomize_with_unitary`.
num_copies : int, optional
The number of randomized models to create when only a *single* gate
set is passed via `model_list`. Otherwise, `num_copies` must be set
to `None`.
seed : int, optional
Seed for generating random unitary perturbations to models.
op_penalty : float, optional
Coefficient for a penalty linear in the sum of the germ lengths.
score_func : {'all', 'worst'}, optional
Sets the objective function for scoring the eigenvalues. If 'all',
score is ``sum(1/eigenvalues)``. If 'worst', score is
``1/min(eiganvalues)``.
tol : float, optional
Tolerance (`eps` arg) for :func:`_compute_bulk_twirled_ddd`, which sets
the differece between eigenvalues below which they're treated as
degenerate.
threshold : float, optional
Value which the score (before penalties are applied) must be lower than
for a germ set to be considered AC.
check : bool, optional
Whether to perform internal checks (will slow down run time
substantially).
force : list of Circuits
A list of `Circuit` objects which *must* be included in the final
germ set. If the special string "singletons" is given, then all of
the single gates (length-1 sequences) must be included.
verbosity : int, optional
Level of detail printed to stdout.
Returns
-------
list
A list of the built-up germ set (a list of :class:`Circuit` objects).
"""
printer = _baseobjs.VerbosityPrinter.create_printer(verbosity)
model_list = _setup_model_list(model_list, randomize,
randomization_strength, num_copies, seed)
(reducedModelList,
numGaugeParams, _, _) = _get_model_params(model_list)
germLengths = _np.array([len(germ) for germ in germs_list], _np.int64)
numGerms = len(germs_list)
weights = _np.zeros(numGerms, _np.int64)
goodGerms = []
if force:
if force == "singletons":
weights[_np.where(germLengths == 1)] = 1
goodGerms = [germ for germ
in _np.array(germs_list)[_np.where(germLengths == 1)]]
else: # force should be a list of Circuits
for opstr in force:
weights[germs_list.index(opstr)] = 1
goodGerms = force[:]
undercompleteModelNum = test_germs_list_completeness(model_list,
germs_list,
score_func,
threshold)
if undercompleteModelNum > -1:
printer.warning("Complete initial germ set FAILS on model "
+ str(undercompleteModelNum) + ". Aborting search.")
return None
printer.log("Complete initial germ set succeeds on all input models.", 1)
printer.log("Now searching for best germ set.", 1)
printer.log("Starting germ set optimization. Lower score is better.", 1)
twirledDerivDaggerDerivList = [_compute_bulk_twirled_ddd(model, germs_list, tol,
check, germLengths)
for model in model_list]
# Dict of keyword arguments passed to compute_score_non_AC that don't
# change from call to call
nonAC_kwargs = {
'score_fn': lambda x: _scoring.list_score(x, score_func=score_func),
'threshold_ac': threshold,
'num_gauge_params': numGaugeParams,
'op_penalty': op_penalty,
'germ_lengths': germLengths,
}
for modelNum, reducedModel in enumerate(reducedModelList):
derivDaggerDeriv = twirledDerivDaggerDerivList[modelNum]
# Make sure the set of germs you come up with is AC for all
# models.
# Remove any SPAM vectors from model since we only want
# to consider the set of *gate* parameters for amplification
# and this makes sure our parameter counting is correct
while _np.any(weights == 0):
# As long as there are some unused germs, see if you need to add
# another one.
if test_germ_set_infl(reducedModel, goodGerms,
score_func=score_func, threshold=threshold):
# The germs are sufficient for the current model
break
candidateGerms = _np.where(weights == 0)[0]
candidateGermScores = []
for candidateGermIdx in _np.where(weights == 0)[0]:
# If the germs aren't sufficient, try adding a single germ
candidateWeights = weights.copy()
candidateWeights[candidateGermIdx] = 1
partialDDD = derivDaggerDeriv[
_np.where(candidateWeights == 1)[0], :, :]
candidateGermScore = compute_composite_germ_set_score(
partial_deriv_dagger_deriv=partialDDD, **nonAC_kwargs)
candidateGermScores.append(candidateGermScore)
# Add the germ that give the best score
bestCandidateGerm = candidateGerms[_np.array(
candidateGermScores).argmin()]
weights[bestCandidateGerm] = 1
goodGerms.append(germs_list[bestCandidateGerm])
return goodGerms
def find_germs_breadthfirst(model_list, germs_list, randomize=True,
randomization_strength=1e-3, num_copies=None, seed=0,
op_penalty=0, score_func='all', tol=1e-6, threshold=1e6,
check=False, force="singletons", pretest=True, mem_limit=None,
comm=None, profiler=None, verbosity=0):
"""
Greedy algorithm starting with 0 germs.
Tries to minimize the number of germs needed to achieve amplificational
completeness (AC). Begins with 0 germs and adds the germ that increases the
score used to check for AC by the largest amount (for the model that
currently has the lowest score) at each step, stopping when the threshold
for AC is achieved. This strategy is something of a "breadth-first"
approach, in contrast to :func:`find_germs_depthfirst`, which only looks at the
scores for one model at a time until that model achieves AC, then
turning it's attention to the remaining models.
Parameters
----------
model_list : Model or list
The model or list of `Model`s to select germs for.
germs_list : list of Circuit
The list of germs to contruct a germ set from.
randomize : bool, optional
Whether or not to randomize `model_list` (usually just a single
`Model`) with small (see `randomizationStrengh`) unitary maps
in order to avoid "accidental" symmetries which could allow for
fewer germs but *only* for that particular model. Setting this
to `True` will increase the run time by a factor equal to the
numer of randomized copies (`num_copies`).
randomization_strength : float, optional
The strength of the unitary noise used to randomize input Model(s);
is passed to :func:`~pygsti.objects.Model.randomize_with_unitary`.
num_copies : int, optional
The number of randomized models to create when only a *single* gate
set is passed via `model_list`. Otherwise, `num_copies` must be set
to `None`.
seed : int, optional
Seed for generating random unitary perturbations to models.
op_penalty : float, optional
Coefficient for a penalty linear in the sum of the germ lengths.
score_func : {'all', 'worst'}, optional
Sets the objective function for scoring the eigenvalues. If 'all',
score is ``sum(1/eigenvalues)``. If 'worst', score is
``1/min(eiganvalues)``.
tol : float, optional
Tolerance (`eps` arg) for :func:`_compute_bulk_twirled_ddd`, which sets
the differece between eigenvalues below which they're treated as
degenerate.
threshold : float, optional
Value which the score (before penalties are applied) must be lower than
for a germ set to be considered AC.
check : bool, optional
Whether to perform internal checks (will slow down run time
substantially).
force : list of Circuits
A list of `Circuit` objects which *must* be included in the final
germ set. If the special string "singletons" is given, then all of
the single gates (length-1 sequences) must be included.
pretest : boolean, optional
Whether germ list should be initially checked for completeness.
mem_limit : int, optional
A rough memory limit in bytes which restricts the amount of intermediate
values that are computed and stored.
comm : mpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation
across multiple processors.
profiler : Profiler, optional
A profiler object used for to track timing and memory usage.
verbosity : int, optional
Level of detail printed to stdout.
Returns
-------
list
A list of the built-up germ set (a list of :class:`Circuit` objects).
"""
if comm is not None and comm.Get_size() > 1:
from mpi4py import MPI # not at top so pygsti doesn't require mpi4py
printer = _baseobjs.VerbosityPrinter.create_printer(verbosity, comm)
model_list = _setup_model_list(model_list, randomize,
randomization_strength, num_copies, seed)
dim = model_list[0].dim
#Np = model_list[0].num_params #wrong:? includes spam...
Np = model_list[0].num_params
#print("DB Np = %d, Ng = %d" % (Np,Ng))
assert(all([(mdl.dim == dim) for mdl in model_list])), \
"All models must have the same dimension!"
#assert(all([(mdl.num_params == Np) for mdl in model_list])), \
# "All models must have the same number of parameters!"
(_, numGaugeParams,
numNonGaugeParams, _) = _get_model_params(model_list)
germLengths = _np.array([len(germ) for germ in germs_list], _np.int64)
numGerms = len(germs_list)
goodGerms = []
weights = _np.zeros(numGerms, _np.int64)
if force:
if force == "singletons":
weights[_np.where(germLengths == 1)] = 1
goodGerms = [germ for i, germ in enumerate(germs_list) if germLengths[i] == 1]
else: # force should be a list of Circuits
for opstr in force:
weights[germs_list.index(opstr)] = 1
goodGerms = force[:]
if pretest:
undercompleteModelNum = test_germs_list_completeness(model_list,
germs_list,
score_func,
threshold)
if undercompleteModelNum > -1:
printer.warning("Complete initial germ set FAILS on model "
+ str(undercompleteModelNum) + ".")
printer.warning("Aborting search.")
return None
printer.log("Complete initial germ set succeeds on all input models.", 1)
printer.log("Now searching for best germ set.", 1)
printer.log("Starting germ set optimization. Lower score is better.", 1)
mode = "all-Jac" # compute a all the possible germ's jacobians at once up
# front and store them separately (requires lots of mem)
if mem_limit is not None:
memEstimate = FLOATSIZE * len(model_list) * len(germs_list) * Np**2
# for _compute_bulk_twirled_ddd
memEstimate += FLOATSIZE * len(model_list) * len(germs_list) * dim**2 * Np
# for _bulk_twirled_deriv sub-call
printer.log("Memory estimate of %.1f GB (%.1f GB limit) for all-Jac mode." %
(memEstimate / 1024.0**3, mem_limit / 1024.0**3), 1)
if memEstimate > mem_limit:
mode = "single-Jac" # compute a single germ's jacobian at a time
# and store the needed J-sum over chosen germs.
memEstimate = FLOATSIZE * 3 * len(model_list) * Np**2 + \
FLOATSIZE * 3 * len(model_list) * dim**2 * Np
#Factor of 3 accounts for currentDDDs, testDDDs, and bestDDDs
printer.log("Memory estimate of %.1f GB (%.1f GB limit) for single-Jac mode." %
(memEstimate / 1024.0**3, mem_limit / 1024.0**3), 1)
if memEstimate > mem_limit:
raise MemoryError("Too little memory, even for single-Jac mode!")
twirledDerivDaggerDerivList = None
if mode == "all-Jac":
twirledDerivDaggerDerivList = \
[_compute_bulk_twirled_ddd(model, germs_list, tol,
check, germLengths, comm)
for model in model_list]
currentDDDList = []
for i, derivDaggerDeriv in enumerate(twirledDerivDaggerDerivList):
currentDDDList.append(_np.sum(derivDaggerDeriv[_np.where(weights == 1)[0], :, :], axis=0))
elif mode == "single-Jac":
currentDDDList = [_np.zeros((Np, Np), 'complex') for mdl in model_list]
loc_Indices, _, _ = _mpit.distribute_indices(
list(range(len(goodGerms))), comm, False)
with printer.progress_logging(3):
for i, goodGermIdx in enumerate(loc_Indices):
printer.show_progress(i, len(loc_Indices),
prefix="Initial germ set computation",
suffix=germs_list[goodGermIdx].str)
#print("DB: Rank%d computing initial index %d" % (comm.Get_rank(),goodGermIdx))
for k, model in enumerate(model_list):
currentDDDList[k] += _compute_twirled_ddd(
model, germs_list[goodGermIdx], tol)
#aggregate each currendDDDList across all procs
if comm is not None and comm.Get_size() > 1:
for k, model in enumerate(model_list):
result = _np.empty((Np, Np), 'complex')
comm.Allreduce(currentDDDList[k], result, op=MPI.SUM)
currentDDDList[k][:, :] = result[:, :]
result = None # free mem
else: # should be unreachable since we set 'mode' internally above
raise ValueError("Invalid mode: %s" % mode) # pragma: no cover
# Dict of keyword arguments passed to compute_score_non_AC that don't
# change from call to call
nonAC_kwargs = {
'score_fn': lambda x: _scoring.list_score(x, score_func=score_func),
'threshold_ac': threshold,
'num_gauge_params': numGaugeParams,
'op_penalty': op_penalty,
'germ_lengths': germLengths,
}
initN = 1
while _np.any(weights == 0):
printer.log("Outer iteration: %d of %d amplified, %d germs" %
(initN, numNonGaugeParams, len(goodGerms)), 2)
# As long as there are some unused germs, see if you need to add
# another one.
if initN == numNonGaugeParams:
break # We are AC for all models, so we can stop adding germs.
candidateGermIndices = _np.where(weights == 0)[0]
loc_candidateIndices, owners, _ = _mpit.distribute_indices(
candidateGermIndices, comm, False)
# Since the germs aren't sufficient, add the best single candidate germ
bestDDDs = None
bestGermScore = _scoring.CompositeScore(1.0e100, 0, None) # lower is better
iBestCandidateGerm = None
with printer.progress_logging(3):
for i, candidateGermIdx in enumerate(loc_candidateIndices):
printer.show_progress(i, len(loc_candidateIndices),
prefix="Inner iter over candidate germs",
suffix=germs_list[candidateGermIdx].str)
#print("DB: Rank%d computing index %d" % (comm.Get_rank(),candidateGermIdx))
worstScore = _scoring.CompositeScore(-1.0e100, 0, None) # worst of all models
# Loop over all models
testDDDs = []
for k, currentDDD in enumerate(currentDDDList):
testDDD = currentDDD.copy()
if mode == "all-Jac":
#just get cached value of deriv-dagger-deriv
derivDaggerDeriv = twirledDerivDaggerDerivList[k][candidateGermIdx]
testDDD += derivDaggerDeriv
elif mode == "single-Jac":
#compute value of deriv-dagger-deriv
model = model_list[k]
testDDD += _compute_twirled_ddd(
model, germs_list[candidateGermIdx], tol)
# (else already checked above)
nonAC_kwargs['germ_lengths'] = \
_np.array([len(germ) for germ in
(goodGerms + [germs_list[candidateGermIdx]])])
worstScore = max(worstScore, compute_composite_germ_set_score(
partial_deriv_dagger_deriv=testDDD[None, :, :], init_n=initN,
**nonAC_kwargs))
testDDDs.append(testDDD) # save in case this is a keeper
# Take the score for the current germ to be its worst score
# over all the models.
germScore = worstScore
printer.log(str(germScore), 4)
if germScore < bestGermScore:
bestGermScore = germScore
iBestCandidateGerm = candidateGermIdx
bestDDDs = testDDDs
testDDDs = None
# Add the germ that gives the best germ score
if comm is not None and comm.Get_size() > 1:
#figure out which processor has best germ score and distribute
# its information to the rest of the procs
globalMinScore = comm.allreduce(bestGermScore, op=MPI.MIN)
toSend = comm.Get_rank() if (globalMinScore == bestGermScore) \
else comm.Get_size() + 1
winningRank = comm.allreduce(toSend, op=MPI.MIN)
bestGermScore = globalMinScore
toCast = iBestCandidateGerm if (comm.Get_rank() == winningRank) else None
iBestCandidateGerm = comm.bcast(toCast, root=winningRank)
for k in range(len(model_list)):
comm.Bcast(bestDDDs[k], root=winningRank)
#Update variables for next outer iteration
weights[iBestCandidateGerm] = 1
initN = bestGermScore.N
goodGerms.append(germs_list[iBestCandidateGerm])
for k in range(len(model_list)):
currentDDDList[k][:, :] = bestDDDs[k][:, :]
bestDDDs[k] = None
printer.log("Added %s to final germs (%s)" %
(germs_list[iBestCandidateGerm].str, str(bestGermScore)), 3)
return goodGerms
#@profile
def find_germs_integer_slack(model_list, germs_list, randomize=True,
randomization_strength=1e-3, num_copies=None,
seed=0, l1_penalty=1e-2, op_penalty=0,
initial_weights=None, score_func='all',
max_iter=100, fixed_slack=False,
slack_frac=False, return_all=False, tol=1e-6,
check=False, force="singletons",
force_score=1e100, threshold=1e6,
verbosity=1):
"""
Find a locally optimal subset of the germs in germs_list.
Locally optimal here means that no single germ can be excluded
without making the smallest non-gauge eigenvalue of the
Jacobian.H*Jacobian matrix smaller, i.e. less amplified,
by more than a fixed or variable amount of "slack", as
specified by `fixed_slack` or `slack_frac`.
Parameters
----------
model_list : Model or list of Model
The list of Models to be tested. To ensure that the returned germ
set is amplficationally complete, it is a good idea to score potential
germ sets against a collection (~5-10) of similar models. The user
may specify a single Model and a number of unitarily close copies to
be made (set by the kwarg `num_copies`), or the user may specify their
own list of Models, each of which in turn may or may not be
randomized (set by the kwarg `randomize`).
germs_list : list of Circuit
List of all germ circuits to consider.
randomize : Bool, optional
Whether or not the input Model(s) are first subject to unitary
randomization. If ``False``, the user should perform the unitary
randomization themselves. Note: If the Model(s) are perfect (e.g.
``std1Q_XYI.target_model()``), then the germ selection output should not be
trusted, due to accidental degeneracies in the Model. If the
Model(s) include stochastic (non-unitary) error, then germ selection
will fail, as we score amplificational completeness in the limit of
infinite sequence length (so any stochastic noise will completely
depolarize any sequence in that limit). Default is ``True``.
randomization_strength : float, optional
The strength of the unitary noise used to randomize input Model(s);
is passed to :func:`~pygsti.objects.Model.randomize_with_unitary`.
Default is ``1e-3``.
num_copies : int, optional
The number of Model copies to be made of the input Model (prior to
unitary randomization). If more than one Model is passed in,
`num_copies` should be ``None``. If only one Model is passed in and
`num_copies` is ``None``, no extra copies are made.
seed : float, optional
The starting seed used for unitary randomization. If multiple Models
are to be randomized, ``model_list[i]`` is randomized with ``seed +
i``. Default is 0.
l1_penalty : float, optional
How strong the penalty should be for increasing the germ set list by a
single germ. Default is 1e-2.
op_penalty : float, optional
How strong the penalty should be for increasing a germ in the germ set
list by a single gate. Default is 0.
initial_weights : list-like
List or array of either booleans or (0 or 1) integers
specifying which germs in `germ_list` comprise the initial
germ set. If ``None``, then starting point includes all
germs.
score_func : string
Label to indicate how a germ set is scored. See
:func:`~pygsti.algorithms.scoring.list_score` for details.
max_iter : int, optional
The maximum number of iterations before giving up.
fixed_slack : float, optional
If not ``None``, a floating point number which specifies that excluding
a germ is allowed to increase 1.0/smallest-non-gauge-eigenvalue by
`fixed_slack`. You must specify *either* `fixed_slack` or `slack_frac`.
slack_frac : float, optional
If not ``None``, a floating point number which specifies that excluding
a germ is allowed to increase 1.0/smallest-non-gauge-eigenvalue by
`fixedFrac`*100 percent. You must specify *either* `fixed_slack` or
`slack_frac`.
return_all : bool, optional
If ``True``, return the final ``weights`` vector and score dictionary
in addition to the optimal germ list (see below).
tol : float, optional
Tolerance used for eigenvector degeneracy testing in twirling
operation.
check : bool, optional
Whether to perform internal consistency checks, at the
expense of making the function slower.
force : str or list, optional
A list of Circuits which *must* be included in the final germ set.
If set to the special string "singletons" then all length-1 strings will
be included. Seting to None is the same as an empty list.
force_score : float, optional (default is 1e100)
When `force` designates a non-empty set of circuits, the score to
assign any germ set that does not contain each and every required germ.
threshold : float, optional (default is 1e6)
Specifies a maximum score for the score matrix, above which the germ
set is rejected as amplificationally incomplete.
verbosity : int, optional
Integer >= 0 indicating the amount of detail to print.
See Also
--------
:class:`~pygsti.objects.Model`
:class:`~pygsti.objects.Circuit`
"""
printer = _baseobjs.VerbosityPrinter.create_printer(verbosity)
model_list = _setup_model_list(model_list, randomize,
randomization_strength, num_copies, seed)
if (fixed_slack and slack_frac) or (not fixed_slack and not slack_frac):
raise ValueError("Either fixed_slack *or* slack_frac should be specified")
if initial_weights is not None:
if len(germs_list) != len(initial_weights):
raise ValueError("The lengths of germs_list (%d) and "
"initial_weights (%d) must match."
% (len(germs_list), len(initial_weights)))
# Normalize the weights array to be 0s and 1s even if it is provided as
# bools
weights = _np.array([1 if x else 0 for x in initial_weights])
else:
weights = _np.ones(len(germs_list), _np.int64) # default: start with all germs
# lessWeightOnly = True # we're starting at the max-weight vector
undercompleteModelNum = test_germs_list_completeness(model_list,
germs_list, score_func,
threshold)
if undercompleteModelNum > -1:
printer.log("Complete initial germ set FAILS on model "
+ str(undercompleteModelNum) + ".", 1)
printer.log("Aborting search.", 1)
return (None, None, None) if return_all else None
printer.log("Complete initial germ set succeeds on all input models.", 1)
printer.log("Now searching for best germ set.", 1)
num_models = len(model_list)
# Remove any SPAM vectors from model since we only want
# to consider the set of *gate* parameters for amplification
# and this makes sure our parameter counting is correct
model0 = _remove_spam_vectors(model_list[0])
# Initially allow adding to weight. -- maybe make this an argument??
lessWeightOnly = False
nGaugeParams = model0.num_gauge_params
# score dictionary:
# keys = (modelNum, tuple-ized weight vector of 1's and 0's only)
# values = list_score
scoreD = {}
germLengths = _np.array([len(germ) for germ in germs_list], _np.int64)
if force:
if force == "singletons":
forceIndices = _np.where(germLengths == 1)
else: # force should be a list of Circuits
forceIndices = _np.array([germs_list.index(opstr) for opstr in force])
else:
forceIndices = None
twirledDerivDaggerDerivList = [_compute_bulk_twirled_ddd(model, germs_list, tol)
for model in model_list]
# Dict of keyword arguments passed to _germ_set_score_slack that don't change from
# call to call
cs_kwargs = {
'score_func': score_func,
'deriv_dagger_deriv_list': twirledDerivDaggerDerivList,
'force_indices': forceIndices,
'force_score': force_score,
'n_gauge_params': nGaugeParams,
'op_penalty': op_penalty,
'germ_lengths': germLengths,
'l1_penalty': l1_penalty,
'score_dict': scoreD,
}
scoreList = [_germ_set_score_slack(weights, model_num, **cs_kwargs)
for model_num in range(num_models)]
score = _np.max(scoreList)
L1 = sum(weights) # ~ L1 norm of weights
printer.log("Starting germ set optimization. Lower score is better.", 1)
printer.log("Model has %d gauge params." % nGaugeParams, 1)
def _get_neighbors(bool_vec):
for i in range(len(bool_vec)):
v = bool_vec.copy()
v[i] = (v[i] + 1) % 2 # Toggle v[i] btwn 0 and 1
yield v
with printer.progress_logging(1):
for iIter in range(max_iter):
printer.show_progress(iIter, max_iter,
suffix="score=%g, nGerms=%d" % (score, L1))
bFoundBetterNeighbor = False
for neighbor in _get_neighbors(weights):
neighborScoreList = []
for model_num in range(len(model_list)):
if (model_num, tuple(neighbor)) not in scoreD:
neighborL1 = sum(neighbor)
neighborScoreList.append(_germ_set_score_slack(neighbor,
model_num,
**cs_kwargs))
else:
neighborL1 = sum(neighbor)
neighborScoreList.append(scoreD[model_num,
tuple(neighbor)])
neighborScore = _np.max(neighborScoreList) # Take worst case.
# Move if we've found better position; if we've relaxed, we
# only move when L1 is improved.
if neighborScore <= score and (neighborL1 < L1 or not lessWeightOnly):
weights, score, L1 = neighbor, neighborScore, neighborL1
bFoundBetterNeighbor = True
printer.log("Found better neighbor: "
"nGerms = %d score = %g" % (L1, score), 2)
if not bFoundBetterNeighbor: # Time to relax our search.
# From now on, don't allow increasing weight L1
lessWeightOnly = True
if fixed_slack is False:
# Note score is positive (for sum of 1/lambda)
slack = score * slack_frac
# print "slack =", slack
else:
slack = fixed_slack
assert slack > 0
printer.log("No better neighbor. Relaxing score w/slack: "
+ "%g => %g" % (score, score + slack), 2)
# Artificially increase score and see if any neighbor is better
# now...
score += slack
for neighbor in _get_neighbors(weights):
scoreList = [scoreD[model_num, tuple(neighbor)]
for model_num in range(len(model_list))]
maxScore = _np.max(scoreList)
if sum(neighbor) < L1 and maxScore < score:
weights, score, L1 = neighbor, maxScore, sum(neighbor)
bFoundBetterNeighbor = True
printer.log("Found better neighbor: "
"nGerms = %d score = %g" % (L1, score), 2)
if not bFoundBetterNeighbor: # Relaxing didn't help!
printer.log("Stationary point found!", 1)
break # end main for loop
printer.log("Moving to better neighbor", 1)
# print score
else:
printer.log("Hit max. iterations", 1)
printer.log("score = %s" % score, 1)
printer.log("weights = %s" % weights, 1)
printer.log("L1(weights) = %s" % sum(weights), 1)
goodGerms = []
for index, val in enumerate(weights):
if val == 1:
goodGerms.append(germs_list[index])
if return_all:
return goodGerms, weights, scoreD
else:
return goodGerms
def _germ_set_score_grasp(germ_set, germs_list, twirled_deriv_dagger_deriv_list,
non_ac_kwargs, init_n=1):
"""
Score a germ set against a collection of models.
Calculate the score of the germ set with respect to each member of a
collection of models and return the worst score among that collection.
Parameters
----------
germ_set : list of Circuit
The set of germs to score.
germs_list : list of Circuit
The list of all germs whose Jacobians are provided in
`twirled_deriv_dagger_deriv_list`.
twirled_deriv_dagger_deriv_list : numpy.array
Jacobians for all the germs in `germs_list` stored as a 3-dimensional
array, where the first index indexes the particular germ.
non_ac_kwargs : dict
Dictionary containing further arguments to pass to
:func:`compute_composite_germ_set_score` for the scoring of the germ set against
individual models.
init_n : int
The number of eigenvalues to begin checking for amplificational
completeness with respect to. Passed as an argument to
:func:`compute_composite_germ_set_score`.
Returns
-------
CompositeScore
The worst score over all models of the germ set.
"""
weights = _np.zeros(len(germs_list))
for germ in germ_set:
weights[germs_list.index(germ)] = 1
germsVsModelScores = []
for derivDaggerDeriv in twirled_deriv_dagger_deriv_list:
# Loop over all models
partialDDD = derivDaggerDeriv[_np.where(weights == 1)[0], :, :]
germsVsModelScores.append(compute_composite_germ_set_score(
partial_deriv_dagger_deriv=partialDDD, init_n=init_n, **non_ac_kwargs))
# Take the score for the current germ set to be its worst score over all
# models.
return max(germsVsModelScores)
def find_germs_grasp(model_list, germs_list, alpha, randomize=True,
randomization_strength=1e-3, num_copies=None,
seed=None, l1_penalty=1e-2, op_penalty=0.0,
score_func='all', tol=1e-6, threshold=1e6,
check=False, force="singletons",
iterations=5, return_all=False, shuffle=False,
verbosity=0):
"""
Use GRASP to find a high-performing germ set.
Parameters
----------
model_list : Model or list of Model
The list of Models to be tested. To ensure that the returned germ
set is amplficationally complete, it is a good idea to score potential
germ sets against a collection (~5-10) of similar models. The user
may specify a single Model and a number of unitarily close copies to
be made (set by the kwarg `num_copies`, or the user may specify their
own list of Models, each of which in turn may or may not be
randomized (set by the kwarg `randomize`).
germs_list : list of Circuit
List of all germ circuits to consider.
alpha : float
A number between 0 and 1 that roughly specifies a score theshold
relative to the spread of scores that a germ must score better than in
order to be included in the RCL. A value of 0 for `alpha` corresponds
to a purely greedy algorithm (only the best-scoring germ set is
included in the RCL), while a value of 1 for `alpha` will include all
germs in the RCL.
See :func:`pygsti.algorithms.scoring.filter_composite_rcl` for more details.
randomize : Bool, optional
Whether or not the input Model(s) are first subject to unitary
randomization. If ``False``, the user should perform the unitary
randomization themselves. Note: If the Model(s) are perfect (e.g.
``std1Q_XYI.target_model()``), then the germ selection output should not be
trusted, due to accidental degeneracies in the Model. If the
Model(s) include stochastic (non-unitary) error, then germ selection
will fail, as we score amplificational completeness in the limit of
infinite sequence length (so any stochastic noise will completely
depolarize any sequence in that limit).
randomization_strength : float, optional
The strength of the unitary noise used to randomize input Model(s);
is passed to :func:`~pygsti.objects.Model.randomize_with_unitary`.
Default is ``1e-3``.
num_copies : int, optional
The number of Model copies to be made of the input Model (prior to
unitary randomization). If more than one Model is passed in,
`num_copies` should be ``None``. If only one Model is passed in and
`num_copies` is ``None``, no extra copies are made.
seed : float, optional
The starting seed used for unitary randomization. If multiple Models
are to be randomized, ``model_list[i]`` is randomized with ``seed +
i``.
l1_penalty : float, optional
How strong the penalty should be for increasing the germ set list by a
single germ. Used for choosing between outputs of various GRASP
iterations.
op_penalty : float, optional
How strong the penalty should be for increasing a germ in the germ set
list by a single gate.
score_func : string
Label to indicate how a germ set is scored. See
:func:`~pygsti.algorithms.scoring.list_score` for details.
tol : float, optional
Tolerance used for eigenvector degeneracy testing in twirling
operation.
threshold : float, optional (default is 1e6)
Specifies a maximum score for the score matrix, above which the germ
set is rejected as amplificationally incomplete.
check : bool, optional
Whether to perform internal consistency checks, at the
expense of making the function slower.
force : str or list, optional
A list of Circuits which *must* be included in the final germ set.
If set to the special string "singletons" then all length-1 strings will
be included. Seting to None is the same as an empty list.
iterations : int, optional
The number of GRASP iterations to perform.
return_all : bool, optional
Flag set to tell the routine if it should return lists of all
initial constructions and local optimizations in addition to the
optimal solution (useful for diagnostic purposes or if you're not sure
what your `finalScoreFn` should really be).
shuffle : bool, optional
Whether the neighborhood should be presented to the optimizer in a
random order (important since currently the local optimizer updates the
solution to the first better solution it finds in the neighborhood).
verbosity : int, optional
Integer >= 0 indicating the amount of detail to print.
Returns
-------
finalGermList : list of Circuit
Sublist of `germs_list` specifying the final, optimal set of germs.
"""
printer = _baseobjs.VerbosityPrinter.create_printer(verbosity)
model_list = _setup_model_list(model_list, randomize,
randomization_strength, num_copies, seed)
(_, numGaugeParams,
numNonGaugeParams, _) = _get_model_params(model_list)
germLengths = _np.array([len(germ) for germ in germs_list], _np.int64)
numGerms = len(germs_list)
initialWeights = _np.zeros(numGerms, dtype=_np.int64)
if force:
if force == "singletons":
initialWeights[_np.where(germLengths == 1)] = 1
else: # force should be a list of Circuits
for opstr in force:
initialWeights[germs_list.index(opstr)] = 1
def get_neighbors_fn(weights): return _grasp.get_swap_neighbors(
weights, forced_weights=initialWeights, shuffle=shuffle)
undercompleteModelNum = test_germs_list_completeness(model_list,
germs_list,
score_func,
threshold)
if undercompleteModelNum > -1:
printer.warning("Complete initial germ set FAILS on model "
+ str(undercompleteModelNum) + ".")
printer.warning("Aborting search.")
return (None, None, None) if return_all else None
printer.log("Complete initial germ set succeeds on all input models.", 1)
printer.log("Now searching for best germ set.", 1)
printer.log("Starting germ set optimization. Lower score is better.", 1)
twirledDerivDaggerDerivList = [_compute_bulk_twirled_ddd(model, germs_list, tol,
check, germLengths)
for model in model_list]
# Dict of keyword arguments passed to compute_score_non_AC that don't
# change from call to call
nonAC_kwargs = {
'score_fn': lambda x: _scoring.list_score(x, score_func=score_func),
'threshold_ac': threshold,
'num_gauge_params': numGaugeParams,
'op_penalty': op_penalty,
'germ_lengths': germLengths,
}
final_nonAC_kwargs = nonAC_kwargs.copy()
final_nonAC_kwargs['l1_penalty'] = l1_penalty
scoreFn = (lambda germSet:
_germ_set_score_grasp(germSet, germs_list,
twirledDerivDaggerDerivList, nonAC_kwargs,
init_n=1))
finalScoreFn = (lambda germSet:
_germ_set_score_grasp(germSet, germs_list,
twirledDerivDaggerDerivList,
final_nonAC_kwargs, init_n=1))
#OLD: feasibleThreshold = _scoring.CompositeScore(-numNonGaugeParams,threshold,numNonGaugeParams))
def _feasible_fn(germ_set): # now that scoring is not ordered entirely by N
s = _germ_set_score_grasp(germ_set, germs_list,
twirledDerivDaggerDerivList, nonAC_kwargs,
init_n=1)
return (s.N >= numNonGaugeParams and s.minor < threshold)
def rcl_fn(x): return _scoring.filter_composite_rcl(x, alpha)
initialSolns = []
localSolns = []
for iteration in range(iterations):
# This loop is parallelizable (each iteration is independent of all
# other iterations).
printer.log('Starting iteration {} of {}.'.format(iteration + 1,
iterations), 1)
success = False
failCount = 0
while not success and failCount < 10:
try:
iterSolns = _grasp.run_grasp_iteration(
elements=germs_list, greedy_score_fn=scoreFn, rcl_fn=rcl_fn,
local_score_fn=scoreFn,
get_neighbors_fn=get_neighbors_fn,
feasible_fn=_feasible_fn,
initial_elements=initialWeights, seed=seed,
verbosity=verbosity)
initialSolns.append(iterSolns[0])
localSolns.append(iterSolns[1])
success = True
printer.log('Finished iteration {} of {}.'.format(
iteration + 1, iterations), 1)
except Exception as e:
failCount += 1
raise e if (failCount == 10) else printer.warning(e)
finalScores = _np.array([finalScoreFn(localSoln)
for localSoln in localSolns])
bestSoln = localSolns[_np.argmin(finalScores)]
return (bestSoln, initialSolns, localSolns) if return_all else bestSoln
| 42.064798 | 114 | 0.631641 |
import warnings as _warnings
import numpy as _np
import numpy.linalg as _nla
from pygsti.algorithms import grasp as _grasp
from pygsti.algorithms import scoring as _scoring
from pygsti import circuits as _circuits
from pygsti import baseobjs as _baseobjs
from pygsti.tools import mpitools as _mpit
FLOATSIZE = 8
def find_germs(target_model, randomize=True, randomization_strength=1e-2,
num_gs_copies=5, seed=None, candidate_germ_counts=None,
candidate_seed=None, force="singletons", algorithm='greedy',
algorithm_kwargs=None, mem_limit=None, comm=None,
profiler=None, verbosity=1):
printer = _baseobjs.VerbosityPrinter.create_printer(verbosity, comm)
modelList = _setup_model_list(target_model, randomize,
randomization_strength, num_gs_copies, seed)
gates = list(target_model.operations.keys())
availableGermsList = []
if candidate_germ_counts is None: candidate_germ_counts = {6: 'all upto'}
for germLength, count in candidate_germ_counts.items():
if count == "all upto":
availableGermsList.extend(_circuits.list_all_circuits_without_powers_and_cycles(
gates, max_length=germLength))
else:
seed = None if candidate_seed is None else candidate_seed + germLength
availableGermsList.extend(_circuits.list_random_circuits_onelen(
gates, germLength, count, seed=seed))
if algorithm_kwargs is None:
algorithm_kwargs = {}
if algorithm == 'greedy':
printer.log('Using greedy algorithm.', 1)
default_kwargs = {
'germs_list': availableGermsList,
'randomize': False,
'seed': seed,
'verbosity': max(0, verbosity - 1),
'force': force,
'score_func': 'all',
'comm': comm,
'mem_limit': mem_limit,
'profiler': profiler
}
for key in default_kwargs:
if key not in algorithm_kwargs:
algorithm_kwargs[key] = default_kwargs[key]
germList = find_germs_breadthfirst(model_list=modelList,
**algorithm_kwargs)
if germList is not None:
germsetScore = compute_germ_set_score(
germList, neighborhood=modelList,
score_func=algorithm_kwargs['score_func'])
printer.log('Constructed germ set:', 1)
printer.log(str([germ.str for germ in germList]), 1)
printer.log('Score: {}'.format(germsetScore), 1)
elif algorithm == 'grasp':
printer.log('Using GRASP algorithm.', 1)
default_kwargs = {
'alpha': 0.1,
'germs_list': availableGermsList,
'randomize': False,
'seed': seed,
'verbosity': max(0, verbosity - 1),
'force': force,
'return_all': False,
'score_func': 'all',
}
for key in default_kwargs:
if key not in algorithm_kwargs:
algorithm_kwargs[key] = default_kwargs[key]
germList = find_germs_grasp(model_list=modelList,
**algorithm_kwargs)
printer.log('Constructed germ set:', 1)
if algorithm_kwargs['return_all'] and germList[0] is not None:
germsetScore = compute_germ_set_score(
germList[0], neighborhood=modelList,
score_func=algorithm_kwargs['score_func'])
printer.log(str([germ.str for germ in germList[0]]), 1)
printer.log('Score: {}'.format(germsetScore))
elif not algorithm_kwargs['return_all'] and germList is not None:
germsetScore = compute_germ_set_score(germList,
neighborhood=modelList)
printer.log(str([germ.str for germ in germList]), 1)
printer.log('Score: {}'.format(germsetScore), 1)
elif algorithm == 'slack':
printer.log('Using slack algorithm.', 1)
default_kwargs = {
'germs_list': availableGermsList,
'randomize': False,
'seed': seed,
'verbosity': max(0, verbosity - 1),
'force': force,
'score_func': 'all',
}
if ('slack_frac' not in algorithm_kwargs
and 'fixed_slack' not in algorithm_kwargs):
algorithm_kwargs['slack_frac'] = 0.1
for key in default_kwargs:
if key not in algorithm_kwargs:
algorithm_kwargs[key] = default_kwargs[key]
germList = find_germs_integer_slack(modelList,
**algorithm_kwargs)
if germList is not None:
germsetScore = compute_germ_set_score(
germList, neighborhood=modelList,
score_func=algorithm_kwargs['score_func'])
printer.log('Constructed germ set:', 1)
printer.log(str([germ.str for germ in germList]), 1)
printer.log('Score: {}'.format(germsetScore), 1)
else:
raise ValueError("'{}' is not a valid algorithm "
"identifier.".format(algorithm))
return germList
def compute_germ_set_score(germs, target_model=None, neighborhood=None,
neighborhood_size=5,
randomization_strength=1e-2, score_func='all',
op_penalty=0.0, l1_penalty=0.0):
def score_fn(x): return _scoring.list_score(x, score_func=score_func)
if neighborhood is None:
neighborhood = [target_model.randomize_with_unitary(randomization_strength)
for n in range(neighborhood_size)]
scores = [compute_composite_germ_set_score(score_fn, model=model,
partial_germs_list=germs,
op_penalty=op_penalty,
l1_penalty=l1_penalty)
for model in neighborhood]
return max(scores)
def _get_model_params(model_list):
reducedModelList = [_remove_spam_vectors(model)
for model in model_list]
numGaugeParamsList = [reducedModel.num_gauge_params
for reducedModel in reducedModelList]
numGaugeParams = numGaugeParamsList[0]
if not all([numGaugeParams == otherNumGaugeParams
for otherNumGaugeParams in numGaugeParamsList[1:]]):
raise ValueError("All models must have the same number of gauge "
"parameters!")
numNonGaugeParamsList = [reducedModel.num_nongauge_params
for reducedModel in reducedModelList]
numNonGaugeParams = numNonGaugeParamsList[0]
if not all([numNonGaugeParams == otherNumNonGaugeParams
for otherNumNonGaugeParams in numNonGaugeParamsList[1:]]):
raise ValueError("All models must have the same number of non-gauge "
"parameters!")
numOpsList = [len(reducedModel.operations)
for reducedModel in reducedModelList]
numOps = numOpsList[0]
if not all([numOps == otherNumOps
for otherNumOps in numOpsList[1:]]):
raise ValueError("All models must have the same number of gates!")
return reducedModelList, numGaugeParams, numNonGaugeParams, numOps
def _setup_model_list(model_list, randomize, randomization_strength,
num_copies, seed):
if not isinstance(model_list, (list, tuple)):
model_list = [model_list]
if len(model_list) > 1 and num_copies is not None:
_warnings.warn("Ignoring num_copies={} since multiple models were "
"supplied.".format(num_copies))
if randomize:
model_list = randomize_model_list(model_list, randomization_strength,
num_copies, seed)
return model_list
def compute_composite_germ_set_score(score_fn, threshold_ac=1e6, init_n=1,
partial_deriv_dagger_deriv=None, model=None,
partial_germs_list=None, eps=None, num_gauge_params=None,
op_penalty=0.0, germ_lengths=None, l1_penalty=0.0):
if partial_deriv_dagger_deriv is None:
if model is None or partial_germs_list is None:
raise ValueError("Must provide either partial_deriv_dagger_deriv or "
"(model, partial_germs_list)!")
else:
pDDD_kwargs = {'model': model, 'germs_list': partial_germs_list}
if eps is not None:
pDDD_kwargs['eps'] = eps
if germ_lengths is not None:
pDDD_kwargs['germ_lengths'] = germ_lengths
partial_deriv_dagger_deriv = _compute_bulk_twirled_ddd(**pDDD_kwargs)
if num_gauge_params is None:
if model is None:
raise ValueError("Must provide either num_gauge_params or model!")
else:
num_gauge_params = _remove_spam_vectors(model).num_gauge_params
# Calculate penalty scores
numGerms = partial_deriv_dagger_deriv.shape[0]
l1Score = l1_penalty * numGerms
opScore = 0.0
if op_penalty != 0.0:
if germ_lengths is None:
if partial_germs_list is None:
raise ValueError("Must provide either germ_lengths or "
"partial_germs_list when op_penalty != 0.0!")
else:
germ_lengths = _np.array([len(germ)
for germ in partial_germs_list])
opScore = op_penalty * _np.sum(germ_lengths)
combinedDDD = _np.sum(partial_deriv_dagger_deriv, axis=0)
sortedEigenvals = _np.sort(_np.real(_nla.eigvalsh(combinedDDD)))
observableEigenvals = sortedEigenvals[num_gauge_params:]
N_AC = 0
AC_score = _np.inf
for N in range(init_n, len(observableEigenvals) + 1):
scoredEigenvals = observableEigenvals[-N:]
candidate_AC_score = score_fn(scoredEigenvals)
if candidate_AC_score > threshold_ac:
break # We've found a set of parameters for which the germ set
else:
AC_score = candidate_AC_score
N_AC = N
major_score = -N_AC + opScore + l1Score
minor_score = AC_score
ret = _scoring.CompositeScore(major_score, minor_score, N_AC)
return ret
def _compute_bulk_twirled_ddd(model, germs_list, eps=1e-6, check=False,
germ_lengths=None, comm=None):
if germ_lengths is None:
germ_lengths = _np.array([len(germ) for germ in germs_list])
twirledDeriv = _bulk_twirled_deriv(model, germs_list, eps, check, comm) / germ_lengths[:, None, None]
nGerms, _, vec_model_dim = twirledDeriv.shape
twirledDerivDaggerDeriv = _np.empty((nGerms, vec_model_dim, vec_model_dim),
dtype=_np.complex)
for i in range(nGerms):
twirledDerivDaggerDeriv[i, :, :] = _np.dot(
twirledDeriv[i, :, :].conjugate().T, twirledDeriv[i, :, :])
return twirledDerivDaggerDeriv
def _compute_twirled_ddd(model, germ, eps=1e-6):
twirledDeriv = _twirled_deriv(model, germ, eps) / len(germ)
twirledDerivDaggerDeriv = _np.tensordot(_np.conjugate(twirledDeriv),
twirledDeriv, (0, 0))
return twirledDerivDaggerDeriv
def _germ_set_score_slack(weights, model_num, score_func, deriv_dagger_deriv_list,
force_indices, force_score,
n_gauge_params, op_penalty, germ_lengths, l1_penalty=1e-2,
score_dict=None):
if force_indices is not None and _np.any(weights[force_indices] <= 0):
score = force_score
else:
combinedDDD = _np.squeeze(
_np.tensordot(_np.expand_dims(weights, 1),
deriv_dagger_deriv_list[model_num], (0, 0)))
assert len(combinedDDD.shape) == 2
sortedEigenvals = _np.sort(_np.real(_nla.eigvalsh(combinedDDD)))
observableEigenvals = sortedEigenvals[n_gauge_params:]
score = (_scoring.list_score(observableEigenvals, score_func)
+ l1_penalty * _np.sum(weights)
+ op_penalty * _np.dot(germ_lengths, weights))
if score_dict is not None:
score_dict[model_num, tuple(weights)] = score
return score
def randomize_model_list(model_list, randomization_strength, num_copies,
seed=None):
if len(model_list) > 1 and num_copies is not None:
raise ValueError("Input multiple models XOR request multiple "
"copies only!")
newmodelList = []
if len(model_list) > 1:
for modelnum, model in enumerate(model_list):
newmodelList.append(model.randomize_with_unitary(
randomization_strength,
seed=None if seed is None else seed + modelnum))
else:
for modelnum in range(num_copies if num_copies is not None else 1):
newmodelList.append(model_list[0].randomize_with_unitary(
randomization_strength,
seed=None if seed is None else seed + modelnum))
return newmodelList
def test_germs_list_completeness(model_list, germs_list, score_func, threshold):
for modelNum, model in enumerate(model_list):
initial_test = test_germ_set_infl(model, germs_list,
score_func=score_func,
threshold=threshold)
if not initial_test:
return modelNum
return -1
def _remove_spam_vectors(model):
reducedModel = model.copy()
for prepLabel in list(reducedModel.preps.keys()):
del reducedModel.preps[prepLabel]
for povmLabel in list(reducedModel.povms.keys()):
del reducedModel.povms[povmLabel]
return reducedModel
def _num_non_spam_gauge_params(model):
return _remove_spam_vectors(model).num_gauge_params
def _super_op_for_perfect_twirl(wrt, eps):
assert wrt.shape[0] == wrt.shape[1]
dim = wrt.shape[0]
SuperOp = _np.zeros((dim**2, dim**2), 'complex')
wrtEvals, wrtEvecs = _np.linalg.eig(wrt)
wrtEvecsInv = _np.linalg.inv(wrtEvecs)
for i in range(dim):
Proj_i = _np.diag([(1 if (abs(wrtEvals[i] - wrtEvals[j]) <= eps)
else 0) for j in range(dim)])
A = _np.dot(wrtEvecs, _np.dot(Proj_i, wrtEvecsInv))
SuperOp += _np.kron(A, A.T) / _np.trace(Proj_i)
x op_dim^2 matrix
def _sq_sing_vals_from_deriv(deriv, weights=None):
# shape (nGerms, vec_model_dim, vec_model_dim)
derivDaggerDeriv = _np.einsum('ijk,ijl->ikl', _np.conjugate(deriv), deriv)
# awkward to convert to tensordot, so leave as einsum
# Take the average of the D^dagger*D/L^2 matrices associated with each germ
# with optional weights.
combinedDDD = _np.average(derivDaggerDeriv, weights=weights, axis=0)
sortedEigenvals = _np.sort(_np.real(_nla.eigvalsh(combinedDDD)))
return sortedEigenvals
def _twirled_deriv(model, circuit, eps=1e-6):
prod = model.sim.product(circuit)
# flattened_op_dim x vec_model_dim
dProd = model.sim.dproduct(circuit, flat=True)
# flattened_op_dim x flattened_op_dim
twirler = _super_op_for_perfect_twirl(prod, eps)
# flattened_op_dim x vec_model_dim
return _np.dot(twirler, dProd)
def _bulk_twirled_deriv(model, circuits, eps=1e-6, check=False, comm=None):
if len(model.preps) > 0 or len(model.povms) > 0:
model = _remove_spam_vectors(model)
# This function assumes model has no spam elements so `lookup` below
# gives indexes into products computed by evalTree.
resource_alloc = _baseobjs.ResourceAllocation(comm=comm)
dProds, prods = model.sim.bulk_dproduct(circuits, flat=True, return_prods=True, resource_alloc=resource_alloc)
op_dim = model.dim
fd = op_dim**2 # flattened gate dimension
nCircuits = len(circuits)
ret = _np.empty((nCircuits, fd, dProds.shape[1]), 'complex')
for i in range(nCircuits):
# flattened_op_dim x flattened_op_dim
twirler = _super_op_for_perfect_twirl(prods[i], eps)
# flattened_op_dim x vec_model_dim
ret[i] = _np.dot(twirler, dProds[i * fd:(i + 1) * fd])
if check:
for i, circuit in enumerate(circuits):
chk_ret = _twirled_deriv(model, circuit, eps)
if _nla.norm(ret[i] - chk_ret) > 1e-6:
_warnings.warn("bulk twirled derivative norm mismatch = "
"%g - %g = %g"
% (_nla.norm(ret[i]), _nla.norm(chk_ret),
_nla.norm(ret[i] - chk_ret))) # pragma: no cover
return ret # nSimplifiedCircuits x flattened_op_dim x vec_model_dim
def test_germ_set_finitel(model, germs_to_test, length, weights=None,
return_spectrum=False, tol=1e-6):
# Remove any SPAM vectors from model since we only want
# to consider the set of *gate* parameters for amplification
# and this makes sure our parameter counting is correct
model = _remove_spam_vectors(model)
nGerms = len(germs_to_test)
germToPowL = [germ * length for germ in germs_to_test]
op_dim = model.dim
dprods = model.sim.bulk_dproduct(germToPowL, flat=True) # shape (nGerms*flattened_op_dim, vec_model_dim)
dprods.shape = (nGerms, op_dim**2, dprods.shape[1])
germLengths = _np.array([len(germ) for germ in germs_to_test], 'd')
normalizedDeriv = dprods / (length * germLengths[:, None, None])
sortedEigenvals = _sq_sing_vals_from_deriv(normalizedDeriv, weights)
nGaugeParams = model.num_gauge_params
observableEigenvals = sortedEigenvals[nGaugeParams:]
bSuccess = bool(_scoring.list_score(observableEigenvals, 'worst') < 1 / tol)
return (bSuccess, sortedEigenvals) if return_spectrum else bSuccess
def test_germ_set_infl(model, germs_to_test, score_func='all', weights=None,
return_spectrum=False, threshold=1e6, check=False):
# Remove any SPAM vectors from model since we only want
# to consider the set of *gate* parameters for amplification
# and this makes sure our parameter counting is correct
model = _remove_spam_vectors(model)
germLengths = _np.array([len(germ) for germ in germs_to_test], _np.int64)
twirledDerivDaggerDeriv = _compute_bulk_twirled_ddd(model, germs_to_test,
1. / threshold, check,
germLengths)
# result[i] = _np.dot( twirledDeriv[i].H, twirledDeriv[i] ) i.e. matrix
# product
# result[i,k,l] = sum_j twirledDerivH[i,k,j] * twirledDeriv(i,j,l)
# result[i,k,l] = sum_j twirledDeriv_conj[i,j,k] * twirledDeriv(i,j,l)
if weights is None:
nGerms = len(germs_to_test)
# weights = _np.array( [1.0/nGerms]*nGerms, 'd')
weights = _np.array([1.0] * nGerms, 'd')
#combinedTDDD = _np.einsum('i,ijk->jk', weights, twirledDerivDaggerDeriv)
combinedTDDD = _np.tensordot(weights, twirledDerivDaggerDeriv, (0, 0))
sortedEigenvals = _np.sort(_np.real(_np.linalg.eigvalsh(combinedTDDD)))
nGaugeParams = model.num_gauge_params
observableEigenvals = sortedEigenvals[nGaugeParams:]
bSuccess = bool(_scoring.list_score(observableEigenvals, score_func)
< threshold)
return (bSuccess, sortedEigenvals) if return_spectrum else bSuccess
def find_germs_depthfirst(model_list, germs_list, randomize=True,
randomization_strength=1e-3, num_copies=None, seed=0, op_penalty=0,
score_func='all', tol=1e-6, threshold=1e6, check=False,
force="singletons", verbosity=0):
printer = _baseobjs.VerbosityPrinter.create_printer(verbosity)
model_list = _setup_model_list(model_list, randomize,
randomization_strength, num_copies, seed)
(reducedModelList,
numGaugeParams, _, _) = _get_model_params(model_list)
germLengths = _np.array([len(germ) for germ in germs_list], _np.int64)
numGerms = len(germs_list)
weights = _np.zeros(numGerms, _np.int64)
goodGerms = []
if force:
if force == "singletons":
weights[_np.where(germLengths == 1)] = 1
goodGerms = [germ for germ
in _np.array(germs_list)[_np.where(germLengths == 1)]]
else: # force should be a list of Circuits
for opstr in force:
weights[germs_list.index(opstr)] = 1
goodGerms = force[:]
undercompleteModelNum = test_germs_list_completeness(model_list,
germs_list,
score_func,
threshold)
if undercompleteModelNum > -1:
printer.warning("Complete initial germ set FAILS on model "
+ str(undercompleteModelNum) + ". Aborting search.")
return None
printer.log("Complete initial germ set succeeds on all input models.", 1)
printer.log("Now searching for best germ set.", 1)
printer.log("Starting germ set optimization. Lower score is better.", 1)
twirledDerivDaggerDerivList = [_compute_bulk_twirled_ddd(model, germs_list, tol,
check, germLengths)
for model in model_list]
# Dict of keyword arguments passed to compute_score_non_AC that don't
nonAC_kwargs = {
'score_fn': lambda x: _scoring.list_score(x, score_func=score_func),
'threshold_ac': threshold,
'num_gauge_params': numGaugeParams,
'op_penalty': op_penalty,
'germ_lengths': germLengths,
}
for modelNum, reducedModel in enumerate(reducedModelList):
derivDaggerDeriv = twirledDerivDaggerDerivList[modelNum]
while _np.any(weights == 0):
if test_germ_set_infl(reducedModel, goodGerms,
score_func=score_func, threshold=threshold):
break
candidateGerms = _np.where(weights == 0)[0]
candidateGermScores = []
for candidateGermIdx in _np.where(weights == 0)[0]:
candidateWeights = weights.copy()
candidateWeights[candidateGermIdx] = 1
partialDDD = derivDaggerDeriv[
_np.where(candidateWeights == 1)[0], :, :]
candidateGermScore = compute_composite_germ_set_score(
partial_deriv_dagger_deriv=partialDDD, **nonAC_kwargs)
candidateGermScores.append(candidateGermScore)
# Add the germ that give the best score
bestCandidateGerm = candidateGerms[_np.array(
candidateGermScores).argmin()]
weights[bestCandidateGerm] = 1
goodGerms.append(germs_list[bestCandidateGerm])
return goodGerms
def find_germs_breadthfirst(model_list, germs_list, randomize=True,
randomization_strength=1e-3, num_copies=None, seed=0,
op_penalty=0, score_func='all', tol=1e-6, threshold=1e6,
check=False, force="singletons", pretest=True, mem_limit=None,
comm=None, profiler=None, verbosity=0):
if comm is not None and comm.Get_size() > 1:
from mpi4py import MPI # not at top so pygsti doesn't require mpi4py
printer = _baseobjs.VerbosityPrinter.create_printer(verbosity, comm)
model_list = _setup_model_list(model_list, randomize,
randomization_strength, num_copies, seed)
dim = model_list[0].dim
um_params
assert(all([(mdl.dim == dim) for mdl in model_list])), \
"All models must have the same dimension!"
(_, numGaugeParams,
numNonGaugeParams, _) = _get_model_params(model_list)
germLengths = _np.array([len(germ) for germ in germs_list], _np.int64)
numGerms = len(germs_list)
goodGerms = []
weights = _np.zeros(numGerms, _np.int64)
if force:
if force == "singletons":
weights[_np.where(germLengths == 1)] = 1
goodGerms = [germ for i, germ in enumerate(germs_list) if germLengths[i] == 1]
else:
for opstr in force:
weights[germs_list.index(opstr)] = 1
goodGerms = force[:]
if pretest:
undercompleteModelNum = test_germs_list_completeness(model_list,
germs_list,
score_func,
threshold)
if undercompleteModelNum > -1:
printer.warning("Complete initial germ set FAILS on model "
+ str(undercompleteModelNum) + ".")
printer.warning("Aborting search.")
return None
printer.log("Complete initial germ set succeeds on all input models.", 1)
printer.log("Now searching for best germ set.", 1)
printer.log("Starting germ set optimization. Lower score is better.", 1)
mode = "all-Jac"
# front and store them separately (requires lots of mem)
if mem_limit is not None:
memEstimate = FLOATSIZE * len(model_list) * len(germs_list) * Np**2
# for _compute_bulk_twirled_ddd
memEstimate += FLOATSIZE * len(model_list) * len(germs_list) * dim**2 * Np
# for _bulk_twirled_deriv sub-call
printer.log("Memory estimate of %.1f GB (%.1f GB limit) for all-Jac mode." %
(memEstimate / 1024.0**3, mem_limit / 1024.0**3), 1)
if memEstimate > mem_limit:
mode = "single-Jac" # compute a single germ's jacobian at a time
memEstimate = FLOATSIZE * 3 * len(model_list) * Np**2 + \
FLOATSIZE * 3 * len(model_list) * dim**2 * Np
printer.log("Memory estimate of %.1f GB (%.1f GB limit) for single-Jac mode." %
(memEstimate / 1024.0**3, mem_limit / 1024.0**3), 1)
if memEstimate > mem_limit:
raise MemoryError("Too little memory, even for single-Jac mode!")
twirledDerivDaggerDerivList = None
if mode == "all-Jac":
twirledDerivDaggerDerivList = \
[_compute_bulk_twirled_ddd(model, germs_list, tol,
check, germLengths, comm)
for model in model_list]
currentDDDList = []
for i, derivDaggerDeriv in enumerate(twirledDerivDaggerDerivList):
currentDDDList.append(_np.sum(derivDaggerDeriv[_np.where(weights == 1)[0], :, :], axis=0))
elif mode == "single-Jac":
currentDDDList = [_np.zeros((Np, Np), 'complex') for mdl in model_list]
loc_Indices, _, _ = _mpit.distribute_indices(
list(range(len(goodGerms))), comm, False)
with printer.progress_logging(3):
for i, goodGermIdx in enumerate(loc_Indices):
printer.show_progress(i, len(loc_Indices),
prefix="Initial germ set computation",
suffix=germs_list[goodGermIdx].str)
for k, model in enumerate(model_list):
currentDDDList[k] += _compute_twirled_ddd(
model, germs_list[goodGermIdx], tol)
if comm is not None and comm.Get_size() > 1:
for k, model in enumerate(model_list):
result = _np.empty((Np, Np), 'complex')
comm.Allreduce(currentDDDList[k], result, op=MPI.SUM)
currentDDDList[k][:, :] = result[:, :]
result = None
else:
raise ValueError("Invalid mode: %s" % mode)
# change from call to call
nonAC_kwargs = {
'score_fn': lambda x: _scoring.list_score(x, score_func=score_func),
'threshold_ac': threshold,
'num_gauge_params': numGaugeParams,
'op_penalty': op_penalty,
'germ_lengths': germLengths,
}
initN = 1
while _np.any(weights == 0):
printer.log("Outer iteration: %d of %d amplified, %d germs" %
(initN, numNonGaugeParams, len(goodGerms)), 2)
# As long as there are some unused germs, see if you need to add
# another one.
if initN == numNonGaugeParams:
break # We are AC for all models, so we can stop adding germs.
candidateGermIndices = _np.where(weights == 0)[0]
loc_candidateIndices, owners, _ = _mpit.distribute_indices(
candidateGermIndices, comm, False)
# Since the germs aren't sufficient, add the best single candidate germ
bestDDDs = None
bestGermScore = _scoring.CompositeScore(1.0e100, 0, None)
iBestCandidateGerm = None
with printer.progress_logging(3):
for i, candidateGermIdx in enumerate(loc_candidateIndices):
printer.show_progress(i, len(loc_candidateIndices),
prefix="Inner iter over candidate germs",
suffix=germs_list[candidateGermIdx].str)
worstScore = _scoring.CompositeScore(-1.0e100, 0, None)
testDDDs = []
for k, currentDDD in enumerate(currentDDDList):
testDDD = currentDDD.copy()
if mode == "all-Jac":
derivDaggerDeriv = twirledDerivDaggerDerivList[k][candidateGermIdx]
testDDD += derivDaggerDeriv
elif mode == "single-Jac":
model = model_list[k]
testDDD += _compute_twirled_ddd(
model, germs_list[candidateGermIdx], tol)
nonAC_kwargs['germ_lengths'] = \
_np.array([len(germ) for germ in
(goodGerms + [germs_list[candidateGermIdx]])])
worstScore = max(worstScore, compute_composite_germ_set_score(
partial_deriv_dagger_deriv=testDDD[None, :, :], init_n=initN,
**nonAC_kwargs))
testDDDs.append(testDDD)
germScore = worstScore
printer.log(str(germScore), 4)
if germScore < bestGermScore:
bestGermScore = germScore
iBestCandidateGerm = candidateGermIdx
bestDDDs = testDDDs
testDDDs = None
if comm is not None and comm.Get_size() > 1:
globalMinScore = comm.allreduce(bestGermScore, op=MPI.MIN)
toSend = comm.Get_rank() if (globalMinScore == bestGermScore) \
else comm.Get_size() + 1
winningRank = comm.allreduce(toSend, op=MPI.MIN)
bestGermScore = globalMinScore
toCast = iBestCandidateGerm if (comm.Get_rank() == winningRank) else None
iBestCandidateGerm = comm.bcast(toCast, root=winningRank)
for k in range(len(model_list)):
comm.Bcast(bestDDDs[k], root=winningRank)
weights[iBestCandidateGerm] = 1
initN = bestGermScore.N
goodGerms.append(germs_list[iBestCandidateGerm])
for k in range(len(model_list)):
currentDDDList[k][:, :] = bestDDDs[k][:, :]
bestDDDs[k] = None
printer.log("Added %s to final germs (%s)" %
(germs_list[iBestCandidateGerm].str, str(bestGermScore)), 3)
return goodGerms
def find_germs_integer_slack(model_list, germs_list, randomize=True,
randomization_strength=1e-3, num_copies=None,
seed=0, l1_penalty=1e-2, op_penalty=0,
initial_weights=None, score_func='all',
max_iter=100, fixed_slack=False,
slack_frac=False, return_all=False, tol=1e-6,
check=False, force="singletons",
force_score=1e100, threshold=1e6,
verbosity=1):
printer = _baseobjs.VerbosityPrinter.create_printer(verbosity)
model_list = _setup_model_list(model_list, randomize,
randomization_strength, num_copies, seed)
if (fixed_slack and slack_frac) or (not fixed_slack and not slack_frac):
raise ValueError("Either fixed_slack *or* slack_frac should be specified")
if initial_weights is not None:
if len(germs_list) != len(initial_weights):
raise ValueError("The lengths of germs_list (%d) and "
"initial_weights (%d) must match."
% (len(germs_list), len(initial_weights)))
weights = _np.array([1 if x else 0 for x in initial_weights])
else:
weights = _np.ones(len(germs_list), _np.int64)
list_completeness(model_list,
germs_list, score_func,
threshold)
if undercompleteModelNum > -1:
printer.log("Complete initial germ set FAILS on model "
+ str(undercompleteModelNum) + ".", 1)
printer.log("Aborting search.", 1)
return (None, None, None) if return_all else None
printer.log("Complete initial germ set succeeds on all input models.", 1)
printer.log("Now searching for best germ set.", 1)
num_models = len(model_list)
# Remove any SPAM vectors from model since we only want
# to consider the set of *gate* parameters for amplification
# and this makes sure our parameter counting is correct
model0 = _remove_spam_vectors(model_list[0])
# Initially allow adding to weight. -- maybe make this an argument??
lessWeightOnly = False
nGaugeParams = model0.num_gauge_params
# score dictionary:
# keys = (modelNum, tuple-ized weight vector of 1's and 0's only)
# values = list_score
scoreD = {}
germLengths = _np.array([len(germ) for germ in germs_list], _np.int64)
if force:
if force == "singletons":
forceIndices = _np.where(germLengths == 1)
else: # force should be a list of Circuits
forceIndices = _np.array([germs_list.index(opstr) for opstr in force])
else:
forceIndices = None
twirledDerivDaggerDerivList = [_compute_bulk_twirled_ddd(model, germs_list, tol)
for model in model_list]
# Dict of keyword arguments passed to _germ_set_score_slack that don't change from
cs_kwargs = {
'score_func': score_func,
'deriv_dagger_deriv_list': twirledDerivDaggerDerivList,
'force_indices': forceIndices,
'force_score': force_score,
'n_gauge_params': nGaugeParams,
'op_penalty': op_penalty,
'germ_lengths': germLengths,
'l1_penalty': l1_penalty,
'score_dict': scoreD,
}
scoreList = [_germ_set_score_slack(weights, model_num, **cs_kwargs)
for model_num in range(num_models)]
score = _np.max(scoreList)
L1 = sum(weights)
printer.log("Starting germ set optimization. Lower score is better.", 1)
printer.log("Model has %d gauge params." % nGaugeParams, 1)
def _get_neighbors(bool_vec):
for i in range(len(bool_vec)):
v = bool_vec.copy()
v[i] = (v[i] + 1) % 2
yield v
with printer.progress_logging(1):
for iIter in range(max_iter):
printer.show_progress(iIter, max_iter,
suffix="score=%g, nGerms=%d" % (score, L1))
bFoundBetterNeighbor = False
for neighbor in _get_neighbors(weights):
neighborScoreList = []
for model_num in range(len(model_list)):
if (model_num, tuple(neighbor)) not in scoreD:
neighborL1 = sum(neighbor)
neighborScoreList.append(_germ_set_score_slack(neighbor,
model_num,
**cs_kwargs))
else:
neighborL1 = sum(neighbor)
neighborScoreList.append(scoreD[model_num,
tuple(neighbor)])
neighborScore = _np.max(neighborScoreList)
if neighborScore <= score and (neighborL1 < L1 or not lessWeightOnly):
weights, score, L1 = neighbor, neighborScore, neighborL1
bFoundBetterNeighbor = True
printer.log("Found better neighbor: "
"nGerms = %d score = %g" % (L1, score), 2)
if not bFoundBetterNeighbor:
lessWeightOnly = True
if fixed_slack is False:
# Note score is positive (for sum of 1/lambda)
slack = score * slack_frac
# print "slack =", slack
else:
slack = fixed_slack
assert slack > 0
printer.log("No better neighbor. Relaxing score w/slack: "
+ "%g => %g" % (score, score + slack), 2)
# Artificially increase score and see if any neighbor is better
# now...
score += slack
for neighbor in _get_neighbors(weights):
scoreList = [scoreD[model_num, tuple(neighbor)]
for model_num in range(len(model_list))]
maxScore = _np.max(scoreList)
if sum(neighbor) < L1 and maxScore < score:
weights, score, L1 = neighbor, maxScore, sum(neighbor)
bFoundBetterNeighbor = True
printer.log("Found better neighbor: "
"nGerms = %d score = %g" % (L1, score), 2)
if not bFoundBetterNeighbor: # Relaxing didn't help!
printer.log("Stationary point found!", 1)
break
printer.log("Moving to better neighbor", 1)
else:
printer.log("Hit max. iterations", 1)
printer.log("score = %s" % score, 1)
printer.log("weights = %s" % weights, 1)
printer.log("L1(weights) = %s" % sum(weights), 1)
goodGerms = []
for index, val in enumerate(weights):
if val == 1:
goodGerms.append(germs_list[index])
if return_all:
return goodGerms, weights, scoreD
else:
return goodGerms
def _germ_set_score_grasp(germ_set, germs_list, twirled_deriv_dagger_deriv_list,
non_ac_kwargs, init_n=1):
weights = _np.zeros(len(germs_list))
for germ in germ_set:
weights[germs_list.index(germ)] = 1
germsVsModelScores = []
for derivDaggerDeriv in twirled_deriv_dagger_deriv_list:
partialDDD = derivDaggerDeriv[_np.where(weights == 1)[0], :, :]
germsVsModelScores.append(compute_composite_germ_set_score(
partial_deriv_dagger_deriv=partialDDD, init_n=init_n, **non_ac_kwargs))
return max(germsVsModelScores)
def find_germs_grasp(model_list, germs_list, alpha, randomize=True,
randomization_strength=1e-3, num_copies=None,
seed=None, l1_penalty=1e-2, op_penalty=0.0,
score_func='all', tol=1e-6, threshold=1e6,
check=False, force="singletons",
iterations=5, return_all=False, shuffle=False,
verbosity=0):
printer = _baseobjs.VerbosityPrinter.create_printer(verbosity)
model_list = _setup_model_list(model_list, randomize,
randomization_strength, num_copies, seed)
(_, numGaugeParams,
numNonGaugeParams, _) = _get_model_params(model_list)
germLengths = _np.array([len(germ) for germ in germs_list], _np.int64)
numGerms = len(germs_list)
initialWeights = _np.zeros(numGerms, dtype=_np.int64)
if force:
if force == "singletons":
initialWeights[_np.where(germLengths == 1)] = 1
else:
for opstr in force:
initialWeights[germs_list.index(opstr)] = 1
def get_neighbors_fn(weights): return _grasp.get_swap_neighbors(
weights, forced_weights=initialWeights, shuffle=shuffle)
undercompleteModelNum = test_germs_list_completeness(model_list,
germs_list,
score_func,
threshold)
if undercompleteModelNum > -1:
printer.warning("Complete initial germ set FAILS on model "
+ str(undercompleteModelNum) + ".")
printer.warning("Aborting search.")
return (None, None, None) if return_all else None
printer.log("Complete initial germ set succeeds on all input models.", 1)
printer.log("Now searching for best germ set.", 1)
printer.log("Starting germ set optimization. Lower score is better.", 1)
twirledDerivDaggerDerivList = [_compute_bulk_twirled_ddd(model, germs_list, tol,
check, germLengths)
for model in model_list]
# change from call to call
nonAC_kwargs = {
'score_fn': lambda x: _scoring.list_score(x, score_func=score_func),
'threshold_ac': threshold,
'num_gauge_params': numGaugeParams,
'op_penalty': op_penalty,
'germ_lengths': germLengths,
}
final_nonAC_kwargs = nonAC_kwargs.copy()
final_nonAC_kwargs['l1_penalty'] = l1_penalty
scoreFn = (lambda germSet:
_germ_set_score_grasp(germSet, germs_list,
twirledDerivDaggerDerivList, nonAC_kwargs,
init_n=1))
finalScoreFn = (lambda germSet:
_germ_set_score_grasp(germSet, germs_list,
twirledDerivDaggerDerivList,
final_nonAC_kwargs, init_n=1))
#OLD: feasibleThreshold = _scoring.CompositeScore(-numNonGaugeParams,threshold,numNonGaugeParams))
def _feasible_fn(germ_set): # now that scoring is not ordered entirely by N
s = _germ_set_score_grasp(germ_set, germs_list,
twirledDerivDaggerDerivList, nonAC_kwargs,
init_n=1)
return (s.N >= numNonGaugeParams and s.minor < threshold)
def rcl_fn(x): return _scoring.filter_composite_rcl(x, alpha)
initialSolns = []
localSolns = []
for iteration in range(iterations):
# This loop is parallelizable (each iteration is independent of all
# other iterations).
printer.log('Starting iteration {} of {}.'.format(iteration + 1,
iterations), 1)
success = False
failCount = 0
while not success and failCount < 10:
try:
iterSolns = _grasp.run_grasp_iteration(
elements=germs_list, greedy_score_fn=scoreFn, rcl_fn=rcl_fn,
local_score_fn=scoreFn,
get_neighbors_fn=get_neighbors_fn,
feasible_fn=_feasible_fn,
initial_elements=initialWeights, seed=seed,
verbosity=verbosity)
initialSolns.append(iterSolns[0])
localSolns.append(iterSolns[1])
success = True
printer.log('Finished iteration {} of {}.'.format(
iteration + 1, iterations), 1)
except Exception as e:
failCount += 1
raise e if (failCount == 10) else printer.warning(e)
finalScores = _np.array([finalScoreFn(localSoln)
for localSoln in localSolns])
bestSoln = localSolns[_np.argmin(finalScores)]
return (bestSoln, initialSolns, localSolns) if return_all else bestSoln
| true | true |
f723b33ce8bf99ada316a7b4f05f6f288349975d | 97 | py | Python | web/handlers/__init__.py | jessiepullaro414/Toastifai | d2ad89fc4c4de3881eeaa3fa011cdedaeb37d58f | [
"MIT"
] | 3 | 2016-10-16T02:43:53.000Z | 2018-10-10T22:52:41.000Z | web/handlers/__init__.py | jessiepullaro414/Toastifai | d2ad89fc4c4de3881eeaa3fa011cdedaeb37d58f | [
"MIT"
] | null | null | null | web/handlers/__init__.py | jessiepullaro414/Toastifai | d2ad89fc4c4de3881eeaa3fa011cdedaeb37d58f | [
"MIT"
] | null | null | null | import os
__all__ = [mod.split(".")[0] for mod in os.listdir("handlers") if mod != "__init__.py"] | 48.5 | 87 | 0.659794 | import os
__all__ = [mod.split(".")[0] for mod in os.listdir("handlers") if mod != "__init__.py"] | true | true |
f723b351b9c87bf7e64adf7c1a163e6a763dc043 | 60,986 | py | Python | homeassistant/helpers/script.py | mtarjoianu/core | 44e9146463ac505eb3d1c0651ad126cb25c28a54 | [
"Apache-2.0"
] | null | null | null | homeassistant/helpers/script.py | mtarjoianu/core | 44e9146463ac505eb3d1c0651ad126cb25c28a54 | [
"Apache-2.0"
] | null | null | null | homeassistant/helpers/script.py | mtarjoianu/core | 44e9146463ac505eb3d1c0651ad126cb25c28a54 | [
"Apache-2.0"
] | null | null | null | """Helpers to execute scripts."""
from __future__ import annotations
import asyncio
from collections.abc import Callable, Sequence
from contextlib import asynccontextmanager, suppress
from contextvars import ContextVar
from copy import copy
from datetime import datetime, timedelta
from functools import partial
import itertools
import logging
from types import MappingProxyType
from typing import Any, TypedDict, Union, cast
import async_timeout
import voluptuous as vol
from homeassistant import exceptions
from homeassistant.components import scene
from homeassistant.components.device_automation import action as device_action
from homeassistant.components.logger import LOGSEVERITY
from homeassistant.const import (
ATTR_AREA_ID,
ATTR_DEVICE_ID,
ATTR_ENTITY_ID,
CONF_ALIAS,
CONF_CHOOSE,
CONF_CONDITION,
CONF_CONDITIONS,
CONF_CONTINUE_ON_TIMEOUT,
CONF_COUNT,
CONF_DEFAULT,
CONF_DELAY,
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ELSE,
CONF_ERROR,
CONF_EVENT,
CONF_EVENT_DATA,
CONF_EVENT_DATA_TEMPLATE,
CONF_IF,
CONF_MODE,
CONF_PARALLEL,
CONF_REPEAT,
CONF_SCENE,
CONF_SEQUENCE,
CONF_SERVICE,
CONF_STOP,
CONF_TARGET,
CONF_THEN,
CONF_TIMEOUT,
CONF_UNTIL,
CONF_VARIABLES,
CONF_WAIT_FOR_TRIGGER,
CONF_WAIT_TEMPLATE,
CONF_WHILE,
EVENT_HOMEASSISTANT_STOP,
SERVICE_TURN_ON,
)
from homeassistant.core import (
SERVICE_CALL_LIMIT,
Context,
HassJob,
HomeAssistant,
callback,
)
from homeassistant.util import slugify
from homeassistant.util.dt import utcnow
from . import condition, config_validation as cv, service, template
from .condition import ConditionCheckerType, trace_condition_function
from .dispatcher import async_dispatcher_connect, async_dispatcher_send
from .event import async_call_later, async_track_template
from .script_variables import ScriptVariables
from .trace import (
TraceElement,
async_trace_path,
script_execution_set,
trace_append_element,
trace_id_get,
trace_path,
trace_path_get,
trace_path_stack_cv,
trace_set_result,
trace_stack_cv,
trace_stack_pop,
trace_stack_push,
trace_stack_top,
trace_update_result,
)
from .trigger import async_initialize_triggers, async_validate_trigger_config
from .typing import ConfigType
# mypy: allow-untyped-calls, allow-untyped-defs, no-check-untyped-defs
SCRIPT_MODE_PARALLEL = "parallel"
SCRIPT_MODE_QUEUED = "queued"
SCRIPT_MODE_RESTART = "restart"
SCRIPT_MODE_SINGLE = "single"
SCRIPT_MODE_CHOICES = [
SCRIPT_MODE_PARALLEL,
SCRIPT_MODE_QUEUED,
SCRIPT_MODE_RESTART,
SCRIPT_MODE_SINGLE,
]
DEFAULT_SCRIPT_MODE = SCRIPT_MODE_SINGLE
CONF_MAX = "max"
DEFAULT_MAX = 10
CONF_MAX_EXCEEDED = "max_exceeded"
_MAX_EXCEEDED_CHOICES = list(LOGSEVERITY) + ["SILENT"]
DEFAULT_MAX_EXCEEDED = "WARNING"
ATTR_CUR = "current"
ATTR_MAX = "max"
DATA_SCRIPTS = "helpers.script"
DATA_SCRIPT_BREAKPOINTS = "helpers.script_breakpoints"
DATA_NEW_SCRIPT_RUNS_NOT_ALLOWED = "helpers.script_not_allowed"
RUN_ID_ANY = "*"
NODE_ANY = "*"
_LOGGER = logging.getLogger(__name__)
_LOG_EXCEPTION = logging.ERROR + 1
_TIMEOUT_MSG = "Timeout reached, abort script."
_SHUTDOWN_MAX_WAIT = 60
ACTION_TRACE_NODE_MAX_LEN = 20 # Max length of a trace node for repeated actions
SCRIPT_BREAKPOINT_HIT = "script_breakpoint_hit"
SCRIPT_DEBUG_CONTINUE_STOP = "script_debug_continue_stop_{}_{}"
SCRIPT_DEBUG_CONTINUE_ALL = "script_debug_continue_all"
script_stack_cv: ContextVar[list[int] | None] = ContextVar("script_stack", default=None)
def action_trace_append(variables, path):
"""Append a TraceElement to trace[path]."""
trace_element = TraceElement(variables, path)
trace_append_element(trace_element, ACTION_TRACE_NODE_MAX_LEN)
return trace_element
@asynccontextmanager
async def trace_action(hass, script_run, stop, variables):
"""Trace action execution."""
path = trace_path_get()
trace_element = action_trace_append(variables, path)
trace_stack_push(trace_stack_cv, trace_element)
trace_id = trace_id_get()
if trace_id:
key = trace_id[0]
run_id = trace_id[1]
breakpoints = hass.data[DATA_SCRIPT_BREAKPOINTS]
if key in breakpoints and (
(
run_id in breakpoints[key]
and (
path in breakpoints[key][run_id]
or NODE_ANY in breakpoints[key][run_id]
)
)
or (
RUN_ID_ANY in breakpoints[key]
and (
path in breakpoints[key][RUN_ID_ANY]
or NODE_ANY in breakpoints[key][RUN_ID_ANY]
)
)
):
async_dispatcher_send(hass, SCRIPT_BREAKPOINT_HIT, key, run_id, path)
done = asyncio.Event()
@callback
def async_continue_stop(command=None):
if command == "stop":
stop.set()
done.set()
signal = SCRIPT_DEBUG_CONTINUE_STOP.format(key, run_id)
remove_signal1 = async_dispatcher_connect(hass, signal, async_continue_stop)
remove_signal2 = async_dispatcher_connect(
hass, SCRIPT_DEBUG_CONTINUE_ALL, async_continue_stop
)
tasks = [hass.async_create_task(flag.wait()) for flag in (stop, done)]
await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
for task in tasks:
task.cancel()
remove_signal1()
remove_signal2()
try:
yield trace_element
except _AbortScript as ex:
trace_element.set_error(ex.__cause__ or ex)
raise ex
except _StopScript as ex:
raise ex
except Exception as ex:
trace_element.set_error(ex)
raise ex
finally:
trace_stack_pop(trace_stack_cv)
def make_script_schema(schema, default_script_mode, extra=vol.PREVENT_EXTRA):
"""Make a schema for a component that uses the script helper."""
return vol.Schema(
{
**schema,
vol.Optional(CONF_MODE, default=default_script_mode): vol.In(
SCRIPT_MODE_CHOICES
),
vol.Optional(CONF_MAX, default=DEFAULT_MAX): vol.All(
vol.Coerce(int), vol.Range(min=2)
),
vol.Optional(CONF_MAX_EXCEEDED, default=DEFAULT_MAX_EXCEEDED): vol.All(
vol.Upper, vol.In(_MAX_EXCEEDED_CHOICES)
),
},
extra=extra,
)
STATIC_VALIDATION_ACTION_TYPES = (
cv.SCRIPT_ACTION_CALL_SERVICE,
cv.SCRIPT_ACTION_DELAY,
cv.SCRIPT_ACTION_WAIT_TEMPLATE,
cv.SCRIPT_ACTION_FIRE_EVENT,
cv.SCRIPT_ACTION_ACTIVATE_SCENE,
cv.SCRIPT_ACTION_VARIABLES,
cv.SCRIPT_ACTION_ERROR,
cv.SCRIPT_ACTION_STOP,
)
async def async_validate_actions_config(
hass: HomeAssistant, actions: list[ConfigType]
) -> list[ConfigType]:
"""Validate a list of actions."""
return await asyncio.gather(
*(async_validate_action_config(hass, action) for action in actions)
)
async def async_validate_action_config(
hass: HomeAssistant, config: ConfigType
) -> ConfigType:
"""Validate config."""
action_type = cv.determine_script_action(config)
if action_type in STATIC_VALIDATION_ACTION_TYPES:
pass
elif action_type == cv.SCRIPT_ACTION_DEVICE_AUTOMATION:
config = await device_action.async_validate_action_config(hass, config)
elif action_type == cv.SCRIPT_ACTION_CHECK_CONDITION:
config = await condition.async_validate_condition_config(hass, config)
elif action_type == cv.SCRIPT_ACTION_WAIT_FOR_TRIGGER:
config[CONF_WAIT_FOR_TRIGGER] = await async_validate_trigger_config(
hass, config[CONF_WAIT_FOR_TRIGGER]
)
elif action_type == cv.SCRIPT_ACTION_REPEAT:
if CONF_UNTIL in config[CONF_REPEAT]:
conditions = await condition.async_validate_conditions_config(
hass, config[CONF_REPEAT][CONF_UNTIL]
)
config[CONF_REPEAT][CONF_UNTIL] = conditions
if CONF_WHILE in config[CONF_REPEAT]:
conditions = await condition.async_validate_conditions_config(
hass, config[CONF_REPEAT][CONF_WHILE]
)
config[CONF_REPEAT][CONF_WHILE] = conditions
config[CONF_REPEAT][CONF_SEQUENCE] = await async_validate_actions_config(
hass, config[CONF_REPEAT][CONF_SEQUENCE]
)
elif action_type == cv.SCRIPT_ACTION_CHOOSE:
if CONF_DEFAULT in config:
config[CONF_DEFAULT] = await async_validate_actions_config(
hass, config[CONF_DEFAULT]
)
for choose_conf in config[CONF_CHOOSE]:
conditions = await condition.async_validate_conditions_config(
hass, choose_conf[CONF_CONDITIONS]
)
choose_conf[CONF_CONDITIONS] = conditions
choose_conf[CONF_SEQUENCE] = await async_validate_actions_config(
hass, choose_conf[CONF_SEQUENCE]
)
elif action_type == cv.SCRIPT_ACTION_IF:
config[CONF_IF] = await condition.async_validate_conditions_config(
hass, config[CONF_IF]
)
config[CONF_THEN] = await async_validate_actions_config(hass, config[CONF_THEN])
if CONF_ELSE in config:
config[CONF_ELSE] = await async_validate_actions_config(
hass, config[CONF_ELSE]
)
elif action_type == cv.SCRIPT_ACTION_PARALLEL:
for parallel_conf in config[CONF_PARALLEL]:
parallel_conf[CONF_SEQUENCE] = await async_validate_actions_config(
hass, parallel_conf[CONF_SEQUENCE]
)
else:
raise ValueError(f"No validation for {action_type}")
return config
class _AbortScript(Exception):
"""Throw if script needs to abort because of an unexpected error."""
class _StopScript(Exception):
"""Throw if script needs to stop."""
class _ScriptRun:
"""Manage Script sequence run."""
def __init__(
self,
hass: HomeAssistant,
script: Script,
variables: dict[str, Any],
context: Context | None,
log_exceptions: bool,
) -> None:
self._hass = hass
self._script = script
self._variables = variables
self._context = context
self._log_exceptions = log_exceptions
self._step = -1
self._action: dict[str, Any] | None = None
self._stop = asyncio.Event()
self._stopped = asyncio.Event()
def _changed(self) -> None:
if not self._stop.is_set():
self._script._changed() # pylint: disable=protected-access
async def _async_get_condition(self, config):
# pylint: disable=protected-access
return await self._script._async_get_condition(config)
def _log(
self, msg: str, *args: Any, level: int = logging.INFO, **kwargs: Any
) -> None:
self._script._log( # pylint: disable=protected-access
msg, *args, level=level, **kwargs
)
def _step_log(self, default_message, timeout=None):
self._script.last_action = self._action.get(CONF_ALIAS, default_message)
_timeout = (
"" if timeout is None else f" (timeout: {timedelta(seconds=timeout)})"
)
self._log("Executing step %s%s", self._script.last_action, _timeout)
async def async_run(self) -> None:
"""Run script."""
# Push the script to the script execution stack
if (script_stack := script_stack_cv.get()) is None:
script_stack = []
script_stack_cv.set(script_stack)
script_stack.append(id(self._script))
try:
self._log("Running %s", self._script.running_description)
for self._step, self._action in enumerate(self._script.sequence):
if self._stop.is_set():
script_execution_set("cancelled")
break
await self._async_step(log_exceptions=False)
else:
script_execution_set("finished")
except _StopScript:
script_execution_set("finished")
except _AbortScript:
script_execution_set("aborted")
except Exception:
script_execution_set("error")
raise
finally:
# Pop the script from the script execution stack
script_stack.pop()
self._finish()
async def _async_step(self, log_exceptions):
with trace_path(str(self._step)):
async with trace_action(self._hass, self, self._stop, self._variables):
if self._stop.is_set():
return
try:
handler = f"_async_{cv.determine_script_action(self._action)}_step"
await getattr(self, handler)()
except Exception as ex:
if not isinstance(ex, (_AbortScript, _StopScript)) and (
self._log_exceptions or log_exceptions
):
self._log_exception(ex)
raise
def _finish(self) -> None:
self._script._runs.remove(self) # pylint: disable=protected-access
if not self._script.is_running:
self._script.last_action = None
self._changed()
self._stopped.set()
async def async_stop(self) -> None:
"""Stop script run."""
self._stop.set()
await self._stopped.wait()
def _log_exception(self, exception):
action_type = cv.determine_script_action(self._action)
error = str(exception)
level = logging.ERROR
if isinstance(exception, vol.Invalid):
error_desc = "Invalid data"
elif isinstance(exception, exceptions.TemplateError):
error_desc = "Error rendering template"
elif isinstance(exception, exceptions.Unauthorized):
error_desc = "Unauthorized"
elif isinstance(exception, exceptions.ServiceNotFound):
error_desc = "Service not found"
elif isinstance(exception, exceptions.HomeAssistantError):
error_desc = "Error"
else:
error_desc = "Unexpected error"
level = _LOG_EXCEPTION
self._log(
"Error executing script. %s for %s at pos %s: %s",
error_desc,
action_type,
self._step + 1,
error,
level=level,
)
def _get_pos_time_period_template(self, key):
try:
return cv.positive_time_period(
template.render_complex(self._action[key], self._variables)
)
except (exceptions.TemplateError, vol.Invalid) as ex:
self._log(
"Error rendering %s %s template: %s",
self._script.name,
key,
ex,
level=logging.ERROR,
)
raise _AbortScript from ex
async def _async_delay_step(self):
"""Handle delay."""
delay = self._get_pos_time_period_template(CONF_DELAY)
self._step_log(f"delay {delay}")
delay = delay.total_seconds()
self._changed()
trace_set_result(delay=delay, done=False)
try:
async with async_timeout.timeout(delay):
await self._stop.wait()
except asyncio.TimeoutError:
trace_set_result(delay=delay, done=True)
async def _async_wait_template_step(self):
"""Handle a wait template."""
if CONF_TIMEOUT in self._action:
timeout = self._get_pos_time_period_template(CONF_TIMEOUT).total_seconds()
else:
timeout = None
self._step_log("wait template", timeout)
self._variables["wait"] = {"remaining": timeout, "completed": False}
trace_set_result(wait=self._variables["wait"])
wait_template = self._action[CONF_WAIT_TEMPLATE]
wait_template.hass = self._hass
# check if condition already okay
if condition.async_template(self._hass, wait_template, self._variables, False):
self._variables["wait"]["completed"] = True
return
@callback
def async_script_wait(entity_id, from_s, to_s):
"""Handle script after template condition is true."""
wait_var = self._variables["wait"]
if to_context and to_context.deadline:
wait_var["remaining"] = to_context.deadline - self._hass.loop.time()
else:
wait_var["remaining"] = timeout
wait_var["completed"] = True
done.set()
to_context = None
unsub = async_track_template(
self._hass, wait_template, async_script_wait, self._variables
)
self._changed()
done = asyncio.Event()
tasks = [
self._hass.async_create_task(flag.wait()) for flag in (self._stop, done)
]
try:
async with async_timeout.timeout(timeout) as to_context:
await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
except asyncio.TimeoutError as ex:
self._variables["wait"]["remaining"] = 0.0
if not self._action.get(CONF_CONTINUE_ON_TIMEOUT, True):
self._log(_TIMEOUT_MSG)
trace_set_result(wait=self._variables["wait"], timeout=True)
raise _AbortScript from ex
finally:
for task in tasks:
task.cancel()
unsub()
async def _async_run_long_action(self, long_task: asyncio.Task) -> None:
"""Run a long task while monitoring for stop request."""
async def async_cancel_long_task() -> None:
# Stop long task and wait for it to finish.
long_task.cancel()
with suppress(Exception):
await long_task
# Wait for long task while monitoring for a stop request.
stop_task = self._hass.async_create_task(self._stop.wait())
try:
await asyncio.wait(
{long_task, stop_task}, return_when=asyncio.FIRST_COMPLETED
)
# If our task is cancelled, then cancel long task, too. Note that if long task
# is cancelled otherwise the CancelledError exception will not be raised to
# here due to the call to asyncio.wait(). Rather we'll check for that below.
except asyncio.CancelledError:
await async_cancel_long_task()
raise
finally:
stop_task.cancel()
if long_task.cancelled():
raise asyncio.CancelledError
if long_task.done():
# Propagate any exceptions that occurred.
long_task.result()
else:
# Stopped before long task completed, so cancel it.
await async_cancel_long_task()
async def _async_call_service_step(self):
"""Call the service specified in the action."""
self._step_log("call service")
params = service.async_prepare_call_from_config(
self._hass, self._action, self._variables
)
running_script = (
params[CONF_DOMAIN] == "automation"
and params[CONF_SERVICE] == "trigger"
or params[CONF_DOMAIN] in ("python_script", "script")
)
# If this might start a script then disable the call timeout.
# Otherwise use the normal service call limit.
if running_script:
limit = None
else:
limit = SERVICE_CALL_LIMIT
trace_set_result(params=params, running_script=running_script, limit=limit)
service_task = self._hass.async_create_task(
self._hass.services.async_call(
**params,
blocking=True,
context=self._context,
limit=limit,
)
)
if limit is not None:
# There is a call limit, so just wait for it to finish.
await service_task
return
await self._async_run_long_action(service_task)
async def _async_device_step(self):
"""Perform the device automation specified in the action."""
self._step_log("device automation")
await device_action.async_call_action_from_config(
self._hass, self._action, self._variables, self._context
)
async def _async_scene_step(self):
"""Activate the scene specified in the action."""
self._step_log("activate scene")
trace_set_result(scene=self._action[CONF_SCENE])
await self._hass.services.async_call(
scene.DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: self._action[CONF_SCENE]},
blocking=True,
context=self._context,
)
async def _async_event_step(self):
"""Fire an event."""
self._step_log(self._action.get(CONF_ALIAS, self._action[CONF_EVENT]))
event_data = {}
for conf in (CONF_EVENT_DATA, CONF_EVENT_DATA_TEMPLATE):
if conf not in self._action:
continue
try:
event_data.update(
template.render_complex(self._action[conf], self._variables)
)
except exceptions.TemplateError as ex:
self._log(
"Error rendering event data template: %s", ex, level=logging.ERROR
)
trace_set_result(event=self._action[CONF_EVENT], event_data=event_data)
self._hass.bus.async_fire(
self._action[CONF_EVENT], event_data, context=self._context
)
async def _async_condition_step(self):
"""Test if condition is matching."""
self._script.last_action = self._action.get(
CONF_ALIAS, self._action[CONF_CONDITION]
)
cond = await self._async_get_condition(self._action)
try:
trace_element = trace_stack_top(trace_stack_cv)
if trace_element:
trace_element.reuse_by_child = True
check = cond(self._hass, self._variables)
except exceptions.ConditionError as ex:
_LOGGER.warning("Error in 'condition' evaluation:\n%s", ex)
check = False
self._log("Test condition %s: %s", self._script.last_action, check)
trace_update_result(result=check)
if not check:
raise _AbortScript
def _test_conditions(self, conditions, name, condition_path=None):
if condition_path is None:
condition_path = name
@trace_condition_function
def traced_test_conditions(hass, variables):
try:
with trace_path(condition_path):
for idx, cond in enumerate(conditions):
with trace_path(str(idx)):
if not cond(hass, variables):
return False
except exceptions.ConditionError as ex:
_LOGGER.warning("Error in '%s[%s]' evaluation: %s", name, idx, ex)
return None
return True
result = traced_test_conditions(self._hass, self._variables)
return result
@async_trace_path("repeat")
async def _async_repeat_step(self):
"""Repeat a sequence."""
description = self._action.get(CONF_ALIAS, "sequence")
repeat = self._action[CONF_REPEAT]
saved_repeat_vars = self._variables.get("repeat")
def set_repeat_var(iteration, count=None):
repeat_vars = {"first": iteration == 1, "index": iteration}
if count:
repeat_vars["last"] = iteration == count
self._variables["repeat"] = repeat_vars
# pylint: disable=protected-access
script = self._script._get_repeat_script(self._step)
async def async_run_sequence(iteration, extra_msg=""):
self._log("Repeating %s: Iteration %i%s", description, iteration, extra_msg)
with trace_path("sequence"):
await self._async_run_script(script)
if CONF_COUNT in repeat:
count = repeat[CONF_COUNT]
if isinstance(count, template.Template):
try:
count = int(count.async_render(self._variables))
except (exceptions.TemplateError, ValueError) as ex:
self._log(
"Error rendering %s repeat count template: %s",
self._script.name,
ex,
level=logging.ERROR,
)
raise _AbortScript from ex
extra_msg = f" of {count}"
for iteration in range(1, count + 1):
set_repeat_var(iteration, count)
await async_run_sequence(iteration, extra_msg)
if self._stop.is_set():
break
elif CONF_WHILE in repeat:
conditions = [
await self._async_get_condition(config) for config in repeat[CONF_WHILE]
]
for iteration in itertools.count(1):
set_repeat_var(iteration)
try:
if self._stop.is_set():
break
if not self._test_conditions(conditions, "while"):
break
except exceptions.ConditionError as ex:
_LOGGER.warning("Error in 'while' evaluation:\n%s", ex)
break
await async_run_sequence(iteration)
elif CONF_UNTIL in repeat:
conditions = [
await self._async_get_condition(config) for config in repeat[CONF_UNTIL]
]
for iteration in itertools.count(1):
set_repeat_var(iteration)
await async_run_sequence(iteration)
try:
if self._stop.is_set():
break
if self._test_conditions(conditions, "until") in [True, None]:
break
except exceptions.ConditionError as ex:
_LOGGER.warning("Error in 'until' evaluation:\n%s", ex)
break
if saved_repeat_vars:
self._variables["repeat"] = saved_repeat_vars
else:
self._variables.pop("repeat", None) # Not set if count = 0
async def _async_choose_step(self) -> None:
"""Choose a sequence."""
# pylint: disable=protected-access
choose_data = await self._script._async_get_choose_data(self._step)
with trace_path("choose"):
for idx, (conditions, script) in enumerate(choose_data["choices"]):
with trace_path(str(idx)):
try:
if self._test_conditions(conditions, "choose", "conditions"):
trace_set_result(choice=idx)
with trace_path("sequence"):
await self._async_run_script(script)
return
except exceptions.ConditionError as ex:
_LOGGER.warning("Error in 'choose' evaluation:\n%s", ex)
if choose_data["default"] is not None:
trace_set_result(choice="default")
with trace_path(["default"]):
await self._async_run_script(choose_data["default"])
async def _async_if_step(self) -> None:
"""If sequence."""
# pylint: disable=protected-access
if_data = await self._script._async_get_if_data(self._step)
test_conditions = False
try:
with trace_path("if"):
test_conditions = self._test_conditions(
if_data["if_conditions"], "if", "condition"
)
except exceptions.ConditionError as ex:
_LOGGER.warning("Error in 'if' evaluation:\n%s", ex)
if test_conditions:
trace_set_result(choice="then")
with trace_path("then"):
await self._async_run_script(if_data["if_then"])
return
if if_data["if_else"] is not None:
trace_set_result(choice="else")
with trace_path("else"):
await self._async_run_script(if_data["if_else"])
async def _async_wait_for_trigger_step(self):
"""Wait for a trigger event."""
if CONF_TIMEOUT in self._action:
timeout = self._get_pos_time_period_template(CONF_TIMEOUT).total_seconds()
else:
timeout = None
self._step_log("wait for trigger", timeout)
variables = {**self._variables}
self._variables["wait"] = {"remaining": timeout, "trigger": None}
trace_set_result(wait=self._variables["wait"])
done = asyncio.Event()
async def async_done(variables, context=None):
wait_var = self._variables["wait"]
if to_context and to_context.deadline:
wait_var["remaining"] = to_context.deadline - self._hass.loop.time()
else:
wait_var["remaining"] = timeout
wait_var["trigger"] = variables["trigger"]
done.set()
def log_cb(level, msg, **kwargs):
self._log(msg, level=level, **kwargs)
to_context = None
remove_triggers = await async_initialize_triggers(
self._hass,
self._action[CONF_WAIT_FOR_TRIGGER],
async_done,
self._script.domain,
self._script.name,
log_cb,
variables=variables,
)
if not remove_triggers:
return
self._changed()
tasks = [
self._hass.async_create_task(flag.wait()) for flag in (self._stop, done)
]
try:
async with async_timeout.timeout(timeout) as to_context:
await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
except asyncio.TimeoutError as ex:
self._variables["wait"]["remaining"] = 0.0
if not self._action.get(CONF_CONTINUE_ON_TIMEOUT, True):
self._log(_TIMEOUT_MSG)
trace_set_result(wait=self._variables["wait"], timeout=True)
raise _AbortScript from ex
finally:
for task in tasks:
task.cancel()
remove_triggers()
async def _async_variables_step(self):
"""Set a variable value."""
self._step_log("setting variables")
self._variables = self._action[CONF_VARIABLES].async_render(
self._hass, self._variables, render_as_defaults=False
)
async def _async_stop_step(self):
"""Stop script execution."""
stop = self._action[CONF_STOP]
self._log("Stop script sequence: %s", stop)
trace_set_result(stop=stop)
raise _StopScript(stop)
async def _async_error_step(self):
"""Abort and error script execution."""
error = self._action[CONF_ERROR]
self._log("Error script sequence: %s", error)
trace_set_result(error=error)
raise _AbortScript(error)
@async_trace_path("parallel")
async def _async_parallel_step(self) -> None:
"""Run a sequence in parallel."""
# pylint: disable=protected-access
scripts = await self._script._async_get_parallel_scripts(self._step)
async def async_run_with_trace(idx: int, script: Script) -> None:
"""Run a script with a trace path."""
trace_path_stack_cv.set(copy(trace_path_stack_cv.get()))
with trace_path([str(idx), "sequence"]):
await self._async_run_script(script)
results = await asyncio.gather(
*(async_run_with_trace(idx, script) for idx, script in enumerate(scripts)),
return_exceptions=True,
)
for result in results:
if isinstance(result, Exception):
raise result
async def _async_run_script(self, script: Script) -> None:
"""Execute a script."""
await self._async_run_long_action(
self._hass.async_create_task(
script.async_run(self._variables, self._context)
)
)
class _QueuedScriptRun(_ScriptRun):
"""Manage queued Script sequence run."""
lock_acquired = False
async def async_run(self) -> None:
"""Run script."""
# Wait for previous run, if any, to finish by attempting to acquire the script's
# shared lock. At the same time monitor if we've been told to stop.
lock_task = self._hass.async_create_task(
self._script._queue_lck.acquire() # pylint: disable=protected-access
)
stop_task = self._hass.async_create_task(self._stop.wait())
try:
await asyncio.wait(
{lock_task, stop_task}, return_when=asyncio.FIRST_COMPLETED
)
except asyncio.CancelledError:
self._finish()
raise
else:
self.lock_acquired = lock_task.done() and not lock_task.cancelled()
finally:
lock_task.cancel()
stop_task.cancel()
# If we've been told to stop, then just finish up. Otherwise, we've acquired the
# lock so we can go ahead and start the run.
if self._stop.is_set():
self._finish()
else:
await super().async_run()
def _finish(self) -> None:
# pylint: disable=protected-access
if self.lock_acquired:
self._script._queue_lck.release()
self.lock_acquired = False
super()._finish()
async def _async_stop_scripts_after_shutdown(hass, point_in_time):
"""Stop running Script objects started after shutdown."""
hass.data[DATA_NEW_SCRIPT_RUNS_NOT_ALLOWED] = None
running_scripts = [
script for script in hass.data[DATA_SCRIPTS] if script["instance"].is_running
]
if running_scripts:
names = ", ".join([script["instance"].name for script in running_scripts])
_LOGGER.warning("Stopping scripts running too long after shutdown: %s", names)
await asyncio.gather(
*(
script["instance"].async_stop(update_state=False)
for script in running_scripts
)
)
async def _async_stop_scripts_at_shutdown(hass, event):
"""Stop running Script objects started before shutdown."""
async_call_later(
hass, _SHUTDOWN_MAX_WAIT, partial(_async_stop_scripts_after_shutdown, hass)
)
running_scripts = [
script
for script in hass.data[DATA_SCRIPTS]
if script["instance"].is_running and script["started_before_shutdown"]
]
if running_scripts:
names = ", ".join([script["instance"].name for script in running_scripts])
_LOGGER.debug("Stopping scripts running at shutdown: %s", names)
await asyncio.gather(
*(script["instance"].async_stop() for script in running_scripts)
)
_VarsType = Union[dict[str, Any], MappingProxyType]
def _referenced_extract_ids(data: dict[str, Any], key: str, found: set[str]) -> None:
"""Extract referenced IDs."""
if not data:
return
item_ids = data.get(key)
if item_ids is None or isinstance(item_ids, template.Template):
return
if isinstance(item_ids, str):
found.add(item_ids)
else:
for item_id in item_ids:
found.add(item_id)
class _ChooseData(TypedDict):
choices: list[tuple[list[ConditionCheckerType], Script]]
default: Script | None
class _IfData(TypedDict):
if_conditions: list[ConditionCheckerType]
if_then: Script
if_else: Script | None
class Script:
"""Representation of a script."""
def __init__(
self,
hass: HomeAssistant,
sequence: Sequence[dict[str, Any]],
name: str,
domain: str,
*,
# Used in "Running <running_description>" log message
running_description: str | None = None,
change_listener: Callable[..., Any] | None = None,
script_mode: str = DEFAULT_SCRIPT_MODE,
max_runs: int = DEFAULT_MAX,
max_exceeded: str = DEFAULT_MAX_EXCEEDED,
logger: logging.Logger | None = None,
log_exceptions: bool = True,
top_level: bool = True,
variables: ScriptVariables | None = None,
) -> None:
"""Initialize the script."""
if not (all_scripts := hass.data.get(DATA_SCRIPTS)):
all_scripts = hass.data[DATA_SCRIPTS] = []
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, partial(_async_stop_scripts_at_shutdown, hass)
)
self._top_level = top_level
if top_level:
all_scripts.append(
{"instance": self, "started_before_shutdown": not hass.is_stopping}
)
if DATA_SCRIPT_BREAKPOINTS not in hass.data:
hass.data[DATA_SCRIPT_BREAKPOINTS] = {}
self._hass = hass
self.sequence = sequence
template.attach(hass, self.sequence)
self.name = name
self.domain = domain
self.running_description = running_description or f"{domain} script"
self._change_listener = change_listener
self._change_listener_job = (
None if change_listener is None else HassJob(change_listener)
)
self.script_mode = script_mode
self._set_logger(logger)
self._log_exceptions = log_exceptions
self.last_action = None
self.last_triggered: datetime | None = None
self._runs: list[_ScriptRun] = []
self.max_runs = max_runs
self._max_exceeded = max_exceeded
if script_mode == SCRIPT_MODE_QUEUED:
self._queue_lck = asyncio.Lock()
self._config_cache: dict[set[tuple], Callable[..., bool]] = {}
self._repeat_script: dict[int, Script] = {}
self._choose_data: dict[int, _ChooseData] = {}
self._if_data: dict[int, _IfData] = {}
self._parallel_scripts: dict[int, list[Script]] = {}
self._referenced_entities: set[str] | None = None
self._referenced_devices: set[str] | None = None
self._referenced_areas: set[str] | None = None
self.variables = variables
self._variables_dynamic = template.is_complex(variables)
if self._variables_dynamic:
template.attach(hass, variables)
@property
def change_listener(self) -> Callable[..., Any] | None:
"""Return the change_listener."""
return self._change_listener
@change_listener.setter
def change_listener(self, change_listener: Callable[..., Any]) -> None:
"""Update the change_listener."""
self._change_listener = change_listener
if (
self._change_listener_job is None
or change_listener != self._change_listener_job.target
):
self._change_listener_job = HassJob(change_listener)
def _set_logger(self, logger: logging.Logger | None = None) -> None:
if logger:
self._logger = logger
else:
self._logger = logging.getLogger(f"{__name__}.{slugify(self.name)}")
def update_logger(self, logger: logging.Logger | None = None) -> None:
"""Update logger."""
self._set_logger(logger)
for script in self._repeat_script.values():
script.update_logger(self._logger)
for parallel_scripts in self._parallel_scripts.values():
for parallel_script in parallel_scripts:
parallel_script.update_logger(self._logger)
for choose_data in self._choose_data.values():
for _, script in choose_data["choices"]:
script.update_logger(self._logger)
if choose_data["default"] is not None:
choose_data["default"].update_logger(self._logger)
for if_data in self._if_data.values():
if_data["if_then"].update_logger(self._logger)
if if_data["if_else"] is not None:
if_data["if_else"].update_logger(self._logger)
def _changed(self) -> None:
if self._change_listener_job:
self._hass.async_run_hass_job(self._change_listener_job)
@callback
def _chain_change_listener(self, sub_script: Script) -> None:
if sub_script.is_running:
self.last_action = sub_script.last_action
self._changed()
@property
def is_running(self) -> bool:
"""Return true if script is on."""
return len(self._runs) > 0
@property
def runs(self) -> int:
"""Return the number of current runs."""
return len(self._runs)
@property
def supports_max(self) -> bool:
"""Return true if the current mode support max."""
return self.script_mode in (SCRIPT_MODE_PARALLEL, SCRIPT_MODE_QUEUED)
@property
def referenced_areas(self):
"""Return a set of referenced areas."""
if self._referenced_areas is not None:
return self._referenced_areas
self._referenced_areas: set[str] = set()
Script._find_referenced_areas(self._referenced_areas, self.sequence)
return self._referenced_areas
@staticmethod
def _find_referenced_areas(referenced, sequence):
for step in sequence:
action = cv.determine_script_action(step)
if action == cv.SCRIPT_ACTION_CALL_SERVICE:
for data in (
step.get(CONF_TARGET),
step.get(service.CONF_SERVICE_DATA),
step.get(service.CONF_SERVICE_DATA_TEMPLATE),
):
_referenced_extract_ids(data, ATTR_AREA_ID, referenced)
elif action == cv.SCRIPT_ACTION_CHOOSE:
for choice in step[CONF_CHOOSE]:
Script._find_referenced_areas(referenced, choice[CONF_SEQUENCE])
if CONF_DEFAULT in step:
Script._find_referenced_areas(referenced, step[CONF_DEFAULT])
elif action == cv.SCRIPT_ACTION_IF:
Script._find_referenced_areas(referenced, step[CONF_THEN])
if CONF_ELSE in step:
Script._find_referenced_areas(referenced, step[CONF_ELSE])
elif action == cv.SCRIPT_ACTION_PARALLEL:
for script in step[CONF_PARALLEL]:
Script._find_referenced_areas(referenced, script[CONF_SEQUENCE])
@property
def referenced_devices(self):
"""Return a set of referenced devices."""
if self._referenced_devices is not None:
return self._referenced_devices
self._referenced_devices: set[str] = set()
Script._find_referenced_devices(self._referenced_devices, self.sequence)
return self._referenced_devices
@staticmethod
def _find_referenced_devices(referenced, sequence):
for step in sequence:
action = cv.determine_script_action(step)
if action == cv.SCRIPT_ACTION_CALL_SERVICE:
for data in (
step.get(CONF_TARGET),
step.get(service.CONF_SERVICE_DATA),
step.get(service.CONF_SERVICE_DATA_TEMPLATE),
):
_referenced_extract_ids(data, ATTR_DEVICE_ID, referenced)
elif action == cv.SCRIPT_ACTION_CHECK_CONDITION:
referenced |= condition.async_extract_devices(step)
elif action == cv.SCRIPT_ACTION_DEVICE_AUTOMATION:
referenced.add(step[CONF_DEVICE_ID])
elif action == cv.SCRIPT_ACTION_CHOOSE:
for choice in step[CONF_CHOOSE]:
for cond in choice[CONF_CONDITIONS]:
referenced |= condition.async_extract_devices(cond)
Script._find_referenced_devices(referenced, choice[CONF_SEQUENCE])
if CONF_DEFAULT in step:
Script._find_referenced_devices(referenced, step[CONF_DEFAULT])
elif action == cv.SCRIPT_ACTION_IF:
for cond in step[CONF_IF]:
referenced |= condition.async_extract_devices(cond)
Script._find_referenced_devices(referenced, step[CONF_THEN])
if CONF_ELSE in step:
Script._find_referenced_devices(referenced, step[CONF_ELSE])
elif action == cv.SCRIPT_ACTION_PARALLEL:
for script in step[CONF_PARALLEL]:
Script._find_referenced_devices(referenced, script[CONF_SEQUENCE])
@property
def referenced_entities(self):
"""Return a set of referenced entities."""
if self._referenced_entities is not None:
return self._referenced_entities
self._referenced_entities: set[str] = set()
Script._find_referenced_entities(self._referenced_entities, self.sequence)
return self._referenced_entities
@staticmethod
def _find_referenced_entities(referenced, sequence):
for step in sequence:
action = cv.determine_script_action(step)
if action == cv.SCRIPT_ACTION_CALL_SERVICE:
for data in (
step,
step.get(CONF_TARGET),
step.get(service.CONF_SERVICE_DATA),
step.get(service.CONF_SERVICE_DATA_TEMPLATE),
):
_referenced_extract_ids(data, ATTR_ENTITY_ID, referenced)
elif action == cv.SCRIPT_ACTION_CHECK_CONDITION:
referenced |= condition.async_extract_entities(step)
elif action == cv.SCRIPT_ACTION_ACTIVATE_SCENE:
referenced.add(step[CONF_SCENE])
elif action == cv.SCRIPT_ACTION_CHOOSE:
for choice in step[CONF_CHOOSE]:
for cond in choice[CONF_CONDITIONS]:
referenced |= condition.async_extract_entities(cond)
Script._find_referenced_entities(referenced, choice[CONF_SEQUENCE])
if CONF_DEFAULT in step:
Script._find_referenced_entities(referenced, step[CONF_DEFAULT])
elif action == cv.SCRIPT_ACTION_IF:
for cond in step[CONF_IF]:
referenced |= condition.async_extract_entities(cond)
Script._find_referenced_entities(referenced, step[CONF_THEN])
if CONF_ELSE in step:
Script._find_referenced_entities(referenced, step[CONF_ELSE])
elif action == cv.SCRIPT_ACTION_PARALLEL:
for script in step[CONF_PARALLEL]:
Script._find_referenced_entities(referenced, script[CONF_SEQUENCE])
def run(
self, variables: _VarsType | None = None, context: Context | None = None
) -> None:
"""Run script."""
asyncio.run_coroutine_threadsafe(
self.async_run(variables, context), self._hass.loop
).result()
async def async_run(
self,
run_variables: _VarsType | None = None,
context: Context | None = None,
started_action: Callable[..., Any] | None = None,
) -> None:
"""Run script."""
if context is None:
self._log(
"Running script requires passing in a context", level=logging.WARNING
)
context = Context()
# Prevent spawning new script runs when Home Assistant is shutting down
if DATA_NEW_SCRIPT_RUNS_NOT_ALLOWED in self._hass.data:
self._log("Home Assistant is shutting down, starting script blocked")
return
# Prevent spawning new script runs if not allowed by script mode
if self.is_running:
if self.script_mode == SCRIPT_MODE_SINGLE:
if self._max_exceeded != "SILENT":
self._log("Already running", level=LOGSEVERITY[self._max_exceeded])
script_execution_set("failed_single")
return
if self.script_mode != SCRIPT_MODE_RESTART and self.runs == self.max_runs:
if self._max_exceeded != "SILENT":
self._log(
"Maximum number of runs exceeded",
level=LOGSEVERITY[self._max_exceeded],
)
script_execution_set("failed_max_runs")
return
# If this is a top level Script then make a copy of the variables in case they
# are read-only, but more importantly, so as not to leak any variables created
# during the run back to the caller.
if self._top_level:
if self.variables:
try:
variables = self.variables.async_render(
self._hass,
run_variables,
)
except exceptions.TemplateError as err:
self._log("Error rendering variables: %s", err, level=logging.ERROR)
raise
elif run_variables:
variables = dict(run_variables)
else:
variables = {}
variables["context"] = context
else:
variables = cast(dict, run_variables)
# Prevent non-allowed recursive calls which will cause deadlocks when we try to
# stop (restart) or wait for (queued) our own script run.
script_stack = script_stack_cv.get()
if (
self.script_mode in (SCRIPT_MODE_RESTART, SCRIPT_MODE_QUEUED)
and (script_stack := script_stack_cv.get()) is not None
and id(self) in script_stack
):
script_execution_set("disallowed_recursion_detected")
self._log("Disallowed recursion detected", level=logging.WARNING)
return
if self.script_mode != SCRIPT_MODE_QUEUED:
cls = _ScriptRun
else:
cls = _QueuedScriptRun
run = cls(
self._hass, self, cast(dict, variables), context, self._log_exceptions
)
self._runs.append(run)
if self.script_mode == SCRIPT_MODE_RESTART:
# When script mode is SCRIPT_MODE_RESTART, first add the new run and then
# stop any other runs. If we stop other runs first, self.is_running will
# return false after the other script runs were stopped until our task
# resumes running.
self._log("Restarting")
await self.async_stop(update_state=False, spare=run)
if started_action:
self._hass.async_run_job(started_action)
self.last_triggered = utcnow()
self._changed()
try:
await asyncio.shield(run.async_run())
except asyncio.CancelledError:
await run.async_stop()
self._changed()
raise
async def _async_stop(
self, aws: list[asyncio.Task], update_state: bool, spare: _ScriptRun | None
) -> None:
await asyncio.wait(aws)
if update_state:
self._changed()
async def async_stop(
self, update_state: bool = True, spare: _ScriptRun | None = None
) -> None:
"""Stop running script."""
# Collect a a list of script runs to stop. This must be done before calling
# asyncio.shield as asyncio.shield yields to the event loop, which would cause
# us to wait for script runs added after the call to async_stop.
aws = [
asyncio.create_task(run.async_stop()) for run in self._runs if run != spare
]
if not aws:
return
await asyncio.shield(self._async_stop(aws, update_state, spare))
async def _async_get_condition(self, config):
if isinstance(config, template.Template):
config_cache_key = config.template
else:
config_cache_key = frozenset((k, str(v)) for k, v in config.items())
if not (cond := self._config_cache.get(config_cache_key)):
cond = await condition.async_from_config(self._hass, config)
self._config_cache[config_cache_key] = cond
return cond
def _prep_repeat_script(self, step: int) -> Script:
action = self.sequence[step]
step_name = action.get(CONF_ALIAS, f"Repeat at step {step+1}")
sub_script = Script(
self._hass,
action[CONF_REPEAT][CONF_SEQUENCE],
f"{self.name}: {step_name}",
self.domain,
running_description=self.running_description,
script_mode=SCRIPT_MODE_PARALLEL,
max_runs=self.max_runs,
logger=self._logger,
top_level=False,
)
sub_script.change_listener = partial(self._chain_change_listener, sub_script)
return sub_script
def _get_repeat_script(self, step: int) -> Script:
if not (sub_script := self._repeat_script.get(step)):
sub_script = self._prep_repeat_script(step)
self._repeat_script[step] = sub_script
return sub_script
async def _async_prep_choose_data(self, step: int) -> _ChooseData:
action = self.sequence[step]
step_name = action.get(CONF_ALIAS, f"Choose at step {step+1}")
choices = []
for idx, choice in enumerate(action[CONF_CHOOSE], start=1):
conditions = [
await self._async_get_condition(config)
for config in choice.get(CONF_CONDITIONS, [])
]
choice_name = choice.get(CONF_ALIAS, f"choice {idx}")
sub_script = Script(
self._hass,
choice[CONF_SEQUENCE],
f"{self.name}: {step_name}: {choice_name}",
self.domain,
running_description=self.running_description,
script_mode=SCRIPT_MODE_PARALLEL,
max_runs=self.max_runs,
logger=self._logger,
top_level=False,
)
sub_script.change_listener = partial(
self._chain_change_listener, sub_script
)
choices.append((conditions, sub_script))
default_script: Script | None
if CONF_DEFAULT in action:
default_script = Script(
self._hass,
action[CONF_DEFAULT],
f"{self.name}: {step_name}: default",
self.domain,
running_description=self.running_description,
script_mode=SCRIPT_MODE_PARALLEL,
max_runs=self.max_runs,
logger=self._logger,
top_level=False,
)
default_script.change_listener = partial(
self._chain_change_listener, default_script
)
else:
default_script = None
return {"choices": choices, "default": default_script}
async def _async_get_choose_data(self, step: int) -> _ChooseData:
if not (choose_data := self._choose_data.get(step)):
choose_data = await self._async_prep_choose_data(step)
self._choose_data[step] = choose_data
return choose_data
async def _async_prep_if_data(self, step: int) -> _IfData:
"""Prepare data for an if statement."""
action = self.sequence[step]
step_name = action.get(CONF_ALIAS, f"If at step {step+1}")
conditions = [
await self._async_get_condition(config) for config in action[CONF_IF]
]
then_script = Script(
self._hass,
action[CONF_THEN],
f"{self.name}: {step_name}",
self.domain,
running_description=self.running_description,
script_mode=SCRIPT_MODE_PARALLEL,
max_runs=self.max_runs,
logger=self._logger,
top_level=False,
)
then_script.change_listener = partial(self._chain_change_listener, then_script)
if CONF_ELSE in action:
else_script = Script(
self._hass,
action[CONF_ELSE],
f"{self.name}: {step_name}",
self.domain,
running_description=self.running_description,
script_mode=SCRIPT_MODE_PARALLEL,
max_runs=self.max_runs,
logger=self._logger,
top_level=False,
)
else_script.change_listener = partial(
self._chain_change_listener, else_script
)
else:
else_script = None
return _IfData(
if_conditions=conditions,
if_then=then_script,
if_else=else_script,
)
async def _async_get_if_data(self, step: int) -> _IfData:
if not (if_data := self._if_data.get(step)):
if_data = await self._async_prep_if_data(step)
self._if_data[step] = if_data
return if_data
async def _async_prep_parallel_scripts(self, step: int) -> list[Script]:
action = self.sequence[step]
step_name = action.get(CONF_ALIAS, f"Parallel action at step {step+1}")
parallel_scripts: list[Script] = []
for idx, parallel_script in enumerate(action[CONF_PARALLEL], start=1):
parallel_name = parallel_script.get(CONF_ALIAS, f"parallel {idx}")
parallel_script = Script(
self._hass,
parallel_script[CONF_SEQUENCE],
f"{self.name}: {step_name}: {parallel_name}",
self.domain,
running_description=self.running_description,
script_mode=SCRIPT_MODE_PARALLEL,
max_runs=self.max_runs,
logger=self._logger,
top_level=False,
)
parallel_script.change_listener = partial(
self._chain_change_listener, parallel_script
)
parallel_scripts.append(parallel_script)
return parallel_scripts
async def _async_get_parallel_scripts(self, step: int) -> list[Script]:
if not (parallel_scripts := self._parallel_scripts.get(step)):
parallel_scripts = await self._async_prep_parallel_scripts(step)
self._parallel_scripts[step] = parallel_scripts
return parallel_scripts
def _log(
self, msg: str, *args: Any, level: int = logging.INFO, **kwargs: Any
) -> None:
msg = f"%s: {msg}"
args = (self.name, *args)
if level == _LOG_EXCEPTION:
self._logger.exception(msg, *args, **kwargs)
else:
self._logger.log(level, msg, *args, **kwargs)
@callback
def breakpoint_clear(hass, key, run_id, node):
"""Clear a breakpoint."""
run_id = run_id or RUN_ID_ANY
breakpoints = hass.data[DATA_SCRIPT_BREAKPOINTS]
if key not in breakpoints or run_id not in breakpoints[key]:
return
breakpoints[key][run_id].discard(node)
@callback
def breakpoint_clear_all(hass: HomeAssistant) -> None:
"""Clear all breakpoints."""
hass.data[DATA_SCRIPT_BREAKPOINTS] = {}
@callback
def breakpoint_set(hass, key, run_id, node):
"""Set a breakpoint."""
run_id = run_id or RUN_ID_ANY
breakpoints = hass.data[DATA_SCRIPT_BREAKPOINTS]
if key not in breakpoints:
breakpoints[key] = {}
if run_id not in breakpoints[key]:
breakpoints[key][run_id] = set()
breakpoints[key][run_id].add(node)
@callback
def breakpoint_list(hass: HomeAssistant) -> list[dict[str, Any]]:
"""List breakpoints."""
breakpoints = hass.data[DATA_SCRIPT_BREAKPOINTS]
return [
{"key": key, "run_id": run_id, "node": node}
for key in breakpoints
for run_id in breakpoints[key]
for node in breakpoints[key][run_id]
]
@callback
def debug_continue(hass, key, run_id):
"""Continue execution of a halted script."""
# Clear any wildcard breakpoint
breakpoint_clear(hass, key, run_id, NODE_ANY)
signal = SCRIPT_DEBUG_CONTINUE_STOP.format(key, run_id)
async_dispatcher_send(hass, signal, "continue")
@callback
def debug_step(hass, key, run_id):
"""Single step a halted script."""
# Set a wildcard breakpoint
breakpoint_set(hass, key, run_id, NODE_ANY)
signal = SCRIPT_DEBUG_CONTINUE_STOP.format(key, run_id)
async_dispatcher_send(hass, signal, "continue")
@callback
def debug_stop(hass, key, run_id):
"""Stop execution of a running or halted script."""
signal = SCRIPT_DEBUG_CONTINUE_STOP.format(key, run_id)
async_dispatcher_send(hass, signal, "stop")
| 36.150563 | 88 | 0.610812 | from __future__ import annotations
import asyncio
from collections.abc import Callable, Sequence
from contextlib import asynccontextmanager, suppress
from contextvars import ContextVar
from copy import copy
from datetime import datetime, timedelta
from functools import partial
import itertools
import logging
from types import MappingProxyType
from typing import Any, TypedDict, Union, cast
import async_timeout
import voluptuous as vol
from homeassistant import exceptions
from homeassistant.components import scene
from homeassistant.components.device_automation import action as device_action
from homeassistant.components.logger import LOGSEVERITY
from homeassistant.const import (
ATTR_AREA_ID,
ATTR_DEVICE_ID,
ATTR_ENTITY_ID,
CONF_ALIAS,
CONF_CHOOSE,
CONF_CONDITION,
CONF_CONDITIONS,
CONF_CONTINUE_ON_TIMEOUT,
CONF_COUNT,
CONF_DEFAULT,
CONF_DELAY,
CONF_DEVICE_ID,
CONF_DOMAIN,
CONF_ELSE,
CONF_ERROR,
CONF_EVENT,
CONF_EVENT_DATA,
CONF_EVENT_DATA_TEMPLATE,
CONF_IF,
CONF_MODE,
CONF_PARALLEL,
CONF_REPEAT,
CONF_SCENE,
CONF_SEQUENCE,
CONF_SERVICE,
CONF_STOP,
CONF_TARGET,
CONF_THEN,
CONF_TIMEOUT,
CONF_UNTIL,
CONF_VARIABLES,
CONF_WAIT_FOR_TRIGGER,
CONF_WAIT_TEMPLATE,
CONF_WHILE,
EVENT_HOMEASSISTANT_STOP,
SERVICE_TURN_ON,
)
from homeassistant.core import (
SERVICE_CALL_LIMIT,
Context,
HassJob,
HomeAssistant,
callback,
)
from homeassistant.util import slugify
from homeassistant.util.dt import utcnow
from . import condition, config_validation as cv, service, template
from .condition import ConditionCheckerType, trace_condition_function
from .dispatcher import async_dispatcher_connect, async_dispatcher_send
from .event import async_call_later, async_track_template
from .script_variables import ScriptVariables
from .trace import (
TraceElement,
async_trace_path,
script_execution_set,
trace_append_element,
trace_id_get,
trace_path,
trace_path_get,
trace_path_stack_cv,
trace_set_result,
trace_stack_cv,
trace_stack_pop,
trace_stack_push,
trace_stack_top,
trace_update_result,
)
from .trigger import async_initialize_triggers, async_validate_trigger_config
from .typing import ConfigType
SCRIPT_MODE_PARALLEL = "parallel"
SCRIPT_MODE_QUEUED = "queued"
SCRIPT_MODE_RESTART = "restart"
SCRIPT_MODE_SINGLE = "single"
SCRIPT_MODE_CHOICES = [
SCRIPT_MODE_PARALLEL,
SCRIPT_MODE_QUEUED,
SCRIPT_MODE_RESTART,
SCRIPT_MODE_SINGLE,
]
DEFAULT_SCRIPT_MODE = SCRIPT_MODE_SINGLE
CONF_MAX = "max"
DEFAULT_MAX = 10
CONF_MAX_EXCEEDED = "max_exceeded"
_MAX_EXCEEDED_CHOICES = list(LOGSEVERITY) + ["SILENT"]
DEFAULT_MAX_EXCEEDED = "WARNING"
ATTR_CUR = "current"
ATTR_MAX = "max"
DATA_SCRIPTS = "helpers.script"
DATA_SCRIPT_BREAKPOINTS = "helpers.script_breakpoints"
DATA_NEW_SCRIPT_RUNS_NOT_ALLOWED = "helpers.script_not_allowed"
RUN_ID_ANY = "*"
NODE_ANY = "*"
_LOGGER = logging.getLogger(__name__)
_LOG_EXCEPTION = logging.ERROR + 1
_TIMEOUT_MSG = "Timeout reached, abort script."
_SHUTDOWN_MAX_WAIT = 60
ACTION_TRACE_NODE_MAX_LEN = 20
SCRIPT_BREAKPOINT_HIT = "script_breakpoint_hit"
SCRIPT_DEBUG_CONTINUE_STOP = "script_debug_continue_stop_{}_{}"
SCRIPT_DEBUG_CONTINUE_ALL = "script_debug_continue_all"
script_stack_cv: ContextVar[list[int] | None] = ContextVar("script_stack", default=None)
def action_trace_append(variables, path):
trace_element = TraceElement(variables, path)
trace_append_element(trace_element, ACTION_TRACE_NODE_MAX_LEN)
return trace_element
@asynccontextmanager
async def trace_action(hass, script_run, stop, variables):
path = trace_path_get()
trace_element = action_trace_append(variables, path)
trace_stack_push(trace_stack_cv, trace_element)
trace_id = trace_id_get()
if trace_id:
key = trace_id[0]
run_id = trace_id[1]
breakpoints = hass.data[DATA_SCRIPT_BREAKPOINTS]
if key in breakpoints and (
(
run_id in breakpoints[key]
and (
path in breakpoints[key][run_id]
or NODE_ANY in breakpoints[key][run_id]
)
)
or (
RUN_ID_ANY in breakpoints[key]
and (
path in breakpoints[key][RUN_ID_ANY]
or NODE_ANY in breakpoints[key][RUN_ID_ANY]
)
)
):
async_dispatcher_send(hass, SCRIPT_BREAKPOINT_HIT, key, run_id, path)
done = asyncio.Event()
@callback
def async_continue_stop(command=None):
if command == "stop":
stop.set()
done.set()
signal = SCRIPT_DEBUG_CONTINUE_STOP.format(key, run_id)
remove_signal1 = async_dispatcher_connect(hass, signal, async_continue_stop)
remove_signal2 = async_dispatcher_connect(
hass, SCRIPT_DEBUG_CONTINUE_ALL, async_continue_stop
)
tasks = [hass.async_create_task(flag.wait()) for flag in (stop, done)]
await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
for task in tasks:
task.cancel()
remove_signal1()
remove_signal2()
try:
yield trace_element
except _AbortScript as ex:
trace_element.set_error(ex.__cause__ or ex)
raise ex
except _StopScript as ex:
raise ex
except Exception as ex:
trace_element.set_error(ex)
raise ex
finally:
trace_stack_pop(trace_stack_cv)
def make_script_schema(schema, default_script_mode, extra=vol.PREVENT_EXTRA):
return vol.Schema(
{
**schema,
vol.Optional(CONF_MODE, default=default_script_mode): vol.In(
SCRIPT_MODE_CHOICES
),
vol.Optional(CONF_MAX, default=DEFAULT_MAX): vol.All(
vol.Coerce(int), vol.Range(min=2)
),
vol.Optional(CONF_MAX_EXCEEDED, default=DEFAULT_MAX_EXCEEDED): vol.All(
vol.Upper, vol.In(_MAX_EXCEEDED_CHOICES)
),
},
extra=extra,
)
STATIC_VALIDATION_ACTION_TYPES = (
cv.SCRIPT_ACTION_CALL_SERVICE,
cv.SCRIPT_ACTION_DELAY,
cv.SCRIPT_ACTION_WAIT_TEMPLATE,
cv.SCRIPT_ACTION_FIRE_EVENT,
cv.SCRIPT_ACTION_ACTIVATE_SCENE,
cv.SCRIPT_ACTION_VARIABLES,
cv.SCRIPT_ACTION_ERROR,
cv.SCRIPT_ACTION_STOP,
)
async def async_validate_actions_config(
hass: HomeAssistant, actions: list[ConfigType]
) -> list[ConfigType]:
return await asyncio.gather(
*(async_validate_action_config(hass, action) for action in actions)
)
async def async_validate_action_config(
hass: HomeAssistant, config: ConfigType
) -> ConfigType:
action_type = cv.determine_script_action(config)
if action_type in STATIC_VALIDATION_ACTION_TYPES:
pass
elif action_type == cv.SCRIPT_ACTION_DEVICE_AUTOMATION:
config = await device_action.async_validate_action_config(hass, config)
elif action_type == cv.SCRIPT_ACTION_CHECK_CONDITION:
config = await condition.async_validate_condition_config(hass, config)
elif action_type == cv.SCRIPT_ACTION_WAIT_FOR_TRIGGER:
config[CONF_WAIT_FOR_TRIGGER] = await async_validate_trigger_config(
hass, config[CONF_WAIT_FOR_TRIGGER]
)
elif action_type == cv.SCRIPT_ACTION_REPEAT:
if CONF_UNTIL in config[CONF_REPEAT]:
conditions = await condition.async_validate_conditions_config(
hass, config[CONF_REPEAT][CONF_UNTIL]
)
config[CONF_REPEAT][CONF_UNTIL] = conditions
if CONF_WHILE in config[CONF_REPEAT]:
conditions = await condition.async_validate_conditions_config(
hass, config[CONF_REPEAT][CONF_WHILE]
)
config[CONF_REPEAT][CONF_WHILE] = conditions
config[CONF_REPEAT][CONF_SEQUENCE] = await async_validate_actions_config(
hass, config[CONF_REPEAT][CONF_SEQUENCE]
)
elif action_type == cv.SCRIPT_ACTION_CHOOSE:
if CONF_DEFAULT in config:
config[CONF_DEFAULT] = await async_validate_actions_config(
hass, config[CONF_DEFAULT]
)
for choose_conf in config[CONF_CHOOSE]:
conditions = await condition.async_validate_conditions_config(
hass, choose_conf[CONF_CONDITIONS]
)
choose_conf[CONF_CONDITIONS] = conditions
choose_conf[CONF_SEQUENCE] = await async_validate_actions_config(
hass, choose_conf[CONF_SEQUENCE]
)
elif action_type == cv.SCRIPT_ACTION_IF:
config[CONF_IF] = await condition.async_validate_conditions_config(
hass, config[CONF_IF]
)
config[CONF_THEN] = await async_validate_actions_config(hass, config[CONF_THEN])
if CONF_ELSE in config:
config[CONF_ELSE] = await async_validate_actions_config(
hass, config[CONF_ELSE]
)
elif action_type == cv.SCRIPT_ACTION_PARALLEL:
for parallel_conf in config[CONF_PARALLEL]:
parallel_conf[CONF_SEQUENCE] = await async_validate_actions_config(
hass, parallel_conf[CONF_SEQUENCE]
)
else:
raise ValueError(f"No validation for {action_type}")
return config
class _AbortScript(Exception):
class _StopScript(Exception):
class _ScriptRun:
def __init__(
self,
hass: HomeAssistant,
script: Script,
variables: dict[str, Any],
context: Context | None,
log_exceptions: bool,
) -> None:
self._hass = hass
self._script = script
self._variables = variables
self._context = context
self._log_exceptions = log_exceptions
self._step = -1
self._action: dict[str, Any] | None = None
self._stop = asyncio.Event()
self._stopped = asyncio.Event()
def _changed(self) -> None:
if not self._stop.is_set():
self._script._changed()
async def _async_get_condition(self, config):
return await self._script._async_get_condition(config)
def _log(
self, msg: str, *args: Any, level: int = logging.INFO, **kwargs: Any
) -> None:
self._script._log(
msg, *args, level=level, **kwargs
)
def _step_log(self, default_message, timeout=None):
self._script.last_action = self._action.get(CONF_ALIAS, default_message)
_timeout = (
"" if timeout is None else f" (timeout: {timedelta(seconds=timeout)})"
)
self._log("Executing step %s%s", self._script.last_action, _timeout)
async def async_run(self) -> None:
if (script_stack := script_stack_cv.get()) is None:
script_stack = []
script_stack_cv.set(script_stack)
script_stack.append(id(self._script))
try:
self._log("Running %s", self._script.running_description)
for self._step, self._action in enumerate(self._script.sequence):
if self._stop.is_set():
script_execution_set("cancelled")
break
await self._async_step(log_exceptions=False)
else:
script_execution_set("finished")
except _StopScript:
script_execution_set("finished")
except _AbortScript:
script_execution_set("aborted")
except Exception:
script_execution_set("error")
raise
finally:
script_stack.pop()
self._finish()
async def _async_step(self, log_exceptions):
with trace_path(str(self._step)):
async with trace_action(self._hass, self, self._stop, self._variables):
if self._stop.is_set():
return
try:
handler = f"_async_{cv.determine_script_action(self._action)}_step"
await getattr(self, handler)()
except Exception as ex:
if not isinstance(ex, (_AbortScript, _StopScript)) and (
self._log_exceptions or log_exceptions
):
self._log_exception(ex)
raise
def _finish(self) -> None:
self._script._runs.remove(self)
if not self._script.is_running:
self._script.last_action = None
self._changed()
self._stopped.set()
async def async_stop(self) -> None:
self._stop.set()
await self._stopped.wait()
def _log_exception(self, exception):
action_type = cv.determine_script_action(self._action)
error = str(exception)
level = logging.ERROR
if isinstance(exception, vol.Invalid):
error_desc = "Invalid data"
elif isinstance(exception, exceptions.TemplateError):
error_desc = "Error rendering template"
elif isinstance(exception, exceptions.Unauthorized):
error_desc = "Unauthorized"
elif isinstance(exception, exceptions.ServiceNotFound):
error_desc = "Service not found"
elif isinstance(exception, exceptions.HomeAssistantError):
error_desc = "Error"
else:
error_desc = "Unexpected error"
level = _LOG_EXCEPTION
self._log(
"Error executing script. %s for %s at pos %s: %s",
error_desc,
action_type,
self._step + 1,
error,
level=level,
)
def _get_pos_time_period_template(self, key):
try:
return cv.positive_time_period(
template.render_complex(self._action[key], self._variables)
)
except (exceptions.TemplateError, vol.Invalid) as ex:
self._log(
"Error rendering %s %s template: %s",
self._script.name,
key,
ex,
level=logging.ERROR,
)
raise _AbortScript from ex
async def _async_delay_step(self):
delay = self._get_pos_time_period_template(CONF_DELAY)
self._step_log(f"delay {delay}")
delay = delay.total_seconds()
self._changed()
trace_set_result(delay=delay, done=False)
try:
async with async_timeout.timeout(delay):
await self._stop.wait()
except asyncio.TimeoutError:
trace_set_result(delay=delay, done=True)
async def _async_wait_template_step(self):
if CONF_TIMEOUT in self._action:
timeout = self._get_pos_time_period_template(CONF_TIMEOUT).total_seconds()
else:
timeout = None
self._step_log("wait template", timeout)
self._variables["wait"] = {"remaining": timeout, "completed": False}
trace_set_result(wait=self._variables["wait"])
wait_template = self._action[CONF_WAIT_TEMPLATE]
wait_template.hass = self._hass
if condition.async_template(self._hass, wait_template, self._variables, False):
self._variables["wait"]["completed"] = True
return
@callback
def async_script_wait(entity_id, from_s, to_s):
wait_var = self._variables["wait"]
if to_context and to_context.deadline:
wait_var["remaining"] = to_context.deadline - self._hass.loop.time()
else:
wait_var["remaining"] = timeout
wait_var["completed"] = True
done.set()
to_context = None
unsub = async_track_template(
self._hass, wait_template, async_script_wait, self._variables
)
self._changed()
done = asyncio.Event()
tasks = [
self._hass.async_create_task(flag.wait()) for flag in (self._stop, done)
]
try:
async with async_timeout.timeout(timeout) as to_context:
await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
except asyncio.TimeoutError as ex:
self._variables["wait"]["remaining"] = 0.0
if not self._action.get(CONF_CONTINUE_ON_TIMEOUT, True):
self._log(_TIMEOUT_MSG)
trace_set_result(wait=self._variables["wait"], timeout=True)
raise _AbortScript from ex
finally:
for task in tasks:
task.cancel()
unsub()
async def _async_run_long_action(self, long_task: asyncio.Task) -> None:
async def async_cancel_long_task() -> None:
long_task.cancel()
with suppress(Exception):
await long_task
stop_task = self._hass.async_create_task(self._stop.wait())
try:
await asyncio.wait(
{long_task, stop_task}, return_when=asyncio.FIRST_COMPLETED
)
except asyncio.CancelledError:
await async_cancel_long_task()
raise
finally:
stop_task.cancel()
if long_task.cancelled():
raise asyncio.CancelledError
if long_task.done():
# Propagate any exceptions that occurred.
long_task.result()
else:
# Stopped before long task completed, so cancel it.
await async_cancel_long_task()
async def _async_call_service_step(self):
self._step_log("call service")
params = service.async_prepare_call_from_config(
self._hass, self._action, self._variables
)
running_script = (
params[CONF_DOMAIN] == "automation"
and params[CONF_SERVICE] == "trigger"
or params[CONF_DOMAIN] in ("python_script", "script")
)
# If this might start a script then disable the call timeout.
# Otherwise use the normal service call limit.
if running_script:
limit = None
else:
limit = SERVICE_CALL_LIMIT
trace_set_result(params=params, running_script=running_script, limit=limit)
service_task = self._hass.async_create_task(
self._hass.services.async_call(
**params,
blocking=True,
context=self._context,
limit=limit,
)
)
if limit is not None:
# There is a call limit, so just wait for it to finish.
await service_task
return
await self._async_run_long_action(service_task)
async def _async_device_step(self):
self._step_log("device automation")
await device_action.async_call_action_from_config(
self._hass, self._action, self._variables, self._context
)
async def _async_scene_step(self):
self._step_log("activate scene")
trace_set_result(scene=self._action[CONF_SCENE])
await self._hass.services.async_call(
scene.DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: self._action[CONF_SCENE]},
blocking=True,
context=self._context,
)
async def _async_event_step(self):
self._step_log(self._action.get(CONF_ALIAS, self._action[CONF_EVENT]))
event_data = {}
for conf in (CONF_EVENT_DATA, CONF_EVENT_DATA_TEMPLATE):
if conf not in self._action:
continue
try:
event_data.update(
template.render_complex(self._action[conf], self._variables)
)
except exceptions.TemplateError as ex:
self._log(
"Error rendering event data template: %s", ex, level=logging.ERROR
)
trace_set_result(event=self._action[CONF_EVENT], event_data=event_data)
self._hass.bus.async_fire(
self._action[CONF_EVENT], event_data, context=self._context
)
async def _async_condition_step(self):
self._script.last_action = self._action.get(
CONF_ALIAS, self._action[CONF_CONDITION]
)
cond = await self._async_get_condition(self._action)
try:
trace_element = trace_stack_top(trace_stack_cv)
if trace_element:
trace_element.reuse_by_child = True
check = cond(self._hass, self._variables)
except exceptions.ConditionError as ex:
_LOGGER.warning("Error in 'condition' evaluation:\n%s", ex)
check = False
self._log("Test condition %s: %s", self._script.last_action, check)
trace_update_result(result=check)
if not check:
raise _AbortScript
def _test_conditions(self, conditions, name, condition_path=None):
if condition_path is None:
condition_path = name
@trace_condition_function
def traced_test_conditions(hass, variables):
try:
with trace_path(condition_path):
for idx, cond in enumerate(conditions):
with trace_path(str(idx)):
if not cond(hass, variables):
return False
except exceptions.ConditionError as ex:
_LOGGER.warning("Error in '%s[%s]' evaluation: %s", name, idx, ex)
return None
return True
result = traced_test_conditions(self._hass, self._variables)
return result
@async_trace_path("repeat")
async def _async_repeat_step(self):
description = self._action.get(CONF_ALIAS, "sequence")
repeat = self._action[CONF_REPEAT]
saved_repeat_vars = self._variables.get("repeat")
def set_repeat_var(iteration, count=None):
repeat_vars = {"first": iteration == 1, "index": iteration}
if count:
repeat_vars["last"] = iteration == count
self._variables["repeat"] = repeat_vars
# pylint: disable=protected-access
script = self._script._get_repeat_script(self._step)
async def async_run_sequence(iteration, extra_msg=""):
self._log("Repeating %s: Iteration %i%s", description, iteration, extra_msg)
with trace_path("sequence"):
await self._async_run_script(script)
if CONF_COUNT in repeat:
count = repeat[CONF_COUNT]
if isinstance(count, template.Template):
try:
count = int(count.async_render(self._variables))
except (exceptions.TemplateError, ValueError) as ex:
self._log(
"Error rendering %s repeat count template: %s",
self._script.name,
ex,
level=logging.ERROR,
)
raise _AbortScript from ex
extra_msg = f" of {count}"
for iteration in range(1, count + 1):
set_repeat_var(iteration, count)
await async_run_sequence(iteration, extra_msg)
if self._stop.is_set():
break
elif CONF_WHILE in repeat:
conditions = [
await self._async_get_condition(config) for config in repeat[CONF_WHILE]
]
for iteration in itertools.count(1):
set_repeat_var(iteration)
try:
if self._stop.is_set():
break
if not self._test_conditions(conditions, "while"):
break
except exceptions.ConditionError as ex:
_LOGGER.warning("Error in 'while' evaluation:\n%s", ex)
break
await async_run_sequence(iteration)
elif CONF_UNTIL in repeat:
conditions = [
await self._async_get_condition(config) for config in repeat[CONF_UNTIL]
]
for iteration in itertools.count(1):
set_repeat_var(iteration)
await async_run_sequence(iteration)
try:
if self._stop.is_set():
break
if self._test_conditions(conditions, "until") in [True, None]:
break
except exceptions.ConditionError as ex:
_LOGGER.warning("Error in 'until' evaluation:\n%s", ex)
break
if saved_repeat_vars:
self._variables["repeat"] = saved_repeat_vars
else:
self._variables.pop("repeat", None) # Not set if count = 0
async def _async_choose_step(self) -> None:
# pylint: disable=protected-access
choose_data = await self._script._async_get_choose_data(self._step)
with trace_path("choose"):
for idx, (conditions, script) in enumerate(choose_data["choices"]):
with trace_path(str(idx)):
try:
if self._test_conditions(conditions, "choose", "conditions"):
trace_set_result(choice=idx)
with trace_path("sequence"):
await self._async_run_script(script)
return
except exceptions.ConditionError as ex:
_LOGGER.warning("Error in 'choose' evaluation:\n%s", ex)
if choose_data["default"] is not None:
trace_set_result(choice="default")
with trace_path(["default"]):
await self._async_run_script(choose_data["default"])
async def _async_if_step(self) -> None:
# pylint: disable=protected-access
if_data = await self._script._async_get_if_data(self._step)
test_conditions = False
try:
with trace_path("if"):
test_conditions = self._test_conditions(
if_data["if_conditions"], "if", "condition"
)
except exceptions.ConditionError as ex:
_LOGGER.warning("Error in 'if' evaluation:\n%s", ex)
if test_conditions:
trace_set_result(choice="then")
with trace_path("then"):
await self._async_run_script(if_data["if_then"])
return
if if_data["if_else"] is not None:
trace_set_result(choice="else")
with trace_path("else"):
await self._async_run_script(if_data["if_else"])
async def _async_wait_for_trigger_step(self):
if CONF_TIMEOUT in self._action:
timeout = self._get_pos_time_period_template(CONF_TIMEOUT).total_seconds()
else:
timeout = None
self._step_log("wait for trigger", timeout)
variables = {**self._variables}
self._variables["wait"] = {"remaining": timeout, "trigger": None}
trace_set_result(wait=self._variables["wait"])
done = asyncio.Event()
async def async_done(variables, context=None):
wait_var = self._variables["wait"]
if to_context and to_context.deadline:
wait_var["remaining"] = to_context.deadline - self._hass.loop.time()
else:
wait_var["remaining"] = timeout
wait_var["trigger"] = variables["trigger"]
done.set()
def log_cb(level, msg, **kwargs):
self._log(msg, level=level, **kwargs)
to_context = None
remove_triggers = await async_initialize_triggers(
self._hass,
self._action[CONF_WAIT_FOR_TRIGGER],
async_done,
self._script.domain,
self._script.name,
log_cb,
variables=variables,
)
if not remove_triggers:
return
self._changed()
tasks = [
self._hass.async_create_task(flag.wait()) for flag in (self._stop, done)
]
try:
async with async_timeout.timeout(timeout) as to_context:
await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
except asyncio.TimeoutError as ex:
self._variables["wait"]["remaining"] = 0.0
if not self._action.get(CONF_CONTINUE_ON_TIMEOUT, True):
self._log(_TIMEOUT_MSG)
trace_set_result(wait=self._variables["wait"], timeout=True)
raise _AbortScript from ex
finally:
for task in tasks:
task.cancel()
remove_triggers()
async def _async_variables_step(self):
self._step_log("setting variables")
self._variables = self._action[CONF_VARIABLES].async_render(
self._hass, self._variables, render_as_defaults=False
)
async def _async_stop_step(self):
stop = self._action[CONF_STOP]
self._log("Stop script sequence: %s", stop)
trace_set_result(stop=stop)
raise _StopScript(stop)
async def _async_error_step(self):
error = self._action[CONF_ERROR]
self._log("Error script sequence: %s", error)
trace_set_result(error=error)
raise _AbortScript(error)
@async_trace_path("parallel")
async def _async_parallel_step(self) -> None:
# pylint: disable=protected-access
scripts = await self._script._async_get_parallel_scripts(self._step)
async def async_run_with_trace(idx: int, script: Script) -> None:
trace_path_stack_cv.set(copy(trace_path_stack_cv.get()))
with trace_path([str(idx), "sequence"]):
await self._async_run_script(script)
results = await asyncio.gather(
*(async_run_with_trace(idx, script) for idx, script in enumerate(scripts)),
return_exceptions=True,
)
for result in results:
if isinstance(result, Exception):
raise result
async def _async_run_script(self, script: Script) -> None:
await self._async_run_long_action(
self._hass.async_create_task(
script.async_run(self._variables, self._context)
)
)
class _QueuedScriptRun(_ScriptRun):
lock_acquired = False
async def async_run(self) -> None:
# Wait for previous run, if any, to finish by attempting to acquire the script's
lock_task = self._hass.async_create_task(
self._script._queue_lck.acquire() # pylint: disable=protected-access
)
stop_task = self._hass.async_create_task(self._stop.wait())
try:
await asyncio.wait(
{lock_task, stop_task}, return_when=asyncio.FIRST_COMPLETED
)
except asyncio.CancelledError:
self._finish()
raise
else:
self.lock_acquired = lock_task.done() and not lock_task.cancelled()
finally:
lock_task.cancel()
stop_task.cancel()
# If we've been told to stop, then just finish up. Otherwise, we've acquired the
# lock so we can go ahead and start the run.
if self._stop.is_set():
self._finish()
else:
await super().async_run()
def _finish(self) -> None:
# pylint: disable=protected-access
if self.lock_acquired:
self._script._queue_lck.release()
self.lock_acquired = False
super()._finish()
async def _async_stop_scripts_after_shutdown(hass, point_in_time):
hass.data[DATA_NEW_SCRIPT_RUNS_NOT_ALLOWED] = None
running_scripts = [
script for script in hass.data[DATA_SCRIPTS] if script["instance"].is_running
]
if running_scripts:
names = ", ".join([script["instance"].name for script in running_scripts])
_LOGGER.warning("Stopping scripts running too long after shutdown: %s", names)
await asyncio.gather(
*(
script["instance"].async_stop(update_state=False)
for script in running_scripts
)
)
async def _async_stop_scripts_at_shutdown(hass, event):
async_call_later(
hass, _SHUTDOWN_MAX_WAIT, partial(_async_stop_scripts_after_shutdown, hass)
)
running_scripts = [
script
for script in hass.data[DATA_SCRIPTS]
if script["instance"].is_running and script["started_before_shutdown"]
]
if running_scripts:
names = ", ".join([script["instance"].name for script in running_scripts])
_LOGGER.debug("Stopping scripts running at shutdown: %s", names)
await asyncio.gather(
*(script["instance"].async_stop() for script in running_scripts)
)
_VarsType = Union[dict[str, Any], MappingProxyType]
def _referenced_extract_ids(data: dict[str, Any], key: str, found: set[str]) -> None:
if not data:
return
item_ids = data.get(key)
if item_ids is None or isinstance(item_ids, template.Template):
return
if isinstance(item_ids, str):
found.add(item_ids)
else:
for item_id in item_ids:
found.add(item_id)
class _ChooseData(TypedDict):
choices: list[tuple[list[ConditionCheckerType], Script]]
default: Script | None
class _IfData(TypedDict):
if_conditions: list[ConditionCheckerType]
if_then: Script
if_else: Script | None
class Script:
def __init__(
self,
hass: HomeAssistant,
sequence: Sequence[dict[str, Any]],
name: str,
domain: str,
*,
# Used in "Running <running_description>" log message
running_description: str | None = None,
change_listener: Callable[..., Any] | None = None,
script_mode: str = DEFAULT_SCRIPT_MODE,
max_runs: int = DEFAULT_MAX,
max_exceeded: str = DEFAULT_MAX_EXCEEDED,
logger: logging.Logger | None = None,
log_exceptions: bool = True,
top_level: bool = True,
variables: ScriptVariables | None = None,
) -> None:
if not (all_scripts := hass.data.get(DATA_SCRIPTS)):
all_scripts = hass.data[DATA_SCRIPTS] = []
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, partial(_async_stop_scripts_at_shutdown, hass)
)
self._top_level = top_level
if top_level:
all_scripts.append(
{"instance": self, "started_before_shutdown": not hass.is_stopping}
)
if DATA_SCRIPT_BREAKPOINTS not in hass.data:
hass.data[DATA_SCRIPT_BREAKPOINTS] = {}
self._hass = hass
self.sequence = sequence
template.attach(hass, self.sequence)
self.name = name
self.domain = domain
self.running_description = running_description or f"{domain} script"
self._change_listener = change_listener
self._change_listener_job = (
None if change_listener is None else HassJob(change_listener)
)
self.script_mode = script_mode
self._set_logger(logger)
self._log_exceptions = log_exceptions
self.last_action = None
self.last_triggered: datetime | None = None
self._runs: list[_ScriptRun] = []
self.max_runs = max_runs
self._max_exceeded = max_exceeded
if script_mode == SCRIPT_MODE_QUEUED:
self._queue_lck = asyncio.Lock()
self._config_cache: dict[set[tuple], Callable[..., bool]] = {}
self._repeat_script: dict[int, Script] = {}
self._choose_data: dict[int, _ChooseData] = {}
self._if_data: dict[int, _IfData] = {}
self._parallel_scripts: dict[int, list[Script]] = {}
self._referenced_entities: set[str] | None = None
self._referenced_devices: set[str] | None = None
self._referenced_areas: set[str] | None = None
self.variables = variables
self._variables_dynamic = template.is_complex(variables)
if self._variables_dynamic:
template.attach(hass, variables)
@property
def change_listener(self) -> Callable[..., Any] | None:
return self._change_listener
@change_listener.setter
def change_listener(self, change_listener: Callable[..., Any]) -> None:
self._change_listener = change_listener
if (
self._change_listener_job is None
or change_listener != self._change_listener_job.target
):
self._change_listener_job = HassJob(change_listener)
def _set_logger(self, logger: logging.Logger | None = None) -> None:
if logger:
self._logger = logger
else:
self._logger = logging.getLogger(f"{__name__}.{slugify(self.name)}")
def update_logger(self, logger: logging.Logger | None = None) -> None:
self._set_logger(logger)
for script in self._repeat_script.values():
script.update_logger(self._logger)
for parallel_scripts in self._parallel_scripts.values():
for parallel_script in parallel_scripts:
parallel_script.update_logger(self._logger)
for choose_data in self._choose_data.values():
for _, script in choose_data["choices"]:
script.update_logger(self._logger)
if choose_data["default"] is not None:
choose_data["default"].update_logger(self._logger)
for if_data in self._if_data.values():
if_data["if_then"].update_logger(self._logger)
if if_data["if_else"] is not None:
if_data["if_else"].update_logger(self._logger)
def _changed(self) -> None:
if self._change_listener_job:
self._hass.async_run_hass_job(self._change_listener_job)
@callback
def _chain_change_listener(self, sub_script: Script) -> None:
if sub_script.is_running:
self.last_action = sub_script.last_action
self._changed()
@property
def is_running(self) -> bool:
return len(self._runs) > 0
@property
def runs(self) -> int:
return len(self._runs)
@property
def supports_max(self) -> bool:
return self.script_mode in (SCRIPT_MODE_PARALLEL, SCRIPT_MODE_QUEUED)
@property
def referenced_areas(self):
if self._referenced_areas is not None:
return self._referenced_areas
self._referenced_areas: set[str] = set()
Script._find_referenced_areas(self._referenced_areas, self.sequence)
return self._referenced_areas
@staticmethod
def _find_referenced_areas(referenced, sequence):
for step in sequence:
action = cv.determine_script_action(step)
if action == cv.SCRIPT_ACTION_CALL_SERVICE:
for data in (
step.get(CONF_TARGET),
step.get(service.CONF_SERVICE_DATA),
step.get(service.CONF_SERVICE_DATA_TEMPLATE),
):
_referenced_extract_ids(data, ATTR_AREA_ID, referenced)
elif action == cv.SCRIPT_ACTION_CHOOSE:
for choice in step[CONF_CHOOSE]:
Script._find_referenced_areas(referenced, choice[CONF_SEQUENCE])
if CONF_DEFAULT in step:
Script._find_referenced_areas(referenced, step[CONF_DEFAULT])
elif action == cv.SCRIPT_ACTION_IF:
Script._find_referenced_areas(referenced, step[CONF_THEN])
if CONF_ELSE in step:
Script._find_referenced_areas(referenced, step[CONF_ELSE])
elif action == cv.SCRIPT_ACTION_PARALLEL:
for script in step[CONF_PARALLEL]:
Script._find_referenced_areas(referenced, script[CONF_SEQUENCE])
@property
def referenced_devices(self):
if self._referenced_devices is not None:
return self._referenced_devices
self._referenced_devices: set[str] = set()
Script._find_referenced_devices(self._referenced_devices, self.sequence)
return self._referenced_devices
@staticmethod
def _find_referenced_devices(referenced, sequence):
for step in sequence:
action = cv.determine_script_action(step)
if action == cv.SCRIPT_ACTION_CALL_SERVICE:
for data in (
step.get(CONF_TARGET),
step.get(service.CONF_SERVICE_DATA),
step.get(service.CONF_SERVICE_DATA_TEMPLATE),
):
_referenced_extract_ids(data, ATTR_DEVICE_ID, referenced)
elif action == cv.SCRIPT_ACTION_CHECK_CONDITION:
referenced |= condition.async_extract_devices(step)
elif action == cv.SCRIPT_ACTION_DEVICE_AUTOMATION:
referenced.add(step[CONF_DEVICE_ID])
elif action == cv.SCRIPT_ACTION_CHOOSE:
for choice in step[CONF_CHOOSE]:
for cond in choice[CONF_CONDITIONS]:
referenced |= condition.async_extract_devices(cond)
Script._find_referenced_devices(referenced, choice[CONF_SEQUENCE])
if CONF_DEFAULT in step:
Script._find_referenced_devices(referenced, step[CONF_DEFAULT])
elif action == cv.SCRIPT_ACTION_IF:
for cond in step[CONF_IF]:
referenced |= condition.async_extract_devices(cond)
Script._find_referenced_devices(referenced, step[CONF_THEN])
if CONF_ELSE in step:
Script._find_referenced_devices(referenced, step[CONF_ELSE])
elif action == cv.SCRIPT_ACTION_PARALLEL:
for script in step[CONF_PARALLEL]:
Script._find_referenced_devices(referenced, script[CONF_SEQUENCE])
@property
def referenced_entities(self):
if self._referenced_entities is not None:
return self._referenced_entities
self._referenced_entities: set[str] = set()
Script._find_referenced_entities(self._referenced_entities, self.sequence)
return self._referenced_entities
@staticmethod
def _find_referenced_entities(referenced, sequence):
for step in sequence:
action = cv.determine_script_action(step)
if action == cv.SCRIPT_ACTION_CALL_SERVICE:
for data in (
step,
step.get(CONF_TARGET),
step.get(service.CONF_SERVICE_DATA),
step.get(service.CONF_SERVICE_DATA_TEMPLATE),
):
_referenced_extract_ids(data, ATTR_ENTITY_ID, referenced)
elif action == cv.SCRIPT_ACTION_CHECK_CONDITION:
referenced |= condition.async_extract_entities(step)
elif action == cv.SCRIPT_ACTION_ACTIVATE_SCENE:
referenced.add(step[CONF_SCENE])
elif action == cv.SCRIPT_ACTION_CHOOSE:
for choice in step[CONF_CHOOSE]:
for cond in choice[CONF_CONDITIONS]:
referenced |= condition.async_extract_entities(cond)
Script._find_referenced_entities(referenced, choice[CONF_SEQUENCE])
if CONF_DEFAULT in step:
Script._find_referenced_entities(referenced, step[CONF_DEFAULT])
elif action == cv.SCRIPT_ACTION_IF:
for cond in step[CONF_IF]:
referenced |= condition.async_extract_entities(cond)
Script._find_referenced_entities(referenced, step[CONF_THEN])
if CONF_ELSE in step:
Script._find_referenced_entities(referenced, step[CONF_ELSE])
elif action == cv.SCRIPT_ACTION_PARALLEL:
for script in step[CONF_PARALLEL]:
Script._find_referenced_entities(referenced, script[CONF_SEQUENCE])
def run(
self, variables: _VarsType | None = None, context: Context | None = None
) -> None:
asyncio.run_coroutine_threadsafe(
self.async_run(variables, context), self._hass.loop
).result()
async def async_run(
self,
run_variables: _VarsType | None = None,
context: Context | None = None,
started_action: Callable[..., Any] | None = None,
) -> None:
if context is None:
self._log(
"Running script requires passing in a context", level=logging.WARNING
)
context = Context()
# Prevent spawning new script runs when Home Assistant is shutting down
if DATA_NEW_SCRIPT_RUNS_NOT_ALLOWED in self._hass.data:
self._log("Home Assistant is shutting down, starting script blocked")
return
# Prevent spawning new script runs if not allowed by script mode
if self.is_running:
if self.script_mode == SCRIPT_MODE_SINGLE:
if self._max_exceeded != "SILENT":
self._log("Already running", level=LOGSEVERITY[self._max_exceeded])
script_execution_set("failed_single")
return
if self.script_mode != SCRIPT_MODE_RESTART and self.runs == self.max_runs:
if self._max_exceeded != "SILENT":
self._log(
"Maximum number of runs exceeded",
level=LOGSEVERITY[self._max_exceeded],
)
script_execution_set("failed_max_runs")
return
# If this is a top level Script then make a copy of the variables in case they
# are read-only, but more importantly, so as not to leak any variables created
# during the run back to the caller.
if self._top_level:
if self.variables:
try:
variables = self.variables.async_render(
self._hass,
run_variables,
)
except exceptions.TemplateError as err:
self._log("Error rendering variables: %s", err, level=logging.ERROR)
raise
elif run_variables:
variables = dict(run_variables)
else:
variables = {}
variables["context"] = context
else:
variables = cast(dict, run_variables)
# Prevent non-allowed recursive calls which will cause deadlocks when we try to
# stop (restart) or wait for (queued) our own script run.
script_stack = script_stack_cv.get()
if (
self.script_mode in (SCRIPT_MODE_RESTART, SCRIPT_MODE_QUEUED)
and (script_stack := script_stack_cv.get()) is not None
and id(self) in script_stack
):
script_execution_set("disallowed_recursion_detected")
self._log("Disallowed recursion detected", level=logging.WARNING)
return
if self.script_mode != SCRIPT_MODE_QUEUED:
cls = _ScriptRun
else:
cls = _QueuedScriptRun
run = cls(
self._hass, self, cast(dict, variables), context, self._log_exceptions
)
self._runs.append(run)
if self.script_mode == SCRIPT_MODE_RESTART:
# When script mode is SCRIPT_MODE_RESTART, first add the new run and then
# stop any other runs. If we stop other runs first, self.is_running will
# return false after the other script runs were stopped until our task
# resumes running.
self._log("Restarting")
await self.async_stop(update_state=False, spare=run)
if started_action:
self._hass.async_run_job(started_action)
self.last_triggered = utcnow()
self._changed()
try:
await asyncio.shield(run.async_run())
except asyncio.CancelledError:
await run.async_stop()
self._changed()
raise
async def _async_stop(
self, aws: list[asyncio.Task], update_state: bool, spare: _ScriptRun | None
) -> None:
await asyncio.wait(aws)
if update_state:
self._changed()
async def async_stop(
self, update_state: bool = True, spare: _ScriptRun | None = None
) -> None:
# Collect a a list of script runs to stop. This must be done before calling
# asyncio.shield as asyncio.shield yields to the event loop, which would cause
# us to wait for script runs added after the call to async_stop.
aws = [
asyncio.create_task(run.async_stop()) for run in self._runs if run != spare
]
if not aws:
return
await asyncio.shield(self._async_stop(aws, update_state, spare))
async def _async_get_condition(self, config):
if isinstance(config, template.Template):
config_cache_key = config.template
else:
config_cache_key = frozenset((k, str(v)) for k, v in config.items())
if not (cond := self._config_cache.get(config_cache_key)):
cond = await condition.async_from_config(self._hass, config)
self._config_cache[config_cache_key] = cond
return cond
def _prep_repeat_script(self, step: int) -> Script:
action = self.sequence[step]
step_name = action.get(CONF_ALIAS, f"Repeat at step {step+1}")
sub_script = Script(
self._hass,
action[CONF_REPEAT][CONF_SEQUENCE],
f"{self.name}: {step_name}",
self.domain,
running_description=self.running_description,
script_mode=SCRIPT_MODE_PARALLEL,
max_runs=self.max_runs,
logger=self._logger,
top_level=False,
)
sub_script.change_listener = partial(self._chain_change_listener, sub_script)
return sub_script
def _get_repeat_script(self, step: int) -> Script:
if not (sub_script := self._repeat_script.get(step)):
sub_script = self._prep_repeat_script(step)
self._repeat_script[step] = sub_script
return sub_script
async def _async_prep_choose_data(self, step: int) -> _ChooseData:
action = self.sequence[step]
step_name = action.get(CONF_ALIAS, f"Choose at step {step+1}")
choices = []
for idx, choice in enumerate(action[CONF_CHOOSE], start=1):
conditions = [
await self._async_get_condition(config)
for config in choice.get(CONF_CONDITIONS, [])
]
choice_name = choice.get(CONF_ALIAS, f"choice {idx}")
sub_script = Script(
self._hass,
choice[CONF_SEQUENCE],
f"{self.name}: {step_name}: {choice_name}",
self.domain,
running_description=self.running_description,
script_mode=SCRIPT_MODE_PARALLEL,
max_runs=self.max_runs,
logger=self._logger,
top_level=False,
)
sub_script.change_listener = partial(
self._chain_change_listener, sub_script
)
choices.append((conditions, sub_script))
default_script: Script | None
if CONF_DEFAULT in action:
default_script = Script(
self._hass,
action[CONF_DEFAULT],
f"{self.name}: {step_name}: default",
self.domain,
running_description=self.running_description,
script_mode=SCRIPT_MODE_PARALLEL,
max_runs=self.max_runs,
logger=self._logger,
top_level=False,
)
default_script.change_listener = partial(
self._chain_change_listener, default_script
)
else:
default_script = None
return {"choices": choices, "default": default_script}
async def _async_get_choose_data(self, step: int) -> _ChooseData:
if not (choose_data := self._choose_data.get(step)):
choose_data = await self._async_prep_choose_data(step)
self._choose_data[step] = choose_data
return choose_data
async def _async_prep_if_data(self, step: int) -> _IfData:
action = self.sequence[step]
step_name = action.get(CONF_ALIAS, f"If at step {step+1}")
conditions = [
await self._async_get_condition(config) for config in action[CONF_IF]
]
then_script = Script(
self._hass,
action[CONF_THEN],
f"{self.name}: {step_name}",
self.domain,
running_description=self.running_description,
script_mode=SCRIPT_MODE_PARALLEL,
max_runs=self.max_runs,
logger=self._logger,
top_level=False,
)
then_script.change_listener = partial(self._chain_change_listener, then_script)
if CONF_ELSE in action:
else_script = Script(
self._hass,
action[CONF_ELSE],
f"{self.name}: {step_name}",
self.domain,
running_description=self.running_description,
script_mode=SCRIPT_MODE_PARALLEL,
max_runs=self.max_runs,
logger=self._logger,
top_level=False,
)
else_script.change_listener = partial(
self._chain_change_listener, else_script
)
else:
else_script = None
return _IfData(
if_conditions=conditions,
if_then=then_script,
if_else=else_script,
)
async def _async_get_if_data(self, step: int) -> _IfData:
if not (if_data := self._if_data.get(step)):
if_data = await self._async_prep_if_data(step)
self._if_data[step] = if_data
return if_data
async def _async_prep_parallel_scripts(self, step: int) -> list[Script]:
action = self.sequence[step]
step_name = action.get(CONF_ALIAS, f"Parallel action at step {step+1}")
parallel_scripts: list[Script] = []
for idx, parallel_script in enumerate(action[CONF_PARALLEL], start=1):
parallel_name = parallel_script.get(CONF_ALIAS, f"parallel {idx}")
parallel_script = Script(
self._hass,
parallel_script[CONF_SEQUENCE],
f"{self.name}: {step_name}: {parallel_name}",
self.domain,
running_description=self.running_description,
script_mode=SCRIPT_MODE_PARALLEL,
max_runs=self.max_runs,
logger=self._logger,
top_level=False,
)
parallel_script.change_listener = partial(
self._chain_change_listener, parallel_script
)
parallel_scripts.append(parallel_script)
return parallel_scripts
async def _async_get_parallel_scripts(self, step: int) -> list[Script]:
if not (parallel_scripts := self._parallel_scripts.get(step)):
parallel_scripts = await self._async_prep_parallel_scripts(step)
self._parallel_scripts[step] = parallel_scripts
return parallel_scripts
def _log(
self, msg: str, *args: Any, level: int = logging.INFO, **kwargs: Any
) -> None:
msg = f"%s: {msg}"
args = (self.name, *args)
if level == _LOG_EXCEPTION:
self._logger.exception(msg, *args, **kwargs)
else:
self._logger.log(level, msg, *args, **kwargs)
@callback
def breakpoint_clear(hass, key, run_id, node):
run_id = run_id or RUN_ID_ANY
breakpoints = hass.data[DATA_SCRIPT_BREAKPOINTS]
if key not in breakpoints or run_id not in breakpoints[key]:
return
breakpoints[key][run_id].discard(node)
@callback
def breakpoint_clear_all(hass: HomeAssistant) -> None:
hass.data[DATA_SCRIPT_BREAKPOINTS] = {}
@callback
def breakpoint_set(hass, key, run_id, node):
run_id = run_id or RUN_ID_ANY
breakpoints = hass.data[DATA_SCRIPT_BREAKPOINTS]
if key not in breakpoints:
breakpoints[key] = {}
if run_id not in breakpoints[key]:
breakpoints[key][run_id] = set()
breakpoints[key][run_id].add(node)
@callback
def breakpoint_list(hass: HomeAssistant) -> list[dict[str, Any]]:
breakpoints = hass.data[DATA_SCRIPT_BREAKPOINTS]
return [
{"key": key, "run_id": run_id, "node": node}
for key in breakpoints
for run_id in breakpoints[key]
for node in breakpoints[key][run_id]
]
@callback
def debug_continue(hass, key, run_id):
# Clear any wildcard breakpoint
breakpoint_clear(hass, key, run_id, NODE_ANY)
signal = SCRIPT_DEBUG_CONTINUE_STOP.format(key, run_id)
async_dispatcher_send(hass, signal, "continue")
@callback
def debug_step(hass, key, run_id):
# Set a wildcard breakpoint
breakpoint_set(hass, key, run_id, NODE_ANY)
signal = SCRIPT_DEBUG_CONTINUE_STOP.format(key, run_id)
async_dispatcher_send(hass, signal, "continue")
@callback
def debug_stop(hass, key, run_id):
signal = SCRIPT_DEBUG_CONTINUE_STOP.format(key, run_id)
async_dispatcher_send(hass, signal, "stop")
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.