input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
'bundleId': 'string',
'isStaticIp': True|False,
'privateIpAddress': 'string',
'publicIpAddress': 'string',
'ipv6Address': 'string',
'hardware': {
'cpuCount': 123,
'disks': [
{
'name': 'string',
'arn': 'string',
'supportCode': 'string',
'createdAt': datetime(2015, 1, 1),
'location': {
'availabilityZone': 'string',
'regionName': 'us-east-1'|'us-west-1'|'us-west-2'|'eu-west-1'|'eu-central-1'|'ap-south-1'|'ap-southeast-1'|'ap-southeast-2'|'ap-northeast-1'|'ap-northeast-2'
},
'resourceType': 'Instance'|'StaticIp'|'KeyPair'|'InstanceSnapshot'|'Domain'|'PeeredVpc',
'sizeInGb': 123,
'gbInUse': 123,
'isSystemDisk': True|False,
'iops': 123,
'path': 'string',
'attachedTo': 'string',
'isAttached': True|False,
'attachmentState': 'string'
},
],
'ramSizeInGb': ...
},
'networking': {
'monthlyTransfer': {
'gbPerMonthAllocated': 123
},
'ports': [
{
'fromPort': 123,
'toPort': 123,
'protocol': 'tcp'|'all'|'udp',
'accessFrom': 'string',
'accessType': 'Public'|'Private',
'commonName': 'string',
'accessDirection': 'inbound'|'outbound'
},
]
},
'state': {
'code': 123,
'name': 'string'
},
'username': 'string',
'sshKeyName': 'string'
},
],
'nextPageToken': 'string'
}
"""
pass
def get_key_pair(keyPairName=None):
"""
Returns information about a specific key pair.
See also: AWS API Documentation
:example: response = client.get_key_pair(
keyPairName='string'
)
:type keyPairName: string
:param keyPairName: [REQUIRED]
The name of the key pair for which you are requesting information.
:rtype: dict
:return: {
'keyPair': {
'name': 'string',
'arn': 'string',
'supportCode': 'string',
'createdAt': datetime(2015, 1, 1),
'location': {
'availabilityZone': 'string',
'regionName': 'us-east-1'|'us-west-1'|'us-west-2'|'eu-west-1'|'eu-central-1'|'ap-south-1'|'ap-southeast-1'|'ap-southeast-2'|'ap-northeast-1'|'ap-northeast-2'
},
'resourceType': 'Instance'|'StaticIp'|'KeyPair'|'InstanceSnapshot'|'Domain'|'PeeredVpc',
'fingerprint': 'string'
}
}
"""
pass
def get_key_pairs(pageToken=None):
"""
Returns information about all key pairs in the user's account.
See also: AWS API Documentation
:example: response = client.get_key_pairs(
pageToken='string'
)
:type pageToken: string
:param pageToken: A token used for advancing to the next page of results from your get key pairs request.
:rtype: dict
:return: {
'keyPairs': [
{
'name': 'string',
'arn': 'string',
'supportCode': 'string',
'createdAt': datetime(2015, 1, 1),
'location': {
'availabilityZone': 'string',
'regionName': 'us-east-1'|'us-west-1'|'us-west-2'|'eu-west-1'|'eu-central-1'|'ap-south-1'|'ap-southeast-1'|'ap-southeast-2'|'ap-northeast-1'|'ap-northeast-2'
},
'resourceType': 'Instance'|'StaticIp'|'KeyPair'|'InstanceSnapshot'|'Domain'|'PeeredVpc',
'fingerprint': 'string'
},
],
'nextPageToken': 'string'
}
"""
pass
def get_operation(operationId=None):
"""
Returns information about a specific operation. Operations include events such as when you create an instance, allocate a static IP, attach a static IP, and so on.
See also: AWS API Documentation
:example: response = client.get_operation(
operationId='string'
)
:type operationId: string
:param operationId: [REQUIRED]
A GUID used to identify the operation.
:rtype: dict
:return: {
'operation': {
'id': 'string',
'resourceName': 'string',
'resourceType': 'Instance'|'StaticIp'|'KeyPair'|'InstanceSnapshot'|'Domain'|'PeeredVpc',
'createdAt': datetime(2015, 1, 1),
'location': {
'availabilityZone': 'string',
'regionName': 'us-east-1'|'us-west-1'|'us-west-2'|'eu-west-1'|'eu-central-1'|'ap-south-1'|'ap-southeast-1'|'ap-southeast-2'|'ap-northeast-1'|'ap-northeast-2'
},
'isTerminal': True|False,
'operationDetails': 'string',
'operationType': 'DeleteInstance'|'CreateInstance'|'StopInstance'|'StartInstance'|'RebootInstance'|'OpenInstancePublicPorts'|'PutInstancePublicPorts'|'CloseInstancePublicPorts'|'AllocateStaticIp'|'ReleaseStaticIp'|'AttachStaticIp'|'DetachStaticIp'|'UpdateDomainEntry'|'DeleteDomainEntry'|'CreateDomain'|'DeleteDomain'|'CreateInstanceSnapshot'|'DeleteInstanceSnapshot'|'CreateInstancesFromSnapshot',
'status': 'NotStarted'|'Started'|'Failed'|'Completed',
'statusChangedAt': datetime(2015, 1, 1),
'errorCode': 'string',
'errorDetails': 'string'
}
}
"""
pass
def get_operations(pageToken=None):
"""
Returns information about all operations.
Results are returned from oldest to newest, up to a maximum of 200. Results can be paged by making each subsequent call to GetOperations use the maximum (last) statusChangedAt value from the previous request.
See also: AWS API Documentation
:example: response = client.get_operations(
pageToken='string'
)
:type pageToken: string
:param pageToken: A token used for advancing to the next page of results from your get operations request.
:rtype: dict
:return: {
'operations': [
{
'id': 'string',
'resourceName': 'string',
'resourceType': 'Instance'|'StaticIp'|'KeyPair'|'InstanceSnapshot'|'Domain'|'PeeredVpc',
'createdAt': datetime(2015, 1, 1),
'location': {
'availabilityZone': 'string',
'regionName': 'us-east-1'|'us-west-1'|'us-west-2'|'eu-west-1'|'eu-central-1'|'ap-south-1'|'ap-southeast-1'|'ap-southeast-2'|'ap-northeast-1'|'ap-northeast-2'
},
'isTerminal': True|False,
'operationDetails': 'string',
'operationType': 'DeleteInstance'|'CreateInstance'|'StopInstance'|'StartInstance'|'RebootInstance'|'OpenInstancePublicPorts'|'PutInstancePublicPorts'|'CloseInstancePublicPorts'|'AllocateStaticIp'|'ReleaseStaticIp'|'AttachStaticIp'|'DetachStaticIp'|'UpdateDomainEntry'|'DeleteDomainEntry'|'CreateDomain'|'DeleteDomain'|'CreateInstanceSnapshot'|'DeleteInstanceSnapshot'|'CreateInstancesFromSnapshot',
'status': 'NotStarted'|'Started'|'Failed'|'Completed',
'statusChangedAt': datetime(2015, 1, 1),
'errorCode': 'string',
'errorDetails': 'string'
},
],
'nextPageToken': 'string'
}
"""
pass
def get_operations_for_resource(resourceName=None, pageToken=None):
"""
Gets operations for a specific resource (e.g., an instance or a static IP).
See also: AWS API Documentation
:example: response = client.get_operations_for_resource(
resourceName='string',
pageToken='string'
)
:type resourceName: string
:param resourceName: [REQUIRED]
The name of the resource for which you are requesting information.
:type pageToken: string
:param pageToken: A token used for advancing to the next page of results from your get operations for resource request.
:rtype: dict
:return: {
'operations': [
{
'id': 'string',
'resourceName': 'string',
'resourceType': 'Instance'|'StaticIp'|'KeyPair'|'InstanceSnapshot'|'Domain'|'PeeredVpc',
'createdAt': datetime(2015, 1, 1),
'location': {
'availabilityZone': 'string',
'regionName': 'us-east-1'|'us-west-1'|'us-west-2'|'eu-west-1'|'eu-central-1'|'ap-south-1'|'ap-southeast-1'|'ap-southeast-2'|'ap-northeast-1'|'ap-northeast-2'
},
'isTerminal': True|False,
'operationDetails': 'string',
'operationType': 'DeleteInstance'|'CreateInstance'|'StopInstance'|'StartInstance'|'RebootInstance'|'OpenInstancePublicPorts'|'PutInstancePublicPorts'|'CloseInstancePublicPorts'|'AllocateStaticIp'|'ReleaseStaticIp'|'AttachStaticIp'|'DetachStaticIp'|'UpdateDomainEntry'|'DeleteDomainEntry'|'CreateDomain'|'DeleteDomain'|'CreateInstanceSnapshot'|'DeleteInstanceSnapshot'|'CreateInstancesFromSnapshot',
'status': 'NotStarted'|'Started'|'Failed'|'Completed',
'statusChangedAt': datetime(2015, 1, 1),
'errorCode': 'string',
'errorDetails': 'string'
},
],
'nextPageCount': 'string'
}
"""
pass
def get_paginator(operation_name=None):
"""
Create a paginator for an operation.
:type operation_name: string
:param operation_name: The operation name. This is the same name
as the method name on the client. For example, if the
method name is create_foo, and you'd normally invoke the
operation as client.create_foo(**kwargs), if the
create_foo operation can be paginated, you can use the
call client.get_paginator('create_foo').
:rtype: L{botocore.paginate.Paginator}
"""
pass
def get_regions(includeAvailabilityZones=None):
"""
Returns a list of all valid regions for Amazon Lightsail. Use the include availability zones parameter to also return the availability zones in a region.
See also: AWS API Documentation
:example: response = client.get_regions(
includeAvailabilityZones=True|False
)
:type includeAvailabilityZones: boolean
:param includeAvailabilityZones: A Boolean value indicating whether to also include Availability Zones in your get regions request. Availability Zones are indicated with a letter: e.g., us-east-1a .
:rtype: dict
:return: {
'regions': [
{
'continentCode': 'string',
'description': 'string',
'displayName': 'string',
'name': 'us-east-1'|'us-west-1'|'us-west-2'|'eu-west-1'|'eu-central-1'|'ap-south-1'|'ap-southeast-1'|'ap-southeast-2'|'ap-northeast-1'|'ap-northeast-2',
'availabilityZones': [
{
'zoneName': 'string',
'state': 'string'
},
]
},
]
}
"""
pass
def get_static_ip(staticIpName=None):
"""
Returns information about a specific static IP.
See also: AWS API Documentation
:example: response = client.get_static_ip(
staticIpName='string'
)
:type staticIpName: string
:param staticIpName: [REQUIRED]
The name of the static IP in Lightsail.
:rtype: dict
:return: {
'staticIp': {
'name': 'string',
'arn': 'string',
'supportCode': 'string',
'createdAt': datetime(2015, 1, 1),
'location': {
'availabilityZone': 'string',
'regionName': 'us-east-1'|'us-west-1'|'us-west-2'|'eu-west-1'|'eu-central-1'|'ap-south-1'|'ap-southeast-1'|'ap-southeast-2'|'ap-northeast-1'|'ap-northeast-2'
},
'resourceType': 'Instance'|'StaticIp'|'KeyPair'|'InstanceSnapshot'|'Domain'|'PeeredVpc',
'ipAddress': 'string',
'attachedTo': 'string',
'isAttached': True|False
}
}
"""
pass
def get_static_ips(pageToken=None):
"""
Returns information about all static IPs in the user's account.
See also: AWS API Documentation
:example: response = client.get_static_ips(
pageToken='string'
)
:type pageToken: string
:param pageToken: A token used for advancing to the next page of results from your get static IPs request.
:rtype: dict
:return: {
'staticIps': [
{
'name': 'string',
'arn': 'string',
'supportCode': 'string',
'createdAt': datetime(2015, 1, 1),
'location': {
'availabilityZone': 'string',
'regionName': 'us-east-1'|'us-west-1'|'us-west-2'|'eu-west-1'|'eu-central-1'|'ap-south-1'|'ap-southeast-1'|'ap-southeast-2'|'ap-northeast-1'|'ap-northeast-2'
},
'resourceType': 'Instance'|'StaticIp'|'KeyPair'|'InstanceSnapshot'|'Domain'|'PeeredVpc',
'ipAddress': 'string',
'attachedTo': 'string',
'isAttached': True|False
},
],
'nextPageToken': 'string'
}
"""
pass
def get_waiter():
"""
"""
pass
def import_key_pair(keyPairName=None, publicKeyBase64=None):
"""
Imports a public SSH key from a specific key pair.
See also: AWS API Documentation
:example: response = client.import_key_pair(
keyPairName='string',
publicKeyBase64='string'
)
:type keyPairName: string
:param keyPairName: [REQUIRED]
The name of the key pair for which you want to import the public key.
:type publicKeyBase64: string
:param publicKeyBase64: [REQUIRED]
A base64-encoded public key of the ssh-rsa type.
:rtype: dict
:return: {
'operation': {
'id': 'string',
'resourceName': 'string',
'resourceType': 'Instance'|'StaticIp'|'KeyPair'|'InstanceSnapshot'|'Domain'|'PeeredVpc',
'createdAt': datetime(2015, 1, 1),
'location': {
'availabilityZone': 'string',
'regionName': 'us-east-1'|'us-west-1'|'us-west-2'|'eu-west-1'|'eu-central-1'|'ap-south-1'|'ap-southeast-1'|'ap-southeast-2'|'ap-northeast-1'|'ap-northeast-2'
},
'isTerminal': True|False,
'operationDetails': 'string',
'operationType': 'DeleteInstance'|'CreateInstance'|'StopInstance'|'StartInstance'|'RebootInstance'|'OpenInstancePublicPorts'|'PutInstancePublicPorts'|'CloseInstancePublicPorts'|'AllocateStaticIp'|'ReleaseStaticIp'|'AttachStaticIp'|'DetachStaticIp'|'UpdateDomainEntry'|'DeleteDomainEntry'|'CreateDomain'|'DeleteDomain'|'CreateInstanceSnapshot'|'DeleteInstanceSnapshot'|'CreateInstancesFromSnapshot',
'status': 'NotStarted'|'Started'|'Failed'|'Completed',
'statusChangedAt': datetime(2015, 1, 1),
'errorCode': 'string',
'errorDetails': 'string'
}
}
"""
pass
def is_vpc_peered():
"""
Returns a Boolean value indicating whether your Lightsail VPC is peered.
See also: AWS API Documentation
:example: response = client.is_vpc_peered()
:rtype: dict
:return: {
'isPeered': True|False
}
"""
pass
def open_instance_public_ports(portInfo=None, instanceName=None):
"""
Adds public ports to an Amazon Lightsail instance.
See also: AWS API Documentation
:example: response = client.open_instance_public_ports(
portInfo={
'fromPort': 123,
'toPort': 123,
'protocol': 'tcp'|'all'|'udp'
},
instanceName='string'
)
:type portInfo: dict
:param portInfo: [REQUIRED]
An array of key-value pairs containing information about the port mappings.
fromPort (integer) --The first port in the range.
toPort (integer) --The last port in the range.
protocol (string) --The protocol.
:type instanceName: string
:param instanceName: [REQUIRED]
The name of the instance for which you want to open the public ports.
:rtype: dict
:return: {
'operation': {
'id': 'string',
'resourceName': 'string',
'resourceType': 'Instance'|'StaticIp'|'KeyPair'|'InstanceSnapshot'|'Domain'|'PeeredVpc',
'createdAt': datetime(2015, 1, 1),
'location': {
'availabilityZone': 'string',
'regionName': 'us-east-1'|'us-west-1'|'us-west-2'|'eu-west-1'|'eu-central-1'|'ap-south-1'|'ap-southeast-1'|'ap-southeast-2'|'ap-northeast-1'|'ap-northeast-2'
},
'isTerminal': True|False,
'operationDetails': 'string',
'operationType': 'DeleteInstance'|'CreateInstance'|'StopInstance'|'StartInstance'|'RebootInstance'|'OpenInstancePublicPorts'|'PutInstancePublicPorts'|'CloseInstancePublicPorts'|'AllocateStaticIp'|'ReleaseStaticIp'|'AttachStaticIp'|'DetachStaticIp'|'UpdateDomainEntry'|'DeleteDomainEntry'|'CreateDomain'|'DeleteDomain'|'CreateInstanceSnapshot'|'DeleteInstanceSnapshot'|'CreateInstancesFromSnapshot',
'status': 'NotStarted'|'Started'|'Failed'|'Completed',
'statusChangedAt': datetime(2015, 1, 1),
'errorCode': 'string',
'errorDetails': 'string'
}
}
"""
pass
def peer_vpc():
"""
Tries to peer the Lightsail VPC with the user's default VPC.
See also: AWS API Documentation
:example: response = client.peer_vpc()
:rtype: dict
:return: {
'operation': {
'id': 'string',
'resourceName': 'string',
'resourceType': 'Instance'|'StaticIp'|'KeyPair'|'InstanceSnapshot'|'Domain'|'PeeredVpc',
'createdAt': datetime(2015, 1, | |
= aRNApipe_path.strip("\r")
genome = ""
# Open the configuration file for the run and extract
# the value of genome_build
f = open(path, 'r')
for i in f:
i = i.strip("\n").split("\t")
if len(i) > 1:
if i[0] == "genome_build":
genome = i[1]
break
f.close()
genome = genome.strip("\r")
# Did we extract a value for the name of
# the genome?
if genome == "":
exit("Error recovering genome build")
# Opent the
path = aRNApipe_path + genome + "/genesets.feature.txt".replace("feature", feature).strip("\r")
if not os.path.exists(path):
exit("Annotation file not found")
f = open(path, 'r')
h = f.readline().strip("\n").strip("\r").split("\t")
k = 0
for i in range(len(h)):
if h[i] == feature:
k = i
break
d = dict()
L = dict()
for i in f:
i = i.strip("\n").split("\t")
d[i[k]] = "\t".join(i)
L[i[k]] = i[6]
f.close()
return d, h, L
def parselog(path):
# Given a LSF log file returns a dictionary with the relevant parameters
M = {"CPU time :":"cpu_time","Max Memory :":"max_memo",
"Average Memory :":"ave_memo","Max Swap :":"max_swap",}
f = open(path,'r')
results = dict()
for i in f:
if i.startswith("Started at"):
results["time_start"] = i.rstrip().replace("Started at ","")
elif i.startswith("Results reported on"):
results["time_results"] = i.rstrip().replace("Results reported on ","")
elif i.startswith("Successfully completed."):
results["success"] = "Yes"
else:
for j in M.keys():
if j in i:
results[M[j]] = " ".join(i.rstrip().split()[3:5])
if not results.has_key("success"):
results["success"] = "No"
path = path.split("/")
results["link"] = '<a href="LINK" target="_blank">+</a>'.replace("LINK","../logs/" + path[-1])
return results
def stats_log(path):
# Given a path to a 'logs' folder parses all the LSF log files and writes the relevant parameters
# in a table format on an ouptut file
order = ["success", "time_start", "time_results", "cpu_time", "max_memo", "ave_memo", "max_swap", "link"]
Lorder= ["Success", "Started", "Ended", "CPU time", "Memory (max) [MB]", "Memory (mean) [MB]", "Swap (max) [MB]", "Link"]
progs = ["trimgalore", "fastqc", "star", "bowtie2"
"htseq-gene", "htseq-exon", "sam2sortbam"]
L = os.listdir(path)
logs = dict()
for i in L:
if i.endswith(".log") and (not i.endswith("_M.log")):
j = i.replace(".log","").replace('picard_IS', 'picard-IS').split("_")
if (len(j) == 4):
date, time, prog, proc = j
if not logs.has_key(date + "_" + time):
logs[date + "_" + time] = dict()
if not logs[date + "_" + time].has_key(prog):
logs[date + "_" + time][prog] = dict()
logs[date + "_" + time][prog][int(proc)] = [path + "/" + i, parselog(path + "/" + i)]
out = open(path.replace("/logs/", "/outputs/") + "log_stats.txt", 'w')
print >> out, "Run number\tTimestamp\tModule\tJob\t"+"\t".join(Lorder)
if len(logs) > 0:
ki = 0
k = 0
for timestamp in sorted(logs.keys()):
ki += 1
for prog in progs:
if logs[timestamp].has_key(prog):
for proc, data in (logs[timestamp][prog].iteritems()):
n = [str(ki), timestamp, prog, str(proc)]
for ordi in order:
if data[1].has_key(ordi):
n.append(data[1][ordi])
else:
n.append("NA")
print >> out, ("\t".join(n)).replace(" sec.", "").replace(" MB", "")
k += 1
print " Recovered stats from " + str(k) + " log files."
out.close()
return 1
def summary_star(path):
print "> Recovering stats from final STAR logs: " + path
if not os.path.exists(path):
print path + " does not exist!"
return 1
os.system("/share/code/lib/star_summary.sh " + path + " " + path.replace("/results_star/", "/outputs/star_summary.txt"))
def stats_star(path, samples, btw=False):
# If RNA was removed, the sample name should have a _noRNA suffix
suffix = ""
if btw:
suffix = "_noRNA"
print "> Recovering stats from STAR logs: " + path
if not os.path.exists(path):
print path + " does not exist!"
return 1
g = os.listdir(path)
out = open(path.replace("/results_star/", "/outputs/star_stats_log.txt") , "w")
print >> out, "\t".join(head_star_log)
for sample in samples:
if os.path.exists(path + "/" + sample + suffix + "_Log.final.out"):
n = read_star_log(path + "/" + sample + suffix + "_Log.final.out", sample)
print >> out, "\t".join(n)
else:
print "Missing file: " + path + "/" + sample + suffix + "_Log.final.out"
out.close()
print "> Recovering stats from STAR counts and building count matrices: " + path
M = ["unstranded", "stranded", "stranded-reverse"]
g = os.listdir(path)
k = 0
N = [{},{},{}]
S = [{},{},{}]
ng = list()
na = list()
print "Number of samples = " + str(len(samples))
for sample in samples:
if sample + suffix + "_ReadsPerGene.out.tab" in g:
for i in range(3):
N[i][sample] = []
S[i][sample] = []
# print "OPENING FILE FOR STAR INPUTS:\n" + path + "/" + sample + suffix + "_ReadsPerGene.out.tab"
if os.path.exists:
f = open(path + "/" + sample + suffix + "_ReadsPerGene.out.tab", 'r')
else:
print "Missing file: " + path + "/" + sample + suffix + "_ReadsPerGene.out.tab"
# header stats
naa = list()
for i in range(4):
i = f.readline().strip("\n").split("\t")
naa.append(i[0])
for k in range(3):
S[k][sample].append(i[k+1])
if len(naa) > len(na):
na = naa
# counts
nt = list()
for i in f:
i = i.strip("\n").split("\t")
nt.append(i[0])
for k in range(3):
N[k][sample].append(i[k+1])
f.close()
if len(nt) > len(ng):
ng = nt
if len(naa) > len(na):
na = naa
for i in range(len(M)):
MT = dict()
out = open(path.replace("/results_star/","/outputs/") + "/star_" + M[i] + "_counts.txt", 'w')
print >> out, "gene_id\t" + "\t".join(samples)
for j in range(len(ng)):
r = list()
for sample in samples:
if not MT.has_key(sample):
MT[sample] = 0
if N[i].has_key(sample):
if j < len(N[i][sample]):
r.append(N[i][sample][j])
MT[sample] += int(N[i][sample][j])
else:
r.append("NA")
else:
r.append("NA")
print >> out, ng[j] + "\t" + "\t".join(r)
out.close()
out = open(path.replace("/results_star/","/outputs/") + "/star_" + M[i] + "_stats.txt", 'w')
print >> out, "sample_id\t" + "\t".join(na) + "\tTotalCounts\tLink"
for sample in samples:
if S[i].has_key(sample):
if len(S[i][sample]) > 0:
print >> out, sample + "\t" + "\t".join(S[i][sample]) + "\t" + str(MT[sample]) + "\t" + '<a href="../results_star/"+sample+suffix+"_ReadsPerGene.out.tab" target="_blank">+</a>'
else:
print >> out, sample + "\t" + "\t".join(["0" for k in range(len(na))]) + "\t0\t"
else:
print >> out, sample + "\t" + "\t".join(["0" for k in range(len(na))]) + "\t0\t"
out.close()
print " Data found for " + str(len(N[0])) + " of " + str(len(samples)) + " samples"
print " Creating annotation file..."
D, H, L = get_annotation("gene", path.replace("/results_star/", "/config.txt"))
out = open(path.replace("/results_star/","/outputs/") + "/star_annotation.txt", 'w')
print >> out, "\t".join(H)
k = 0
for gene in ng:
if D.has_key(gene):
print >> out, D[gene]
k += 1
else:
print >> out, "\t".join(["NA" for i in range(len(H))])
out.close()
print " Recovered annotation for " + str(k) + " of " + str(len(ng)) + " genes"
print " Computing RPKMs..."
for i in range(len(M)):
out = open(path.replace("/results_star/","/outputs/") + "/star_" + M[i] + "_rpkms.txt", 'w')
print >> out, "gene_id\t" + "\t".join(samples)
for j in range(len(ng)):
r = list()
for sample in samples:
s = "NA"
if N[i].has_key(sample) and MT.has_key(sample):
if (len(N[i][sample]) > j) and (MT[sample] > 0):
if L.has_key(ng[j]):
s = str(round(float(N[i][sample][j]) * 1000000000 / (float(L[ng[j]]) * MT[sample]),4))
r.append(s)
print >> out, ng[j] + "\t" + "\t".join(r)
out.close()
return 1
# path: the directory containing htseq results: results_htseq-exon
# samples: list of sample names
# mode: should always be exon for us
def stats_htseq(path, samples, mode):
print "> Recovering stats from HTseq " + mode + " counts and building count matrices: " + path
special = "no_feature","ambiguous","too_low_aQual","not_aligned","alignment_not_unique"
# Does the results_htseq-exon directory exist?
if not os.path.exists(path):
return 0,0
# g will contain a list of files in that directory.
g = os.listdir(path)
# Declare two lists of dictionaries
# One list will contain names, the other will contain counts
N = [{}]
S = [{}]
# Declare two empty lists
na = list()
ng = list()
# for each samlple
for sample in samples:
# Check if there is a table in the directory for that sample
if sample + ".tab" in g:
# Each table contains two columns
# Column 0: Exon name
# Column 1: Exon count
for i in range(1):
# Initialize the sets to empty sets
N[i][sample] = []
S[i][sample] = []
f = open(path + "/" + sample + ".tab", 'r')
naa = list()
ngg = list()
for i in f:
i = i.strip("\n").split("\t")
if i[0][:2] == "__" :
i[0] = i[0][2:]
if i[0] in special:
naa.append(i[0])
S[0][sample].append(i[1])
else:
ngg.append(i[0])
N[0][sample].append(i[1])
if len(naa) > len(na):
na = naa
if len(ngg) > len(ng):
ng = ngg
f.close()
MT = dict()
out = open(path.replace("/results_htseq-" + mode +"/","/outputs/") + "/htseq-" | |
connection = vpn_service.get_connection(u'1')
self.assertIsNotNone(connection)
self.assertFalse(connection.is_dirty)
def test_sweep_connection_dirty(self):
"""Sync did not update connection - delete."""
# Create a service and connection
vpn_service = self.driver.create_vpn_service(self.service123_data)
vpn_service.create_connection(self.conn1_data)
self.driver.mark_existing_connections_as_dirty()
# Simulate that the update phase only visited the service
vpn_service.is_dirty = False
self.driver.remove_unknown_connections(self.context)
vpn_service = self.driver.service_state.get(u'123')
self.assertIsNotNone(vpn_service)
self.assertFalse(vpn_service.is_dirty)
connection = vpn_service.get_connection(u'1')
self.assertIsNone(connection)
self.assertEqual(1, self.conn_delete.call_count)
def test_sweep_service_dirty(self):
"""Sync did not update service - delete it and all conns."""
# Create a service and connection
vpn_service = self.driver.create_vpn_service(self.service123_data)
vpn_service.create_connection(self.conn1_data)
self.driver.mark_existing_connections_as_dirty()
# Both the service and the connection are still 'dirty'
self.driver.remove_unknown_connections(self.context)
self.assertIsNone(self.driver.service_state.get(u'123'))
self.assertEqual(1, self.conn_delete.call_count)
def test_sweep_multiple_services(self):
"""One service and conn updated, one service and conn not."""
# Create two services, each with a connection
vpn_service1 = self.driver.create_vpn_service(self.service123_data)
vpn_service1.create_connection(self.conn1_data)
service456_data = {u'id': u'456',
u'status': constants.ACTIVE,
u'admin_state_up': False,
u'external_ip': u'1.1.1.1'}
conn2_data = {u'id': u'2', u'status': constants.ACTIVE,
u'admin_state_up': True,
u'cisco': {u'site_conn_id': u'Tunnel0'}}
prev_vpn_service2 = self.driver.create_vpn_service(service456_data)
prev_connection2 = prev_vpn_service2.create_connection(conn2_data)
self.driver.mark_existing_connections_as_dirty()
# Simulate that the update phase visited the first service and conn
prev_vpn_service2.is_dirty = False
prev_connection2.is_dirty = False
self.driver.remove_unknown_connections(self.context)
self.assertIsNone(self.driver.service_state.get(u'123'))
vpn_service2 = self.driver.service_state.get(u'456')
self.assertEqual(prev_vpn_service2, vpn_service2)
self.assertFalse(vpn_service2.is_dirty)
connection2 = vpn_service2.get_connection(u'2')
self.assertEqual(prev_connection2, connection2)
self.assertFalse(connection2.is_dirty)
self.assertEqual(1, self.conn_delete.call_count)
def simulate_mark_update_sweep_for_service_with_conn(self, service_state,
connection_state):
"""Create internal structures for single service with connection.
The service and connection will be marked as clean, and since
none are being deleted, the service's connections_removed
attribute will remain false.
"""
# Simulate that we have done mark, update, and sweep.
conn_data = {u'id': u'1', u'status': connection_state,
u'admin_state_up': True,
u'cisco': {u'site_conn_id': u'Tunnel0'}}
service_data = {u'id': u'123',
u'status': service_state,
u'external_ip': u'1.1.1.1',
u'admin_state_up': True,
u'ipsec_conns': [conn_data]}
return self.driver.update_service(self.context, service_data)
def test_report_fragment_connection_created(self):
"""Generate report section for a created connection."""
# Prepare service and connection in PENDING_CREATE state
vpn_service = self.simulate_mark_update_sweep_for_service_with_conn(
constants.PENDING_CREATE, constants.PENDING_CREATE)
# Simulate that CSR has reported the connection is still up
self.csr.read_tunnel_statuses.return_value = [
(u'Tunnel0', u'UP-ACTIVE'), ]
# Get the statuses for connections existing on CSR
tunnels = vpn_service.get_ipsec_connections_status()
self.assertEqual({u'Tunnel0': constants.ACTIVE}, tunnels)
# Check that there is a status for this connection
connection = vpn_service.get_connection(u'1')
self.assertIsNotNone(connection)
current_status = connection.find_current_status_in(tunnels)
self.assertEqual(constants.ACTIVE, current_status)
# Create report fragment due to change
self.assertNotEqual(connection.last_status, current_status)
report_frag = connection.update_status_and_build_report(current_status)
self.assertEqual(current_status, connection.last_status)
expected = {'1': {'status': constants.ACTIVE,
'updated_pending_status': True}}
self.assertEqual(expected, report_frag)
def test_report_fragment_connection_unchanged_status(self):
"""No report section generated for a created connection."""
# Prepare service and connection in ACTIVE state
vpn_service = self.simulate_mark_update_sweep_for_service_with_conn(
constants.ACTIVE, constants.ACTIVE)
# Simulate that CSR has reported the connection is up
self.csr.read_tunnel_statuses.return_value = [
(u'Tunnel0', u'UP-IDLE'), ]
# Get the statuses for connections existing on CSR
tunnels = vpn_service.get_ipsec_connections_status()
self.assertEqual({u'Tunnel0': constants.ACTIVE}, tunnels)
# Check that there is a status for this connection
connection = vpn_service.get_connection(u'1')
self.assertIsNotNone(connection)
current_status = connection.find_current_status_in(tunnels)
self.assertEqual(constants.ACTIVE, current_status)
# Should be no report, as no change
self.assertEqual(connection.last_status, current_status)
report_frag = connection.update_status_and_build_report(current_status)
self.assertEqual(current_status, connection.last_status)
self.assertEqual({}, report_frag)
def test_report_fragment_connection_changed_status(self):
"""Generate report section for connection with changed state."""
# Prepare service in ACTIVE state and connection in DOWN state
vpn_service = self.simulate_mark_update_sweep_for_service_with_conn(
constants.ACTIVE, constants.DOWN)
# Simulate that CSR has reported the connection is still up
self.csr.read_tunnel_statuses.return_value = [
(u'Tunnel0', u'UP-NO-IKE'), ]
# Get the statuses for connections existing on CSR
tunnels = vpn_service.get_ipsec_connections_status()
self.assertEqual({u'Tunnel0': constants.ACTIVE}, tunnels)
# Check that there is a status for this connection
connection = vpn_service.get_connection(u'1')
self.assertIsNotNone(connection)
current_status = connection.find_current_status_in(tunnels)
self.assertEqual(constants.ACTIVE, current_status)
# Create report fragment due to change
self.assertNotEqual(connection.last_status, current_status)
report_frag = connection.update_status_and_build_report(current_status)
self.assertEqual(current_status, connection.last_status)
expected = {'1': {'status': constants.ACTIVE,
'updated_pending_status': False}}
self.assertEqual(expected, report_frag)
def test_report_fragment_connection_failed_create(self):
"""Failure test of report fragment for conn that failed creation.
Normally, without any status from the CSR, the connection report would
be skipped, but we need to report back failures.
"""
# Prepare service and connection in PENDING_CREATE state
vpn_service = self.simulate_mark_update_sweep_for_service_with_conn(
constants.PENDING_CREATE, constants.PENDING_CREATE)
# Simulate that CSR does NOT report the status (no tunnel)
self.csr.read_tunnel_statuses.return_value = []
# Get the statuses for connections existing on CSR
tunnels = vpn_service.get_ipsec_connections_status()
self.assertEqual({}, tunnels)
# Check that there is a status for this connection
connection = vpn_service.get_connection(u'1')
self.assertIsNotNone(connection)
current_status = connection.find_current_status_in(tunnels)
self.assertEqual(constants.ERROR, current_status)
# Create report fragment due to change
self.assertNotEqual(connection.last_status, current_status)
report_frag = connection.update_status_and_build_report(current_status)
self.assertEqual(current_status, connection.last_status)
expected = {'1': {'status': constants.ERROR,
'updated_pending_status': True}}
self.assertEqual(expected, report_frag)
def test_report_fragment_connection_admin_down(self):
"""Report for a connection that is in admin down state."""
# Prepare service and connection with previous status ACTIVE, but
# with connection admin down
conn_data = {u'id': u'1', u'status': constants.ACTIVE,
u'admin_state_up': False,
u'cisco': {u'site_conn_id': u'Tunnel0'}}
service_data = {u'id': u'123',
u'status': constants.ACTIVE,
u'external_ip': u'1.1.1.1',
u'admin_state_up': True,
u'ipsec_conns': [conn_data]}
vpn_service = self.driver.update_service(self.context, service_data)
# Tunnel would have been deleted, so simulate no status
self.csr.read_tunnel_statuses.return_value = []
connection = vpn_service.get_connection(u'1')
self.assertIsNotNone(connection)
self.assertTrue(connection.forced_down)
self.assertEqual(constants.ACTIVE, connection.last_status)
# Create report fragment due to change
report_frag = self.driver.build_report_for_connections_on(vpn_service)
self.assertEqual(constants.DOWN, connection.last_status)
expected = {'1': {'status': constants.DOWN,
'updated_pending_status': False}}
self.assertEqual(expected, report_frag)
def test_report_fragment_two_connections(self):
"""Generate report fragment for two connections on a service."""
# Prepare service with two connections, one ACTIVE, one DOWN
conn1_data = {u'id': u'1', u'status': constants.DOWN,
u'admin_state_up': True,
u'cisco': {u'site_conn_id': u'Tunnel1'}}
conn2_data = {u'id': u'2', u'status': constants.ACTIVE,
u'admin_state_up': True,
u'cisco': {u'site_conn_id': u'Tunnel2'}}
service_data = {u'id': u'123',
u'status': constants.ACTIVE,
u'external_ip': u'1.1.1.1',
u'admin_state_up': True,
u'ipsec_conns': [conn1_data, conn2_data]}
vpn_service = self.driver.update_service(self.context, service_data)
# Simulate that CSR has reported the connections with diff status
self.csr.read_tunnel_statuses.return_value = [
(u'Tunnel1', u'UP-IDLE'), (u'Tunnel2', u'DOWN-NEGOTIATING')]
# Get the report fragments for the connections
report_frag = self.driver.build_report_for_connections_on(vpn_service)
expected = {u'1': {u'status': constants.ACTIVE,
u'updated_pending_status': False},
u'2': {u'status': constants.DOWN,
u'updated_pending_status': False}}
self.assertEqual(expected, report_frag)
def test_report_service_create(self):
"""VPN service and IPSec connection created - report."""
# Simulate creation of the service and connection
vpn_service = self.simulate_mark_update_sweep_for_service_with_conn(
constants.PENDING_CREATE, constants.PENDING_CREATE)
# Simulate that the CSR has created the connection
self.csr.read_tunnel_statuses.return_value = [
(u'Tunnel0', u'UP-ACTIVE'), ]
report = self.driver.build_report_for_service(vpn_service)
expected_report = {
u'id': u'123',
u'updated_pending_status': True,
u'status': constants.ACTIVE,
u'ipsec_site_connections': {
u'1': {u'status': constants.ACTIVE,
u'updated_pending_status': True}
}
}
self.assertEqual(expected_report, report)
# Check that service and connection statuses are updated
self.assertEqual(constants.ACTIVE, vpn_service.last_status)
self.assertEqual(constants.ACTIVE,
vpn_service.get_connection(u'1').last_status)
def test_report_service_create_of_first_conn_fails(self):
"""VPN service and IPSec conn created, but conn failed - report.
Since this is the sole IPSec connection on the service, and the
create failed (connection in ERROR state), the VPN service's
status will be set to DOWN.
"""
# Simulate creation of the service and connection
vpn_service = self.simulate_mark_update_sweep_for_service_with_conn(
constants.PENDING_CREATE, constants.PENDING_CREATE)
# Simulate that the CSR has no info due to failed create
self.csr.read_tunnel_statuses.return_value = []
report = self.driver.build_report_for_service(vpn_service)
expected_report = {
u'id': u'123',
u'updated_pending_status': True,
u'status': constants.DOWN,
u'ipsec_site_connections': {
u'1': {u'status': constants.ERROR,
u'updated_pending_status': True}
}
}
self.assertEqual(expected_report, report)
# Check that service and connection statuses are updated
self.assertEqual(constants.DOWN, vpn_service.last_status)
self.assertEqual(constants.ERROR,
vpn_service.get_connection(u'1').last_status)
def test_report_connection_created_on_existing_service(self):
"""Creating connection on existing service - report."""
# Simulate existing service and connection create
vpn_service = self.simulate_mark_update_sweep_for_service_with_conn(
constants.ACTIVE, constants.PENDING_CREATE)
# Simulate that the CSR has created the connection
self.csr.read_tunnel_statuses.return_value = [
(u'Tunnel0', u'UP-IDLE'), ]
report = self.driver.build_report_for_service(vpn_service)
expected_report = {
u'id': u'123',
u'updated_pending_status': False,
u'status': constants.ACTIVE,
u'ipsec_site_connections': {
u'1': {u'status': constants.ACTIVE,
u'updated_pending_status': True}
}
}
self.assertEqual(expected_report, report)
# Check that service and connection statuses are updated
self.assertEqual(constants.ACTIVE, vpn_service.last_status)
self.assertEqual(constants.ACTIVE,
vpn_service.get_connection(u'1').last_status)
def test_no_report_no_changes(self):
"""VPN service with unchanged IPSec connection - no report.
Note: No report will be generated if the last connection on the
service is deleted. The service (and connection) objects will
have been removed by the sweep operation and thus not reported.
On the plugin, the service should be changed to DOWN. Likewise,
if the service goes to admin down state.
"""
# Simulate an existing service and connection that are ACTIVE
vpn_service = self.simulate_mark_update_sweep_for_service_with_conn(
constants.ACTIVE, constants.ACTIVE)
# Simulate that the CSR reports the connection still active
self.csr.read_tunnel_statuses.return_value = [
(u'Tunnel0', u'UP-ACTIVE'), ]
report = self.driver.build_report_for_service(vpn_service)
self.assertEqual({}, report)
# Check that service and connection statuses are still same
self.assertEqual(constants.ACTIVE, vpn_service.last_status)
self.assertEqual(constants.ACTIVE,
vpn_service.get_connection(u'1').last_status)
def test_report_sole_connection_goes_down(self):
"""Only connection on VPN service goes down - report.
In addition to reporting the status change and recording the new
state for the IPSec connection, the VPN service status will be
DOWN.
"""
# Simulate an existing service and connection that are ACTIVE
vpn_service = self.simulate_mark_update_sweep_for_service_with_conn(
constants.ACTIVE, constants.ACTIVE)
# Simulate that the CSR reports the connection went down
self.csr.read_tunnel_statuses.return_value = [
(u'Tunnel0', u'DOWN-NEGOTIATING'), ]
report = self.driver.build_report_for_service(vpn_service)
expected_report = | |
<gh_stars>0
#!/usr/bin/env python
'''
http://www.last.fm/music/+free-music-downloads/acoustic
'''
import os
import sys
import random
import hashlib
import subprocess
from datetime import datetime, timedelta
OUT_DIR = os.path.expanduser('~/video_archive/music/')
# # a terrible ordered dict
# FILES = {
# 0:dict(
# artist = '<NAME>',
# title = 'Starling',
# length = 60+45, # seconds
# url = 'http://freemusicarchive.org/music/Podington_Bear/Solo_Instruments/Starling',
# audio = 'http://freemusicarchive.org/music/download/be51c174a8a2ebcb5735aefc9bc573208f180e41',
# ),
# 1:dict(
# artist = '<NAME>',
# title = 'Moonlight Reprise',
# length = 3*60+1, # seconds
# url = 'http://freemusicarchive.org/music/Kai_Engel/Irsens_Tale/Kai_Engel_-_Irsens_Tale_-_04_Moonlight_Reprise',
# audio = 'http://freemusicarchive.org/music/download/84b48280791fbc4c81a355621aa1f13a8d15cd00',
# ),
# 2:dict( # TO REPLACE! single channel
# artist = 'Rolemusic',
# title = 'The Pirate And The Dancer',
# length = 4*60+4, # seconds
# url = 'http://freemusicarchive.org/music/Rolemusic/The_Pirate_And_The_Dancer/04_rolemusic_-_the_pirate_and_the_dancer',
# audio = 'http://freemusicarchive.org/music/download/14102245609a0233dbf3d8b1552739ee3e00011a',
# ),
# 3:dict(
# artist = 'deef',
# title = 'nostalgia of an ex-gangsta-rapper',
# length = 5*60+30, # seconds
# url = 'http://freemusicarchive.org/music/deef/Beat_Scene_Routine/4_-_deef_-_nostalgia_of_an_ex-gangsta-rapper',
# audio = 'http://freemusicarchive.org/music/download/ce5a59c22c7e1cbbc54e1d00f828c7ca8b0ed1e0',
# ),
# 4:dict(
# artist = '<NAME>',
# title = 'Snowing',
# length = 2*60+22, # seconds
# url = 'http://freemusicarchive.org/music/Peter_Rudenko/15_Etudes/12_-_Peter_Rudenko_-_Snowing',
# audio = 'http://freemusicarchive.org/music/download/665fcd660419021138d22ddefee9609030006143',
# ),
# 5:dict(
# artist = '<NAME>',
# title = 'The Smiler (1907, Zonophone Concert Band)',
# length = 2*60+27, # seconds
# url = 'http://freemusicarchive.org/music/Percy_Wenrich/Frog_Legs_Ragtime_Era_Favorites/02_-_percy_wenrich_-_the_smiler',
# audio = 'http://freemusicarchive.org/music/download/e6cd7ef9fdca57a9778a8b685066d8afa2f65d12',
# ),
# 6:dict(
# artist = 'Project 5am',
# title = 'Yves',
# length = 7*60+27, # seconds
# url = 'http://freemusicarchive.org/music/Project_5am/5am_Wabi_Sabi/03_project_5am_-_yves',
# audio = 'http://freemusicarchive.org/music/download/fe55b17293f53bfea559e6fae82bbaf20a3c05d5',
# ),
# 7:dict(
# artist = 'Project 5am',
# title = 'My Mind To Me, My Kingdom Is',
# length = 3*60+14, # seconds
# url = 'http://freemusicarchive.org/music/Project_5am/5am_Wabi_Sabi/04_project_5am_-_my_mind_to_me__my_kingdom_is',
# audio = 'http://freemusicarchive.org/music/download/96827f4cfd8561d1614c7f7004ce2a13836d0684',
# ),
# }
#
# TRACKS = [
# ['simple',[3]],
# ['odd',[0,3]],
# ['snow',[4,5]],
# # ['5am', [6]],
# # ['mind', [7,6]],
# ]
#
# def call(cmd):
# print 'Running: {}'.format(cmd)
# subprocess.call(cmd, shell=True)
#
#
# def get_filename(index, length=None):
# '''Hash the artist-title to get a simple filename'''
# key = '{} - {}'.format(FILES[index]['artist'], FILES[index]['title'])
# key_hash = hashlib.sha1(key).hexdigest()
# filename = 'audio_{key_hash}.mp3'
# if length:
# filename = 'audio_{key_hash}_{length:04d}.mp3'
# return os.path.join(OUT_DIR, filename.format(**locals()))
#
# def get_music_filename(name, length):
# filename = 'music_{name}_{length:04d}.mp3'
# return os.path.join(OUT_DIR, filename.format(**locals()))
#
#
# def get_track(index):
# '''Download the audio from the filename.'''
#
# if not os.path.exists(OUT_DIR):
# os.makedirs(OUT_DIR)
#
# url = FILES[index]['audio']
# outfile = get_filename(index)
#
# if not os.path.exists(outfile):
# print 'Getting file: %s'%os.path.basename(outfile)
# call('wget -O {outfile} {url}'.format(**locals()))
# return outfile
#
# def get_audio(index, length):
# '''Get te audio of a specific length with a fade.'''
#
# # ensure that the track exists
# filename = get_track(index)
#
# outfile = get_filename(index, length)
# if os.path.exists(outfile):
# print 'Have shortened file: %s'%os.path.basename(outfile)
# return outfile
#
# # it would be better to read in the length, but eh
# # cmd = 'sox {} 2>&1 -n stat | grep Length | cut -d : -f 2 | cut -f 1'.format(filename)
# # print subprocess.check_output(cmd, shell=True)
# if length > 10:
# call('sox {filename} {outfile} fade 5 {length} 5'.format(**locals()))
# return outfile
# else:
# call('sox {filename} {outfile} trim 0 {length}'.format(**locals()))
# # call('ln -s {filename} {outfile}'.format(**locals()))
# return outfile
#
# def get_music(name, indicies, request_length):
# '''Get some length of music defaults to 5 minutes'''
# outfile = get_music_filename(name, request_length)
# if os.path.exists(outfile):
# print 'Music already created: %s'%os.path.basename(outfile)
# return outfile
#
# files = []
# lengths = []
# for index in indicies:
#
# file_length = FILES[index]['length']
# current_length = sum(lengths)
# if (current_length + file_length) > request_length:
# file_length = request_length - current_length
# if file_length <= 0:
# break
#
# filename = get_audio(index, file_length)
# files.append(filename)
# lengths.append(file_length)
#
# if current_length >= request_length:
# break
#
# if len(files) > 1:
# files = ' '.join(files)
# call('sox --combine concatenate {files} {outfile}'.format(**locals()))
# return outfile
# else:
# call('ln -s {files[0]} {outfile}'.format(**locals()))
# return outfile
#
#
# def get_info(indicies):
# # fmt = ' * {artist} - {title}\n > {url}\n'
# fmt = ' {artist} - {title}\n'
# out = ' Included Music:\n'
# for index in indicies:
# out += fmt.format(**FILES[index])
# return out.strip()
#
# def get_date(date, request_length):
# random.seed(0)
# random.jumpahead(int((date-datetime(2014,12,25)).total_seconds()/86400))
# i = random.randint(0, len(TRACKS)-1)
# name, indicies = TRACKS[i]
#
#
# # only load when run build music
# # musicfile = get_music(name, indicies, request_length)
# musicfile = get_music_filename(name, request_length)
# musictext = get_info(indicies)
# info = dict(musicfile=musicfile,
# musictext=musictext,
# date=date,
# name=name,
# indicies=indicies,
# request_length=request_length)
# return info
#
# def build(info):
# date = info['date']
# name = info['name']
# indicies = info['indicies']
# request_length = info['request_length']
# print 'Loading {name} {indicies} for date: {date}'.format(**locals())
# musicfile = get_music(name, indicies, request_length)
# return musicfile
import json
import glob
import tempfile
from pprint import pprint
try:
import eyed3
import audioread
except:
# print 'eyed3 and audioread only required for processing of music'
pass
# where to save the files before the pi
TEMP_DIR = os.path.expanduser('~/tmp/music/output/')
PI_DIR = os.path.expanduser('~/video_archive/music')
if os.path.exists(PI_DIR):
TEMP_DIR = PI_DIR
JSON_FILE = os.path.join(TEMP_DIR, 'tracksets.json')
README_FILE = os.path.join(TEMP_DIR, 'readme.txt')
def check_call(cmd):
print ' Running: {}'.format(cmd)
subprocess.check_call(cmd, shell=True)
def get_info(filename):
'''Get the information of the track'''
audiofile = eyed3.load(filename)
audio = audioread.audio_open(filename)
info = dict(
artist = audiofile.tag.artist,
title = audiofile.tag.title,
channels = audio.channels,
samplerate = audio.samplerate,
duration = audio.duration,
filename = filename,
)
return info
def cut_file(filename, playtime, fadelength):
'''Cut the file with some fade at the end
add a 1 sec intro fade just in case
'''
if (fadelength > 0) and (playtime > (fadelength+1)):
options = 'fade 1 {playtime} {fadelength}'.format(**locals())
else:
options = 'trim 0 {playtime}'.format(**locals())
f = tempfile.NamedTemporaryFile('w', prefix='timerasp_', suffix='.mp3')
outfile = f.name
cmd = 'sox "{filename}" "{outfile}" {options}'.format(**locals())
check_call(cmd)
return f
def get_concatenate_fileprop(tracks):
'''Return the filename, key (artist-title series), and hash for a concatenated
trackset'''
key = u' ;; '.join([u'{} - {}'.format(t['artist'], t['title']) for t in tracks])
key_hash = hashlib.sha1(key.encode('utf8')).hexdigest()
outfile = os.path.join(TEMP_DIR, 'trackset_{}.mp3'.format(key_hash))
return outfile, key, key_hash
def concatenate_files(files, tracks, length, fadelength):
'''Combine a set of files/tracks into a singlefile
returns a dict of its properties.'''
outfile, outnames, outhash = get_concatenate_fileprop(tracks)
if os.path.exists(outfile):
print u'File already exists:\n {}\n {}'.format(outfile, outnames)
else:
# carve up files if needed
for tmp in files:
if not isinstance(tmp, str):
filename, playtime = tmp
cutfile = cut_file(filename, playtime, fadelength)
ifiles = files.index(tmp)
files[ifiles] = cutfile.name
# unicode strings here breaks things. wtf!
safefiles = ' '.join(['"{}"'.format(f) for f in files])
if len(files) > 1:
# need to combine them
cmd = 'sox --combine concatenate {safefiles} {outfile}'.format(**locals())
else:
# just move to the right location
cmd = 'rsync -rav {safefiles} {outfile}'.format(**locals())
check_call(cmd)
# clean up tmp files
# for cutfile in cleanup:
# cutfile.close()
info = dict(
filekey = outnames,
basename = os.path.basename(outfile),
filehash = outhash,
nicename = outnames.replace(';;','\n'),
length = length,
)
return info
def build_trackset(tracks, length, fadelength=None):
'''Combine the tracks into a nice auto trackset.
length in seconds
fadelength in seconds [10]'''
if fadelength is None: fadelength = 10
currentlength = 0
files = []
cleanup = []
for track in tracks:
currentlength += track['duration']
if currentlength < length:
files.append(track['filename'])
else:
# above current length so cut and fade
playtime = length - (currentlength - track['duration'])
files.append((track['filename'], playtime))
# print ' !! CUTTING: {} {}'.format(track['filename'], playtime)
# combine files into a single mp3
info = concatenate_files(files, tracks, length, fadelength)
return info
def save_tracksets_json(tracksets):
'''update the json with information from the tracksets
update the flat text file for simplicity
'''
try:
data = json.load(open(JSON_FILE,'r'))
except Exception as e:
print u'Failed to load trackset json: {}'.format(e)
if raw_input('is this ok? [y/n]').lower() != 'y':
raise e
data = []
hashes = [d['filehash'] for d in data]
for trackset in tracksets:
if trackset['filehash'] not in hashes:
data.append(trackset)
print '---track info---'
pprint(data)
print '--- end track info---'
if raw_input('save? [y/n]').lower() == 'y':
json.dump(data, open(JSON_FILE,'w'), indent=2)
def save_tracksets_readme(tracksets):
# make a nice readme file too
try:
# make sure there is a file there
if not os.path.exists(README_FILE):
# touch file
with open(README_FILE, 'w') as f:
f.write('# FILENAME :: artists - tracks')
# get the current file -- rw breaks things so here this is.
with open(README_FILE, 'r') as f:
tmp = f.readlines()
# write out the data
with open(README_FILE, 'a') as f:
filenames = [t.split(' :: ')[0] for t in tmp if ' :: ' in t]
for trackset in tracksets:
if trackset['basename'] not in filenames:
f.write(u'\n{basename} :: {filekey}'.format(**trackset).encode('utf8'))
except Exception as e:
print 'Failed to adjust readme_file: {}'.format(e)
raise e
def get_directory(directory, length=None, fadelength=None):
'''Build a nice json + music files from a directory
length -- length of composition [s]
fadelength -- length to fade last song [s]
# for each file in a directory
# Grab info of the file (artist, title, length)
# for each track:
# accumulate enough to make length
# for each trackset
# fade the last song
# combine
'''
if length is None: length = 5 * 60
tracks = []
for filename in glob.glob(os.path.join(directory, | |
:
return ( ( self . priority == 254 and self . mpriority == 255 and self . weight == 0 and self . mweight == 0 ) )
if 38 - 38: OoOoOO00 / OOooOOo % OoooooooOO * I1ii11iIi11i
if 7 - 7: I11i * O0 + Oo0Ooo / O0 * oO0o + i11iIiiIii
if 74 - 74: OoOoOO00
def print_state_change ( self , new_state ) :
Oo000 = self . print_state ( )
iI = "{} -> {}" . format ( Oo000 , new_state )
if ( new_state == "up" and self . unreach_state ( ) ) :
iI = bold ( iI , False )
if 66 - 66: i11iIiiIii . I11i % IiII % OoO0O00
return ( iI )
if 25 - 25: OoO0O00 % Oo0Ooo / Ii1I / Ii1I * IiII
if 33 - 33: ooOoO0o
def print_rloc_probe_rtt ( self ) :
if ( self . rloc_probe_rtt == - 1 ) : return ( "none" )
return ( self . rloc_probe_rtt )
if 14 - 14: Oo0Ooo % I1Ii111 % ooOoO0o . oO0o * iIii1I11I1II1 . I1ii11iIi11i
if 50 - 50: O0 * i11iIiiIii / iIii1I11I1II1 . I11i + i11iIiiIii
def print_recent_rloc_probe_rtts ( self ) :
OO0Ooo = str ( self . recent_rloc_probe_rtts )
OO0Ooo = OO0Ooo . replace ( "-1" , "?" )
return ( OO0Ooo )
if 23 - 23: I1ii11iIi11i
if 68 - 68: OoO0O00 . oO0o / IiII - II111iiii % Oo0Ooo
def compute_rloc_probe_rtt ( self ) :
I1IIII = self . rloc_probe_rtt
self . rloc_probe_rtt = - 1
if ( self . last_rloc_probe_reply == None ) : return
if ( self . last_rloc_probe == None ) : return
self . rloc_probe_rtt = self . last_rloc_probe_reply - self . last_rloc_probe
self . rloc_probe_rtt = round ( self . rloc_probe_rtt , 3 )
IiIIi = self . recent_rloc_probe_rtts
self . recent_rloc_probe_rtts = [ I1IIII ] + IiIIi [ 0 : - 1 ]
if 65 - 65: iII111i % oO0o * IiII
if 16 - 16: iII111i % I11i % OoOoOO00
def print_rloc_probe_hops ( self ) :
return ( self . rloc_probe_hops )
if 80 - 80: OoooooooOO * i11iIiiIii % oO0o / Oo0Ooo - I1ii11iIi11i
if 92 - 92: o0oOOo0O0Ooo % i1IIi / I1Ii111 % ooOoO0o / oO0o
def print_recent_rloc_probe_hops ( self ) :
IiI1 = str ( self . recent_rloc_probe_hops )
return ( IiI1 )
if 80 - 80: iIii1I11I1II1 . II111iiii
if 50 - 50: o0oOOo0O0Ooo - O0 + OoO0O00
def store_rloc_probe_hops ( self , to_hops , from_ttl ) :
if ( to_hops == 0 ) :
to_hops = "?"
elif ( to_hops < LISP_RLOC_PROBE_TTL / 2 ) :
to_hops = "!"
else :
to_hops = str ( LISP_RLOC_PROBE_TTL - to_hops )
if 22 - 22: I1Ii111 % O0 / I1Ii111 / I1Ii111
if ( from_ttl < LISP_RLOC_PROBE_TTL / 2 ) :
oO0ooo = "!"
else :
oO0ooo = str ( LISP_RLOC_PROBE_TTL - from_ttl )
if 64 - 64: O0 * OOooOOo * I1IiiI - o0oOOo0O0Ooo
if 86 - 86: i1IIi
I1IIII = self . rloc_probe_hops
self . rloc_probe_hops = to_hops + "/" + oO0ooo
IiIIi = self . recent_rloc_probe_hops
self . recent_rloc_probe_hops = [ I1IIII ] + IiIIi [ 0 : - 1 ]
if 84 - 84: OoOoOO00
if 31 - 31: iIii1I11I1II1 + I1IiiI
def process_rloc_probe_reply ( self , nonce , eid , group , hop_count , ttl ) :
oOo00O = self
while ( True ) :
if ( oOo00O . last_rloc_probe_nonce == nonce ) : break
oOo00O = oOo00O . next_rloc
if ( oOo00O == None ) :
lprint ( " No matching nonce state found for nonce 0x{}" . format ( lisp_hex_string ( nonce ) ) )
if 82 - 82: I1Ii111 / Ii1I % OoooooooOO - IiII / OoooooooOO
return
if 23 - 23: iIii1I11I1II1
if 7 - 7: IiII / OOooOOo + Oo0Ooo . I1IiiI
if 33 - 33: I1Ii111 + OoooooooOO
oOo00O . last_rloc_probe_reply = lisp_get_timestamp ( )
oOo00O . compute_rloc_probe_rtt ( )
ooiii1iiI1 = oOo00O . print_state_change ( "up" )
if ( oOo00O . state != LISP_RLOC_UP_STATE ) :
lisp_update_rtr_updown ( oOo00O . rloc , True )
oOo00O . state = LISP_RLOC_UP_STATE
oOo00O . last_state_change = lisp_get_timestamp ( )
IiiiiII1i = lisp_map_cache . lookup_cache ( eid , True )
if ( IiiiiII1i ) : lisp_write_ipc_map_cache ( True , IiiiiII1i )
if 48 - 48: II111iiii % I1ii11iIi11i - II111iiii
if 29 - 29: I1Ii111 - I1Ii111 - I11i * iIii1I11I1II1 % OoO0O00 % IiII
oOo00O . store_rloc_probe_hops ( hop_count , ttl )
if 73 - 73: i1IIi . OoooooooOO / OoOoOO00 % Ii1I / Ii1I / Ii1I
OO0oOOOO0O0OOo00 = bold ( "RLOC-probe reply" , False )
oo0o00OO = oOo00O . rloc . print_address_no_iid ( )
i1i1I1I1 = bold ( str ( oOo00O . print_rloc_probe_rtt ( ) ) , False )
III1I1Iii1 = ":{}" . format ( self . translated_port ) if self . translated_port != 0 else ""
if 6 - 6: iIii1I11I1II1 / oO0o % ooOoO0o
iiIIII1I1ii = ""
if ( oOo00O . rloc_next_hop != None ) :
OooOOOoOoo0O0 , IiI1Ii = oOo00O . rloc_next_hop
iiIIII1I1ii = ", nh {}({})" . format ( IiI1Ii , OooOOOoOoo0O0 )
if 1 - 1: Ii1I * I1IiiI + Oo0Ooo + IiII + OOooOOo
if 61 - 61: OoO0O00 . i1IIi / Ii1I % iII111i + Ii1I / i1IIi
oOo = green ( lisp_print_eid_tuple ( eid , group ) , False )
lprint ( ( " Received {} from {}{} for {}, {}, rtt {}{}, " + "to-ttl/from-ttl {}" ) . format ( OO0oOOOO0O0OOo00 , red ( oo0o00OO , False ) , III1I1Iii1 , oOo ,
# O0
ooiii1iiI1 , i1i1I1I1 , iiIIII1I1ii , str ( hop_count ) + "/" + str ( ttl ) ) )
if 40 - 40: O0
if ( oOo00O . rloc_next_hop == None ) : return
if 87 - 87: i1IIi / OoooooooOO . o0oOOo0O0Ooo % IiII
if 22 - 22: OoO0O00 . OOooOOo
if 95 - 95: OOooOOo + Oo0Ooo - OoOoOO00
if 33 - 33: OoO0O00
oOo00O = None
o0O0 = None
while ( True ) :
oOo00O = self if oOo00O == None else oOo00O . next_rloc
if ( oOo00O == None ) : break
if ( oOo00O . up_state ( ) == False ) : continue
if ( oOo00O . rloc_probe_rtt == - 1 ) : continue
if 79 - 79: OOooOOo % I1Ii111 / IiII - Oo0Ooo
if ( o0O0 == None ) : o0O0 = oOo00O
if ( oOo00O . rloc_probe_rtt < o0O0 . rloc_probe_rtt ) : o0O0 = oOo00O
if 48 - 48: Oo0Ooo * iII111i - Oo0Ooo + I11i % II111iiii
if 71 - 71: OoOoOO00 % o0oOOo0O0Ooo . oO0o
if ( o0O0 != None ) :
OooOOOoOoo0O0 , IiI1Ii = o0O0 . rloc_next_hop
iiIIII1I1ii = bold ( "nh {}({})" . format ( IiI1Ii , OooOOOoOoo0O0 ) , False )
lprint ( " Install host-route via best {}" . format ( iiIIII1I1ii ) )
lisp_install_host_route ( oo0o00OO , None , False )
lisp_install_host_route ( oo0o00OO , IiI1Ii , True )
if 65 - 65: OoO0O00
if 48 - 48: OoO0O00
if 59 - 59: OoooooooOO + I11i . oO0o
def add_to_rloc_probe_list ( self , eid , group ) :
oo0o00OO = self . rloc . print_address_no_iid ( )
IiI1iI1 = self . translated_port
if ( IiI1iI1 != 0 ) : oo0o00OO += ":" + str ( IiI1iI1 )
if 65 - 65: I1ii11iIi11i * II111iiii % I11i + II111iiii . i1IIi / ooOoO0o
if ( lisp_rloc_probe_list . has_key ( oo0o00OO ) == False ) :
lisp_rloc_probe_list [ oo0o00OO ] = [ ]
if 74 - 74: OoOoOO00 % OoO0O00 . OoOoOO00
if 16 - 16: OoO0O00 / Ii1I | |
from __future__ import print_function
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import argparse
from tqdm import tqdm
import os
import cv2
import pickle
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms, models
import numpy as np
from scipy import ndimage
from datasets import CoCoDataset
from sklearn.metrics import average_precision_score
import sklearn.metrics as metrics
TOTAL_LABELS = 66
class Identity(nn.Module):
def __init__(self):
super(Identity, self).__init__()
def forward(self, x):
return x
def get_bogs(all_preds, all_labels):
bog_tilde = np.zeros((TOTAL_LABELS, 2))
bog_gt_g = np.zeros((TOTAL_LABELS, 2))
bog_gt_o = np.zeros((TOTAL_LABELS, 2))
bog_preds = np.zeros((TOTAL_LABELS, 2))
for i, objs in enumerate([all_preds, all_labels]):
female = np.where(objs[:, -1] == 0)[0]
male = np.where(objs[:, -1] == 1)[0]
for j in range(TOTAL_LABELS):
if i == 0:
bog_preds[j][0] = np.sum(objs[male][:, j])
bog_preds[j][1] = np.sum(objs[female][:, j])
bog_gt_o[j][0] = np.sum(all_labels[male][:, j])
bog_gt_o[j][1] = np.sum(all_labels[female][:, j])
elif i == 1:
bog_tilde[j][0] = np.sum(objs[male][:, j])
bog_tilde[j][1] = np.sum(objs[female][:, j])
female = np.where(all_labels[:, -1] == 0)[0]
male = np.where(all_labels[:, -1] == 1)[0]
all_preds, all_labels = all_preds[:, :-1], all_labels[:, :-1]
for i, objs in enumerate([all_preds]):
for j in range(TOTAL_LABELS):
bog_gt_g[j][0] = np.sum(objs[male][:, j])
bog_gt_g[j][1] = np.sum(objs[female][:, j])
return bog_tilde, bog_gt_g, bog_gt_o, bog_preds
def train(args, model, device, train_loader, optimizer, epoch, criterion, loss_info, file):
model.train()
all_preds = []
all_probs = []
all_labels = []
running_loss = []
for batch_idx, (data, target) in (enumerate(tqdm(train_loader)) if args.interact else enumerate(train_loader)):
target = target.float()
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model.forward(data)
loss = criterion(output, target)
weight = target*(args.pos_weight - 1.) + 1.
if args.training_version == 1: # will cancel out positive weight if that is an argument
num_a = torch.sum(target[:, -1])
num_b = len(target) - num_a
alpha = ((len(target) // 2) - num_a) / (len(target) // 2)
weight = (target[:, -1] * 2) - 1
weight = weight * alpha
weight = torch.ones_like(weight) + weight
weight = weight.unsqueeze(1)
loss = loss * weight
loss = loss.mean()
loss.backward()
optimizer.step()
if batch_idx % 100 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
running_loss.append(loss.item()*len(data))
all_labels.extend(target.data.cpu().numpy())
all_probs.extend(output.data.cpu().numpy())
preds = torch.round(output).data.cpu().numpy()
all_preds.extend(preds)
all_probs, all_preds, all_labels = np.array(all_probs), np.array(all_preds), np.array(all_labels)
corrects = np.equal(all_preds, all_labels)
running_batch_loss = np.sum(running_loss) / len(all_labels)
if len(all_preds.shape) == 1:
all_preds = np.expand_dims(all_preds, 1)
probs_ap_score = average_precision_score(all_labels, all_probs)
print("Train Epoch: {0}, AP: {1}, Loss: {2} ".format(epoch, probs_ap_score, running_batch_loss))
female = np.where(all_labels[:, -1] == 0)[0]
male = np.where(all_labels[:, -1] == 1)[0]
for indices in [male, female]:
accuracies = np.mean(corrects[indices], axis=0)
this_ap_score = average_precision_score(all_labels[indices, :-1], all_probs[indices, :-1])
sep_acc = [this_ap_score, accuracies[-1]]
print(corrects[indices].shape)
print(sep_acc)
if file is not None:
file.write("Train Epoch: {0}, AP: {1}, Loss: {2}\n\n".format(epoch, probs_ap_score, running_batch_loss))
loss_info['train_map'].append(probs_ap_score)
loss_info['train_gen'].append(np.mean(all_labels[:, -1] == all_preds[:, -1]))
loss_info['train_loss'].append(running_batch_loss)
return loss_info
def test(args, model, device, test_loader, epoch, criterion, loss_info, file):
valid_loader, test_loader = test_loader
model.eval()
test_loss = 0
all_preds = []
all_probs = []
all_labels = []
with torch.no_grad():
for batch_idx, (data, target) in (enumerate(tqdm(test_loader)) if args.interact else enumerate(test_loader)):
target = target.float()
data, target = data.to(device), target.to(device)
output = model.forward(data)
loss = criterion(output, target).mean() # sum up batch loss
test_loss += loss.item() * len(target)
all_labels.extend(target.data.cpu().numpy())
all_probs.extend(output.data.cpu().numpy())
preds = torch.round(output).data.cpu().numpy()
all_preds.extend(preds)
test_loss /= len(all_labels)
all_preds, all_labels, all_probs = np.array(all_preds), np.array(all_labels), np.array(all_probs)
if len(all_preds.shape) == 1:
all_preds = np.expand_dims(all_preds, 1)
corrects = np.equal(all_preds, all_labels)
probs_ap_score = average_precision_score(all_labels, all_probs)
loss_info['test_loss'].append(test_loss)
loss_info['test_probs'].append(all_probs)
loss_info['test_labels'].append(all_labels)
per_group = []
labels_to_names = test_loader.dataset.labels_to_names
categories = test_loader.dataset.categories
test_map = average_precision_score(all_labels[:, :-1], all_probs[:, :-1])
test_gender = np.mean(corrects, axis=0)[-1]
print("Total mAP: {0}, Total gender: {1}".format(test_map, test_gender))
loss_info['test_map'].append(test_map)
loss_info['test_gen'].append(test_gender)
# validation set
valid_probs = []
valid_preds = []
valid_labels = []
val_loss = 0
with torch.no_grad():
for batch_idx, (data, target) in (enumerate(tqdm(valid_loader)) if args.interact else enumerate(valid_loader)):
target = target.float()
data, target = data.to(device), target.to(device)
output = model.forward(data)
loss = criterion(output, target).mean() # sum up batch loss
val_loss += loss.item() * len(target)
valid_labels.extend(target.data.cpu().numpy())
valid_probs.extend(output.data.cpu().numpy())
preds = torch.round(output).data.cpu().numpy()
valid_preds.extend(preds)
val_loss /= len(valid_labels)
valid_preds, valid_probs, valid_labels = np.array(valid_preds), np.array(valid_probs), np.array(valid_labels)
loss_info['val_labels'].append(valid_labels)
loss_info['val_probs'].append(valid_probs)
loss_info['val_loss'].append(val_loss)
if file is not None:
file.write("Test Epoch: {0}, mAP: {1}, Loss: {2}\n\n".format(epoch, probs_ap_score, test_loss))
print("\n--------\n\n")
return loss_info
def main():
# Training settings
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
help='input batch size for training (default: 64)')
parser.add_argument('--epochs', type=int, default=10, metavar='N',
help='number of epochs to train (default: 10)')
parser.add_argument('--lr', type=float, default=0.01, metavar='LR',
help='learning rate (default: 0.01)')
parser.add_argument('--momentum', type=float, default=0.5, metavar='M',
help='SGD momentum (default: 0.5)')
parser.add_argument('--model_name', type=str, default="",
help='path to model to load, or model to save')
parser.add_argument('--model_type', type=str, default="vgg16",
help='model type')
parser.add_argument('--pos_weight', type=float, default=1.,
help='how much to weigh the positive examples')
parser.add_argument('--maskloss_weight', type=float, default=0.,
help='weight for mask norm on optimal mask')
parser.add_argument('--interact', action='store_true', default=False,
help='For if showing tqdm')
parser.add_argument('--pretrained', action='store_false', default=True,
help='if the model weights taken should be pretrained, defaulrt is false')
parser.add_argument('--test_is_train', action='store_true', default=False,
help='test dataset is train')
parser.add_argument('--mask_person', type=int, default=0,
help='0 is not masked, 1 is masked with box, 2 is masked with segmentation map'+
'3 is noisy half mask of segmentation map, 4 is opposite of 2 where all is covered except person' +
'5 is random mask blocking the size of the person, 6 is random mask blocking the size of the background'+
'7 is better version of 2 since masks person, but adds back any background objects'+
'8 is opposite of 7 where objects are all removed but person is added back')
parser.add_argument('--training_version', type=int, default=0,
help='0 is regular, 1 is equalize genders where losses equal between two genders, 2 is adversarial loss at no gender')
parser.add_argument('--save-model', action='store_true', default=False,
help='For Saving the current Model')
parser.add_argument('--load-model', action='store_true', default=False,
help='if loading a model')
parser.add_argument('--continue-model', action='store_true', default=False,
help='if loading a model but want to continue training, not testing')
args = parser.parse_args()
print(args)
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
print("Device: {}".format(device))
workers = 1
folder = "models/" + args.model_name
if not os.path.exists(folder):
os.makedirs(folder)
transform=transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
global TOTAL_LABELS
train_dataset = CoCoDataset(transform, mask_person=args.mask_person)
test_dataset = CoCoDataset(transform, version='val', mask_person=args.mask_person)
val_dataset = CoCoDataset(transform, mask_person=args.mask_person)
train_indices, val_indices = pickle.load(open('coco_validation_indices.pkl', 'rb'))
print("len train: {0}, len val: {1}".format(len(train_indices), len(val_indices)))
train_dataset.image_ids = list(np.array(train_dataset.image_ids)[train_indices])
val_dataset.image_ids = list(np.array(val_dataset.image_ids)[val_indices])
val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=args.batch_size,
shuffle=True, num_workers=workers)
##tiny
#train_dataset.image_ids = train_dataset.image_ids[:100]
#test_dataset.image_ids = test_dataset.image_ids[:100]
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=args.batch_size,
shuffle=True, num_workers=workers)
if args.test_is_train:
test_loader = torch.utils.data.DataLoader(train_dataset, batch_size=args.batch_size//2,
shuffle=False, num_workers=workers)
else:
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=args.batch_size//2,
shuffle=False, num_workers=workers)
out_features = TOTAL_LABELS
out_features += 1
if args.model_type == 'vgg16':
model = models.vgg16(pretrained=args.pretrained)
model.classifier[6] = nn.Linear(4096, out_features)
model.classifier.add_module('last_sigmoid', nn.Sigmoid())
model.to(device)
elif args.model_type == 'alexnet':
model = models.alexnet(pretrained=args.pretrained)
model.classifier[6] = nn.Linear(4096, out_features)
model.classifier.add_module('last_sigmoid', nn.Sigmoid())
model.to(device)
elif args.model_type == 'resnet101':
model = models.resnet101(pretrained=args.pretrained)
model.fc = nn.Sequential(nn.Linear(2048, out_features), nn.Sigmoid())
model.to(device)
elif args.model_type == 'resnet18':
model = models.resnet18(pretrained=args.pretrained)
if args.training_version == 2:
model.fc = Identity()
gen_classifier = nn.Sequential(nn.Linear(512, 1), nn.Sigmoid())
label_classifier = nn.Sequential(nn.Linear(512, out_features - 1), nn.Sigmoid())
else:
model.fc = nn.Sequential(nn.Linear(512, out_features), nn.Sigmoid())
model.to(device)
elif args.model_type == 'resnet34':
model = models.resnet34(pretrained=args.pretrained)
model.fc = nn.Sequential(nn.Linear(512, out_features), nn.Sigmoid())
model.to(device)
elif args.model_type == 'resnet50':
model = models.resnet50(pretrained=args.pretrained)
model.fc = nn.Sequential(nn.Linear(2048, out_features), nn.Sigmoid())
model.to(device)
criterion = nn.BCELoss(reduction='none')
optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum)
loss_info = None
if args.load_model:
model.load_state_dict(torch.load("{0}/model.pt".format(folder)))
loss_info = pickle.load(open("{0}/loss_info.pkl".format(folder), 'rb'))
if args.continue_model:
keys = ['test_menalsoshop', 'test_all_gts', 'test_all_tgs', 'test_gen']
for key in keys:
if key not in loss_info.keys():
loss_info[key] = []
file = open("{0}/training.txt".format(folder),"a")
for epoch in range(1+len(loss_info['test_map']), args.epochs + 1):
loss_info = train(args, model, device, train_loader, optimizer, epoch, criterion, loss_info, file)
loss_info = test(args, model, device, [val_loader, test_loader], epoch, criterion, loss_info, file)
else:
loss_info = test(args, model, device, [val_loader, test_loader], args.epochs, criterion, loss_info, None)
else:
if args.save_model:
file = open("{0}/training.txt".format(folder),"a")
loss_info = {}
loss_info['train_map'] = []
loss_info['train_loss'] = []
loss_info['train_gen'] = []
loss_info['test_map'] = []
loss_info['test_loss'] = []
loss_info['test_gen'] = []
loss_info['val_loss'] = []
loss_info['val_labels'] = []
loss_info['val_probs'] = []
loss_info['test_labels'] = []
loss_info['test_probs'] = []
else:
file = None
for epoch in range(1, args.epochs + 1):
loss_info = train(args, model, device, train_loader, optimizer, epoch, criterion, loss_info, file)
loss_info = test(args, model, device, [val_loader, test_loader], epoch, criterion, loss_info, file)
if args.save_model:
file.close()
if (args.save_model):
torch.save(model.state_dict(),"{0}/model.pt".format(folder))
pickle.dump(loss_info, open("{0}/loss_info.pkl".format(folder), 'wb'))
plt.plot(np.arange(len(loss_info['test_map'])), loss_info['test_map'], label='test')
plt.plot(np.arange(len(loss_info['train_map'])), loss_info['train_map'], | |
<gh_stars>1-10
import numpy as np
import yfinance
import pandas as pd
from gym.utils import seeding
import gym
from gym import spaces
import matplotlib
import matplotlib.pyplot as plt
import pickle
from stable_baselines3.common.vec_env import DummyVecEnv
from stable_baselines3.common import logger
matplotlib.use("Agg")
def _cal_exp(x, ind=2.0):
return abs(x) ** ind * (-1) ** int(x < 0)
class StockTradingEnv(gym.Env):
"""A stock trading environment for OpenAI gym"""
metadata = {'render.modes': ['human']}
def __init__(
self,
df,
stock_dim,
state_space,
action_space,
tech_indicator_list,
buy_cost_pct=0,
sell_cost_pct=0,
turbulence_threshold=None,
make_plots=False,
print_verbosity=10,
day=0,
initial=True,
previous_state=[],
model_name="",
mode="",
iteration="",
initial_amount=10000,
stepmoney=10000,
# transaction_cost = 0.015,
transaction_cost=0.07,
time_range_benchmark=10,
reward_scaling=1,
# reward
ind=3,
rt_scaling=1000,
roi_threshold=0.0,
rt_positive_minus=0,
rt_negative_minus=1,
# timeb_positive_scaling=1,
# timeb_negative_scaling=2,
ratio_threshold=0.2,
_b_add=1,
_b_ind=2,
_a_add=1,
_a_mul=1.5,
r_negative_minus=10, # 0 - 50
rr_positive_mul=30, # 0 - 50
ce_positive_mul=1,
tr_bm_coef=2,
# holding reward
latest_day=30,
time_range_allowed=7,
time_range_bm=20,
ratio_base=0.05,
ratio_bm=0.07,
hr_mul=1, # 1- 100
):
self.day = day
self.df = df
self.close = df[['close', 'tic']]
self.stock_dim = stock_dim
self.initial_amount = initial_amount
self.end_total_asset = initial_amount
self.end_total_account = initial_amount
self.buy_cost_pct = buy_cost_pct
self.sell_cost_pct = sell_cost_pct
self.reward_scaling = reward_scaling
self.state_space = state_space
self.action_space = action_space
self.tech_indicator_list = tech_indicator_list
# self.action_space = spaces.Box(low=-1, high=1, shape=(self.action_space,))
self.action_space = spaces.Discrete(3)
self.observation_space = spaces.Box(
low=-np.inf, high=np.inf, shape=(self.state_space,))
# self.data = self.df.loc[self.day, :]
self.data = self.df[self.df.tic ==
self.df.tic.unique()[0]].loc[self.day]
self.terminal = False
self.make_plots = make_plots
self.print_verbosity = print_verbosity
self.turbulence_threshold = turbulence_threshold
self.initial = initial
self.previous_state = previous_state
self.model_name = model_name
self.mode = mode
self.iteration = iteration
self.stepmoney = stepmoney
self.transaction_cost = transaction_cost
self.time_range_benchmark = time_range_benchmark
self.fr_day = 10
# initializes
self.state = self._initiate_state()
self.trade_cache = self._initiate_trade_cache()
self.trade_state_memory = self._initiate_trade_state_memory()
self.empty_state_memory = self._initiate_empty_state_memory()
# self.trade_data_list = []
self.buy_day = -1
self.sell_day = -1
self.tic = None
self.trade_index = 0
self.reward = 0
self.turbulence = 0
self.cost = 0
self.trades = 0
self.episode = 0
# memorize all the total balance change
self.asset_memory = [self.initial_amount]
# self.rewards_memory = []
# self.actions_memory = []
# self.states_memory = []
self.date_memory = [self._get_date()]
self.reset()
self._seed()
# reward pars
self.ind = ind
self.rt_scaling = rt_scaling # 1000
self.roi_threshold = roi_threshold # 0.0
self.ratio_threshold = ratio_threshold
self.rt_positive_minus = rt_positive_minus # 0
self.rt_negative_minus = rt_negative_minus # 1
self._b_add = _b_add
self._b_ind = _b_ind
self._a_add = _a_add
self._a_mul = _a_mul
self.tr_bm_coef = tr_bm_coef
# self.timeb_positive_scaling = timeb_positive_scaling # 1
# self.timeb_negative_scaling = timeb_negative_scaling # 2
self.r_negative_minus = r_negative_minus
self.rr_positive_mul = rr_positive_mul
self.ce_positive_mul = ce_positive_mul
# holding reward
self.latest_day = latest_day
self.time_range_allowed = time_range_allowed
self.time_range_bm = time_range_bm
self.ratio_base = ratio_base
self.ratio_bm = ratio_bm
self.hr_mul = hr_mul
def _sell_stock(self):
def _do_sell_normal():
close_price = self.close[self.close['tic']
== self.tic].iloc[self.day]['close']
if close_price > 0:
# Sell only if the price is > 0 (no missing data in this
# particular date)
if self.buy_day > -1 and self.sell_day == -1 and self.day != self.buy_day:
# Sell only if sell_day != -1 and it is not sold yet
buy_timestamp = int(self.buy_day)
sell_num_shares = self.stepmoney // self.close[self.close['tic']
== self.tic].iloc[buy_timestamp]['close']
sell_amount = close_price * \
sell_num_shares * (1 - self.sell_cost_pct)
# update balance
self.end_total_account += sell_amount
self.cost += close_price * \
sell_num_shares * self.sell_cost_pct
else:
sell_num_shares = 0
else:
sell_num_shares = 0
return sell_num_shares
close_price = self.close[self.close['tic']
== self.tic].iloc[self.day]['close']
# perform sell action based on the sign of the action
if self.turbulence_threshold is not None:
if self.turbulence >= self.turbulence_threshold:
if close_price > 0:
# # Sell only if the price is > 0 (no missing data in this particular date)
# # if turbulence goes over threshold, just clear out all positions
sell_num_shares = _do_sell_normal()
else:
sell_num_shares = 0
else:
sell_num_shares = _do_sell_normal()
else:
sell_num_shares = _do_sell_normal()
if sell_num_shares != 0:
self.sell_day = self.day
else:
self.sell_day = -1
return sell_num_shares
def _buy_stock(self):
def _do_buy():
close_price = self.close[self.close['tic']
== self.tic].iloc[self.day]['close']
if close_price > 0:
# Buy only if the price is > 0 (no missing data in this
# particular date)
if self.trade_index <= -1 and self.buy_day == -1 and self.sell_day == -1:
available_amount = self.stepmoney // close_price
# update balance
buy_num_shares = available_amount
buy_amount = close_price * \
buy_num_shares * (1 + self.buy_cost_pct)
self.end_total_account -= buy_amount
self.cost += close_price * \
buy_num_shares * self.buy_cost_pct
self.buy_day = self.day
self.trades += 1
self.trade_index = self.trades
else:
buy_num_shares = 0
else:
buy_num_shares = 0
return buy_num_shares
# perform buy action based on the sign of the action
if self.turbulence_threshold is None:
buy_num_shares = _do_buy()
else:
if self.turbulence < self.turbulence_threshold:
buy_num_shares = _do_buy()
else:
buy_num_shares = 0
pass
# self.states_buy.append(self.day)
return buy_num_shares
def _make_plot(self):
plt.plot(self.asset_memory, 'r')
plt.savefig('results/account_value_trade_{}.png'.format(self.episode))
plt.close()
def _get_close(self, timestamp):
if timestamp == -1:
return 0
return self.df[self.df.tic == self.tic].loc[timestamp].close
def steps(self, action, state):
self.state = state
self.trade_index = int(state[0])
trade_data = self.trade_cache[self.trade_cache['trade_index']
== self.trade_index]
try:
self.day = int(trade_data.today)
self.buy_day = int(trade_data.buy_day)
self.sell_day = int(trade_data.sell_day)
self.tic = trade_data.tic.values[0]
self.terminal = self.day >= len(self.df.index.unique()) - 1
except BaseException:
# print('self.trade_data_list:', self.trade_data_list)
print('self.trade_index', self.trade_index)
print('failed')
if self.terminal:
print('terminal')
return self.state, self.reward, action, self.terminal, {}
else:
temp = action
# if self.stock_dim == 1:
if action == 0:
action_num = self._sell_stock()
elif action == 2:
action_num = self._buy_stock()
else:
action_num = 0
if action_num == 0:
action = 1
# just 4 test
# self.reward = self._get_reward()
# buy_price = self.get_close(self.buy_day)
# sell_price = self.get_close(self.sell_day)
# today_price = self.get_close(self.day)
# print(f"state:{self.state[:4]}\tb4action:{temp}\taction:{action}")
# print(f"buy_day:{self.buy_day}\tsell_day:{self.sell_day}\ttoday:{self.day}")
# print(f"buy_price:{buy_price}\tsell_price:{sell_price}\ttoday_price:{today_price}")
self.day += 1
self.data = self.df[self.df.tic == self.tic].loc[self.day]
self.date_memory.append(self._get_date())
self.reward = self._get_reward()
# self.asset = self._get_asset()
# self.reward = self.reward * self.reward_scaling
self._update_trade_cache()
# update state
self.state = self._update_state()
self.state[-10:] = np.random.rand(10)
if self.state[0] >= 0: # we have bought
# feature_rb
self._update_state_rb()
# feature_rh
self.state[-10:-5] = [0] * 5
# self.state[-10:-5] = self.state[-5:]
# print(self.state[-5:])
elif self.day > self.fr_day: # not buy yet
# feature_rb
self.state[-5:] = [0] * 5
# feature_rh
self._update_state_rh()
# print(self.state[-10:-5])
for i in range(1, 11):
j = -i
v = self.state[j]
if v > 0:
self.state[j] = 1
elif v < 0:
self.state[j] = -1
self._update_trade_state_memory()
self._update_empty_state_memory()
# print(f"next state:{self.state[:4]}\treward:{self.reward}\n")
# TODO: not modified yet
# if self.buy_day != -1:
# buy_timestamp = int(self.buy_day)
# market_asset = self.stepmoney - \
# self.stepmoney % self.close[self.close['tic'] == self.tic].iloc[buy_timestamp]['close']
# else:
# market_asset = 0
#
# end_total_asset = self.end_total_account + market_asset
#
# self.asset_memory.append(end_total_asset)
return self.state, self.reward, action, self.terminal, {}
def reset(self):
# initiate state
self.state = self._initiate_state()
self.trade_cache = self._initiate_trade_cache()
self.trade_state_memory = self._initiate_trade_state_memory()
self.empty_state_memory = self._initiate_empty_state_memory()
if self.initial:
# TODO: update asset_memory or delete it?
self.asset_memory = [self.initial_amount]
self.day = 0
self.data = self.df[self.df.tic ==
self.df.tic.unique()[0]].loc[self.day]
self.turbulence = 0
self.cost = 0
self.trades = 0
self.terminal = False
# self.iteration=self.iteration
# self.rewards_memory = []
# self.actions_memory = []
self.date_memory = [self._get_date()]
self.episode += 1
return self.state
def render(self, mode='human', close=False):
return self.state
def _initiate_state(self):
tics = self.df.tic.unique()
if self.initial:
# For Initial State
if len(tics) == 1:
tic = tics[0]
self.data = self.df[self.df.tic == tic].loc[0]
state = (
[-1] # trade index
+ sum([[self.data[tech]]
for tech in self.tech_indicator_list], [])
)
return state
else:
states = []
i = -len(tics)
for tic in tics:
self.data = self.df[self.df.tic == tic].loc[0]
state = (
[i] # trade index
+ sum([[self.data[tech]]
for tech in self.tech_indicator_list], [])
)
states.append(state)
i += 1
return states
else:
# Using Previous State
state = ([self.previous_state[0]] + sum([[self.data[tech]]
for tech in self.tech_indicator_list], []))
return state
def _cal_reward(self, current_timestamp, buy_timestamp):
# TODO: update for multi stocks
buy_price = self._get_close(buy_timestamp)
current_price = self._get_close(current_timestamp)
ratio = (current_price - buy_price) / buy_price
time_range = current_timestamp - buy_timestamp
roi = min(ratio - self.transaction_cost, self.ratio_threshold)
_b = _cal_exp(self._b_add + roi, self._b_ind)
_a = self._a_add + ratio / self.ind * self._a_mul
if roi > self.roi_threshold:
# time_base = min(max(time_range, self.time_range_bm), self.time_range_bm * self.tr_bm_coef)
time_base = min(max(time_range, self.time_range_bm), self.time_range_bm ** (4/5))
return _cal_exp(
(roi / time_base * 100 * 2 + 1) * _a,
self.ind * _b * _a) * self.ce_positive_mul + ratio * self.rr_positive_mul
# return min(500,reward)
else:
time_base = max(
min(time_range, self.time_range_bm / 2), self.time_range_bm / 4)
return _cal_exp(
roi / time_base * 100 - self.rt_negative_minus,
self.ind) - self.r_negative_minus
def _holding_reward(self):
current_timestamp = int(self.day)
latest_sell_day = max(self.trade_cache.sell_day)
if latest_sell_day == -1:
return 0
start_timestamp = | |
<gh_stars>10-100
"""A version of transform's T5 models with support for custom positional attention bias,
and a fixed forward masking in the decoder"""
import copy
import torch
from torch import nn
from torch.nn import CrossEntropyLoss
from transformers.file_utils import add_start_docstrings_to_model_forward, replace_return_docstrings
from transformers.modeling_outputs import BaseModelOutputWithPastAndCrossAttentions, \
BaseModelOutput, Seq2SeqLMOutput
from transformers.models.t5.modeling_t5 import T5Stack, T5Attention, T5PreTrainedModel, \
T5_INPUTS_DOCSTRING
def build_decoder_attention_mask(labels):
# Manually build a decoder mask, the transformers library builds this mask with
# a value of -10000 on future states, but I have seen models over-power that masking
# to cheat and peak ahead in rare circumstances. Here, we build a mask of
# -inf on future states so cheating is definitely impossible
batch, seq_len = labels.size()
seq_ids = torch.arange(seq_len, device=labels.device)
decoder_mask = seq_ids[None, None, :].repeat(batch, seq_len, 1) <= seq_ids[None, :, None]
return torch.where(
decoder_mask,
torch.full_like(decoder_mask, 0, dtype=torch.float32),
torch.full_like( decoder_mask, -float("Inf"), dtype=torch.float32)
)
class OurT5Stack(T5Stack):
def __init__(self, config, embed_tokens=None):
super().__init__(config)
self.embed_tokens = embed_tokens
def forward(
self,
input_ids=None,
attention_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
inputs_embeds=None,
head_mask=None,
encoder_head_mask=None,
past_key_values=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
encoder_positional_bias=None,
return_dict=None,
):
# Model parallel
if self.model_parallel:
raise NotImplementedError()
use_cache = use_cache if use_cache is not None else self.config.use_cache
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if input_ids is not None and inputs_embeds is not None:
err_msg_prefix = "decoder_" if self.is_decoder else ""
raise ValueError(
f"You cannot specify both {err_msg_prefix}inputs and {err_msg_prefix}inputs_embeds at the same time"
)
elif input_ids is not None:
input_shape = input_ids.size()
input_ids = input_ids.view(-1, input_shape[-1])
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
else:
err_msg_prefix = "decoder_" if self.is_decoder else ""
raise ValueError(f"You have to specify either {err_msg_prefix}inputs or {err_msg_prefix}inputs_embeds")
if inputs_embeds is None:
assert self.embed_tokens is not None, "You have to initialize the model with valid token embeddings"
inputs_embeds = self.embed_tokens(input_ids)
batch_size, seq_length = input_shape
# required mask seq length can be calculated via length of past
mask_seq_length = past_key_values[0][0].shape[2] + seq_length if past_key_values is not None else seq_length
if use_cache is True:
assert self.is_decoder, f":obj:`use_cache` can only be set to `True` if {self} is used as a decoder"
if attention_mask is None:
attention_mask = torch.ones(batch_size, mask_seq_length).to(inputs_embeds.device)
if self.is_decoder and encoder_attention_mask is None and encoder_hidden_states is not None:
encoder_seq_length = encoder_hidden_states.shape[1]
encoder_attention_mask = torch.ones(
batch_size, encoder_seq_length, device=inputs_embeds.device, dtype=torch.long
)
# initialize past_key_values with `None` if past does not exist
if past_key_values is None:
past_key_values = [None] * len(self.block)
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
# ourselves in which case we just need to make it broadcastable to all heads.
extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape, inputs_embeds.device)
if self.is_decoder and encoder_attention_mask is not None:
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
else:
encoder_extended_attention_mask = None
# Prepare head mask if needed
head_mask = self.get_head_mask(head_mask, self.config.num_layers)
encoder_head_mask = self.get_head_mask(encoder_head_mask, self.config.num_layers)
present_key_value_states = () if use_cache else None
all_hidden_states = () if output_hidden_states else None
all_attentions = () if output_attentions else None
all_cross_attentions = () if (output_attentions and self.is_decoder) else None
encoder_decoder_position_bias = None
position_bias = None
if not self.is_decoder:
position_bias = encoder_decoder_position_bias
encoder_decoder_position_bias = None
hidden_states = self.dropout(inputs_embeds)
for i, (layer_module, past_key_value) in enumerate(zip(self.block, past_key_values)):
layer_head_mask = head_mask[i]
encoder_layer_head_mask = encoder_head_mask[i]
if self.model_parallel:
raise NotImplementedError()
layer_outputs = layer_module(
hidden_states,
attention_mask=extended_attention_mask,
position_bias=position_bias,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_extended_attention_mask,
encoder_decoder_position_bias=encoder_decoder_position_bias,
layer_head_mask=layer_head_mask,
encoder_layer_head_mask=encoder_layer_head_mask,
past_key_value=past_key_value,
use_cache=use_cache,
output_attentions=output_attentions,
)
# layer_outputs is a tuple with:
# hidden-states, key-value-states, (self-attention weights), (self-attention position bias), (cross-attention weights), (cross-attention position bias)
hidden_states, present_key_value_state = layer_outputs[:2]
# We share the position biases between the layers - the first layer store them
# layer_outputs = hidden-states, key-value-states (self-attention weights),
# (self-attention position bias), (cross-attention weights), (cross-attention position bias)
position_bias = layer_outputs[2]
if self.is_decoder and encoder_hidden_states is not None:
encoder_decoder_position_bias = layer_outputs[4 if output_attentions else 3]
# append next layer key value states
if use_cache:
present_key_value_states = present_key_value_states + (present_key_value_state,)
if output_attentions:
all_attentions = all_attentions + (layer_outputs[3],)
if self.is_decoder:
all_cross_attentions = all_cross_attentions + (layer_outputs[5],)
# Model Parallel: If it's the last layer for that device, put things on the next device
if self.model_parallel:
for k, v in self.device_map.items():
if i == v[-1] and "cuda:" + str(k) != self.last_device:
hidden_states = hidden_states.to("cuda:" + str(k + 1))
hidden_states = self.final_layer_norm(hidden_states)
hidden_states = self.dropout(hidden_states)
# Add last layer
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(
v
for v in [
hidden_states,
present_key_value_states,
all_hidden_states,
all_attentions,
all_cross_attentions,
]
if v is not None
)
return BaseModelOutputWithPastAndCrossAttentions(
last_hidden_state=hidden_states,
past_key_values=present_key_value_states,
hidden_states=all_hidden_states,
attentions=all_attentions,
cross_attentions=all_cross_attentions,
)
class OurT5ForConditionalGeneration(T5PreTrainedModel):
_keys_to_ignore_on_load_missing = [
r"encoder\.embed_tokens\.weight",
r"decoder\.embed_tokens\.weight",
r"lm_head\.weight",
]
_keys_to_ignore_on_load_unexpected = [
r"decoder\.block\.0\.layer\.1\.EncDecAttention\.relative_attention_bias\.weight",
]
def __init__(self, config):
super().__init__(config)
self.model_dim = config.d_model
self.shared = nn.Embedding(config.vocab_size, config.d_model)
encoder_config = copy.deepcopy(config)
encoder_config.is_decoder = False
encoder_config.use_cache = False
encoder_config.is_encoder_decoder = False
self.encoder = OurT5Stack(encoder_config, self.shared)
decoder_config = copy.deepcopy(config)
decoder_config.is_decoder = True
decoder_config.is_encoder_decoder = False
decoder_config.num_layers = config.num_decoder_layers
self.decoder = OurT5Stack(decoder_config, self.shared)
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
self.init_weights()
# Model parallel
self.model_parallel = False
self.device_map = None
def get_input_embeddings(self):
return self.shared
def set_input_embeddings(self, new_embeddings):
self.shared = new_embeddings
self.encoder.set_input_embeddings(new_embeddings)
self.decoder.set_input_embeddings(new_embeddings)
def set_output_embeddings(self, new_embeddings):
self.lm_head = new_embeddings
def get_output_embeddings(self):
return self.lm_head
def get_encoder(self):
return self.encoder
def get_decoder(self):
return self.decoder
def forward(
self,
input_ids=None,
attention_mask=None,
decoder_input_ids=None,
decoder_attention_mask=None,
encoder_positional_bias=None,
encoder_outputs=None,
past_key_values=None,
inputs_embeds=None,
decoder_inputs_embeds=None,
labels=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# Encode if needed (training, first prediction pass)
if encoder_outputs is None:
# Convert encoder inputs in embeddings if needed
encoder_outputs = self.encoder(
input_ids=input_ids,
attention_mask=attention_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
encoder_positional_bias=encoder_positional_bias
)
elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
encoder_outputs = BaseModelOutput(
last_hidden_state=encoder_outputs[0],
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
)
hidden_states = encoder_outputs[0]
if self.model_parallel:
torch.cuda.set_device(self.decoder.first_device)
if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:
# get decoder inputs from shifting lm labels to the right
decoder_input_ids = self._shift_right(labels)
# If decoding with past key value states, only the last tokens
# should be given as an input
if past_key_values is not None:
assert labels is None, "Decoder should not use cached key value states when training."
if decoder_input_ids is not None:
decoder_input_ids = decoder_input_ids[:, -1:]
if decoder_inputs_embeds is not None:
decoder_inputs_embeds = decoder_inputs_embeds[:, -1:]
if decoder_attention_mask is None and labels is not None:
decoder_attention_mask = build_decoder_attention_mask(labels)
# Decode
decoder_outputs = self.decoder(
input_ids=decoder_input_ids,
attention_mask=decoder_attention_mask,
inputs_embeds=decoder_inputs_embeds,
past_key_values=past_key_values,
encoder_hidden_states=hidden_states,
encoder_attention_mask=attention_mask,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict
)
sequence_output = decoder_outputs[0]
# Set device for model parallelism
if self.model_parallel:
torch.cuda.set_device(self.encoder.first_device)
self.lm_head = self.lm_head.to(self.encoder.first_device)
sequence_output = sequence_output.to(self.lm_head.weight.device)
if self.config.tie_word_embeddings:
# Rescale output before projecting on vocab
# See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/transformer.py#L586
sequence_output = sequence_output * (self.model_dim ** -0.5)
lm_logits = self.lm_head(sequence_output)
loss = None
if labels is not None:
loss_fct = CrossEntropyLoss(ignore_index=-100)
loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))
# TODO(thom): Add z_loss https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L666
if not return_dict:
output = (lm_logits,) + decoder_outputs[1:] + encoder_outputs
return ((loss,) + output) if loss is not None else output
return Seq2SeqLMOutput(
loss=loss,
logits=lm_logits,
past_key_values=decoder_outputs.past_key_values,
decoder_hidden_states=decoder_outputs.hidden_states,
decoder_attentions=decoder_outputs.attentions,
cross_attentions=decoder_outputs.cross_attentions,
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
encoder_hidden_states=encoder_outputs.hidden_states,
encoder_attentions=encoder_outputs.attentions,
)
def prepare_inputs_for_generation(
self, input_ids, past=None, attention_mask=None, use_cache=None, encoder_outputs=None, **kwargs
):
# cut decoder_input_ids if past is used
if past is not None:
input_ids = input_ids[:, -1:]
return {
"decoder_input_ids": input_ids,
"past_key_values": past,
"encoder_outputs": encoder_outputs,
"attention_mask": attention_mask,
"use_cache": use_cache,
}
def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
return self._shift_right(labels)
def _reorder_cache(self, past, beam_idx):
# if decoder past is not included in output
# speedy decoding is disabled and no need to reorder
if past is None:
logger.warning("You might want to consider setting `use_cache=True` to speed up decoding")
return past
reordered_decoder_past = ()
for layer_past_states in past:
# get the correct batch idx from layer past batch dim
# batch dim of `past` is at 2nd position
reordered_layer_past_states = ()
for layer_past_state in layer_past_states:
# need to set correct `past` for each of the four key / value states
reordered_layer_past_states = reordered_layer_past_states + (
layer_past_state.index_select(0, beam_idx),
)
assert reordered_layer_past_states[0].shape == layer_past_states[0].shape
assert len(reordered_layer_past_states) == len(layer_past_states)
reordered_decoder_past = reordered_decoder_past + (reordered_layer_past_states,)
| |
CB LEU B 15 74.441 2.005 6.508 1.00 0.00 C
ATOM 6 CG LEU B 15 73.315 1.794 7.526 1.00 0.00 C
ATOM 7 CD2 LEU B 15 73.362 0.379 8.081 1.00 0.00 C
ATOM 8 CD1 LEU B 15 73.387 2.816 8.654 1.00 0.00 C
ATOM 1 N ALA B 16 76.446 4.570 5.146 1.00 0.00 N
ATOM 2 CA ALA B 16 77.695 4.815 4.434 1.00 0.00 C
ATOM 3 C ALA B 16 78.875 4.865 5.399 1.00 0.00 C
ATOM 4 O ALA B 16 78.995 5.790 6.202 1.00 0.00 O
ATOM 5 CB ALA B 16 77.604 6.114 3.646 1.00 0.00 C
ATOM 1 N PHE B 17 79.745 3.864 5.313 1.00 0.00 N
ATOM 2 CA PHE B 17 80.918 3.791 6.177 1.00 0.00 C
ATOM 3 C PHE B 17 82.204 3.886 5.364 1.00 0.00 C
ATOM 4 O PHE B 17 82.540 2.976 4.606 1.00 0.00 O
ATOM 5 CB PHE B 17 80.905 2.487 6.980 1.00 0.00 C
ATOM 6 CG PHE B 17 79.789 2.401 7.981 1.00 0.00 C
ATOM 7 CD2 PHE B 17 79.892 3.031 9.210 1.00 0.00 C
ATOM 8 CD1 PHE B 17 78.635 1.689 7.693 1.00 0.00 C
ATOM 9 CE2 PHE B 17 78.866 2.952 10.133 1.00 0.00 C
ATOM 10 CE1 PHE B 17 77.606 1.607 8.612 1.00 0.00 C
ATOM 11 CZ PHE B 17 77.722 2.240 9.833 1.00 0.00 C
ATOM 1 N ALA B 18 82.921 4.994 5.528 1.00 0.00 N
ATOM 2 CA ALA B 18 84.172 5.209 4.810 1.00 0.00 C
ATOM 3 C ALA B 18 85.350 5.293 5.775 1.00 0.00 C
ATOM 4 O ALA B 18 85.470 6.247 6.543 1.00 0.00 O
ATOM 5 CB ALA B 18 84.086 6.477 3.973 1.00 0.00 C
ATOM 1 N TYR B 19 86.218 4.286 5.729 1.00 0.00 N
ATOM 2 CA TYR B 19 87.388 4.244 6.598 1.00 0.00 C
ATOM 3 C TYR B 19 88.677 4.305 5.785 1.00 0.00 C
ATOM 4 O TYR B 19 89.013 3.367 5.063 1.00 0.00 O
ATOM 5 CB TYR B 19 87.371 2.972 7.450 1.00 0.00 C
ATOM 6 CG TYR B 19 86.263 2.938 8.479 1.00 0.00 C
ATOM 7 CD2 TYR B 19 85.562 4.091 8.812 1.00 0.00 C
ATOM 8 CD1 TYR B 19 85.916 1.754 9.116 1.00 0.00 C
ATOM 9 CE2 TYR B 19 84.548 4.066 9.751 1.00 0.00 C
ATOM 10 CE1 TYR B 19 84.902 1.719 10.057 1.00 0.00 C
ATOM 11 CZ TYR B 19 84.223 2.877 10.369 1.00 0.00 C
ATOM 12 OH TYR B 19 83.213 2.846 11.305 1.00 0.00 O
ATOM 1 N ALA B 20 89.396 5.417 5.909 1.00 0.00 N
ATOM 2 CA ALA B 20 90.649 5.602 5.187 1.00 0.00 C
ATOM 3 C ALA B 20 91.825 5.719 6.151 1.00 0.00 C
ATOM 4 O ALA B 20 91.946 6.701 6.883 1.00 0.00 O
ATOM 5 CB ALA B 20 90.568 6.839 4.303 1.00 0.00 C
ATOM 1 N VAL B 21 92.691 4.710 6.145 1.00 0.00 N
ATOM 2 CA VAL B 21 93.859 4.697 7.018 1.00 0.00 C
ATOM 3 C VAL B 21 95.150 4.725 6.207 1.00 0.00 C
ATOM 4 O VAL B 21 95.485 3.759 5.521 1.00 0.00 O
ATOM 5 CB VAL B 21 93.867 3.449 7.925 1.00 0.00 C
ATOM 6 CG2 VAL B 21 95.141 3.402 8.760 1.00 0.00 C
ATOM 7 CG1 VAL B 21 92.635 3.429 8.820 1.00 0.00 C
ATOM 1 N ALA B 22 95.871 5.839 6.291 1.00 0.00 N
ATOM 2 CA ALA B 22 97.126 5.995 5.565 1.00 0.00 C
ATOM 3 C ALA B 22 98.300 6.145 6.527 1.00 0.00 C
ATOM 4 O ALA B 22 98.421 7.153 7.222 1.00 0.00 O
ATOM 5 CB ALA B 22 97.050 7.197 4.636 1.00 0.00 C
TER 312 ALA B 22
END
"""
ncs_pars = iotbx.ncs.input.get_default_params()
ncs_pars.ncs_search.chain_max_rmsd=0.1
def test_1():
h = iotbx.pdb.input(source_info=None, lines=test_pdb_1).construct_hierarchy()
asc = h.atom_selection_cache()
ncs_inp = iotbx.ncs.input(
hierarchy=h,
params=ncs_pars.ncs_search)
ncs_groups = ncs_inp.get_ncs_restraints_group_list()
assert len(ncs_groups) == 1
# group 1
assert ncs_groups[0].master_iselection.all_eq(
asc.selection(string = "chain A").iselection())
g1_c = ncs_groups[0].copies
assert len(g1_c)==1
assert g1_c[0].iselection.all_eq(
asc.selection(string = "chain B").iselection())
def test_2():
""" Testing TYR both CD and CE flips"""
h = iotbx.pdb.input(source_info=None, lines=test_pdb_2).construct_hierarchy()
asc = h.atom_selection_cache()
ncs_inp = iotbx.ncs.input(
hierarchy=h,
params=ncs_pars.ncs_search)
ncs_groups = ncs_inp.get_ncs_restraints_group_list()
assert len(ncs_groups) == 1
# group 1
assert ncs_groups[0].master_iselection.all_eq(
asc.selection(string = "chain A").iselection())
g1_c = ncs_groups[0].copies
assert len(g1_c)==1
assert g1_c[0].iselection.all_eq(
asc.selection(string = "chain B").iselection())
def test_3():
""" Testing TYR only CD and flip. Not sure if such flip is valid.
This test is not working when we use torsion angles because in this
procedure we don't flip only one atom out of two like in this case"""
h = iotbx.pdb.input(source_info=None, lines=test_pdb_3).construct_hierarchy()
asc = h.atom_selection_cache()
ncs_inp = iotbx.ncs.input(
hierarchy=h,
params=ncs_pars.ncs_search)
ncs_groups = ncs_inp.get_ncs_restraints_group_list()
assert len(ncs_groups) == 1
# group 1
assert ncs_groups[0].master_iselection.all_eq(
asc.selection(string = "chain A").iselection())
g1_c = ncs_groups[0].copies
assert len(g1_c)==1
assert g1_c[0].iselection.all_eq(
asc.selection(string = "chain B").iselection())
def test_4():
""" HIS is interesting because of different atoms can be flipped """
h = iotbx.pdb.input(source_info=None, lines=test_pdb_4).construct_hierarchy()
asc = h.atom_selection_cache()
ncs_inp = iotbx.ncs.input(
hierarchy=h,
params=ncs_pars.ncs_search)
ncs_groups = ncs_inp.get_ncs_restraints_group_list()
assert len(ncs_groups) == 1
# group 1
assert ncs_groups[0].master_iselection.all_eq(
asc.selection(string = "chain A").iselection())
g1_c = ncs_groups[0].copies
assert len(g1_c)==1
assert g1_c[0].iselection.all_eq(
asc.selection(string = "chain B").iselection())
def test_5():
""" Testing all possible residues at once. All flipped wherever possible
in chain B """
h = iotbx.pdb.input(source_info=None, lines=test_pdb_5).construct_hierarchy()
asc = h.atom_selection_cache()
ncs_inp = iotbx.ncs.input(
hierarchy=h,
params=ncs_pars.ncs_search)
ncs_groups = ncs_inp.get_ncs_restraints_group_list()
assert len(ncs_groups) == 1
# group 1
assert ncs_groups[0].master_iselection.all_eq(
asc.selection(string = "chain A").iselection())
g1_c = ncs_groups[0].copies
assert len(g1_c)==1
assert g1_c[0].iselection.all_eq(
asc.selection(string = "chain B").iselection())
def test_6():
"Actually making flips for test_pdb_1"
h = iotbx.pdb.input(source_info=None, lines=test_pdb_1_1).construct_hierarchy()
asc = h.atom_selection_cache()
ncs_inp = iotbx.ncs.input(
hierarchy=h,
params=ncs_pars.ncs_search)
ncs_groups = ncs_inp.get_ncs_restraints_group_list()
nu.flip_atoms_in_ncs_groups(h, ncs_groups)
h.write_pdb_file("test_6_result.pdb")
def test_7():
"Actually making flips for test_pdb_2"
answer_pdb_str = """
ATOM 1 N TYR A 1 30.440 8.711 1.306 1.00 64.98 N
ATOM 2 CA TYR A 1 29.117 9.171 1.763 1.00 67.34 C
ATOM 3 C TYR A 1 28.007 8.102 1.965 1.00 65.79 C
ATOM 4 O TYR A 1 26.830 8.428 1.845 1.00 58.29 O
ATOM 5 CB TYR A 1 29.262 10.057 3.008 1.00 67.25 C
ATOM 6 CG TYR A 1 29.855 11.415 2.711 1.00 70.44 C
ATOM 7 CD1 TYR A 1 31.185 11.716 3.026 1.00 71.73 C
ATOM 8 CD2 TYR A 1 29.079 12.412 2.112 1.00 68.62 C
ATOM 9 CE1 TYR A 1 31.716 12.971 2.753 1.00 72.09 C
ATOM 10 CE2 TYR A 1 29.603 13.668 1.843 1.00 68.12 C
ATOM 11 CZ TYR A 1 30.919 13.946 2.160 1.00 69.15 C
ATOM 12 OH TYR A 1 31.432 15.200 1.886 1.00 61.93 O
TER
ATOM 13 N TYR B 1 30.440 8.711 6.306 1.00 64.98 N
ATOM 14 CA TYR B 1 29.117 9.171 6.763 1.00 67.34 C
ATOM 15 C TYR B 1 28.007 8.102 6.965 1.00 65.79 C
ATOM 16 O TYR B 1 26.830 8.428 6.845 1.00 58.29 O
ATOM 17 CB TYR B 1 29.262 10.057 8.008 1.00 67.25 C
ATOM 18 CG TYR B 1 29.855 11.415 7.711 1.00 70.44 C
ATOM 19 CD1 TYR B 1 31.187 11.692 8.031 1.00 68.62 C
ATOM 20 CD2 TYR B 1 29.098 12.427 7.109 1.00 71.73 C
ATOM 21 CE1 TYR B 1 31.752 12.929 7.755 1.00 68.12 C
ATOM 22 CE2 TYR B 1 29.658 13.669 6.836 1.00 72.09 C
ATOM 23 CZ TYR B 1 30.988 13.916 7.161 1.00 69.15 C
ATOM 24 OH TYR B 1 31.560 15.146 6.892 1.00 61.93 O
TER
"""
h = iotbx.pdb.input(source_info=None, lines=test_pdb_2).construct_hierarchy()
anwer_h = iotbx.pdb.input(source_info=None, lines=answer_pdb_str).construct_hierarchy()
h.write_pdb_file("test_7_before.pdb")
ncs_inp = iotbx.ncs.input(
hierarchy=h,
params=ncs_pars.ncs_search)
ncs_groups = ncs_inp.get_ncs_restraints_group_list()
nu.flip_atoms_in_ncs_groups(h, ncs_groups)
h.write_pdb_file("test_7_result.pdb")
rmsd_smart = calculate_rmsd_smart(anwer_h, h)
print rmsd_smart
assert rmsd_smart < 0.01
def test_8():
""" Actually making flips for test_pdb_5"""
answer_pdb_str = """
ATOM 1 N ARG A 1 26.061 12.824 1.988 1.00 0.00 N
ATOM 2 CA ARG A 1 27.253 12.525 2.773 1.00 0.00 C
ATOM 3 C ARG A 1 28.520 12.882 2.003 1.00 0.00 C
ATOM 4 O ARG A 1 28.853 12.243 1.005 1.00 0.00 O
ATOM 5 CB ARG A 1 27.280 11.041 3.156 1.00 10.00 C
ATOM 6 CG ARG A 1 26.107 10.591 4.022 1.00 10.00 C
ATOM 7 | |
pickle.loads(pickle.dumps(ts_fixture, protocol=protocol))
assert ts.tables == ts_fixture.tables
# Do some thing to check the ts is init'd properly
ts.draw_text()
class TestFileUuid(HighLevelTestCase):
"""
Tests that the file UUID attribute is handled correctly.
"""
def validate(self, ts):
with tempfile.TemporaryDirectory() as tempdir:
temp_file = pathlib.Path(tempdir) / "tmp.trees"
assert ts.file_uuid is None
ts.dump(temp_file)
other_ts = tskit.load(temp_file)
assert other_ts.file_uuid is not None
assert len(other_ts.file_uuid), 36
uuid = other_ts.file_uuid
other_ts = tskit.load(temp_file)
assert other_ts.file_uuid == uuid
assert ts.tables == other_ts.tables
# Check that the UUID is well-formed.
parsed = _uuid.UUID("{" + uuid + "}")
assert str(parsed) == uuid
# Save the same tree sequence to the file. We should get a different UUID.
ts.dump(temp_file)
other_ts = tskit.load(temp_file)
assert other_ts.file_uuid is not None
assert other_ts.file_uuid != uuid
# Even saving a ts that has a UUID to another file changes the UUID
old_uuid = other_ts.file_uuid
other_ts.dump(temp_file)
assert other_ts.file_uuid == old_uuid
other_ts = tskit.load(temp_file)
assert other_ts.file_uuid is not None
assert other_ts.file_uuid != old_uuid
# Tables dumped from this ts are a deep copy, so they don't have
# the file_uuid.
tables = other_ts.dump_tables()
assert tables.file_uuid is None
# For now, ts.tables also returns a deep copy. This will hopefully
# change in the future though.
assert ts.tables.file_uuid is None
def test_simple_simulation(self):
ts = msprime.simulate(2, random_seed=1)
self.validate(ts)
def test_empty_tables(self):
tables = tskit.TableCollection(1)
self.validate(tables.tree_sequence())
class TestTreeSequenceTextIO(HighLevelTestCase):
"""
Tests for the tree sequence text IO.
"""
def verify_nodes_format(self, ts, nodes_file, precision):
"""
Verifies that the nodes we output have the correct form.
"""
def convert(v):
return "{:.{}f}".format(v, precision)
output_nodes = nodes_file.read().splitlines()
assert len(output_nodes) - 1 == ts.num_nodes
assert list(output_nodes[0].split()) == [
"id",
"is_sample",
"time",
"population",
"individual",
"metadata",
]
for node, line in zip(ts.nodes(), output_nodes[1:]):
splits = line.split("\t")
assert str(node.id) == splits[0]
assert str(node.is_sample()) == splits[1]
assert convert(node.time) == splits[2]
assert str(node.population) == splits[3]
assert str(node.individual) == splits[4]
assert tests.base64_encode(node.metadata) == splits[5]
def verify_edges_format(self, ts, edges_file, precision):
"""
Verifies that the edges we output have the correct form.
"""
def convert(v):
return "{:.{}f}".format(v, precision)
output_edges = edges_file.read().splitlines()
assert len(output_edges) - 1 == ts.num_edges
assert list(output_edges[0].split()) == ["left", "right", "parent", "child"]
for edge, line in zip(ts.edges(), output_edges[1:]):
splits = line.split("\t")
assert convert(edge.left) == splits[0]
assert convert(edge.right) == splits[1]
assert str(edge.parent) == splits[2]
assert str(edge.child) == splits[3]
def verify_sites_format(self, ts, sites_file, precision):
"""
Verifies that the sites we output have the correct form.
"""
def convert(v):
return "{:.{}f}".format(v, precision)
output_sites = sites_file.read().splitlines()
assert len(output_sites) - 1 == ts.num_sites
assert list(output_sites[0].split()) == [
"position",
"ancestral_state",
"metadata",
]
for site, line in zip(ts.sites(), output_sites[1:]):
splits = line.split("\t")
assert convert(site.position) == splits[0]
assert site.ancestral_state == splits[1]
assert tests.base64_encode(site.metadata) == splits[2]
def verify_mutations_format(self, ts, mutations_file, precision):
"""
Verifies that the mutations we output have the correct form.
"""
def convert(v):
return "{:.{}f}".format(v, precision)
output_mutations = mutations_file.read().splitlines()
assert len(output_mutations) - 1 == ts.num_mutations
assert list(output_mutations[0].split()) == [
"site",
"node",
"time",
"derived_state",
"parent",
"metadata",
]
mutations = [mut for site in ts.sites() for mut in site.mutations]
for mutation, line in zip(mutations, output_mutations[1:]):
splits = line.split("\t")
assert str(mutation.site) == splits[0]
assert str(mutation.node) == splits[1]
assert (
"unknown" if util.is_unknown_time(mutation.time) else str(mutation.time)
) == splits[2]
assert str(mutation.derived_state) == splits[3]
assert str(mutation.parent) == splits[4]
assert tests.base64_encode(mutation.metadata) == splits[5]
def verify_individuals_format(self, ts, individuals_file, precision):
"""
Verifies that the individuals we output have the correct form.
"""
def convert(v):
return "{:.{}f}".format(v, precision)
output_individuals = individuals_file.read().splitlines()
assert len(output_individuals) - 1 == ts.num_individuals
assert list(output_individuals[0].split()) == [
"id",
"flags",
"location",
"parents",
"metadata",
]
for individual, line in zip(ts.individuals(), output_individuals[1:]):
splits = line.split("\t")
assert str(individual.id) == splits[0]
assert str(individual.flags) == splits[1]
assert ",".join(map(str, individual.location)) == splits[2]
assert ",".join(map(str, individual.parents)) == splits[3]
assert tests.base64_encode(individual.metadata) == splits[4]
def test_output_format(self):
for ts in get_example_tree_sequences():
for precision in [2, 7]:
nodes_file = io.StringIO()
edges_file = io.StringIO()
sites_file = io.StringIO()
mutations_file = io.StringIO()
individuals_file = io.StringIO()
ts.dump_text(
nodes=nodes_file,
edges=edges_file,
sites=sites_file,
mutations=mutations_file,
individuals=individuals_file,
precision=precision,
)
nodes_file.seek(0)
edges_file.seek(0)
sites_file.seek(0)
mutations_file.seek(0)
individuals_file.seek(0)
self.verify_nodes_format(ts, nodes_file, precision)
self.verify_edges_format(ts, edges_file, precision)
self.verify_sites_format(ts, sites_file, precision)
self.verify_mutations_format(ts, mutations_file, precision)
self.verify_individuals_format(ts, individuals_file, precision)
def verify_approximate_equality(self, ts1, ts2):
"""
Verifies that the specified tree sequences are approximately
equal, taking into account the error incurred in exporting to text.
"""
assert ts1.sample_size == ts2.sample_size
assert ts1.sequence_length == ts2.sequence_length
assert ts1.num_nodes == ts2.num_nodes
assert ts1.num_edges == ts2.num_edges
assert ts1.num_sites == ts2.num_sites
assert ts1.num_mutations == ts2.num_mutations
assert ts1.num_populations == ts2.num_populations
checked = 0
for n1, n2 in zip(ts1.nodes(), ts2.nodes()):
assert n1.population == n2.population
assert n1.metadata == n2.metadata
assert n1.time == pytest.approx(n2.time)
checked += 1
assert checked == ts1.num_nodes
checked = 0
for r1, r2 in zip(ts1.edges(), ts2.edges()):
checked += 1
assert r1.left == pytest.approx(r2.left)
assert r1.right == pytest.approx(r2.right)
assert r1.parent == r2.parent
assert r1.child == r2.child
assert ts1.num_edges == checked
checked = 0
for s1, s2 in zip(ts1.sites(), ts2.sites()):
checked += 1
assert s1.position == pytest.approx(s2.position)
assert s1.ancestral_state == s2.ancestral_state
assert s1.metadata == s2.metadata
assert s1.mutations == s2.mutations
assert ts1.num_sites == checked
checked = 0
for s1, s2 in zip(ts1.mutations(), ts2.mutations()):
checked += 1
assert s1.site == s2.site
assert s1.node == s2.node
if not (math.isnan(s1.time) and math.isnan(s2.time)):
assert s1.time == pytest.approx(s2.time)
assert s1.derived_state == s2.derived_state
assert s1.parent == s2.parent
assert s1.metadata == s2.metadata
assert ts1.num_mutations == checked
# Check the trees
check = 0
for t1, t2 in zip(ts1.trees(), ts2.trees()):
assert list(t1.nodes()) == list(t2.nodes())
check += 1
assert check == ts1.get_num_trees()
def test_text_record_round_trip(self):
for ts1 in get_example_tree_sequences():
nodes_file = io.StringIO()
edges_file = io.StringIO()
sites_file = io.StringIO()
mutations_file = io.StringIO()
individuals_file = io.StringIO()
populations_file = io.StringIO()
ts1.dump_text(
nodes=nodes_file,
edges=edges_file,
sites=sites_file,
mutations=mutations_file,
individuals=individuals_file,
populations=populations_file,
precision=16,
)
nodes_file.seek(0)
edges_file.seek(0)
sites_file.seek(0)
mutations_file.seek(0)
individuals_file.seek(0)
populations_file.seek(0)
ts2 = tskit.load_text(
nodes=nodes_file,
edges=edges_file,
sites=sites_file,
mutations=mutations_file,
individuals=individuals_file,
populations=populations_file,
sequence_length=ts1.sequence_length,
strict=True,
)
self.verify_approximate_equality(ts1, ts2)
def test_empty_files(self):
nodes_file = io.StringIO("is_sample\ttime\n")
edges_file = io.StringIO("left\tright\tparent\tchild\n")
sites_file = io.StringIO("position\tancestral_state\n")
mutations_file = io.StringIO("site\tnode\tderived_state\n")
with pytest.raises(_tskit.LibraryError):
tskit.load_text(
nodes=nodes_file,
edges=edges_file,
sites=sites_file,
mutations=mutations_file,
)
def test_empty_files_sequence_length(self):
nodes_file = io.StringIO("is_sample\ttime\n")
edges_file = io.StringIO("left\tright\tparent\tchild\n")
sites_file = io.StringIO("position\tancestral_state\n")
mutations_file = io.StringIO("site\tnode\tderived_state\n")
ts = tskit.load_text(
nodes=nodes_file,
edges=edges_file,
sites=sites_file,
mutations=mutations_file,
sequence_length=100,
)
assert ts.sequence_length == 100
assert ts.num_nodes == 0
assert ts.num_edges == 0
assert ts.num_sites == 0
assert ts.num_edges == 0
def test_load_text_no_populations(self):
nodes_file = io.StringIO("is_sample\ttime\tpopulation\n1\t0\t2\n")
edges_file = io.StringIO("left\tright\tparent\tchild\n")
ts = tskit.load_text(nodes_file, edges_file, sequence_length=100)
assert ts.num_nodes == 1
assert ts.num_populations == 3
def test_load_text_populations(self):
nodes_file = io.StringIO("is_sample\ttime\tpopulation\n")
edges_file = io.StringIO("left\tright\tparent\tchild\n")
populations_file = io.StringIO("metadata\nmetadata_1\nmetadata_2\n")
ts = tskit.load_text(
nodes_file,
edges_file,
populations=populations_file,
sequence_length=100,
base64_metadata=False,
)
assert ts.num_populations == 2
assert ts.tables.populations[0].metadata == b"metadata_1"
assert ts.tables.populations[1].metadata == b"metadata_2"
class TestTree(HighLevelTestCase):
"""
Some simple tests on the tree API.
"""
def get_tree(self, sample_lists=False):
ts = msprime.simulate(10, random_seed=1, mutation_rate=1, record_full_arg=True)
return next(ts.trees(sample_lists=sample_lists))
def verify_mutations(self, tree):
assert tree.num_mutations > 0
other_mutations = []
for site in tree.sites():
for mutation in site.mutations:
other_mutations.append(mutation)
mutations = list(tree.mutations())
assert tree.num_mutations == len(other_mutations)
assert tree.num_mutations == len(mutations)
for mut, other_mut in zip(mutations, other_mutations):
assert mut == other_mut
def test_simple_mutations(self):
tree = self.get_tree()
self.verify_mutations(tree)
def test_complex_mutations(self):
ts = tsutil.insert_branch_mutations(msprime.simulate(10, random_seed=1))
self.verify_mutations(ts.first())
def test_str(self, ts_fixture):
t = ts_fixture.first()
assert isinstance(str(t), str)
assert re.match(
textwrap.dedent(
r"""
╔═════════════════════════════╗
║Tree ║
╠═══════════════════╤═════════╣
║Index │ 0║
╟───────────────────┼─────────╢
║Interval │ 0-1 \(1\)║
╟───────────────────┼─────────╢
║Roots │[0-9 ]*║
╟───────────────────┼─────────╢
║Nodes │[0-9 ]*║
╟───────────────────┼─────────╢
║Sites │[0-9 ]*║
╟───────────────────┼─────────╢
║Mutations │[0-9 ]*║
╟───────────────────┼─────────╢
║Total Branch Length│[0-9\. ]*║
╚═══════════════════╧═════════╝
"""[
1:
]
),
str(t),
)
def test_html_repr(self, ts_fixture):
html = ts_fixture.first()._repr_html_()
# Parse to check valid
ElementTree.fromstring(html)
assert len(html) > 1900
assert "<tr><td>Total Branch Length</td><td>" in html
def test_samples(self):
for sample_lists in [True, False]:
t = self.get_tree(sample_lists)
n = t.get_sample_size()
all_samples = list(t.samples(t.get_root()))
assert sorted(all_samples) == list(range(n))
for j in range(n):
assert list(t.samples(j)) == [j]
def test_func(t, u):
"""
Simple test definition of the traversal.
"""
stack = [u]
while len(stack) > 0:
v = stack.pop()
if t.is_sample(v):
yield v
if t.is_internal(v):
for c in reversed(t.get_children(v)):
stack.append(c)
for u in t.nodes():
l1 = list(t.samples(u))
l2 = list(test_func(t, u))
assert l1 == l2
assert t.get_num_samples(u) == len(l1)
def test_num_children(self):
tree = self.get_tree()
for u in tree.nodes():
assert tree.num_children(u) == len(tree.children(u))
def test_virtual_root_semantics(self):
for ts in get_example_tree_sequences():
for tree in ts.trees():
assert math.isinf(tree.time(tree.virtual_root))
assert tree.depth(tree.virtual_root) == -1
| |
# -*- coding: utf-8 -*-
"""
All unit tests for the newspaper library should be contained in this file.
"""
import sys
import os
import unittest
import time
import traceback
import re
from collections import defaultdict, OrderedDict
import concurrent.futures
TEST_DIR = os.path.abspath(os.path.dirname(__file__))
PARENT_DIR = os.path.join(TEST_DIR, '..')
# newspaper's unit tests are in their own separate module, so
# insert the parent directory manually to gain scope of the
# core module
sys.path.insert(0, PARENT_DIR)
TEXT_FN = os.path.join(TEST_DIR, 'data', 'text')
HTML_FN = os.path.join(TEST_DIR, 'data', 'html')
URLS_FILE = os.path.join(TEST_DIR, 'data', 'fulltext_url_list.txt')
import newspaper
from newspaper import Article, fulltext, Source, ArticleException, news_pool
from newspaper.article import ArticleDownloadState
from newspaper.configuration import Configuration
from newspaper.urls import get_domain
def print_test(method):
"""
Utility method for print verbalizing test suite, prints out
time taken for test and functions name, and status
"""
def run(*args, **kw):
ts = time.time()
print('\ttesting function %r' % method.__name__)
method(*args, **kw)
te = time.time()
print('\t[OK] in %r %2.2f sec' % (method.__name__, te - ts))
return run
def mock_resource_with(filename, resource_type):
"""
Mocks an HTTP request by pulling text from a pre-downloaded file
"""
VALID_RESOURCES = ['html', 'txt']
if resource_type not in VALID_RESOURCES:
raise Exception('Mocked resource must be one of: %s' %
', '.join(VALID_RESOURCES))
subfolder = 'text' if resource_type == 'txt' else 'html'
resource_path = os.path.join(TEST_DIR, "data/%s/%s.%s" %
(subfolder, filename, resource_type))
with open(resource_path, 'r', encoding='utf-8') as f:
return f.read()
def get_base_domain(url):
"""
For example, the base url of uk.reuters.com => reuters.com
"""
domain = get_domain(url)
tld = '.'.join(domain.split('.')[-2:])
if tld in ['co.uk', 'com.au', 'au.com']: # edge cases
end_chunks = domain.split('.')[-3:]
else:
end_chunks = domain.split('.')[-2:]
base_domain = '.'.join(end_chunks)
return base_domain
def check_url(*args, **kwargs):
return ExhaustiveFullTextCase.check_url(*args, **kwargs)
@unittest.skipIf('fulltext' not in sys.argv, 'Skipping fulltext tests')
class ExhaustiveFullTextCase(unittest.TestCase):
@staticmethod
def check_url(args):
"""
:param (basestr, basestr) url, res_filename:
:return: (pubdate_failed, fulltext_failed)
"""
url, res_filename = args
pubdate_failed, fulltext_failed = False, False
html = mock_resource_with(res_filename, 'html')
try:
a = Article(url)
a.download(html)
a.parse()
if a.publish_date is None:
pubdate_failed = True
except Exception:
print('<< URL: %s parse ERROR >>' % url)
traceback.print_exc()
pubdate_failed, fulltext_failed = True, True
else:
correct_text = mock_resource_with(res_filename, 'txt')
if not (a.text == correct_text):
# print('Diff: ', simplediff.diff(correct_text, a.text))
# `correct_text` holds the reason of failure if failure
print('%s -- %s -- %s' %
('Fulltext failed',
res_filename, correct_text.strip()))
fulltext_failed = True
# TODO: assert statements are commented out for full-text
# extraction tests because we are constantly tweaking the
# algorithm and improving
# assert a.text == correct_text
return pubdate_failed, fulltext_failed
@print_test
def test_exhaustive(self):
with open(URLS_FILE, 'r') as f:
urls = [d.strip() for d in f.readlines() if d.strip()]
domain_counters = {}
def get_filename(url):
domain = get_base_domain(url)
domain_counters[domain] = domain_counters.get(domain, 0) + 1
return '{}{}'.format(domain, domain_counters[domain])
filenames = map(get_filename, urls)
with concurrent.futures.ProcessPoolExecutor() as executor:
test_results = list(executor.map(check_url, zip(urls, filenames)))
total_pubdates_failed, total_fulltext_failed = \
list(map(sum, zip(*test_results)))
print('%s fulltext extractions failed out of %s' %
(total_fulltext_failed, len(urls)))
print('%s pubdate extractions failed out of %s' %
(total_pubdates_failed, len(urls)))
self.assertGreaterEqual(47, total_pubdates_failed)
self.assertGreaterEqual(20, total_fulltext_failed)
class ArticleTestCase(unittest.TestCase):
def setup_stage(self, stage_name):
stages = OrderedDict([
('initial', lambda: None),
('download', lambda: self.article.download(
mock_resource_with('cnn_article', 'html'))),
('parse', lambda: self.article.parse()),
('meta', lambda: None), # Alias for nlp
('nlp', lambda: self.article.nlp())
])
assert stage_name in stages
for name, action in stages.items():
if name == stage_name:
break
action()
def setUp(self):
"""Called before the first test case of this unit begins
"""
self.article = Article(
url='http://www.cnn.com/2013/11/27/travel/weather-'
'thanksgiving/index.html?iref=allsearch')
@print_test
def test_url(self):
self.assertEqual(
'http://www.cnn.com/2013/11/27/travel/weather-'
'thanksgiving/index.html?iref=allsearch',
self.article.url)
@print_test
def test_download_html(self):
self.setup_stage('download')
html = mock_resource_with('cnn_article', 'html')
self.article.download(html)
self.assertEqual(self.article.download_state, ArticleDownloadState.SUCCESS)
self.assertEqual(self.article.download_exception_msg, None)
self.assertEqual(75406, len(self.article.html))
@print_test
def test_meta_refresh_redirect(self):
# TODO: We actually hit example.com in this unit test ... which is bad
# Figure out how to mock an actual redirect
config = Configuration()
config.follow_meta_refresh = True
article = Article(
'', config=config)
html = mock_resource_with('google_meta_refresh', 'html')
article.download(input_html=html)
article.parse()
self.assertEqual(article.title, 'Example Domain')
@print_test
def test_meta_refresh_no_url_redirect(self):
config = Configuration()
config.follow_meta_refresh = True
article = Article(
'', config=config)
html = mock_resource_with('ap_meta_refresh', 'html')
article.download(input_html=html)
article.parse()
self.assertEqual(article.title, 'News from The Associated Press')
@print_test
def test_pre_download_parse(self):
"""Calling `parse()` before `download()` should yield an error
"""
article = Article(self.article.url)
self.assertRaises(ArticleException, article.parse)
@print_test
def test_parse_html(self):
self.setup_stage('parse')
AUTHORS = ['<NAME>', '<NAME>', '<NAME>',
'<NAME>']
TITLE = 'After storm, forecasters see smooth sailing for Thanksgiving'
LEN_IMGS = 46
META_LANG = 'en'
META_SITE_NAME = 'CNN'
self.article.parse()
self.article.nlp()
text = mock_resource_with('cnn', 'txt')
self.assertEqual(text, self.article.text)
self.assertEqual(text, fulltext(self.article.html))
# NOTE: top_img extraction requires an internet connection
# unlike the rest of this test file
TOP_IMG = ('http://i2.cdn.turner.com/cnn/dam/assets/131129200805-'
'01-weather-1128-story-top.jpg')
self.assertEqual(TOP_IMG, self.article.top_img)
self.assertCountEqual(AUTHORS, self.article.authors)
self.assertEqual(TITLE, self.article.title)
self.assertEqual(LEN_IMGS, len(self.article.imgs))
self.assertEqual(META_LANG, self.article.meta_lang)
self.assertEqual(META_SITE_NAME, self.article.meta_site_name)
self.assertEqual('2013-11-27 00:00:00', str(self.article.publish_date))
@print_test
def test_meta_type_extraction(self):
self.setup_stage('meta')
meta_type = self.article.extractor.get_meta_type(
self.article.clean_doc)
self.assertEqual('article', meta_type)
@print_test
def test_meta_extraction(self):
self.setup_stage('meta')
meta = self.article.extractor.get_meta_data(self.article.clean_doc)
META_DATA = defaultdict(dict, {
'medium': 'news',
'googlebot': 'noarchive',
'pubdate': '2013-11-27T08:36:32Z',
'title': 'After storm, forecasters see smooth sailing for Thanksgiving - CNN.com',
'og': {'site_name': 'CNN',
'description': 'A strong storm struck much of the eastern United States on Wednesday, complicating holiday plans for many of the 43 million Americans expected to travel.',
'title': 'After storm, forecasters see smooth sailing for Thanksgiving',
'url': 'http://www.cnn.com/2013/11/27/travel/weather-thanksgiving/index.html',
'image': 'http://i2.cdn.turner.com/cnn/dam/assets/131129200805-01-weather-1128-story-top.jpg',
'type': 'article'},
'section': 'travel',
'author': '<NAME>, <NAME>, <NAME>, and <NAME>, CNN',
'robots': 'index,follow',
'vr': {
'canonical': 'http://edition.cnn.com/2013/11/27/travel/weather-thanksgiving/index.html'},
'source': 'CNN',
'fb': {'page_id': 18793419640, 'app_id': 80401312489},
'keywords': 'winter storm,holiday travel,Thanksgiving storm,Thanksgiving winter storm',
'article': {
'publisher': 'https://www.facebook.com/cnninternational'},
'lastmod': '2013-11-28T02:03:23Z',
'twitter': {'site': {'identifier': '@CNNI', 'id': 2097571},
'card': 'summary',
'creator': {'identifier': '@cnntravel',
'id': 174377718}},
'viewport': 'width=1024',
'news_keywords': 'winter storm,holiday travel,Thanksgiving storm,Thanksgiving winter storm'
})
self.assertDictEqual(META_DATA, meta)
# if the value for a meta key is another dict, that dict ought to be
# filled with keys and values
dict_values = [v for v in list(meta.values()) if isinstance(v, dict)]
self.assertTrue(all([len(d) > 0 for d in dict_values]))
# there are exactly 5 top-level "og:type" type keys
is_dict = lambda v: isinstance(v, dict)
self.assertEqual(5, len([i for i in meta.values() if is_dict(i)]))
# there are exactly 12 top-level "pubdate" type keys
is_string = lambda v: isinstance(v, str)
self.assertEqual(12, len([i for i in meta.values() if is_string(i)]))
@print_test
def test_pre_download_nlp(self):
"""Test running NLP algos before even downloading the article
"""
self.setup_stage('initial')
new_article = Article(self.article.url)
self.assertRaises(ArticleException, new_article.nlp)
@print_test
def test_pre_parse_nlp(self):
"""Test running NLP algos before parsing the article
"""
self.setup_stage('parse')
self.assertRaises(ArticleException, self.article.nlp)
@print_test
def test_nlp_body(self):
self.setup_stage('nlp')
self.article.nlp()
KEYWORDS = ['balloons', 'delays', 'flight', 'forecasters',
'good', 'sailing', 'smooth', 'storm', 'thanksgiving',
'travel', 'weather', 'winds', 'york']
SUMMARY = mock_resource_with('cnn_summary', 'txt')
self.assertEqual(SUMMARY, self.article.summary)
self.assertCountEqual(KEYWORDS, self.article.keywords)
class TestDownloadScheme(unittest.TestCase):
@print_test
def test_download_file_success(self):
url = "file://" + os.path.join(HTML_FN, "cnn_article.html")
article = Article(url=url)
article.download()
self.assertEqual(article.download_state, ArticleDownloadState.SUCCESS)
self.assertEqual(article.download_exception_msg, None)
self.assertEqual(75406, len(article.html))
@print_test
def test_download_file_failure(self):
url = "file://" + os.path.join(HTML_FN, "does_not_exist.html")
article = Article(url=url)
article.download()
self.assertEqual(0, len(article.html))
self.assertEqual(article.download_state, ArticleDownloadState.FAILED_RESPONSE)
self.assertEqual(article.download_exception_msg, "No such file or directory")
class ContentExtractorTestCase(unittest.TestCase):
"""Test specific element extraction cases"""
def setUp(self):
self.extractor = newspaper.extractors.ContentExtractor(Configuration())
self.parser = newspaper.parsers.Parser
def _get_title(self, html):
doc = self.parser.fromstring(html)
return self.extractor.get_title(doc)
def test_get_title_basic(self):
html = '<title>Test title</title>'
self.assertEqual(self._get_title(html), 'Test title')
def test_get_title_split(self):
html = '<title>Test page » Test title</title>'
self.assertEqual(self._get_title(html), 'Test title')
def test_get_title_split_escaped(self):
html = '<title>Test page » Test title</title>'
self.assertEqual(self._get_title(html), 'Test title')
def test_get_title_quotes(self):
title = 'Test page and «something in quotes»'
html = '<title>{}</title>'.format(title)
self.assertEqual(self._get_title(html), title)
def _get_canonical_link(self, article_url, html):
doc = self.parser.fromstring(html)
return self.extractor.get_canonical_link(article_url, doc)
def test_get_canonical_link_rel_canonical(self):
url = 'http://www.example.com/article.html'
html = '<link rel="canonical" href="{}">'.format(url)
self.assertEqual(self._get_canonical_link('', html), url)
def test_get_canonical_link_rel_canonical_absolute_url(self):
url = 'http://www.example.com/article.html'
html = '<link rel="canonical" href="article.html">'
article_url = 'http://www.example.com/article?foo=bar'
self.assertEqual(self._get_canonical_link(article_url, html), url)
def test_get_canonical_link_og_url_absolute_url(self):
url = 'http://www.example.com/article.html'
html = '<meta property="og:url" content="article.html">'
article_url = 'http://www.example.com/article?foo=bar'
self.assertEqual(self._get_canonical_link(article_url, html), url)
def test_get_canonical_link_hostname_og_url_absolute_url(self):
url = 'http://www.example.com/article.html'
html = '<meta property="og:url" content="www.example.com/article.html">'
article_url = 'http://www.example.com/article?foo=bar'
self.assertEqual(self._get_canonical_link(article_url, html), url)
def test_get_top_image_from_meta(self):
html = '<meta property="og:image" content="https://example.com/meta_img_filename.jpg" />' \
'<meta name="og:image" content="https://example.com/meta_another_img_filename.jpg"/>'
html_empty_og_content = '<meta property="og:image" content="" />' \
'<meta name="og:image" content="https://example.com/meta_another_img_filename.jpg"/>'
html_empty_all = '<meta property="og:image" content="" />' \
'<meta name="og:image" />'
html_rel_img_src = html_empty_all + '<link rel="img_src" href="https://example.com/meta_link_image.jpg" />'
html_rel_img_src2 = html_empty_all + '<link rel="image_src" href="https://example.com/meta_link_image2.jpg" />'
html_rel_icon = html_empty_all + '<link rel="icon" href="https://example.com/meta_link_rel_icon.ico" />'
doc = self.parser.fromstring(html)
self.assertEqual(
self.extractor.get_meta_img_url('http://www.example.com/article?foo=bar', doc),
'https://example.com/meta_img_filename.jpg'
)
doc = self.parser.fromstring(html_empty_og_content)
self.assertEqual(
self.extractor.get_meta_img_url('http://www.example.com/article?foo=bar', doc),
'https://example.com/meta_another_img_filename.jpg'
)
doc = self.parser.fromstring(html_empty_all)
self.assertEqual(
self.extractor.get_meta_img_url('http://www.example.com/article?foo=bar', doc),
''
)
doc = self.parser.fromstring(html_rel_img_src)
self.assertEqual(
self.extractor.get_meta_img_url('http://www.example.com/article?foo=bar', doc),
'https://example.com/meta_link_image.jpg'
)
doc = self.parser.fromstring(html_rel_img_src2)
self.assertEqual(
self.extractor.get_meta_img_url('http://www.example.com/article?foo=bar', doc),
'https://example.com/meta_link_image2.jpg'
)
doc = self.parser.fromstring(html_rel_icon)
self.assertEqual(
self.extractor.get_meta_img_url('http://www.example.com/article?foo=bar', doc),
'https://example.com/meta_link_rel_icon.ico'
)
class SourceTestCase(unittest.TestCase):
@print_test
def test_source_url_input_none(self):
with self.assertRaises(Exception):
Source(url=None)
@unittest.skip("Need to mock download")
@print_test
| |
refactor migration has run
'core.TopicPage',
]
template_choices = (('learn/detail_page.html', 'Learn'),)
class Meta:
verbose_name = 'Detail page'
verbose_name_plural = 'Detail pages'
################
# Content fields
################
hero = StreamField(
[
('Image', core_blocks.ImageBlock(template='core/includes/_hero_image.html')),
('Video', core_blocks.SimpleVideoBlock(template='core/includes/_hero_video.html')),
],
null=True,
blank=True,
validators=[hero_singular_validation],
)
objective = StreamField(
[
(
'paragraph',
blocks.RichTextBlock(options={'class': 'objectives'}),
),
('ListItem', core_blocks.Item()),
]
)
body = StreamField(
[
(
'paragraph',
blocks.StructBlock(
[('paragraph', blocks.RichTextBlock())],
template='core/struct_paragraph_block.html',
icon='fa-font',
),
),
(
'video',
blocks.StructBlock(
[('video', core_blocks.VideoBlock())],
template='core/struct_video_block.html',
icon='fa-play',
),
),
('case_study', core_blocks.CaseStudyStaticBlock(icon='fa-book')),
(
'Step',
core_blocks.StepByStepBlock(icon='cog'),
),
(
'fictional_example',
blocks.StructBlock(
[('fiction_body', blocks.RichTextBlock(icon='openquote'))],
template='learn/fictional_company_example.html',
icon='fa-commenting-o',
),
),
(
'ITA_Quote',
core_blocks.ITAQuoteBlock(icon='fa-quote-left'),
),
(
'pros_cons',
blocks.StructBlock(
[
(
'pros',
blocks.StreamBlock(
[
(
'item',
core_blocks.Item(icon='fa-arrow-right'),
)
]
),
),
(
'cons',
blocks.StreamBlock(
[
(
'item',
core_blocks.Item(icon='fa-arrow-right'),
)
]
),
),
],
template='learn/pros_and_cons.html',
icon='fa-arrow-right',
),
),
('choose_do_not_choose', core_blocks.ChooseDoNotChooseBlock()),
(
'image',
core_blocks.ImageBlock(
template='core/includes/_image_full_width.html',
help_text='Image displayed within a full-page-width block',
),
),
(
'video',
core_blocks.SimpleVideoBlock(
template='core/includes/_video_full_width.html',
help_text='Video displayed within a full-page-width block',
),
),
]
)
recap = StreamField(
[
(
'recap_item',
blocks.StructBlock(
[
('title', blocks.CharBlock(icon='fa-header')),
(
'item',
blocks.StreamBlock(
[
(
'item',
core_blocks.Item(),
)
]
),
),
],
template='learn/recap.html',
icon='fa-commenting-o',
),
)
]
)
#########
# Panels
##########
content_panels = Page.content_panels + [
StreamFieldPanel('hero'),
StreamFieldPanel('objective'),
StreamFieldPanel('body'),
StreamFieldPanel('recap'),
]
def handle_page_view(self, request):
if request.user.is_authenticated:
# checking if the page should record read progress
# checking if the page is already marked as read
list_page = (
ListPage.objects.ancestor_of(self)
.filter(record_read_progress=True)
.exclude(page_views_list__sso_id=request.user.pk, page_views_list__page=self)
.first()
)
if list_page:
PageView.objects.get_or_create(
page=self,
list_page=list_page,
sso_id=request.user.pk,
)
def serve(self, request, *args, **kwargs):
self.handle_page_view(request)
return super().serve(request, **kwargs)
@cached_property
def topic_title(self):
return self.get_parent().title
@cached_property
def module(self):
"""Gets the learning module this lesson belongs to"""
return CuratedListPage.objects.live().specific().ancestor_of(self).first()
@cached_property
def _export_plan_url_map(self):
"""Return a lookup dictionary of URL Slugs->title for all the
Export Plan sections we have."""
return {url: values['title'] for url, values in EXPORTPLAN_URL_MAP.items()}
def _get_backlink(self, request):
"""Try to extract a backlink (used for a link to the export plan) from the
querystring on the request that brought us to this view.
Only accepts backlinks that we KNOW are for the export plan, else ignore it."""
backlink_path = request.GET.get(BACKLINK_QUERYSTRING_NAME, '')
if backlink_path is not None:
backlink_path = unquote(backlink_path)
if len(backlink_path.split('/')) > 2 and (
backlink_path.split('/')[3] in EXPORTPLAN_SLUGS and '://' not in backlink_path
):
# The check for '://' will stop us accepting a backlink which
# features a full URL as its OWN querystring param (eg a crafted attack
# URL), but that's an acceptable limitation here and is very unlikely
# to happen.
return backlink_path
return None # safe default
def _get_backlink_title(self, backlink_path):
"""For a given backlink, see if we can get a title that goes with it.
For now, this is limited only to Export Plan pages/links.
"""
# We have to re-arrange EXPORT_PLAN_SECTION_TITLES_URLS after import
# because it features lazily-evaluated URLs that aren't ready when
# models are imported
if backlink_path and len(backlink_path.split('/')) > 3:
_path = backlink_path.split('/')[3]
return self._export_plan_url_map.get(_path)
def get_context(self, request, *args, **kwargs):
context = super().get_context(request)
context['refresh_on_market_change'] = True
# Prepare backlink to the export plan if we detect one and can validate it
_backlink = self._get_backlink(request)
if _backlink:
context['backlink'] = _backlink
context['backlink_title'] = self._get_backlink_title(_backlink)
if isinstance(self.get_parent().specific, TopicPage):
# In a conditional because a DetailPage currently MAY be used as
# a child of another page type...
page_topic_helper = PageTopicHelper(self)
next_lesson = page_topic_helper.get_next_lesson()
context['current_lesson'] = self
context['current_module'] = page_topic_helper.module
if page_topic_helper:
topic_page = page_topic_helper.get_page_topic()
if topic_page:
context['current_topic'] = topic_page
context['page_topic'] = topic_page.title
if next_lesson:
context['next_lesson'] = next_lesson
else:
next_module = self.module.get_next_sibling()
if not next_module:
return context
context['next_module'] = next_module.specific
context['next_lesson'] = get_first_lesson(next_module)
return context
class PageView(TimeStampedModel):
page = models.ForeignKey(DetailPage, on_delete=models.CASCADE, related_name='page_views')
list_page = models.ForeignKey(ListPage, on_delete=models.CASCADE, related_name='page_views_list')
sso_id = models.TextField()
class Meta:
ordering = ['page__pk']
unique_together = ['page', 'sso_id']
# TODO: deprecate and remove
class ContentModuleTag(TaggedItemBase):
content_object = ParentalKey('core.ContentModule', on_delete=models.CASCADE, related_name='tagged_items')
# TODO: deprecate and remove
@register_snippet
class ContentModule(ClusterableModel):
title = models.CharField(max_length=255)
content = RichTextField()
tags = TaggableManager(through=ContentModuleTag, blank=True)
panels = [
FieldPanel('title'),
FieldPanel('content'),
FieldPanel('tags'),
]
def __str__(self):
return self.title
class PersonalisationHSCodeTag(TagBase):
"""Custom tag for personalisation.
Tag value will be a HS6, HS4 or HS2 code"""
# free_tagging = False # DISABLED until tag data only comes via data migration
class Meta:
verbose_name = 'HS Code tag for personalisation'
verbose_name_plural = 'HS Code tags for personalisation'
class PersonalisationCountryTag(TagBase):
"""Custom tag for personalisation.
Tag value will be an ISO-2 Country code ('DE')
"""
free_tagging = False
class Meta:
verbose_name = 'Country tag for personalisation'
verbose_name_plural = 'Country tags for personalisation'
class PersonalisationRegionTag(TagBase):
"""Custom tag for personalisation.
Tag value will be a geographical string ('Europe')
"""
free_tagging = False
class Meta:
verbose_name = 'Region tag for personalisation'
verbose_name_plural = 'Region tags for personalisation'
class PersonalisationTradingBlocTag(TagBase):
"""Custom tag for personalisation.
Tag value will be an Trading blocs
"""
free_tagging = False
class Meta:
verbose_name = 'Trading bloc tag for personalisation'
verbose_name_plural = 'Trading bloc tags for personalisation'
# If you're wondering what's going on here:
# https://docs.wagtail.io/en/stable/reference/pages/model_recipes.html#custom-tag-models
class HSCodeTaggedCaseStudy(ItemBase):
tag = models.ForeignKey(
PersonalisationHSCodeTag, related_name='hscode_tagged_case_studies', on_delete=models.CASCADE
)
content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='hs_code_tagged_items')
class CountryTaggedCaseStudy(ItemBase):
tag = models.ForeignKey(
PersonalisationCountryTag, related_name='country_tagged_case_studies', on_delete=models.CASCADE
)
content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='country_tagged_items')
class RegionTaggedCaseStudy(ItemBase):
tag = models.ForeignKey(
PersonalisationRegionTag, related_name='region_tagged_case_studies', on_delete=models.CASCADE
)
content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='region_tagged_items')
class TradingBlocTaggedCaseStudy(ItemBase):
tag = models.ForeignKey(
PersonalisationTradingBlocTag, related_name='trading_bloc_tagged_case_studies', on_delete=models.CASCADE
)
content_object = ParentalKey(
to='core.CaseStudy', on_delete=models.CASCADE, related_name='trading_bloc_tagged_items'
)
def _high_level_validation(value, error_messages):
TEXT_BLOCK = 'text' # noqa N806
MEDIA_BLOCK = 'media' # noqa N806
QUOTE_BLOCK = 'quote' # noqa N806
# we need to be strict about presence and ordering of these nodes
if [node.block_type for node in value if node.block_type != QUOTE_BLOCK] != [MEDIA_BLOCK, TEXT_BLOCK]:
error_messages.append(
(
'This block must contain one Media section (with one or '
'two items in it) and/or a Quote section, then one Text section following it.'
)
)
return error_messages
def _low_level_validation(value, error_messages):
# Check content of media node, which should be present here
MEDIA_BLOCK = 'media' # noqa N806
VIDEO_BLOCK = 'video' # noqa N806
for node in value:
if node.block_type == MEDIA_BLOCK:
subnode_block_types = [subnode.block_type for subnode in node.value]
if len(subnode_block_types) == 2:
if set(subnode_block_types) == {VIDEO_BLOCK}:
# Two videos: not allowed
error_messages.append('Only one video may be used in a case study.')
elif subnode_block_types[1] == VIDEO_BLOCK:
# implicitly, [0] must be an image
# video after image: not allowed
error_messages.append('The video must come before a still image.')
return error_messages
def case_study_body_validation(value):
"""Ensure the case study has exactly both a media node and a text node
and that the media node has the following content:
* One image, only
* One video, only
* One video + One image
* (video must comes first so that it is displayed first)
* Two images
"""
error_messages = []
if value:
error_messages = _high_level_validation(value, error_messages)
error_messages = _low_level_validation(value, error_messages)
if error_messages:
raise StreamBlockValidationError(
non_block_errors=ValidationError('; '.join(error_messages), code='invalid'),
)
class MagnaPageChooserPanel(PageChooserPanel):
show_label = False
field_template = 'admin/wagtailadmin/edit_handlers/field_panel_field.html'
def render_as_field(self):
instance_obj = self.get_chosen_item()
context = {
'field': self.bound_field,
self.object_type_name: instance_obj,
'is_chosen': bool(instance_obj), # DEPRECATED - passed to templates for backwards compatibility only
# Added obj_type on base class method render_as_field
'obj_type': instance_obj.specific.__class__.__name__ if instance_obj else None,
}
return mark_safe(render_to_string(self.field_template, context))
class CaseStudyRelatedPages(Orderable):
case_study = ParentalKey(
'core.CaseStudy',
related_name='related_pages',
on_delete=models.SET_NULL,
null=True,
blank=True,
)
page = models.ForeignKey(
'wagtailcore.Page',
on_delete=models.CASCADE,
related_name='+',
)
panels = [
MagnaPageChooserPanel('page', [DetailPage, CuratedListPage, TopicPage]),
]
class Meta:
unique_together = ['case_study', 'page']
@register_snippet
class CaseStudy(ClusterableModel):
"""Dedicated snippet for use as a case study. Supports personalised
selection via its tags.
The decision about the appropriate Case Study block to show will happen
when the page attempts to render the relevant CaseStudyBlock.
Note that this is rendered via Wagtail's ModelAdmin, so appears in the sidebar,
but we have to keep it registered as a Snippet to be able to transfer it
with Wagtail-Transfer
"""
title = models.CharField(
max_length=255,
blank=False,
verbose_name='Internal case study title',
)
# old name company_name
summary_context = models.CharField(max_length=255, blank=False, default='How we did it')
# old name summary
lead_title = models.TextField(blank=False) # Deliberately not rich-text / no formatting
body = StreamField(
[
(
'media',
blocks.StreamBlock(
[
('video', core_blocks.SimpleVideoBlock(template='core/includes/_case_study_video.html')),
('image', core_blocks.ImageBlock()),
],
min_num=1,
max_num=2,
),
),
(
'text',
blocks.RichTextBlock(
features=RICHTEXT_FEATURES__MINIMAL,
),
),
| |
# Copyright 2020 NREL
# 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.
# See https://floris.readthedocs.io for documentation
import copy
from itertools import repeat
from multiprocessing import cpu_count
from multiprocessing.pool import Pool
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import norm
from WindAI.floris.simulation import Floris, Turbine, WindMap, TurbineMap
from .cut_plane import CutPlane, get_plane_from_flow_data
from .flow_data import FlowData
from ..utilities import Vec3
from .visualization import visualize_cut_plane
from ..logging_manager import LoggerBase
from .layout_functions import visualize_layout, build_turbine_loc
from .interface_utilities import get_params, set_params, show_params
def global_calc_one_AEP_case(FlorisInterface, wd, ws, freq, yaw=None):
return FlorisInterface._calc_one_AEP_case(wd, ws, freq, yaw)
class FlorisInterface(LoggerBase):
"""
FlorisInterface provides a high-level user interface to many of the
underlying methods within the FLORIS framework. It is meant to act as a
single entry-point for the majority of users, simplifying the calls to
methods on objects within FLORIS.
"""
def __init__(self, input_file=None, input_dict=None):
"""
Initialize the FLORIS interface by pointing toward an input file or
dictionary. Inputs from either **input_file** or **input_dict** are
parsed within the :py:class:`~.simulation.input_reader` through
the :py:class:`~.simulation.floris` object. Either an
**input_file** or **input_dict** is required.
Args:
input_file (str, optional): A string path to the json input file.
Defaults to None.
input_dict (dict, optional): A Python dictionary of inputs.
Defaults to None.
Raises:
ValueError: Input file or dictionary must be supplied.
"""
if input_file is None and input_dict is None:
err_msg = "Input file or dictionary must be supplied"
self.logger.error(err_msg, stack_info=True)
raise ValueError(err_msg)
self.input_file = input_file
self.floris = Floris(input_file=input_file, input_dict=input_dict)
def calculate_wake(
self, yaw_angles=None, no_wake=False, points=None, track_n_upstream_wakes=False
):
"""
Wrapper to the :py:meth:`~.Farm.set_yaw_angles` and
:py:meth:`~.FlowField.calculate_wake` methods.
Args:
yaw_angles (np.array, optional): Turbine yaw angles.
Defaults to None.
no_wake: (bool, optional): When *True* updates the turbine
quantities without calculating the wake or adding the
wake to the flow field. Defaults to *False*.
points: (np.array, optional): The x, y, and z coordinates at
which the flow field velocity is to be recorded. Defaults
to None.
track_n_upstream_wakes (bool, optional): When *True*, will keep
track of the number of upstream wakes a turbine is
experiencing. Defaults to *False*.
"""
if yaw_angles is not None:
self.floris.farm.set_yaw_angles(yaw_angles)
self.floris.farm.flow_field.calculate_wake(
no_wake=no_wake,
points=points,
track_n_upstream_wakes=track_n_upstream_wakes,
)
def reinitialize_flow_field(
self,
wind_speed=None,
wind_layout=None,
wind_direction=None,
wind_shear=None,
wind_veer=None,
specified_wind_height=None,
turbulence_intensity=None,
turbulence_kinetic_energy=None,
air_density=None,
wake=None,
layout_array=None,
with_resolution=None,
):
"""
Wrapper to :py:meth:`~.flow_field.reinitialize_flow_field`. All input
values are used to update the :py:class:`~.flow_field.FlowField`
instance.
Args:
wind_speed (list, optional): Background wind speed.
Defaults to None.
wind_layout (tuple, optional): Tuple of x- and
y-locations of wind speed measurements.
Defaults to None.
wind_direction (list, optional): Background wind direction.
Defaults to None.
wind_shear (float, optional): Shear exponent.
Defaults to None.
wind_veer (float, optional): Direction change over rotor.
Defaults to None.
specified_wind_height (float, optional): Specified wind height for
shear. Defaults to None.
turbulence_intensity (list, optional): Background turbulence
intensity. Defaults to None.
turbulence_kinetic_energy (list, optional): Background turbulence
kinetic energy. Defaults to None.
air_density (float, optional): Ambient air density.
Defaults to None.
wake (:py:class:`~.wake.Wake`, optional): A container
class :py:class:`~.wake.Wake` with wake model
information used to calculate the flow field. Defaults to None.
layout_array (np.array, optional): Array of x- and
y-locations of wind turbines. Defaults to None.
with_resolution (float, optional): Resolution of output
flow_field. Defaults to None.
"""
wind_map = self.floris.farm.wind_map
turbine_map = self.floris.farm.flow_field.turbine_map
if turbulence_kinetic_energy is not None:
if wind_speed is None:
wind_map.input_speed
turbulence_intensity = self.TKE_to_TI(turbulence_kinetic_energy, wind_speed)
if wind_layout or layout_array is not None:
# Build turbine map and wind map (convenience layer for user)
if layout_array is None:
layout_array = self.get_turbine_layout()
else:
turbine_map = TurbineMap(
layout_array[0],
layout_array[1],
[
copy.deepcopy(self.floris.farm.turbines[0])
for ii in range(len(layout_array[0]))
],
)
if wind_layout is None:
wind_layout = wind_map.wind_layout
if wind_speed is None:
wind_speed = wind_map.input_speed
else:
wind_speed = (
wind_speed if isinstance(wind_speed, list) else [wind_speed]
)
if wind_direction is None:
wind_direction = wind_map.input_direction
else:
wind_direction = (
wind_direction
if isinstance(wind_direction, list)
else [wind_direction]
)
if turbulence_intensity is None:
turbulence_intensity = wind_map.input_ti
else:
turbulence_intensity = (
turbulence_intensity
if isinstance(turbulence_intensity, list)
else [turbulence_intensity]
)
wind_map = WindMap(
wind_speed=wind_speed,
layout_array=layout_array,
wind_layout=wind_layout,
turbulence_intensity=turbulence_intensity,
wind_direction=wind_direction,
)
self.floris.farm.wind_map = wind_map
else:
turbine_map = None
if wind_speed is not None:
# If not a list, convert to list
# TODO: What if tuple? Or
wind_speed = (
wind_speed if isinstance(wind_speed, list) else [wind_speed]
)
wind_map.input_speed = wind_speed
wind_map.calculate_wind_speed()
if turbulence_intensity is not None:
# If not a list, convert to list
# TODO: What if tuple? Or
turbulence_intensity = (
turbulence_intensity
if isinstance(turbulence_intensity, list)
else [turbulence_intensity]
)
wind_map.input_ti = turbulence_intensity
wind_map.calculate_turbulence_intensity()
if wind_direction is not None:
# If not a list, convert to list
# TODO: What if tuple? Or
wind_direction = (
wind_direction
if isinstance(wind_direction, list)
else [wind_direction]
)
wind_map.input_direction = wind_direction
wind_map.calculate_wind_direction()
# redefine wind_map in Farm object
self.floris.farm.wind_map = wind_map
self.floris.farm.flow_field.reinitialize_flow_field(
wind_shear=wind_shear,
wind_veer=wind_veer,
specified_wind_height=specified_wind_height,
air_density=air_density,
wake=wake,
turbine_map=turbine_map,
with_resolution=with_resolution,
wind_map=self.floris.farm.wind_map,
)
def get_plane_of_points(
self,
x1_resolution=200,
x2_resolution=200,
normal_vector="z",
x3_value=100,
x1_bounds=None,
x2_bounds=None,
):
"""
Calculates velocity values through the
:py:meth:`~.FlowField.calculate_wake` method at points in plane
specified by inputs.
Args:
x1_resolution (float, optional): Output array resolution.
Defaults to 200 points.
x2_resolution (float, optional): Output array resolution.
Defaults to 200 points.
normal_vector (string, optional): Vector normal to plane.
Defaults to z.
x3_value (float, optional): Value of normal vector to slice through.
Defaults to 100.
x1_bounds (tuple, optional): Limits of output array (in m).
Defaults to None.
x2_bounds (tuple, optional): Limits of output array (in m).
Defaults to None.
Returns:
:py:class:`pandas.DataFrame`: containing values of x1, x2, u, v, w
"""
# Get a copy for the flow field so don't change underlying grid points
flow_field = copy.deepcopy(self.floris.farm.flow_field)
if self.floris.farm.flow_field.wake.velocity_model.requires_resolution:
# If this is a gridded model, must extract from full flow field
self.logger.info(
"Model identified as %s requires use of underlying grid print"
% self.floris.farm.flow_field.wake.velocity_model.model_string
)
# Get the flow data and extract the plane using it
flow_data = self.get_flow_data()
return get_plane_from_flow_data(
flow_data, normal_vector=normal_vector, x3_value=x3_value
)
# If x1 and x2 bounds are not provided, use rules of thumb
if normal_vector == "z": # Rules of thumb for horizontal plane
if x1_bounds is None:
coords = self.floris.farm.flow_field.turbine_map.coords
max_diameter = self.floris.farm.flow_field.max_diameter
x = [coord.x1 for coord in coords]
x1_bounds = (min(x) - 2 * max_diameter, max(x) + 10 * max_diameter)
if x2_bounds is None:
coords = self.floris.farm.flow_field.turbine_map.coords
max_diameter = self.floris.farm.flow_field.max_diameter
y = [coord.x2 for coord in coords]
x2_bounds = (min(y) - 2 * max_diameter, max(y) + 2 * max_diameter)
if normal_vector == "x": # Rules of thumb for cut plane plane
if x1_bounds is None:
coords = self.floris.farm.flow_field.turbine_map.coords
max_diameter = self.floris.farm.flow_field.max_diameter
y = [coord.x2 for coord in coords]
x1_bounds = (min(y) - 2 * max_diameter, max(y) + 2 * max_diameter)
if x2_bounds is None:
hub_height = self.floris.farm.flow_field.turbine_map.turbines[
0
].hub_height
x2_bounds = (10, hub_height * 2)
# Set up the points to test
x1_array = np.linspace(x1_bounds[0], x1_bounds[1], num=x1_resolution)
x2_array = np.linspace(x2_bounds[0], x2_bounds[1], num=x2_resolution)
# Grid the points and flatten
x1_array, x2_array = np.meshgrid(x1_array, x2_array)
x1_array = x1_array.flatten()
x2_array = x2_array.flatten()
x3_array = np.ones_like(x1_array) * x3_value
# Create the points matrix
if normal_vector == "z":
points = np.row_stack((x1_array, x2_array, x3_array))
if normal_vector == "x":
points = np.row_stack((x3_array, x1_array, x2_array))
# Recalculate wake with these points
flow_field.calculate_wake(points=points)
# Get results vectors
x_flat = flow_field.x.flatten()
y_flat = flow_field.y.flatten()
z_flat = flow_field.z.flatten()
u_flat = flow_field.u.flatten()
v_flat = flow_field.v.flatten()
w_flat = flow_field.w.flatten()
# Create a df of these
if normal_vector == "z":
df = pd.DataFrame(
{
"x1": x_flat,
"x2": y_flat,
"x3": z_flat,
"u": u_flat,
"v": v_flat,
"w": w_flat,
}
)
if normal_vector == "x":
df = pd.DataFrame(
{
"x1": y_flat,
"x2": z_flat,
"x3": x_flat,
"u": u_flat,
"v": v_flat,
"w": w_flat,
}
)
if normal_vector == "y":
df = pd.DataFrame(
{
"x1": x_flat,
"x2": z_flat,
| |
mysqldb.username(query_str)
if username_result == 'L1001':
response['code'] = 'L1001'
response['message'] = '系统异常'
return response
elif username_result == None:
response['code'] = 'L1003'
response['message'] = '认证失败'
return response
else:
sql_result = mysqldb.port_list(username_result['username'], pagenum, pagesize, list_query)
port_list = sql_result['result']
total = sql_result['total']
if port_list == 'L1001':
response['code'] = 'L1001'
response['message'] = '系统异常'
else:
response['code'] = 'L1000'
response['message'] = '请求成功'
response['total'] = total
if total == 0:
response['data'] = ''
else:
response['data'] = sql_result
return response
except Exception as e:
print(e)
response['code'] = 'L1001'
response['message'] = '系统异常'
return response
@app.post('/api/poc/name')
async def poc_name(request : VueRequest):
"""
获取所有漏洞名字的接口,以供前端选扫描插件
:param:
:return: str response: 需要返回的数据
"""
try:
response = {'code': '', 'message': '', 'data': ''}
request = rsa_crypto.decrypt(request.data)
request = json.loads(request)
token = request['token']
query_str = {
'type': 'token',
'data': token
}
username_result = mysqldb.username(query_str)
if username_result == 'L1001':
response['code'] = 'L1001'
response['message'] = '系统异常'
return response
elif username_result == None:
response['code'] = 'L1003'
response['message'] = '认证失败'
return response
else:
name_datas = []
for item in os.listdir('app/plugins/http'):
file_names = os.listdir('app/plugins/http/' + item)
for file_name in file_names:
if file_name.endswith(".py") and not file_name.startswith('__') and 'ajpy' not in file_name:
file_name = file_name[:-3].replace('_', '-')
name_datas.append(file_name)
for item in os.listdir('app/plugins/port'):
file_names = os.listdir('app/plugins/port/' + item)
for file_name in file_names:
if file_name.endswith(".py") and not file_name.startswith('__') and 'ajpy' not in file_name:
file_name = file_name[:-3].replace('_', '-')
name_datas.append(file_name)
response['code'] = 'L1000'
response['message'] = '请求成功'
response['data'] = name_datas
return response
except Exception as e:
print(e)
response['code'] = 'L1001'
response['message'] = '系统异常'
return response
@app.post('/api/poc/list')
async def poc_list(request : VueRequest):
"""
获取所有漏洞信息的接口,以供前端选扫描插件
:param:
:return: str response: 需要返回的数据
"""
try:
response = {'code': '', 'message': '', 'data': ''}
request = rsa_crypto.decrypt(request.data)
request = json.loads(request)
pagenum = request['pagenum']
pagesize = request['pagesize']
list_query = json.loads(request['listQuery'])
start = (int(pagenum)-1) * int(pagesize)
pagesize = int (pagesize)
token = request['token']
query_str = {
'type': 'token',
'data': token
}
username_result = mysqldb.username(query_str)
if username_result == 'L1001':
response['code'] = 'L1001'
response['message'] = '系统异常'
return response
elif username_result == None:
response['code'] = 'L1003'
response['message'] = '认证失败'
return response
else:
sql_result = mysqldb.poc_list(username_result['username'], pagenum, pagesize, list_query)
poc_list = sql_result['result']
total = sql_result['total']
if poc_list == 'L1001':
response['code'] = 'L1001'
response['message'] = '系统异常'
return response
else:
response['code'] = 'L1000'
response['message'] = '请求成功'
response['total'] = total
if total == 0:
response['data'] = ''
else:
response['data'] = poc_list
response['code'] = 'L1000'
response['message'] = '请求成功'
return response
except Exception as e:
print(e)
response['code'] = 'L1001'
response['message'] = '系统异常'
return response
@app.post('/api/vulner/list')
async def vuln_list(request : VueRequest):
"""
获取所有漏洞信息的接口
:param:
:return: str response: 需要返回的数据
"""
try:
response = {'code': '', 'message': '', 'data': ''}
request = rsa_crypto.decrypt(request.data)
request = json.loads(request)
pagenum = request['pagenum']
pagesize = request['pagesize']
token = request['token']
query_str = {
'type': 'token',
'data': token
}
list_query = json.loads(request['listQuery'])
username_result = mysqldb.username(query_str)
if username_result == 'L1001':
response['code'] = 'L1001'
response['message'] = '系统异常'
return response
elif username_result == None:
response['code'] = 'L1003'
response['message'] = '认证失败'
return response
else:
sql_result = mysqldb.vulner_list(username_result['username'], pagenum, pagesize, list_query)
vulner_list = sql_result['result']
total = sql_result['total']
if vulner_list == 'L1001':
response['code'] = 'L1001'
response['message'] = '系统异常'
else:
response['code'] = 'L1000'
response['message'] = '请求成功'
response['total'] = total
if total == 0:
response['data'] = ''
else:
response['data'] = sql_result
return response
except Exception as e:
print(e)
response['code'] = 'L1001'
response['message'] = '系统异常'
return response
@app.post('/api/generate/auth')
async def generate_auth(request : VueRequest):
"""
生成xss auth的接口
:param:
:return: str response: 需要返回的数据
"""
try:
response = {'code': '', 'message': '', 'data': ''}
request = rsa_crypto.decrypt(request.data)
request = json.loads(request)
token = request['token']
query_str = {
'type': 'token',
'data': token
}
username_result = mysqldb.username(query_str)
if username_result == 'L1001':
response['code'] = 'L1001'
response['message'] = '系统异常'
return response
elif username_result == None:
response['code'] = 'L1003'
response['message'] = '认证失败'
return response
else:
response['code'] = 'L1000'
response['message'] = '请求正常'
auth_token = aes_crypto.encrypt(get_capta() + get_capta())
url = 'http://uwsgi运行ip:port/api/log?token=' + auth_token + '&data=js语句'
mysqldb.save_xss_auth(username_result['username'], auth_token, url)
response['data'] = auth_token
return response
except Exception as e:
print(e)
response['code'] = 'L1001'
response['message'] = '系统异常'
return response
@app.post('/api/xss/auth')
async def auth_list(request : VueRequest):
"""
获取xss auth的接口
:param:
:return: str response: 需要返回的数据
"""
try:
response = {'code': '', 'message': '', 'data': ''}
request = rsa_crypto.decrypt(request.data)
request = json.loads(request)
pagenum = request['pagenum']
pagesize = request['pagesize']
token = request['token']
query_str = {
'type': 'token',
'data': token
}
list_query = json.loads(request['listQuery'])
if list_query['token_status'] == '全部':
list_query['token_status'] = ''
username_result = mysqldb.username(query_str)
if username_result == 'L1001':
response['code'] = 'L1001'
response['message'] = '系统异常'
return response
elif username_result == None:
response['code'] = 'L1003'
response['message'] = '认证失败'
return response
else:
sql_result = mysqldb.xss_auth_list(username_result['username'], pagenum, pagesize, list_query)
target_list = sql_result['result']
total = sql_result['total']
if target_list == 'L1001':
response['code'] = 'L1001'
response['message'] = '系统异常'
else:
response['code'] = 'L1000'
response['message'] = '请求成功'
if total == 0:
response['data'] = ''
else:
response['data'] = sql_result
return response
except Exception as e:
print(e)
response['code'] = 'L1001'
response['message'] = '系统异常'
return response
@app.post('/api/generate/domain')
async def generate_domain(request : VueRequest):
"""
从dnslog.cn重新获取域名
:param:
:return: str response: 需要返回的数据
"""
try:
response = {'code': '', 'message': '', 'data': ''}
request = rsa_crypto.decrypt(request.data)
request = json.loads(request)
token = request['token']
query_str = {
'type': 'token',
'data': token
}
username_result = mysqldb.username(query_str)
if username_result == 'L1001':
response['code'] = 'L1001'
response['message'] = '系统异常'
return response
elif username_result == None:
response['code'] = 'L1003'
response['message'] = '认证失败'
return response
else:
for thread in dns_thread_list:
stop_thread(thread)
t = threading.Thread(target= handle_dns_log, daemon = True, args = (username_result['username'],))
t.start()
time.sleep(1)
response['code'] = 'L1000'
response['message'] = '请求正常'
domain = config.get('Domain', 'domain')
response['data'] = domain
return response
except Exception as e:
print(e)
response['code'] = 'L1001'
response['message'] = '系统异常'
return response
@app.post('/api/dns/log')
async def dns_log_list(request : VueRequest):
"""
获取dns log的接口
:param:
:return: str response: 需要返回的数据
"""
try:
response = {'code': '', 'message': '', 'data': ''}
request = rsa_crypto.decrypt(request.data)
request = json.loads(request)
pagenum = request['pagenum']
pagesize = request['pagesize']
token = request['token']
query_str = {
'type': 'token',
'data': token
}
list_query = json.loads(request['listQuery'])
username_result = mysqldb.username(query_str)
if username_result == 'L1001':
response['code'] = 'L1001'
response['message'] = '系统异常'
return response
elif username_result == None:
response['code'] = 'L1003'
response['message'] = '认证失败'
return response
else:
sql_result = mysqldb.dns_log_list(username_result['username'], pagenum, pagesize, list_query)
target_list = sql_result['result']
total = sql_result['total']
if target_list == 'L1001':
response['code'] = 'L1001'
response['message'] = '系统异常'
else:
response['code'] = 'L1000'
response['message'] = '请求成功'
if total == 0:
response['data'] = ''
else:
response['data'] = sql_result
response['domain'] = config.get('Domain', 'domain')
return response
except Exception as e:
print(e)
response['code'] = 'L1001'
response['message'] = '系统异常'
return response
@app.post('/api/xss/log')
async def xss_log_list(request : VueRequest):
"""
获取xss log的接口
:param:
:return: str response: 需要返回的数据
"""
try:
response = {'code': '', 'message': '', 'data': ''}
request = rsa_crypto.decrypt(request.data)
request = json.loads(request)
pagenum = request['pagenum']
pagesize = request['pagesize']
token = request['token']
query_str = {
'type': 'token',
'data': token
}
list_query = json.loads(request['listQuery'])
username_result = mysqldb.username(query_str)
if username_result == 'L1001':
response['code'] = 'L1001'
response['message'] = '系统异常'
return response
elif username_result == None:
response['code'] = 'L1003'
response['message'] = '认证失败'
return response
else:
sql_result = mysqldb.xss_log_list(username_result['username'], pagenum, pagesize, list_query)
target_list = sql_result['result']
total = sql_result['total']
if target_list == 'L1001':
response['code'] = 'L1001'
response['message'] = '系统异常'
else:
response['code'] = 'L1000'
response['message'] = '请求成功'
if total == 0:
response['data'] = ''
else:
response['data'] = sql_result
return response
except Exception as e:
print(e)
response['code'] = 'L1001'
response['message'] = '系统异常'
return response
@app.post('/api/account/add')
async def account_add(request : VueRequest):
"""
添加用户的接口
:param:
:return: str response: 需要返回的数据
"""
try:
response = {'code': '', 'message': '', 'data': ''}
request = rsa_crypto.decrypt(request.data)
request = json.loads(request)
username = request['username']
description = request['description']
password = <PASSWORD>(request['password'])
role = request['role']
random_str = get_capta()
user_token = aes_crypto.encrypt(username + random_str)
token = request['token']
query_str = {
'type': 'token',
'data': token
}
username_result = mysqldb.username(query_str)
if username_result == 'L1001':
response['code'] = 'L1001'
response['message'] = '系统异常'
return response
elif username_result == None:
response['code'] = 'L1003'
response['message'] = '认证失败'
return response
elif username_result['role'] != 'admin':
response['code'] = 'L10010'
response['message'] = '权限不足,无法进行操作'
return response
else:
result = mysqldb.save_account(username, description, user_token, password, role, 'avatar.png')
response['code'] = result
if response['code'] == 'L1000':
response['message'] = '请求成功'
else:
response['message'] = '系统异常'
return response
except Exception as e:
print(e)
response['code'] = 'L1001'
response['message'] = | |
import time
import datetime
import serial
import threading
import json
import traceback
import queue
import os
import pty
import subprocess
from multiprocessing import Process
import glob
from elasticsearch import Elasticsearch
from .data_consumers import Datastore, Logger
from .http_cmd import create_usb_session_endpoint
class USBSession(object):
'''
Represents a connection session with a Flight Computer's state system.
This class is used by the simulation software and user command prompt to read and write to a
flight computer's state.
This object is thread-safe; if an instance of this class is shared between the MATLAB simulation
interface (an instance of Simulation) and the user command line (an instance of StateCmdPrompt),
they won't trip over each other in setting/receiving variables from the connected flight computer.
'''
def __init__(self, device_name, uplink_console, port, is_teensy, simulation_run_dir):
'''
Initializes state session with a device.
'''
# Device connection
self.device_name = device_name
self.port = port
self.is_teensy = is_teensy
# Uplink console
self.uplink_console = uplink_console
# Data logging
self.datastore = Datastore(device_name, simulation_run_dir)
self.logger = Logger(device_name, simulation_run_dir)
self.raw_logger = Logger(device_name + "_raw", simulation_run_dir)
self.telem_save_dir = simulation_run_dir
#Start downlink parser. Compile it if it is not available.
downlink_parser_filepath = ".pio/build/gsw_downlink_parser/program"
if not os.path.exists(downlink_parser_filepath):
print("Compiling the downlink parser.")
os.system("pio run -e gsw_downlink_parser > /dev/null")
master_fd, slave_fd = pty.openpty()
self.downlink_parser = subprocess.Popen([downlink_parser_filepath], stdin=master_fd, stdout=master_fd)
self.dp_console = serial.Serial(os.ttyname(slave_fd), 9600, timeout=1)
self.telem_save_dir = simulation_run_dir
# Open a connection to elasticsearch
self.es = Elasticsearch([{'host':"127.0.0.1",'port':"9200"}])
# Simulation
self.overriden_variables = set()
def connect(self, console_port, baud_rate):
'''
Starts serial connection to the desired device.
Args:
- console_port: Serial port to connect to.
- baud_rate: Baud rate of connection.
'''
try:
self.console = serial.Serial(console_port, baud_rate)
self.start_time = datetime.datetime.now() # This is t = 0 on the Teensy, +/- a few milliseconds.
self.device_write_lock = threading.Lock() # Lock to prevent multiple writes to device at the same time.
# Queues used to manage interface between the check_msgs_thread and calls to read_state or write_state
self.field_requests = queue.Queue()
self.field_responses = queue.Queue()
self.datastore.start()
self.logger.start()
self.raw_logger.start()
self.running_logger = True
self.check_msgs_thread = threading.Thread(
name=f"{self.device_name} logger thread",
target=self.check_console_msgs)
self.check_msgs_thread.start()
print(f"Opened connection to {self.device_name}.")
except serial.SerialException:
print(f"Unable to open serial port for {self.device_name}.")
return False
try:
self.flask_app = create_usb_session_endpoint(self)
self.flask_app.config["uplink_console"] = self.uplink_console
self.flask_app.config["console"] = self.console
self.http_thread = Process(name=f"{self.device_name} HTTP Command Endpoint", target=self.flask_app.run, kwargs={"port": self.port})
self.http_thread.start()
print(f"{self.device_name} HTTP command endpoint is running at http://localhost:{self.port}")
return True
except:
print(f"Unable to start {self.device_name} HTTP command endpoint at http://localhost:{self.port}")
return False
def check_console_msgs(self):
'''
Read device output for debug messages and state variable updates. Record debug messages
to the logging file, and update the console's record of the state.
'''
while self.running_logger:
try:
# Read line coming from device and parse it
if self.console.inWaiting() > 0:
line = self.console.readline().rstrip()
self.raw_logger.put("Received: " + line.decode("utf-8"))
else:
continue
data = json.loads(line)
data['time'] = str(self.start_time + datetime.timedelta(milliseconds=data['t']))
if 'msg' in data:
# The logline represents a debugging message created by Flight Software. Report the message to the logger.
logline = f"[{data['time']}] ({data['svrty']}) {data['msg']}"
self.logger.put(logline, add_time = False)
elif 'telem' in data:
logline = f"[{data['time']}] Received requested telemetry from spacecraft.\n"
logline += data['telem']
print("\n" + logline)
self.logger.put(logline, add_time = False)
#log data to a timestamped file
telem_bytes = data['telem'].split(r'\x')
telem_bytes.remove("")
telem_file = open(os.path.join(self.telem_save_dir ,f"telem[{data['time']}].txt"), "wb")
for byte in telem_bytes:
telem_file.write(int(byte, 16).to_bytes(1, byteorder='big'))
telem_file.close()
elif 'uplink' in data:
if data['uplink'] and data['len']:
logline = f"[{data['time']}] Successfully sent telemetry to FlightSoftware.\n"
logline += str(data['uplink'])
else:
logline = f"[{data['time']}] Failed to send telemetry to FlightSoftware."
print("\n" + logline)
self.logger.put(logline, add_time = False)
else:
if 'err' in data:
# The log line represents an error in retrieving or writing state data that
# was caused by a USBSession client improperly setting/retrieving a value.
# Report this failure to the logger.
logline = f"[{data['time']}] (ERROR) Tried to {data['mode']} state value named \"{data['field']}\" but encountered an error: {data['err']}"
self.logger.put(logline, add_time = False)
data['val'] = None
else:
# A valid telemetry field was returned. Manage it.
self.datastore.put(data)
self.field_responses.put(data)
except ValueError:
logline = f'[RAW] {line}'
self.logger.put(logline)
except serial.SerialException:
print('Error: unable to read serial port for {}. Exiting.'.
format(self.device_name))
self.disconnect()
except:
traceback.print_exc()
print('Unspecified error. Exiting.')
self.disconnect()
def _wait_for_state(self, field, timeout = None):
"""
Helper function used by both read_state and write_state to wait for a desired value
to be reported back by the connected device.
"""
self.field_requests.put(field)
try:
data = self.field_responses.get(True, timeout)
return data['val']
except queue.Empty:
return None
def read_state(self, field, timeout = None):
'''
Read state.
Read the value of the state field associated with the given field name on the flight controller.
'''
if not self.running_logger: return
json_cmd = {'mode': ord('r'), 'field': str(field)}
json_cmd = json.dumps(json_cmd) + "\n"
self.device_write_lock.acquire()
self.console.write(json_cmd.encode())
self.device_write_lock.release()
self.raw_logger.put("Sent: " + json_cmd.rstrip())
return self._wait_for_state(field)
def str_to_val(self, field):
'''
Automatically detects floats, ints and bools
Returns a float, int or bool
'''
if 'nan' in field:
return float("NAN")
elif '.' in field:
return float(field)
elif field == 'true':
return True
elif field == 'false':
return False
else:
return int(field)
def smart_read(self, field, **kwargs):
'''
Turns a string state field read into the actual desired vals.
Returns list of vals, or the val itself. Vals can be bools, ints, or floats.
Raises NameError if no state field was found.
'''
ret = self.read_state(field, kwargs.get('timeout'))
if ret is None:
raise NameError(f"State field: {field} not found.")
# begin type inference
if ',' in ret:
# ret is a list
list_of_strings = ret.split(',')
list_of_strings = [x for x in list_of_strings if x is not '']
list_of_vals = [self.str_to_val(x) for x in list_of_strings]
return list_of_vals
else:
return self.str_to_val(ret)
def _write_state_basic(self, fields, vals, timeout = None):
'''
Write multiple state fields to the device at once.
'''
if not self.running_logger: return
assert len(fields) == len(vals)
assert len(fields) <= 20, "Flight Software can't handle more than 20 state field writes at a time"
json_cmds = ""
for field, val in zip(fields, vals):
json_cmd = {
'mode': ord('w'),
'field': str(field),
'val': str(val)
}
json_cmd = json.dumps(json_cmd) + "\n"
json_cmds += json_cmd
if len(json_cmds) >= 512:
print("Error: Flight Software can't handle input buffers >= 512 bytes.")
return False
self.device_write_lock.acquire()
self.console.write(json_cmds.encode())
self.device_write_lock.release()
self.raw_logger.put("Sent: " + json_cmds)
returned_vals = []
for field in fields:
returned_vals.append(self._wait_for_state(field, timeout))
if returned_vals[0] is None:
return False
returned_vals = returned_vals[0].split(",")
returned_vals = [x for x in returned_vals if x is not ""]
if (returned_vals[0].replace('.','').replace('-','')).isnumeric():
numeric_returned_vals = [float(x) for x in returned_vals]
if type(vals[0]) == str:
vals = vals[0]
vals = [float(x) for x in vals.split(",") if x is not '']
return numeric_returned_vals == vals
return returned_vals == vals
def write_multiple_states(self, fields, vals, timeout=None):
'''
Write multiple states and check the write operation with feedback.
Overwrite the value of the state field with the given state field name on the flight computer, and
then verify that the state was actually set. Do not write the state if the variable is being overriden
by the user. (This is the function that sim should exclusively use.)
'''
# Filter out fields that are being overridden by the user
field_val_pairs = [
field_val_pair for field_val_pair in zip(fields, vals)
if field_val_pair[0] not in self.overriden_variables
]
fields, vals = zip(*field_val_pairs)
return self._write_state_basic(list(fields), list(vals), timeout)
def _val_to_str(self, val):
'''
Convert a state value or list of values into a single string writable to
a state.
Currently, the supported types are integers, doubles, integer vectors,
double vectors, and booleans.
'''
if type(val) not in (list, tuple):
if type(val) is bool:
return 'true' if val else 'false'
else:
return str(val)
else:
val_str = ''
for _val in val:
val_str += self._val_to_str(_val) + ', '
return val_str[:len(val_str) - 2]
def write_state(self, field, *args, **kwargs):
'''
Write state and check write operation with feedback.
Overwrite the value of the state field with the given state field name on the flight computer, and
then verify that the state was actually set. Do not write the state if the variable is being overriden
by the user. (This is a function that sim should exclusively use.)
'''
return self.write_multiple_states([field], [self._val_to_str(args)], kwargs.get('timeout'))
def send_uplink(self, filename):
'''
Gets the uplink packet | |
from __future__ import unicode_literals
import unittest
import chance
import chance_exceptions
import datetime
import re
import dictionaries
from chance import text_type
class TestChanceBooleanFunction(unittest.TestCase):
def test_boolean_returns_bool(self):
for x in range(0, 200):
self.assertTrue(isinstance(chance.boolean(), bool))
def test_likelihood_50_approximately_result(self):
true_values, false_values = 0, 0
iterations = 1000000
likelihood = 0.5
infelicity = 0.1
for x in range(0, iterations):
if chance.boolean(int(likelihood*100)):
true_values += 1
else:
false_values += 1
res = float(true_values) / false_values
self.assertTrue(res > (likelihood - infelicity))
def test_likelihood_80_approximately_result(self):
true_values, false_values = 0, 0
iterations = 10000
likelihood = 0.8
infelicity = 0.1
for x in range(0, iterations):
if chance.boolean(int(likelihood*100)):
true_values += 1
else:
false_values += 1
res = float(true_values) / false_values
self.assertTrue(res > (likelihood - infelicity))
def test_likelihood_10_approximately_result(self):
true_values, false_values = 0, 0
iterations = 10000
likelihood = 0.1
infelicity = 0.1
for x in range(0, iterations):
if chance.boolean(int(likelihood * 100)):
true_values += 1
else:
false_values += 1
res = float(true_values) / false_values
self.assertTrue(res > (likelihood - infelicity))
def test_boolean_raise_wrong_argument_exception(self):
wrongs = (-1, -.1, 101, 101.1, 'a', 'b', '!')
for x in wrongs:
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.boolean, x)
class TestChanceCharacterFunction(unittest.TestCase):
def test_character_returns_character(self):
chars = 'abcdefghijklmnopqrstuvwxyz!@#$%^&*()[]'
chars += chars.upper()
for x in range(100):
ch = chance.character()
self.assertTrue(chars.find(ch) >= 0)
def test_character_returns_character_default_params(self):
chars = 'abcdefghijklmnopqrstuvwxyz!@#$%^&*()[]'
chars += chars.upper()
for x in range(100):
ch = chance.character()
self.assertTrue(chars.find(ch) >= 0)
def test_character_returns_character_default_symbols_false(self):
chars = 'abcdefghijklmnopqrstuvwxyz!@#$%^&*()[]'
chars += chars.upper()
for x in range(100):
ch = chance.character(symbols=False)
self.assertTrue(chars.find(ch) >= 0)
def test_character_returns_default_numbers_true(self):
chars = 'abcdefghijklmnopqrstuvwxyz!@#$%^&*()[]'
chars += chars.upper()
chars += '1234567890'
for x in range(100):
ch = chance.character(symbols=False)
self.assertTrue(chars.find(ch) >= 0)
def test_character_returns_only_symbols(self):
chars = '!@#$%^&*()[]'
for x in range(100):
ch = chance.character(symbols=True, alpha=False)
self.assertTrue(chars.find(ch) >= 0)
def test_character_returns_character_only_symbols_and_numbers(self):
chars = '!@#$%^&*()[]'
chars += '1234567890'
for x in range(100):
ch = chance.character(symbols=True, alpha=False, numbers=True)
self.assertTrue(chars.find(ch) >= 0)
def test_character_returns_only_alpha_and_numbers(self):
chars = 'abcdefghijklmnopqrstuvwxyz'
chars += chars.upper()
chars += '1234567890'
for x in range(100):
ch = chance.character(symbols=False, alpha=True, numbers=True)
self.assertTrue(chars.find(ch) >= 0)
def test_character_returns_only_uppercase_alpha(self):
chars = 'abcdefghijklmnopqrstuvwxyz'.upper()
for x in range(100):
ch = chance.character(case='upper', symbols=False, numbers=False)
self.assertTrue(chars.find(ch) >= 0)
def test_character_returns_only_uppercase_alpha_and_symbols(self):
chars = 'abcdefghijklmnopqrstuvwxyz'.upper()
chars += '!@#$%^&*()[]'
for x in range(100):
ch = chance.character(case='upper', symbols=True, numbers=False)
self.assertTrue(chars.find(ch) >= 0)
def test_character_returns_only_uppercase_alpha_and_numbers(self):
chars = 'abcdefghijklmnopqrstuvwxyz'.upper()
chars += '1234567890'
for x in range(100):
ch = chance.character(case='upper', symbols=False, numbers=True)
self.assertTrue(chars.find(ch) >= 0)
def test_character_returns_only_uppercase_alpha_with_symbols_and_numbers(self):
chars = 'abcdefghijklmnopqrstuvwxyz'.upper()
chars += '!@#$%^&*()[]'
chars += '1234567890'
for x in range(100):
ch = chance.character(case='upper', symbols=True, numbers=True)
self.assertTrue(chars.find(ch) >= 0)
def test_character_returns_only_lower_alpha_with_symbols_and_numbers(self):
chars = 'abcdefghijklmnopqrstuvwxyz'
chars += '!@#$%^&*()[]'
chars += '1234567890'
for x in range(100):
ch = chance.character(case='lower', symbols=True, numbers=True)
self.assertTrue(chars.find(ch) >= 0)
def test_character_returns_only_lowecase_alpha(self):
chars = 'abcdefghijklmnopqrstuvwxyz'
for x in range(100):
ch = chance.character(case='lower', symbols=False, numbers=False)
self.assertTrue(chars.find(ch) >= 0)
def test_character_returns_only_lowercase_alpha_and_symbols(self):
chars = 'abcdefghijklmnopqrstuvwxyz'
chars += '!@#$%^&*()[]'
for x in range(100):
ch = chance.character(case='lower', symbols=True, numbers=False)
self.assertTrue(chars.find(ch) >= 0)
def test_character_returns_only_lowercase_alpha_and_numbers(self):
chars = 'abcdefghijklmnopqrstuvwxyz'
chars += '1234567890'
for x in range(100):
ch = chance.character(case='lower', symbols=False, numbers=True)
self.assertTrue(chars.find(ch) >= 0)
def test_character_raise_exception(self):
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.character, 10)
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.character, -1)
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.character, -.25)
self.assertRaises(chance_exceptions.DictionaryException, chance.character, **{'language': 'bbdasasdg'})
self.assertRaises(chance_exceptions.DictionaryException, chance.character, **{'language': 'ff'})
class TestStringFunction(unittest.TestCase):
def test_string_returns_string(self):
for x in range(100):
self.assertTrue(isinstance(chance.string(), text_type))
def test_string_returns_string_with_correct_length(self):
for x in range(1, 100):
self.assertTrue(len(chance.string(length=x)) == x)
def test_string_returns_string_with_correct_min_max(self):
for x in range(1, 100):
l = len(chance.string(minimum=x, maximum=x+5))
self.assertTrue(x <= l <= (x+5))
def test_string_returns_string_from_correct_pool(self):
pools = (
'abcdef',
'hjfj2131',
'$553\&66hjfj2131',
'=_-232fdsf',
)
for pool in pools:
s = chance.string(pool=pool)
for x in s:
self.assertTrue(pool.find(x) != -1)
def test_string_raises_exception(self):
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.string, -1)
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.string, -.1)
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.string, 0)
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.string, 1)
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.string, .1)
self.assertRaises(chance_exceptions.DictionaryException, chance.string, **{'language': 'dfsdf'})
class TestSyllableFunction(unittest.TestCase):
def test_syllable_returns_correct_string(self):
for x in range(20):
syll = chance.syllable(x+1)
n = syll[0]
nxt = dictionaries.vowels['en'] if dictionaries.consonants['en'].find(n) != -1 else \
dictionaries.vowels['en']
prv = dictionaries.vowels['en'] if dictionaries.vowels['en'].find(n) != -1 \
else dictionaries.consonants['en']
for i, ch in enumerate(syll):
if i == 0 or i == (len(syll)-1):
continue
self.assertFalse(nxt.find(ch) == -1)
nxt, prv = prv, nxt
def test_syllable_returns_correct_starting_string(self):
for x in range(20):
syll = chance.syllable(x+1, vowel_first=True)
n = syll[0]
self.assertFalse(dictionaries.vowels['en'].find(n) == -1)
nxt = dictionaries.consonants['en']
prv = dictionaries.vowels['en']
for i, ch in enumerate(syll):
if i == 0 or i == (len(syll)-1):
continue
self.assertFalse(nxt.find(ch) == -1)
nxt, prv = prv, nxt
for x in range(20):
syll = chance.syllable(x+1, vowel_first=False)
n = syll[0]
self.assertFalse(dictionaries.consonants['en'].find(n) == -1)
nxt = dictionaries.vowels['en']
prv = dictionaries.consonants['en']
for i, ch in enumerate(syll):
if i == 0 or i == (len(syll)-1):
continue
self.assertFalse(nxt.find(ch) == -1)
nxt, prv = prv, nxt
def test_syllable_raises_exception(self):
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.syllable, 'a')
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.syllable, dict())
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.syllable, -1)
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.syllable, 1.5)
self.assertRaises(chance_exceptions.DictionaryException, chance.syllable, **{'language': 'dasdas'})
class TestWordFunction(unittest.TestCase):
def test_word_returns_correct_value(self):
for x in range(20):
word = chance.word()
self.assertEquals(text_type, type(word))
self.assertTrue(3 < len(word) < 10)
def test_word_raises_exception(self):
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.word, 'a')
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.word, dict())
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.word, -1)
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.word, 1.5)
self.assertRaises(chance_exceptions.DictionaryException, chance.word, **{'language': 'dasdas'})
class TestSentenceFunction(unittest.TestCase):
def test_sentence_returns_correct_value(self):
for x in range(20):
self.assertTrue(isinstance(chance.sentence(), text_type))
length = len(chance.sentence())
self.assertTrue(45 <= length <= 324)
for x in range(50):
self.assertEqual(text_type, type(chance.sentence(x+1)))
def test_sentence_returns_correct_endings(self):
end_pool = '?!.:'
for x in end_pool:
self.assertEqual(x, chance.sentence(ended_by=x)[-1:])
last = chance.sentence(ended_by=end_pool)[-1:]
self.assertTrue(end_pool.find(last) != -1)
def test_sentence_raises_exception(self):
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.sentence, 'a')
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.sentence, dict())
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.sentence, -1)
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.sentence, 1.5)
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.sentence, 5, 12)
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.sentence, 9, 18)
self.assertRaises(chance_exceptions.DictionaryException, chance.sentence, **{'language': 'dasdas'})
class TestParagraphFunction(unittest.TestCase):
def test_pragraph_returns_correct_value(self):
for x in range(20):
self.assertEquals(text_type, type(chance.paragraph()))
length = len(chance.paragraph())
self.assertTrue(length >= 45)
class TestAgeFunction(unittest.TestCase):
def test_age_returns_correct_value(self):
for x in range(20):
self.assertEquals(int, type(chance.age()))
a = chance.age('child')
self.assertTrue(1 <= a <= 12)
a = chance.age('teen')
self.assertTrue(13 <= a <= 19)
a = chance.age('adult')
self.assertTrue(18 <= a <= 120)
a = chance.age('senior')
self.assertTrue(65 <= a <= 120)
a = chance.age()
self.assertTrue(1 <= a <= 120)
def test_age_raises_exception(self):
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.age, 'i\'m')
class TestDateFunction(unittest.TestCase):
def test_date_returns_correct_value(self):
for x in range(20):
self.assertEquals(datetime.datetime, type(chance.date()))
class TestBirthdayFunction(unittest.TestCase):
def test_birthday_returns_correct_value(self):
current_year = datetime.date.today().year
for x in range(20):
self.assertEquals(datetime.date, type(chance.birthday()))
self.assertTrue(datetime.date(current_year - 121, 1, 1) < chance.birthday())
self.assertTrue(datetime.date(current_year - 13, 1, 1) < chance.birthday('child'))
self.assertTrue(datetime.date(current_year - 20, 1, 1) < chance.birthday('teen'))
self.assertTrue(datetime.date(current_year + 13, 1, 1) > chance.birthday('teen'))
self.assertTrue(datetime.date(current_year + 20, 1, 1) > chance.birthday('teen'))
class TestFirstNameFunction(unittest.TestCase):
def test_first_returns_correct_value(self):
for x in range(20):
self.assertEquals(text_type, type(chance.first()))
def test_first_returns_only_gender_specified_name(self):
from dictionaries import first_names
names = first_names['en']
for x in range(20):
name = chance.first(gender='m')
self.assertTrue(name in names['m'])
for x in range(20):
name = chance.first(gender='female')
self.assertTrue(name in names['f'])
class TestLastNameFunction(unittest.TestCase):
def test_first_returns_correct_value(self):
for x in range(20):
self.assertEquals(text_type, type(chance.last()))
def test_first_returns_only_gender_specified_name(self):
from dictionaries import last_names
names = last_names['en']
for x in range(20):
name = chance.last(gender='m')
self.assertTrue(name in names['m'])
for x in range(20):
name = chance.last(gender='female')
self.assertTrue(name in names['f'])
class TestNameFunction(unittest.TestCase):
def test_name_returns_correct_value(self):
for x in range(20):
self.assertEquals(text_type, type(chance.name()))
def test_name_returns_only_gender_specified_name(self):
from dictionaries import last_names, first_names
first_names = first_names['en']
last_names = last_names['en']
for x in range(20):
name = chance.name(gender='m')
first, last = name.split(' ')
self.assertTrue(first in first_names['m'])
self.assertTrue(last in last_names['m'])
for x in range(20):
name = chance.name(gender='f')
first, last = name.split(' ')
self.assertTrue(first in first_names['f'])
self.assertTrue(last in last_names['f'])
def test_name_returns_only_language_specified_name(self):
from dictionaries import last_names, first_names
first_names = first_names['ru']
last_names = last_names['ru']
for x in range(200):
name = chance.name(gender='m', language='ru')
first, last = name.split(' ')
self.assertTrue(first in first_names['m'])
self.assertTrue(last in last_names['m'])
for x in range(200):
name = chance.name(gender='f', language='ru')
first, last = name.split(' ')
self.assertTrue(first in first_names['f'])
self.assertTrue(last in last_names['f'])
class TestHashFunction(unittest.TestCase):
def test_hash_returns_correct_value(self):
for x in range(20):
self.assertEquals(int, type(hash(chance.hex_hash())))
class TestColorFunction(unittest.TestCase):
def test_color_returns_correct_value(self):
hex_color_pattern = re.compile('^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$')
rgb_color_pattern = re.compile('rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)')
for x in range(20):
hex_color = chance.color(form='hex')
rgb_color = chance.color(form='rgb')
gray_color = chance.color(grayscale=True)
self.assertTrue(hex_color_pattern.match(hex_color) is not None)
self.assertTrue(hex_color_pattern.match(gray_color) is not None)
matches = rgb_color_pattern.findall(rgb_color)
self.assertTrue(len(matches) == 1)
self.assertTrue(len(matches[0]) == 3)
for y in matches[0]:
self.assertTrue(0 <= int(y) <= 255)
def test_color_raises_exception(self):
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.color, 'i\'m')
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.color, 'sitting')
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.color, 'in')
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.color, 'my')
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.color, 'room')
class TestDomainFunction(unittest.TestCase):
def test_domain_returns_correct_value(self):
domain_pattern = re.compile('^([A-Za-z0-9]+\.[a-z\.]{2,5})$')
for x in range(20):
self.assertTrue(domain_pattern.match(chance.domain()) is not None)
def test_domain_raises_exception(self):
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.domain, 2)
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.domain, 1)
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.domain, -1)
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.domain, .1)
class TestEmailFunction(unittest.TestCase):
def test_email_returns_correct_values(self):
email_pattern = re.compile('^([A-Za-z0-9]+@[A-Za-z0-9]+\.[a-z\.]{2,5})$')
for x in range(20):
self.assertTrue(email_pattern.match(chance.email()) is not None)
def test_email_raises_exception(self):
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.email, 2)
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.email, 1)
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.email, -1)
self.assertRaises(chance_exceptions.WrongArgumentValue, chance.email, .1)
class TestIpFunction(unittest.TestCase):
def test_ip_returns_correct_values(self):
ip_pattern = re.compile('^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$')
for x in range(20):
self.assertTrue(ip_pattern.match(chance.ip()) is not None)
class TestIpv6Function(unittest.TestCase):
def test_ip_returns_correct_values(self):
ipv6_pattern = re.compile('^([0-9a-z]{4}:)+[0-9a-z]{4}$')
for | |
<gh_stars>1-10
def normalize_and_rgb(images):
import numpy as np
#normalize image to 0-255 per image.
image_sum = 1/np.sum(np.sum(images,axis=1),axis=-1)
given_axis = 0
# Create an array which would be used to reshape 1D array, b to have
# singleton dimensions except for the given axis where we would put -1
# signifying to use the entire length of elements along that axis
dim_array = np.ones((1,images.ndim),int).ravel()
dim_array[given_axis] = -1
# Reshape b with dim_array and perform elementwise multiplication with
# broadcasting along the singleton dimensions for the final output
image_sum_reshaped = image_sum.reshape(dim_array)
images = images*image_sum_reshaped*255
# make it rgb by duplicating 3 channels.
images = np.stack([images, images, images],axis=-1)
return images
def image_with_label(train_file, istart,iend):
import tables
import numpy as np
f = tables.open_file(train_file, 'r')
a = np.array(f.root.img_pt)[istart:iend].copy() # Images
b = np.array(f.root.label)[istart:iend].copy() # Labels
f.close()
return normalize_and_rgb(a),b
def count_events(train_files):
import tables
n_events = 0
for train_file in train_files:
f = tables.open_file(train_file, 'r')
n_events += f.root.label.shape[0]
f.close()
return n_events
# Create a heatmap of the training file hits.
# Useful for visually confirming the data is well-distributed.
def test_heatmap(train_files, size=224):
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
a, b = image_with_label(train_files[0],0,200)
a = a[0:200:100]
b = b[0:200:100]
print(b)
new_a = np.swapaxes(a[:,:,:,0],0,2)
new_a = np.swapaxes(new_a,0,1)
c = np.dot(new_a,b[:,0])
d = np.dot(new_a,b[:,1])
width = size
height = size
fontsize = 120*size/64
plt.figure(figsize=(width,height))
ax = plt.subplot()
for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontsize(fontsize)
plt.imshow(c, norm=mpl.colors.LogNorm(), origin='lower', interpolation='nearest',label='top')
cbar = plt.colorbar(shrink=0.82)
cbar.ax.tick_params(labelsize=fontsize)
cbar.set_label(r'$p_T$', fontsize=fontsize)
plt.xlabel(r'$i\eta$', fontsize=fontsize)
plt.ylabel(r'$i\phi$', fontsize=fontsize)
plt.savefig('top.pdf')
plt.figure(figsize=(width,height))
ax = plt.subplot()
for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontsize(fontsize)
plt.imshow(d, norm=mpl.colors.LogNorm(), origin='lower', interpolation='nearest',label='QCD')
cbar = plt.colorbar(shrink=0.82)
cbar.ax.tick_params(labelsize=fontsize)
cbar.set_label(r'$p_T$', fontsize=fontsize)
plt.xlabel(r'$i\eta$', fontsize=fontsize)
plt.ylabel(r'$i\phi$', fontsize=fontsize)
plt.savefig('QCD.pdf')
def preprocess_images(size=64):
import tensorflow as tf
# Create a placeholder for our incoming images
in_height = size
in_width = size
in_images = tf.placeholder(tf.float32)
in_images.set_shape([None, in_height, in_width, 3])
# Resize those images to fit our featurizer
if size==64:
out_width = 224
out_height = 224
image_tensors = tf.image.resize_images(in_images, [out_height,out_width])
image_tensors = tf.to_float(image_tensors)
elif size==224:
image_tensors = in_images
return in_images, image_tensors
def construct_classifier():
from keras.layers import Dropout, Dense, Flatten, Input
from keras.models import Model
from keras import backend as K
import tensorflow as tf
K.set_session(tf.get_default_session())
FC_SIZE = 1024
NUM_CLASSES = 2
in_layer = Input(shape=(1, 1, 2048,),name='input_1')
x = Dense(FC_SIZE, activation='relu', input_dim=(1, 1, 2048,),name='dense_1')(in_layer)
x = Flatten(name='flatten_1')(x)
preds = Dense(NUM_CLASSES, activation='softmax', input_dim=FC_SIZE, name='classifier_output')(x)
model = Model(inputs = in_layer, outputs = preds)
return model
def construct_model(quantized, saved_model_dir=None, starting_weights_directory=None, is_frozen=False, is_training=True, size=64):
from azureml.contrib.brainwave.models import Resnet50, QuantizedResnet50
import tensorflow as tf
from keras import backend as K
# Convert images to 3D tensors [width,height,channel]
in_images, image_tensors = preprocess_images(size=size)
# Construct featurizer using quantized or unquantized ResNet50 model
if not quantized:
featurizer = Resnet50(saved_model_dir, is_frozen=is_frozen, custom_weights_directory = starting_weights_directory)
else:
featurizer = QuantizedResnet50(saved_model_dir, is_frozen=is_frozen, custom_weights_directory = starting_weights_directory)
features = featurizer.import_graph_def(input_tensor=image_tensors, is_training=is_training)
# Construct classifier
with tf.name_scope('classifier'):
classifier = construct_classifier()
preds = classifier(features)
# Initialize weights
sess = tf.get_default_session()
tf.global_variables_initializer().run()
if not is_frozen:
featurizer.restore_weights(sess)
if starting_weights_directory is not None:
print("loading classifier weights from", starting_weights_directory+'/class_weights_best.h5')
classifier.load_weights(starting_weights_directory+'/class_weights_best.h5')
return in_images, image_tensors, features, preds, featurizer, classifier
def check_model(preds, features, in_images, train_files, classifier):
import tensorflow as tf
from keras import backend as K
sess = tf.get_default_session()
in_labels = tf.placeholder(tf.float32, shape=(None, 2))
a, b = image_with_label(train_files[0],0,1)
c = classifier.layers[-1].weights[0]
d = classifier.layers[-1].weights[1]
print(" image: ", a)
print(" label: ", b)
print(" features: ", sess.run(features, feed_dict={in_images: a,
in_labels: b,
K.learning_phase(): 0}))
print(" weights: ", sess.run(c))
print(" biases: ", sess.run(d))
print(" preds: ", sess.run(preds, feed_dict={in_images: a,
in_labels: b,
K.learning_phase(): 0}))
def chunks(files, chunksize, max_q_size=4, shuffle=True):
"""Yield successive n-sized chunks from a and b."""
import tables
import numpy as np
for train_file in files:
f = tables.open_file(train_file, 'r')
nrows = f.root.label.nrows
for istart in range(0,nrows,max_q_size*chunksize):
a = np.array(f.root.img_pt[istart:istart+max_q_size*chunksize]) # Images
b = np.array(f.root.label[istart:istart+max_q_size*chunksize]) # Labels
if shuffle:
c = np.c_[a.reshape(len(a), -1), b.reshape(len(b), -1)] # shuffle within queue size
np.random.shuffle(c)
test_images = c[:, :a.size//len(a)].reshape(a.shape)
test_labels = c[:, a.size//len(a):].reshape(b.shape)
else:
test_images = a
test_labels = b
for jstart in range(0,len(test_labels),chunksize):
yield normalize_and_rgb(test_images[jstart:jstart+chunksize].copy()),test_labels[jstart:jstart+chunksize].copy(), len(test_labels[jstart:jstart+chunksize].copy())
f.close()
def train_model(preds, in_images, train_files, val_files, is_retrain = False, train_epoch = 10, classifier=None, saver=None, checkpoint_path=None, chunk_size=64):
""" training model """
import tensorflow as tf
from keras import backend as K
from keras.objectives import binary_crossentropy
from keras.metrics import categorical_accuracy
from tqdm import tqdm
learning_rate = 0.0001 if is_retrain else 0.001
# Specify the loss function
in_labels = tf.placeholder(tf.float32, shape=(None, 2))
with tf.name_scope('xent'):
cross_entropy = tf.reduce_mean(binary_crossentropy(in_labels, preds))
with tf.name_scope('train'):
#optimizer_def = tf.train.GradientDescentOptimizer(learning_rate)
#momentum = 0.9
#optimizer_def = tf.train.MomentumOptimizer(learning_rate, momentum, use_nesterov=True)
optimizer_def = tf.train.AdamOptimizer(learning_rate)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
optimizer = optimizer_def.minimize(cross_entropy)
with tf.name_scope('metrics'):
accuracy = tf.reduce_mean(categorical_accuracy(in_labels, preds))
auc = tf.metrics.auc(tf.cast(in_labels, tf.bool), preds)
sess = tf.get_default_session()
# to re-initialize all variables
#sess.run(tf.group(tf.local_variables_initializer(),tf.global_variables_initializer()))
# to re-initialize just local variables + optimizer variables
sess.run(tf.group(tf.local_variables_initializer(),tf.variables_initializer(optimizer_def.variables())))
# Create a summary to monitor cross_entropy loss
tf.summary.scalar("loss", cross_entropy)
# Create a summary to monitor accuracy
tf.summary.scalar("accuracy", accuracy)
# Create a summary to monitor auc
tf.summary.scalar("auc", auc[0])
# create a summary to look at input images
tf.summary.image("images", in_images, 3)
# Create summaries to visualize batchnorm variables
tensors_per_node = [node.values() for node in tf.get_default_graph().get_operations()]
bn_tensors = [tensor for tensors in tensors_per_node for tensor in tensors if 'BatchNorm/moving_mean:0' in tensor.name or 'BatchNorm/moving_variance:0' in tensor.name or 'BatchNorm/gamma:0' in tensor.name or 'BatchNorm/beta:0' in tensor.name]
for var in bn_tensors:
tf.summary.histogram(var.name.replace(':','_'), var)
#grads = tf.gradients(cross_entropy, tf.trainable_variables())
#grads = list(zip(grads, tf.trainable_variables()))
# Summarize all gradients
#for grad, var in grads:
# tf.summary.histogram(var.name.replace(':','_') + '/gradient', grad)
# Merge all summaries into a single op
merged_summary_op = tf.summary.merge_all()
n_train_events = count_events(train_files)
train_chunk_num = int(n_train_events / chunk_size)+1
train_writer = tf.summary.FileWriter(checkpoint_path + '/logs/train', sess.graph)
val_writer = tf.summary.FileWriter(checkpoint_path + '/logs/val', sess.graph)
loss_over_epoch = []
accuracy_over_epoch = []
auc_over_epoch = []
val_loss_over_epoch = []
val_accuracy_over_epoch = []
val_auc_over_epoch = []
best_val_loss = 999999
is_training = tf.get_default_graph().get_tensor_by_name('is_training:0')
for epoch in range(train_epoch):
avg_loss = 0
avg_accuracy = 0
avg_auc = 0
preds_temp = []
label_temp = []
i = 0
for img_chunk, label_chunk, real_chunk_size in tqdm(chunks(train_files, chunk_size),total=train_chunk_num):
_, loss, summary, accuracy_result, auc_result = sess.run([optimizer,
cross_entropy,
merged_summary_op,
accuracy, auc],
feed_dict={in_images: img_chunk,
in_labels: label_chunk,
K.learning_phase(): 1,
is_training: True})
avg_loss += loss * real_chunk_size / n_train_events
avg_accuracy += accuracy_result * real_chunk_size / n_train_events
avg_auc += auc_result[0] * real_chunk_size / n_train_events
train_writer.add_summary(summary, epoch * train_chunk_num + i)
i += 1
print("Epoch:", (epoch + 1), "loss = ", "{:.3f}".format(avg_loss))
print("Training Accuracy:", "{:.3f}".format(avg_accuracy), ", Area under ROC curve:", "{:.3f}".format(avg_auc))
loss_over_epoch.append(avg_loss)
accuracy_over_epoch.append(avg_accuracy)
auc_over_epoch.append(avg_auc)
n_val_events = count_events(val_files)
val_chunk_num = int(n_val_events / chunk_size)+1
avg_val_loss = 0
avg_val_accuracy = 0
avg_val_auc = 0
i = 0
for img_chunk, label_chunk, real_chunk_size in tqdm(chunks(val_files, chunk_size),total=val_chunk_num):
val_loss, val_accuracy_result, val_auc_result, summary = sess.run([cross_entropy, accuracy, auc, merged_summary_op],
feed_dict={in_images: img_chunk,
in_labels: label_chunk,
K.learning_phase(): 0,
is_training: False})
avg_val_loss += val_loss * real_chunk_size / n_val_events
avg_val_accuracy += val_accuracy_result * real_chunk_size / n_val_events
avg_val_auc += val_auc_result[0] * real_chunk_size / n_val_events
val_writer.add_summary(summary, epoch * val_chunk_num + i)
i += 1
print("Epoch:", (epoch + 1), "val_loss = ", "{:.3f}".format(avg_val_loss))
print("Validation Accuracy:", "{:.3f}".format(avg_val_accuracy), ", Area under ROC curve:", "{:.3f}".format(avg_val_auc))
val_loss_over_epoch.append(avg_val_loss)
val_accuracy_over_epoch.append(avg_val_accuracy)
val_auc_over_epoch.append(avg_val_auc)
if saver is not None and checkpoint_path is not None and classifier is not None:
saver.save(sess, checkpoint_path+'/resnet50_bw', write_meta_graph=True, global_step = epoch)
saver.save(sess, checkpoint_path+'/resnet50_bw', write_meta_graph=True)
classifier.save_weights(checkpoint_path+'/class_weights-%s.h5'%epoch)
classifier.save(checkpoint_path+'/class_model-%s.h5'%epoch)
classifier.save_weights(checkpoint_path+'/class_weights.h5')
classifier.save(checkpoint_path+'/class_model.h5')
if avg_val_loss < best_val_loss:
print("new best model")
best_val_loss = avg_val_loss
saver.save(sess, checkpoint_path+'/resnet50_bw_best', write_meta_graph=True)
classifier.save_weights(checkpoint_path+'/class_weights_best.h5')
classifier.save(checkpoint_path+'/class_model_best.h5')
return loss_over_epoch, accuracy_over_epoch, auc_over_epoch, val_loss_over_epoch, val_accuracy_over_epoch, val_auc_over_epoch
def test_model(preds, in_images, test_files, chunk_size=64, shuffle=True):
"""Test the model"""
import tensorflow as tf
from keras import backend as K
from keras.objectives import binary_crossentropy
import numpy as np
from keras.metrics import categorical_accuracy
from tqdm import tqdm
in_labels = tf.placeholder(tf.float32, shape=(None, 2))
cross_entropy = tf.reduce_mean(binary_crossentropy(in_labels, preds))
accuracy = tf.reduce_mean(categorical_accuracy(in_labels, preds))
auc = tf.metrics.auc(tf.cast(in_labels, tf.bool), preds)
n_test_events = count_events(test_files)
chunk_num | |
models.DecimalField(default=0, max_digits=2, decimal_places=1, blank=True, null=True)
number_of_films_as_actor = models.PositiveIntegerField(default=0)
number_of_ratings_as_actor = models.PositiveIntegerField(default=0)
average_rating_as_actor = models.DecimalField(default=0, max_digits=2, decimal_places=1, blank=True, null=True)
number_of_films_as_director = models.PositiveIntegerField(default=0)
number_of_ratings_as_director = models.PositiveIntegerField(default=0)
average_rating_as_director = models.DecimalField(default=0, max_digits=2, decimal_places=1, blank=True, null=True)
main_picture = models.ForeignKey('Picture', blank=True, null=True, related_name='main_artist_picture', on_delete=models.SET_NULL)
def __unicode__(self):
return self.name
class Meta:
ordering = ['name']
def num_rating(self):
return sum([f.number_of_ratings for f in self.films.all()])
def save(self, *args, **kwargs):
self.slug_cache = slugify(self.name)
super(Artist, self).save(*args, **kwargs)
@classmethod
def get_artist_by_name(cls, name): # case and more importantly accent sensitive getter
artist_list = [artist for artist in cls.objects.filter(name=name) if artist.name == name]
if artist_list:
return artist_list[0]
return None
def calculate_main_picture(self, exclude=None):
for pic in sorted(self.picture_set.all(), key=lambda pic: (-pic.film.number_of_ratings if pic.film else 0, pic.id)):
if pic.number_of_artists == 1 and (exclude is None or exclude != pic.id):
return pic
return None
class FilmArtistRelationship(models.Model):
film = models.ForeignKey(Film)
artist = models.ForeignKey(Artist)
ROLE_TYPE_DIRECTOR = 'D'
ROLE_TYPE_ACTOR = 'A'
ROLE_TYPES = [
(ROLE_TYPE_DIRECTOR, 'Director'),
(ROLE_TYPE_ACTOR, 'Actor/actress'),
]
ACTOR_SUBTYPE_FULL = 'F'
ACTOR_SUBTYPE_VOICE = 'V'
ACTOR_SUBTYPES = [
(ACTOR_SUBTYPE_FULL, 'Full'),
(ACTOR_SUBTYPE_VOICE, 'Voice'),
]
role_type = models.CharField(max_length=1, choices=ROLE_TYPES, default=ROLE_TYPE_DIRECTOR)
actor_subtype = models.CharField(max_length=1, choices=ACTOR_SUBTYPES, default=ACTOR_SUBTYPE_FULL)
role_name = models.CharField(max_length=250, blank=True)
slug_cache = models.CharField(max_length=250, blank=True)
created_by = models.ForeignKey(KTUser, blank=True, null=True, on_delete=models.SET_NULL)
created_at = models.DateTimeField(auto_now_add=True)
main_picture = models.ForeignKey('Picture', blank=True, null=True, related_name='main_role_picture', on_delete=models.SET_NULL)
is_main_role = models.BooleanField(default=False)
def __unicode__(self):
return self.role_type + '[' + self.role_name + ']:' + unicode(self.film) + '/' + unicode(self.artist)
def save(self, *args, **kwargs):
self.slug_cache = slugify(self.role_name)
super(FilmArtistRelationship, self).save(*args, **kwargs)
ids = []
slugs = []
names = []
for idx, d in enumerate(self.film.directors()[:4]):
if idx == 3:
ids.append('') # indicate that there are more than 3 directors
else:
ids.append(unicode(d.id))
slugs.append(d.slug_cache)
names.append(d.name)
if len(ids):
self.film.directors_cache = ('%s;%s;%s' % (','.join(ids), ','.join(slugs), ','.join(names)))[:250]
self.film.director_names_cache = ','.join(names)[:250]
else:
self.film.directors_cache = ''
self.film.director_names_cache = ''
self.film.number_of_actors = FilmArtistRelationship.objects.filter(film_id=self.film, role_type=FilmArtistRelationship.ROLE_TYPE_ACTOR).count()
self.film.save(update_fields=['directors_cache', 'director_names_cache', 'number_of_actors'])
@receiver(post_delete, sender=FilmArtistRelationship)
def delete_role(sender, instance, **kwargs):
instance.film.number_of_actors = FilmArtistRelationship.objects.filter(film_id=instance.film, role_type=FilmArtistRelationship.ROLE_TYPE_ACTOR).count()
instance.film.save(update_fields=['number_of_actors'])
class Biography(models.Model):
artist = models.ForeignKey(Artist)
created_by = models.ForeignKey(KTUser, blank=True, null=True, on_delete=models.SET_NULL)
created_at = models.DateTimeField(auto_now_add=True)
content = models.TextField() # original w bbcode
content_html = models.TextField() # autogenerated from content
content_old_html = models.TextField(blank=True) # migrated from old db
approved = models.BooleanField(default=False)
snippet = models.TextField(blank=True)
def save(self, *args, **kwargs):
self.content = strip_tags(self.content)
self.content_html = kt_utils.bbcode_to_html(self.content)
self.snippet = strip_tags(self.content_html)[:500]
super(Biography, self).save(*args, **kwargs)
self.created_by.number_of_bios = Biography.objects.filter(created_by=self.created_by, approved=True).count()
self.created_by.save(update_fields=['number_of_bios'])
def __unicode__(self):
return self.content[:50]
class Meta:
ordering = ['-created_at']
get_latest_by = 'created_at'
@receiver(post_delete, sender=Biography)
def delete_biography(sender, instance, **kwargs):
instance.created_by.number_of_bios = Biography.objects.filter(created_by=instance.created_by, approved=True).count()
instance.created_by.save(update_fields=['number_of_bios'])
class Keyword(models.Model):
name = models.CharField(max_length=250)
KEYWORD_TYPE_COUNTRY = 'C'
KEYWORD_TYPE_GENRE = 'G'
KEYWORD_TYPE_MAJOR = 'M'
KEYWORD_TYPE_OTHER = 'O'
KEYWORD_TYPES = [
(KEYWORD_TYPE_COUNTRY, 'Country'),
(KEYWORD_TYPE_GENRE, 'Genre'),
(KEYWORD_TYPE_MAJOR, 'Major'),
(KEYWORD_TYPE_OTHER, 'Other'),
]
keyword_type = models.CharField(max_length=1, choices=KEYWORD_TYPES, default=KEYWORD_TYPE_OTHER)
films = models.ManyToManyField(Film, through='FilmKeywordRelationship')
slug_cache = models.CharField(max_length=250, blank=True)
created_by = models.ForeignKey(KTUser, blank=True, null=True, on_delete=models.SET_NULL)
created_at = models.DateTimeField(auto_now_add=True)
old_imdb_name = models.CharField(max_length=250, blank=True)
def __unicode__(self):
return self.keyword_type + ':' + self.name
class Meta:
ordering = ['keyword_type', 'name']
def save(self, *args, **kwargs):
self.slug_cache = slugify(self.name)
super(Keyword, self).save(*args, **kwargs)
@classmethod
def get_keyword_by_name(cls, name, keyword_type): # case and more importantly accent sensitive getter
qs = cls.objects.filter(name=name)
if keyword_type:
if keyword_type == 'K':
qs = qs.filter(keyword_type__in=(cls.KEYWORD_TYPE_MAJOR, cls.KEYWORD_TYPE_OTHER))
else:
qs = qs.filter(keyword_type=keyword_type)
keyword_list = [keyword for keyword in qs if keyword.name == name]
if keyword_list:
return keyword_list[0]
return None
class FilmKeywordRelationship(models.Model):
film = models.ForeignKey(Film)
keyword = models.ForeignKey(Keyword)
created_by = models.ForeignKey(KTUser, blank=True, null=True, on_delete=models.SET_NULL)
created_at = models.DateTimeField(auto_now_add=True)
spoiler = models.BooleanField(default=False)
def __unicode__(self):
return unicode(self.film) + '/' + unicode(self.keyword)
class Meta:
unique_together = ['film', 'keyword']
class Sequel(models.Model):
name = models.CharField(max_length=250)
SEQUEL_TYPE_SEQUEL = 'S'
SEQUEL_TYPE_REMAKE = 'R'
SEQUEL_TYPE_ADAPTATION = 'A'
SEQUEL_TYPES = [
(SEQUEL_TYPE_SEQUEL, 'Sequel'),
(SEQUEL_TYPE_REMAKE, 'Remake'),
(SEQUEL_TYPE_ADAPTATION, 'Adaptation'),
]
sequel_type = models.CharField(max_length=1, choices=SEQUEL_TYPES, default=SEQUEL_TYPE_SEQUEL)
films = models.ManyToManyField(Film, through='FilmSequelRelationship')
slug_cache = models.CharField(max_length=250, blank=True)
created_by = models.ForeignKey(KTUser, blank=True, null=True, on_delete=models.SET_NULL)
created_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.name
class Meta:
ordering = ['sequel_type', 'name']
def all_films(self):
return [
fs.film
for fs in FilmSequelRelationship.objects.filter(
sequel=self,
).select_related('film').order_by(
'film__year', 'serial_number', 'film__orig_title', 'film__id',
)
]
def save(self, *args, **kwargs):
self.slug_cache = slugify(self.name)
super(Sequel, self).save(*args, **kwargs)
class FilmSequelRelationship(models.Model):
film = models.ForeignKey(Film)
sequel = models.ForeignKey(Sequel)
serial_number = models.PositiveSmallIntegerField(default=0)
created_by = models.ForeignKey(KTUser, blank=True, null=True, on_delete=models.SET_NULL)
created_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return unicode(self.film) + '/' + unicode(self.sequel)
class Meta:
ordering = ['serial_number']
def get_picture_upload_name(instance, filename):
file_root, file_ext = os.path.splitext(filename)
random_chunk = ''.join((random.choice(string.ascii_lowercase) for _ in range(8)))
if instance.film:
new_file_name = 'p_%s_%s%s' % (unicode(instance.film.id), random_chunk, file_ext)
elif instance.artist:
new_file_name = 'pa_%s_%s%s' % (unicode(instance.artist.id), random_chunk, file_ext)
elif instance.user:
new_file_name = 'pu_%s_%s%s' % (unicode(instance.user.id), random_chunk, file_ext)
else:
new_file_name = 'px_%s%s' % (random_chunk, file_ext)
hashdir = hashlib.md5(new_file_name).hexdigest()[:3]
return 'pix/orig/%s/%s' % (hashdir, new_file_name)
class Picture(models.Model):
img = models.ImageField(upload_to=get_picture_upload_name, height_field='height', width_field='width')
width = models.PositiveIntegerField(default=0, editable=False)
height = models.PositiveIntegerField(default=0, editable=False)
created_by = models.ForeignKey(KTUser, blank=True, null=True, on_delete=models.SET_NULL)
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
source_url = models.CharField(max_length=250, blank=True)
PICTURE_TYPE_POSTER = 'P'
PICTURE_TYPE_DVD = 'D'
PICTURE_TYPE_SCREENSHOT = 'S'
PICTURE_TYPE_OTHER = 'O'
PICTURE_TYPE_ACTOR_PROFILE = 'A'
PICTURE_TYPE_USER_PROFILE = 'U'
PICTURE_TYPES = [
(PICTURE_TYPE_POSTER, 'Poster'),
(PICTURE_TYPE_DVD, 'DVD'),
(PICTURE_TYPE_SCREENSHOT, 'Screenshot'),
(PICTURE_TYPE_OTHER, 'Other'),
(PICTURE_TYPE_ACTOR_PROFILE, 'Actor profile'),
(PICTURE_TYPE_USER_PROFILE, 'User profile'),
]
picture_type = models.CharField(max_length=1, choices=PICTURE_TYPES, default=PICTURE_TYPE_OTHER)
film = models.ForeignKey(Film, blank=True, null=True, on_delete=models.SET_NULL)
artists = models.ManyToManyField(Artist, blank=True)
artist = models.ForeignKey(Artist, blank=True, null=True, on_delete=models.SET_NULL, related_name='actor_profile')
user = models.ForeignKey(KTUser, blank=True, null=True, on_delete=models.SET_NULL, related_name='user_profile')
number_of_artists = models.PositiveIntegerField(default=0)
THUMBNAIL_SIZES = {
'min': (120, 120),
'mid': (200, 1000), # 200 x whatever
'max': (720, 600),
}
@property
def order_key(self):
if self.picture_type == self.PICTURE_TYPE_POSTER:
return 1
if self.picture_type == self.PICTURE_TYPE_DVD:
return 2
return 3
def get_thumbnail_filename(self, maxwidth, maxheight):
thumbnail_type = 'tn{w}x{h}'.format(w=maxwidth, h=maxheight)
path, filename = os.path.split(unicode(self.img))
file_root, file_ext = os.path.splitext(filename)
hashdir = path[-3:]
filedir = settings.MEDIA_ROOT + 'pix/' + thumbnail_type + '/' + hashdir
filename = filedir + '/' + file_root + '.jpg'
url = settings.MEDIA_URL + 'pix/' + thumbnail_type + '/' + hashdir + '/' + file_root + '.jpg'
s3_key = 'pix/' + thumbnail_type + '/' + hashdir + '/' + file_root + '.jpg'
return filedir, filename, url, s3_key
def generate_thumbnail(self, maxwidth, maxheight):
infilename = settings.MEDIA_ROOT + unicode(self.img)
outfiledir, outfilename, _, _ = self.get_thumbnail_filename(maxwidth, maxheight)
if not os.path.exists(outfiledir):
os.makedirs(outfiledir)
img = Image.open(infilename)
img.thumbnail((maxwidth, maxheight), Image.ANTIALIAS)
try:
img.save(outfilename)
except IOError: # cannot write mode P as JPEG
img.convert('RGB').save(outfilename)
def save(self, *args, **kwargs):
is_new = self.pk is None
super(Picture, self).save(*args, **kwargs)
if is_new:
# upload to s3:
if not kt_utils.upload_file_to_s3(settings.MEDIA_ROOT + unicode(self.img), unicode(self.img)):
self.delete()
raise IOError
# generate thumbnails and upload to s3:
for _, (w, h) in self.THUMBNAIL_SIZES.iteritems():
self.generate_thumbnail(w, h)
_, outfilename, _, s3_key = self.get_thumbnail_filename(w, h)
if not kt_utils.upload_file_to_s3(outfilename, s3_key):
self.delete()
raise IOError
# delete orig locally:
try:
os.remove(settings.MEDIA_ROOT + unicode(self.img))
except OSError:
pass
# delete thumbnails locally:
for _, (w, h) in self.THUMBNAIL_SIZES.iteritems():
_, filename, _, _ = self.get_thumbnail_filename(w, h)
try:
os.remove(filename)
except OSError:
pass
# update number_of_pictures and main_poster for film:
if self.film:
self.film.number_of_pictures = self.film.picture_set.count()
if self.film.main_poster is None and self.picture_type in {self.PICTURE_TYPE_POSTER, self.PICTURE_TYPE_DVD}:
try:
self.film.main_poster = self.film.picture_set.filter(picture_type=self.PICTURE_TYPE_POSTER).order_by('id')[0]
except IndexError:
self.film.main_poster = self.film.picture_set.filter(picture_type=self.PICTURE_TYPE_DVD).order_by('id')[0]
self.film.save(update_fields=['number_of_pictures', 'main_poster'])
def crop(self, x, y, w, h):
orig_name = self.img.name
orig_width, orig_height = self.width, self.height
new_name = get_picture_upload_name(self, self.img.name)
new_local_name = settings.MEDIA_ROOT + new_name
# download from s3:
if not kt_utils.download_file_from_s3_with_retry(unicode(self.img), new_local_name):
raise IOError
# crop:
img = Image.open(new_local_name)
if img.width > img.height:
zoom = 1.0 * img.width / self.get_width('max')
else:
zoom = 1.0 * img.height / self.get_height('max')
x1, x2 = int(round(zoom * x)), int(round(zoom * (x + w)))
y1, y2 = int(round(zoom * y)), int(round(zoom * (y + h)))
img2 = img.crop((x1, y1, x2, y2))
try:
img2.save(new_local_name)
except IOError: # cannot write mode P as JPEG
img2.convert('RGB').save(new_local_name)
self.width = img2.width
self.height = img2.height
self.img.name = new_name
self.save(update_fields=['width', 'height', 'img'])
# upload to s3:
if not kt_utils.upload_file_to_s3(settings.MEDIA_ROOT + unicode(self.img), unicode(self.img)):
# restore original on error:
self.width = orig_width
self.height = orig_height
self.img.name = orig_name
self.save(update_fields=['width', 'height', 'img'])
raise IOError
# generate thumbnails and upload to s3:
for _, (w, h) in self.THUMBNAIL_SIZES.iteritems():
self.generate_thumbnail(w, h)
_, outfilename, _, s3_key = self.get_thumbnail_filename(w, h)
if not kt_utils.upload_file_to_s3(outfilename, s3_key):
self.delete()
raise IOError
# delete orig locally:
try:
os.remove(settings.MEDIA_ROOT + unicode(self.img))
except OSError:
pass
# delete thumbnails locally:
for _, (w, h) in self.THUMBNAIL_SIZES.iteritems():
_, filename, _, _ = self.get_thumbnail_filename(w, h)
try:
os.remove(filename)
except OSError:
pass
def __unicode__(self):
return unicode(self.img)
def get_display_url(self, thumbnail_type):
if thumbnail_type == 'orig':
return settings.MEDIA_URL + unicode(self.img)
| |
<gh_stars>0
#!/usr/bin/env python
import argparse
import matplotlib.pyplot as plt
import numpy as np
import os
from os import path
import sys
import warnings
DEFAULT_HEARTBEAT_DIR='heartbeat_logs'
DEFAULT_PLOTS_DIR='plots'
DEFAULT_APPLICATION_PROFILER='APPLICATION'
HB_LOG_IDX_START_TIME = 7
HB_LOG_IDX_END_TIME = HB_LOG_IDX_START_TIME + 1
HB_LOG_IDX_START_ENERGY = 14
HB_LOG_IDX_END_ENERGY = HB_LOG_IDX_START_ENERGY + 1
def autolabel(rects, ax):
"""Attach some text labels.
"""
for rect in rects:
ax.text(rect.get_x() + rect.get_width() / 2., 1.05 * rect.get_height(), '', ha='center', va='bottom')
def plot_raw_totals(plot_data, max_time, max_time_std, max_energy, max_energy_std, output_dir, normalize):
"""Plot the raw totals.
Keyword arguments:
plot_data -- (profiler name, total_time, total_time_std, total_energy, total_energy_std)
max_time, max_time_std, max_energy, max_energy_std -- single values
normalize -- True/False
"""
plot_data = sorted(plot_data)
keys = [p for (p, tt, tts, te, tes) in plot_data]
total_times = [tt for (p, tt, tts, te, tes) in plot_data]
total_times_std = [tts for (p, tt, tts, te, tes) in plot_data]
total_energies = [te for (p, tt, tts, te, tes) in plot_data]
total_energies_std = [tes for (p, tt, tts, te, tes) in plot_data]
fig, ax1 = plt.subplots()
ind = np.arange(len(keys)) # the x locations for the groups
width = 0.35 # the width of the bars
# add some text for labels, title and axes ticks
ax1.set_title('Time/Energy Data')
ax1.set_xticks(ind + width)
ax1.set_xticklabels(keys, rotation=45)
fig.set_tight_layout(True)
fig.set_size_inches(max(6, len(plot_data)) / 1.5, 8)
ax2 = ax1.twinx()
# Normalize
if normalize:
total_times_std /= np.sum(total_times)
total_times /= np.sum(total_times)
total_energies_std /= np.sum(total_energies)
total_energies /= np.sum(total_energies)
ax1.set_ylabel('Time (Normalized)')
ax2.set_ylabel('Energy (Normalized)')
else:
# set time in us instead of ns
total_times_std /= np.array(1000000.0)
total_times /= np.array(1000000.0)
total_energies_std /= np.array(1000000.0)
total_energies /= np.array(1000000.0)
ax1.set_ylabel('Time (ms)')
ax2.set_ylabel('Energy (Joules)')
rects1 = ax1.bar(ind, total_times, width, color='r', yerr=total_times_std)
rects2 = ax2.bar(ind + width, total_energies, width, color='y', yerr=total_energies_std)
ax1.legend([rects1[0], rects2[0]], ['Time', 'Energy'])
# set axis
x1, x2, y1, y2 = plt.axis()
if normalize:
output_file = "raw_totals_normalized.png"
ax1.set_ylim(ymin=0, ymax=1)
ax2.set_ylim(ymin=0, ymax=1)
else:
output_file = "raw_totals.png"
ax1.set_ylim(ymin=0, ymax=((max_time + max_time_std) * 1.25 / 1000000.0))
ax2.set_ylim(ymin=0, ymax=((max_energy + max_energy_std) * 1.25 / 1000000.0))
autolabel(rects1, ax1)
autolabel(rects2, ax2)
# plt.show()
plt.savefig(path.join(output_dir, output_file))
plt.close(fig)
def create_raw_total_data(trial_list):
"""Get the raw data to plot
Return: [(profiler, time_mean, time_stddev, energy_mean, energy_stddev)]
Keyword arguments:
trial_list -- (trial, trial_data)
"""
# We can't assume that the same number of heartbeats are always issued across trials
# key: profiler name; value: list of timing sums for each trial
profiler_total_times = {}
# key: profiler name; value: list of energy sums for each trial
profiler_total_energies = {}
for (t, td) in trial_list:
for (profiler, ts, te, es, ee) in td:
# sum the total times and energies for each profiler in this trial
total_time = np.sum(te - ts)
total_energy = np.sum(ee - es)
# add to list to be averaged later
time_list = profiler_total_times.get(profiler, [])
time_list.append(total_time)
profiler_total_times[profiler] = time_list
energy_list = profiler_total_energies.get(profiler, [])
energy_list.append(total_energy)
profiler_total_energies[profiler] = energy_list
# Get mean and stddev for time and energy totals
return [(profiler,
np.mean(profiler_total_times[profiler]),
np.std(profiler_total_times[profiler]),
np.mean(profiler_total_energies[profiler]),
np.std(profiler_total_energies[profiler]))
for profiler in profiler_total_times.keys()]
def plot_all_raw_totals(trial_list, output_dir):
"""Plot column charts of the raw total time/energy spent in each profiler category.
Keyword arguments:
trial_list -- [(trial, result of process_trial_dir(...))]
output_dir -- where to write plots to
"""
# [(profiler, time_mean, time_stddev, energy_mean, energy_stddev)]
raw_totals_data = create_raw_total_data(trial_list)
mean_times = []
mean_times_std = []
mean_energies = []
mean_energies_std = []
for (p, tt, tts, te, tes) in raw_totals_data:
mean_times.append(tt)
mean_times_std.append(tts)
mean_energies.append(te)
mean_energies_std.append(tes)
# get consistent max time/energy values across plots
max_t = np.max(mean_times)
max_t_std = np.max(mean_times_std)
max_e = np.max(mean_energies)
max_e_std = np.max(mean_energies_std)
plot_raw_totals(raw_totals_data, max_t, max_t_std, max_e, max_e_std, output_dir, True)
plot_raw_totals(raw_totals_data, max_t, max_t_std, max_e, max_e_std, output_dir, False)
def plot_trial_time_series(trial, trial_data, max_end_time, max_power, output_dir, power_profiler_name):
"""Plot time series for a single trial.
Keyword arguments:
trial -- the trial name
trial_data -- [(profiler, [start times], [end times], [start energies], [end energies])]
max_end_time -- single value to use as max X axis value (for consistency across trials)
output_dir -- the output directory
"""
# TODO: Some profilers may have parallel tasks - need to identify this on plots
max_end_time = max_end_time / 1000000.0
trial_data = sorted(trial_data)
fig, ax1 = plt.subplots()
keys = [p for (p, ts, te, es, ee) in trial_data]
# add some text for labels, title and axes ticks
ax1.set_title('Profiler Activity for ' + trial)
ax1.set_xlabel('Time (ms)')
ax1.grid(True)
width = 8 # the width of the bars
ax1.set_yticks(10 * np.arange(1, len(keys) + 2))
ax1.set_yticklabels(keys)
ax1.set_ylim(ymin=0, ymax=((len(trial_data) + 1) * 10))
ax1.set_xlim(xmin=0, xmax=max_end_time)
fig.set_tight_layout(True)
fig.set_size_inches(16, len(trial_data) / 3.0 + 1)
i = 10
for (p, ts, te, es, ee) in trial_data:
xranges = [(ts[j] / 1000000.0, (te[j] - ts[j]) / 1000000.0) for j in xrange(len(ts))]
ax1.broken_barh(xranges, (i - 0.5 * width, width))
i += 10
# place a vbar at the final time for this trial
last_profiler_times = map(np.nanmax, filter(lambda x: len(x) > 0, [te for (p, ts, te, es, ee) in trial_data]))
plt.axvline(np.max(last_profiler_times) / 1000000.0, color='black')
power_times = []
power_values = []
for (p, ts, te, es, ee) in trial_data:
if p == power_profiler_name:
power_times = te / 1000000.0
power_values = (ee - es) / ((te - ts) / 1000.0)
ax2 = ax1.twinx()
ax2.set_xlim(xmin=0, xmax=max_end_time)
ax2.set_ylim(ymin=0, ymax=max_power)
ax2.set_ylabel('Power (Watts)')
ax2.plot(power_times, power_values, color='r')
# plt.show()
plt.savefig(path.join(output_dir, "ts_" + trial + ".png"))
plt.close(fig)
def hb_energy_times_to_power(es, ee, ts, te):
"""Compute power from start and end energy and times.
Return: power values
"""
return (ee - es) / ((te - ts) / 1000.0)
def plot_all_time_series(trial_list, output_dir, power_profiler_name):
"""Plot column charts of the raw total time/energy spent in each profiler category.
Keyword arguments:
trial_list -- [(trial, result of process_trial_dir(...))]
output_dir -- where to write plots to
"""
max_end_times = []
max_power_values = [0.0]
for (t, td) in trial_list:
trial_max_end_times = map(np.nanmax, filter(lambda x: len(x) > 0, [te for (p, ts, te, es, ee) in td]))
max_end_times.append(np.nanmax(trial_max_end_times))
for (p, ts, te, es, ee) in td:
# We only care about the power profiler (others aren't reliable for instant power anyway)
if p == power_profiler_name and len(te) > 0:
max_power_values.append(np.nanmax(hb_energy_times_to_power(es, ee, ts, te)))
max_time = np.nanmax(max_end_times)
max_power = np.nanmax(np.array(max_power_values)) * 1.2 # leave a little space at the top
[plot_trial_time_series(trial, trial_data, max_time, max_power, output_dir, power_profiler_name)
for (trial, trial_data) in trial_list]
def read_heartbeat_log(profiler_hb_log):
"""Read a heartbeat log file.
Return: (profiler name, [start times], [end times], [start energies], [end energies], [instant powers])
Keyword arguments:
profiler_hb_log -- the file to read
"""
with warnings.catch_warnings():
try:
warnings.simplefilter("ignore")
time_start, time_end, energy_start, energy_end = \
np.loadtxt(profiler_hb_log,
dtype=np.dtype('uint64'),
skiprows=1,
usecols=(HB_LOG_IDX_START_TIME,
HB_LOG_IDX_END_TIME,
HB_LOG_IDX_START_ENERGY,
HB_LOG_IDX_END_ENERGY),
unpack=True,
ndmin=1)
except ValueError:
time_start, time_end, energy_start, energy_end = [], [], [], []
name = path.split(profiler_hb_log)[1].split('-')[1].split('.')[0]
return (name,
np.atleast_1d(time_start),
np.atleast_1d(time_end),
np.atleast_1d(energy_start),
np.atleast_1d(energy_end))
def process_trial_dir(trial_dir):
"""Process trial directory.
Return: [(profiler name, [start times], [end times], [start energies], [end energies])]
Time and energy are normalized to 0 start values.
Keyword arguments:
trial_dir -- the directory for this trial
"""
log_data = map(lambda h: read_heartbeat_log(path.join(trial_dir, h)),
filter(lambda f: f.endswith(".log"), os.listdir(trial_dir)))
# Find the earliest timestamps and energy readings
min_t = np.nanmin(map(np.nanmin, filter(lambda x: len(x) > 0, [ts for (profiler, ts, te, es, ee) in log_data])))
min_e = np.nanmin(map(np.nanmin, filter(lambda x: len(x) > 0, [es for (profiler, ts, te, es, ee) in log_data])))
# Normalize timing/energy data to start values of 0
return [(profiler, ts - min_t, te - min_t, es - min_e, ee - min_e) for (profiler, ts, te, es, ee) in log_data]
def process_all_trials(parent_dir):
"""Process a directory of trials.
Return: [(trial, [(profiler name, [start times], [end times], [start energies], [end energies])])]
Keyword arguments:
parent_dir -- the directory containing subdirectories for each trial
"""
return [(trial_dir, process_trial_dir(path.join(parent_dir, trial_dir))) for trial_dir in os.listdir(parent_dir)]
def main():
"""This script processes heartbeat log files and produces visualizations.
"""
# Parsing the input of the script
parser = argparse.ArgumentParser(description="Process Heartbeat log files")
parser.add_argument("-d", "--directory",
default=DEFAULT_HEARTBEAT_DIR,
help="Heartbeat log directory \"-d heartbeat_logs\"")
parser.add_argument("-o", "--output",
default=DEFAULT_PLOTS_DIR,
help="Specify the log output directory, for example \"-o plots\"")
parser.add_argument("-p", "--power",
default=DEFAULT_APPLICATION_PROFILER,
help="The profiler name to plot the power curve with, for example \"-p APPLICATION\"")
args = parser.parse_args()
directory = args.directory
output_dir = args.output
power_profiler_name = args.power
if not os.path.exists(directory):
print "Input directory does not exist: " + directory
sys.exit(1)
if os.path.exists(output_dir):
print "Output directory already exists: " + output_dir
sys.exit(1)
res = process_all_trials(directory)
os.makedirs(output_dir)
plot_all_raw_totals(res, output_dir)
plot_all_time_series(res, | |
from common.numpy_fast import clip, interp
from selfdrive.car.tesla.values import CruiseButtons
from selfdrive.config import Conversions as CV
import time
from common.params import Params
from cereal import car
ACCEL_MAX = 0.6 #0.6m/s2 * 36 = ~ 0 -> 50mph in 6 seconds
ACCEL_MIN = -3.5
_DT = 0.05 # 20Hz in our case, since we don't want to process more than once the same radarState message
_DT_MPC = _DT
# TODO: these should end up in values.py at some point, probably variable by trim
# Accel limits
MAX_RADAR_DISTANCE = 120.0 # max distance to take in consideration radar reading
MAX_PEDAL_VALUE_AVG = 100
MAX_PEDAL_REGEN_VALUE = 0.0
MAX_BRAKE_VALUE = 1 #ibooster fully pressed BBTODO determine the exact value we need
PEDAL_HYST_GAP = (
1.0 # don't change pedal command for small oscilalitons within this value
)
# Cap the pedal to go from 0 to max in 3 seconds
PEDAL_MAX_UP = MAX_PEDAL_VALUE_AVG * _DT / 3
# Cap the pedal to go from max to 0 in 0.4 seconds
PEDAL_MAX_DOWN = MAX_PEDAL_VALUE_AVG * _DT / 0.4
# BBTODO: move the vehicle variables; maybe make them speed variable
TORQUE_LEVEL_ACC = 0.0
TORQUE_LEVEL_DECEL = -30.0
MIN_PCC_V_KPH = 0.0 #
MAX_PCC_V_KPH = 270.0
# Pull the cruise stalk twice in this many ms for a 'double pull'
STALK_DOUBLE_PULL_MS = 750
class PCCState:
# Possible state of the PCC system, following the DI_cruiseState naming scheme.
OFF = 0 # Disabled by UI (effectively never happens since button switches over to ACC mode).
STANDBY = 1 # Ready to be engaged.
ENABLED = 2 # Engaged.
NOT_READY = 9 # Not ready to be engaged due to the state of the car.
def _current_time_millis():
return int(round(time.time() * 1000))
# this is for the pedal cruise control
class PCCController:
def __init__(self, longcontroller,tesla_can,pedalcan):
self.LongCtr = longcontroller
self.tesla_can = tesla_can
self.human_cruise_action_time = 0
self.pcc_available = self.prev_pcc_available = False
self.pedal_timeout_frame = 0
self.accelerator_pedal_pressed = self.prev_accelerator_pedal_pressed = False
self.automated_cruise_action_time = 0
self.last_angle = 0.0
self.lead_1 = None
self.last_update_time = 0
self.enable_pedal_cruise = False
self.stalk_pull_time_ms = 0
self.prev_stalk_pull_time_ms = -1000
self.prev_cruise_state = 0
self.prev_cruise_buttons = CruiseButtons.IDLE
self.pedal_speed_kph = 0.0
self.speed_limit_kph = 0.0
self.prev_speed_limit_kph = 0.0
self.pedal_idx = 0
self.pedal_steady = 0.0
self.prev_tesla_accel = 0.0
self.prev_tesla_pedal = 0.0
self.prev_tesla_brake = 0.0
self.torqueLevel_last = 0.0
self.prev_v_ego = 0.0
self.PedalForZeroTorque = (
18.0 # starting number for a S85, adjusts down automatically
)
self.lastTorqueForPedalForZeroTorque = TORQUE_LEVEL_DECEL
self.v_pid = 0.0
self.a_pid = 0.0
self.last_output_gb = 0.0
self.last_speed_kph = None
# for smoothing the changes in speed
self.v_acc_start = 0.0
self.a_acc_start = 0.0
self.v_acc = 0.0
self.v_acc_sol = 0.0
self.v_acc_future = 0.0
self.a_acc = 0.0
self.a_acc_sol = 0.0
self.v_cruise = 0.0
self.a_cruise = 0.0
# when was radar data last updated?
self.lead_last_seen_time_ms = 0
self.continuous_lead_sightings = 0
self.params = Params()
self.pedalcan = pedalcan
self.madMax = False
if longcontroller.madMax:
self.madMax = True
def update_stat(self, CS, frame):
if not self.LongCtr.CP.openpilotLongitudinalControl:
self.pcc_available = False
return []
if not CS.enablePedal:
self.pcc_available = False
return []
self._update_pedal_state(CS, frame)
can_sends = []
if not self.pcc_available:
timed_out = frame >= self.pedal_timeout_frame
if timed_out or CS.pedal_interceptor_state > 0:
if frame % 50 == 0:
# send reset command
idx = self.pedal_idx
self.pedal_idx = (self.pedal_idx + 1) % 16
can_sends.append(
self.tesla_can.create_pedal_command_msg(0, 0, idx, self.pedalcan)
)
return can_sends
#prev_enable_pedal_cruise = self.enable_pedal_cruise
# disable on brake
if CS.realBrakePressed and self.enable_pedal_cruise:
CS.longCtrlEvent = car.CarEvent.EventName.pccDisabled
self.enable_pedal_cruise = False
# process any stalk movement
curr_time_ms = _current_time_millis()
speed_uom_kph = 1.0
if CS.speed_units == "MPH":
speed_uom_kph = CV.MPH_TO_KPH
if (
CS.cruise_buttons == CruiseButtons.MAIN
and self.prev_cruise_buttons != CruiseButtons.MAIN
):
self.prev_stalk_pull_time_ms = self.stalk_pull_time_ms
self.stalk_pull_time_ms = curr_time_ms
double_pull = (
self.stalk_pull_time_ms - self.prev_stalk_pull_time_ms
< STALK_DOUBLE_PULL_MS
)
ready = CS.enablePedal
if ready and double_pull:
# A double pull enables ACC. updating the max ACC speed if necessary.
if not self.enable_pedal_cruise:
CS.longCtrlEvent = car.CarEvent.EventName.pccEnabled
self.enable_pedal_cruise = True
# Increase PCC speed to match current, if applicable.
# We round the target speed in the user's units of measurement to avoid jumpy speed readings
current_speed_kph_uom_rounded = (
int(CS.out.vEgo * CV.MS_TO_KPH / speed_uom_kph + 0.5) * speed_uom_kph
)
self.pedal_speed_kph = max(
current_speed_kph_uom_rounded, self.speed_limit_kph
)
# Handle pressing the cancel button.
elif CS.cruise_buttons == CruiseButtons.CANCEL:
if self.enable_pedal_cruise:
CS.longCtrlEvent = car.CarEvent.EventName.pccDisabled
self.enable_pedal_cruise = False
self.pedal_speed_kph = 0.0
self.stalk_pull_time_ms = 0
self.prev_stalk_pull_time_ms = -1000
# Handle pressing up and down buttons.
elif self.enable_pedal_cruise and CS.cruise_buttons != self.prev_cruise_buttons:
# Real stalk command while PCC is already enabled. Adjust the max PCC speed if necessary.
# We round the target speed in the user's units of measurement to avoid jumpy speed readings
actual_speed_kph_uom_rounded = (
int(CS.out.vEgo * CV.MS_TO_KPH / speed_uom_kph + 0.5) * speed_uom_kph
)
if CS.cruise_buttons == CruiseButtons.RES_ACCEL:
self.pedal_speed_kph = (
max(self.pedal_speed_kph, actual_speed_kph_uom_rounded)
+ speed_uom_kph
)
elif CS.cruise_buttons == CruiseButtons.RES_ACCEL_2ND:
self.pedal_speed_kph = (
max(self.pedal_speed_kph, actual_speed_kph_uom_rounded)
+ 5 * speed_uom_kph
)
elif CS.cruise_buttons == CruiseButtons.DECEL_SET:
self.pedal_speed_kph = self.pedal_speed_kph - speed_uom_kph
elif CS.cruise_buttons == CruiseButtons.DECEL_2ND:
self.pedal_speed_kph = self.pedal_speed_kph - 5 * speed_uom_kph
# Clip PCC speed between 0 and 170 KPH.
self.pedal_speed_kph = clip(
self.pedal_speed_kph, MIN_PCC_V_KPH, MAX_PCC_V_KPH
)
# If something disabled cruise control, disable PCC too
elif self.enable_pedal_cruise and CS.cruise_state and not CS.enablePedal:
self.enable_pedal_cruise = False
CS.longCtrlEvent = car.CarEvent.EventName.pccDisabled
# A single pull disables PCC (falling back to just steering). Wait some time
# in case a double pull comes along.
elif (
self.enable_pedal_cruise
and curr_time_ms - self.stalk_pull_time_ms > STALK_DOUBLE_PULL_MS
and self.stalk_pull_time_ms - self.prev_stalk_pull_time_ms
> STALK_DOUBLE_PULL_MS
):
self.enable_pedal_cruise = False
CS.longCtrlEvent = car.CarEvent.EventName.pccDisabled
# Update prev state after all other actions.
self.prev_cruise_buttons = CS.cruise_buttons
self.prev_cruise_state = CS.cruise_state
return can_sends
def update_pdl(
self,
enabled,
CS,
frame,
actuators,
v_target,
pcm_override,
speed_limit_ms,
set_speed_limit_active,
speed_limit_offset,
alca_enabled,
radSt
):
if not self.LongCtr.CP.openpilotLongitudinalControl:
return 0.0, 0.0, -1, -1
if not CS.enablePedal:
return 0.0, 0.0, -1, -1
idx = self.pedal_idx
self.prev_speed_limit_kph = self.speed_limit_kph
######################################################################################
# Determine pedal "zero"
#
# save position for cruising (zero acc, zero brake, no torque) when we are above 10 MPH
######################################################################################
if (
CS.torqueLevel < TORQUE_LEVEL_ACC
and CS.torqueLevel > TORQUE_LEVEL_DECEL
and CS.out.vEgo >= 10.0 * CV.MPH_TO_MS
and abs(CS.torqueLevel) < abs(self.lastTorqueForPedalForZeroTorque)
):
self.PedalForZeroTorque = self.prev_tesla_pedal
self.lastTorqueForPedalForZeroTorque = CS.torqueLevel
# print ("Detected new Pedal For Zero Torque at %s" % (self.PedalForZeroTorque))
# print ("Torque level at detection %s" % (CS.torqueLevel))
# print ("Speed level at detection %s" % (CS.out.vEgo * CV.MS_TO_MPH))
if set_speed_limit_active and speed_limit_ms > 0:
self.speed_limit_kph = (speed_limit_ms + speed_limit_offset) * CV.MS_TO_KPH
if int(self.prev_speed_limit_kph) != int(self.speed_limit_kph):
self.pedal_speed_kph = self.speed_limit_kph
else: # reset internal speed limit, so double pull doesn't set higher speed than current (e.g. after leaving the highway)
self.speed_limit_kph = 0.0
self.pedal_idx = (self.pedal_idx + 1) % 16
if not self.pcc_available or not enabled:
return 0.0, 0.0, 0, idx
##############################################################
# This mode uses the longitudinal MPC built in OP
#
# we use the values from actuators.accel
##############################################################
ZERO_ACCEL = self.PedalForZeroTorque
REGEN_DECEL = -0.5 #BB needs to be calculated based on regen available
if CS.out.vEgo < 5 * CV.MPH_TO_MS:
ZERO_ACCEL = 0
MAX_PEDAL_BP = [0., 5., 20., 30., 40]
MAX_PEDAL_V = [65. , 75., 85., 100., 120.]
if self.madMax:
MAX_PEDAL_V = [65. , 85., 105., 120., 140.]
MAX_PEDAL_VALUE = interp(CS.out.vEgo, MAX_PEDAL_BP, MAX_PEDAL_V)
ACCEL_LOOKUP_BP = [REGEN_DECEL, 0., ACCEL_MAX]
ACCEL_LOOKUP_V = [MAX_PEDAL_REGEN_VALUE, ZERO_ACCEL, MAX_PEDAL_VALUE]
BRAKE_LOOKUP_BP = [ACCEL_MIN, REGEN_DECEL]
BRAKE_LOOKUP_V = [MAX_BRAKE_VALUE, 0.]
enable_pedal = 1.0 if self.enable_pedal_cruise else 0.0
tesla_pedal = int(round(interp(actuators.accel/2, ACCEL_LOOKUP_BP, ACCEL_LOOKUP_V)))
#only do pedal hysteresis when very close to speed set
if abs(CS.out.vEgo * CV.MS_TO_KPH - self.pedal_speed_kph) < 0.5:
tesla_pedal = self.pedal_hysteresis(tesla_pedal, enable_pedal)
if CS.out.vEgo < 0.1 and actuators.accel < 0.01:
#hold brake pressed at when standstill
#BBTODO: show HOLD indicator in IC with integration
tesla_brake = 0.26
else:
tesla_brake = interp(actuators.accel, BRAKE_LOOKUP_BP, BRAKE_LOOKUP_V)
if CS.has_ibooster_ecu and CS.brakeUnavailable:
CS.longCtrlEvent = car.CarEvent.EventName.iBoosterBrakeNotOk
tesla_pedal = clip(tesla_pedal, self.prev_tesla_pedal - PEDAL_MAX_DOWN, self.prev_tesla_pedal + PEDAL_MAX_UP)
self.prev_tesla_brake = tesla_brake * enable_pedal
self.torqueLevel_last = CS.torqueLevel
self.prev_tesla_pedal = tesla_pedal * enable_pedal
self.prev_v_ego = CS.out.vEgo
return self.prev_tesla_pedal, self.prev_tesla_brake, enable_pedal, idx
def pedal_hysteresis(self, pedal, enabled):
# for small accel oscillations within PEDAL_HYST_GAP, don't change the command
if not enabled:
# send 0 when disabled, otherwise acc faults
self.pedal_steady = 0.0
elif pedal > self.pedal_steady + PEDAL_HYST_GAP:
self.pedal_steady = pedal - PEDAL_HYST_GAP
elif pedal < self.pedal_steady - PEDAL_HYST_GAP:
| |
#!/usr/bin/env python3
import yaml
from pprint import pprint
import os
import sys
import collections
import time
import copy
from . import university_info
MAJORS_LOCATION = "../majors/" # relative path to folder containing the major requirements JSONs
CERTIFICATES_LOCATION = "../certificates/" # relative path to folder containing the certificate requirements JSONs
DEGREES_LOCATION = "../degrees/" # relative path to the folder containing the AB/BSE requirements JSONs
REQ_PATH_SEPARATOR = '//'
# REQ_PATH_PREFIX := <type>//<year>//<dept_code or degree_code or certificate_name>
# Limit the type to 12 characters and the code/name to 100 characters
REQ_PATH_PREFIX = "%.12s" + REQ_PATH_SEPARATOR + "%d" + REQ_PATH_SEPARATOR + "%.100s"
DEFAULT_SCHEDULE = [[]]*8
def check_major(major_name, courses, year):
"""
Returns information about the major requirements satisfied by the courses
given in courses.
:param major_name: the name of the major
:param courses: a list of course-listings
:param year: the user's class year for which to read the requirements
:type major_name: string
:type courses: 2D array
:type year: int
:returns: Whether the major requirements are satisfied
:returns: The list of courses with info about the requirements they satisfy
:returns: A simplified json with info about how much of each requirement is satisfied
:rtype: (bool, dict, dict)
"""
year = int(year)
if year < 2000 or year > 3000:
raise ValueError("Year is invalid.")
if (major_name not in university_info.AB_CONCENTRATIONS
and major_name not in university_info.BSE_CONCENTRATIONS):
raise ValueError("Major code not recognized.")
major_filename = "%s.yaml" % major_name
major_filepath = os.path.join(_get_dir_path(), MAJORS_LOCATION, major_filename)
return check_requirements(major_filepath, courses, year)
def check_degree(degree_name, courses, year):
"""
Returns information about the degree requirements satisfied by the courses
given in courses.
:param degree_name: the name of the degree
:param courses: a list of course-listings
:param year: the user's class year for which to read the requirements
:type degree_name: string
:type courses: 2D array
:type year: int
:returns: Whether the degree requirements are satisfied
:returns: The list of courses with info about the requirements they satisfy
:returns: A simplified json with info about how much of each requirement is satisfied
:rtype: (bool, dict, dict)
"""
year = int(year)
degree_name = degree_name.upper()
if year < 2000 or year > 3000:
raise ValueError("Year is invalid.")
if degree_name not in ["AB", "BSE"]:
raise ValueError("Invalid degree name: %s" % degree_name)
degree_filename = "%s.yaml" % degree_name
degree_filepath = os.path.join(_get_dir_path(), DEGREES_LOCATION, degree_filename)
return check_requirements(degree_filepath, courses, year)
def check_certificate(certificate_name, courses, year):
"""
NOTE: Not yet fully supported. Some certificate specific functionality may not
be present, or may break.
Returns information about the certificate requirements satisfied by the courses
given in courses.
:param certificate_name: the name of the certificate
:param courses: a list of course-listings
:param year: the user's class year for which to read the requirements
:type certificate_name: string
:type courses: 2D array
:type year: int
:returns: Whether the certificate requirements are satisfied
:returns: The list of courses with info about the requirements they satisfy
:returns: A simplified json with info about how much of each requirement is satisfied
:rtype: (bool, dict, dict)
"""
year = int(year)
if year < 2000 or year > 3000:
raise ValueError("Year is invalid.")
if (certificate_name not in university_info.CERTIFICATES):
raise ValueError("Certificate not recognized.")
certificate_filename = "%s.yaml" % certificate_name
certificate_filepath = os.path.join(_get_dir_path(), CERTIFICATES_LOCATION, certificate_filename)
return check_requirements(certificate_filepath, courses, year)
def check_requirements(req_file, courses, year):
"""
Returns information about the requirements satisfied by the courses
given in courses.
:param req_file: the name of a file containing a requirements JSON
:param courses: a list of course-listings
:param year: the user's class year for which to read the requirements
:type req_file: string
:type courses: 2D array
:type year: int
:returns: Whether the requirements are satisfied
:returns: The list of courses with info about the requirements they satisfy
:returns: A simplified json with info about how much of each requirement is satisfied
:rtype: (bool, dict, dict)
"""
with open(req_file, 'r', encoding="utf8") as f:
req = yaml.safe_load(f)
courses = _init_courses(courses, req, year)
req = _init_req(req, year)
_mark_possible_reqs(req, courses)
_assign_settled_courses_to_reqs(req, courses)
_add_course_lists_to_req(req, courses)
formatted_courses = _format_courses_output(courses)
formatted_req = _format_req_output(req)
return formatted_req["satisfied"], formatted_courses, formatted_req
def get_courses_by_path(path):
"""
Returns the sets of all courses and all distribution requirements
in the subtree specified by path as a tuple:
(course_set, dist_req_set)
Note: Sets may contain duplicate courses if a course is listed in multiple
different ways
Note: the path parameter must be a requirement path string that was generated
through calling _init_path_to()
Implementation is sensitive to the path format, which must start with
<type>//<year>//<dept_code>
where the <>'s are replaced with the appropriate values.
:param path: the path identifier of a requirement as generated by _init_path_to()
:type path: string
:raises: ValueError - if the path was not generated by _init_path_to()
:returns: the tuple (course_set, dist_req_set)
:rtype: (set, set)
"""
req_type, year, req_name = path.split(REQ_PATH_SEPARATOR)[:3]
year = int(year)
if year < 2000 or year > 3000:
raise ValueError("Path malformatted.")
if not path.startswith(REQ_PATH_PREFIX % (req_type, year, req_name)):
raise ValueError("Path malformatted.")
if "/" in req_type or "/" in req_name:
raise ValueError("Path malformatted.")
filename = "%s.yaml" % req_name
if req_type == "Major":
if (req_name not in university_info.AB_CONCENTRATIONS and req_name not in university_info.BSE_CONCENTRATIONS):
raise ValueError("Path malformatted.")
req_filepath = os.path.join(_get_dir_path(), MAJORS_LOCATION, filename)
elif req_type == "Certificate":
if req_name not in university_info.CERTIFICATES:
raise ValueError("Path malformatted.")
req_filepath = os.path.join(_get_dir_path(), CERTIFICATES_LOCATION, filename)
elif req_type == "Degree":
if req_name not in ["AB", "BSE"]:
raise ValueError("Path malformatted.")
req_filepath = os.path.join(_get_dir_path(), DEGREES_LOCATION, filename)
else:
raise ValueError("Path malformatted.")
with open(req_filepath, 'r', encoding="utf8") as f:
req = yaml.safe_load(f)
_init_year_switch(req, year)
subreq = _get_req_by_path(req, path, year)
if not subreq:
raise ValueError("Path malformatted: " + path)
return _get_collapsed_course_and_dist_req_sets(subreq)
def _init_req(req, year):
req = copy.deepcopy(req)
_init_year_switch(req, year)
_init_req_fields(req)
_init_min_ALL(req)
_init_double_counting_allowed(req)
_init_path_to(req, year)
return req
def _format_req_output(req):
"""
Enforce the type and order of fields in the req output
"""
output = collections.OrderedDict()
if req["name"] == None: # hidden requirement. Do not show.
return None
for key in [
"name",
"code",
"degree",
"path_to",
"urls"
]:
if key in req:
output[key] = req[key]
if "code" in req and "description" in req:
output["description"] = req["description"]
if "contacts" in req:
output["contacts"] = []
for contact in req["contacts"]:
contact_copy = collections.OrderedDict()
for key in ["type", "name", "email"]:
contact_copy[key] = contact[key]
output["contacts"].append(contact_copy)
for key in [
"explanation",
"pdfs_allowed",
"completed_by_semester"
]:
if key in req:
output[key] = req[key]
output["satisfied"] = (req["min_needed"]-req["count"] <= 0)
for key in ["count", "min_needed", "max_counted"]:
output[key] = req[key]
if "req_list" in req: # internal node. recursively call on children
req_list = []
for subreq in req["req_list"]:
child = _format_req_output(subreq)
if (child != None):
req_list.append(_format_req_output(subreq))
if req_list:
output["req_list"] = req_list
if "settled" in req:
output["settled"] = req["settled"]
if "unsettled" in req:
output["unsettled"] = req["unsettled"]
return output
def _add_course_lists_to_req(req, courses):
"""
Add course lists for each requirement that either
(a) has no subrequirements, or
(b) has hidden subrequirements
"""
include_course_lists = False
if "req_list" in req:
for subreq in req["req_list"]:
if subreq["name"] == None:
include_course_lists = True
else: # recursively for all named requirements
_add_course_lists_to_req(subreq, courses)
else:
include_course_lists = True
if include_course_lists:
req["settled"] = []
req["unsettled"] = []
for sem in courses:
for course in sem:
if req["double_counting_allowed"]:
if len(course["reqs_double_counted"]) > 0:
for path in course["reqs_double_counted"]:
if path.startswith(req["path_to"]):
req["settled"].append(course["name"])
## add to reqs_satisfied because couldn't be added in _assign_settled_courses_to_reqs()
course["reqs_satisfied"].append(req["path_to"])
elif len(course["settled"]) > 0:
for path in course["settled"]:
if path.startswith(req["path_to"]):
req["settled"].append(course["name"])
else:
for path in course["possible_reqs"]:
if path.startswith(req["path_to"]):
req["unsettled"].append(course["name"])
break
def _init_courses(courses, req, year):
if not courses:
courses = DEFAULT_SCHEDULE
else:
courses = copy.deepcopy(courses)
for sem_num,semester in enumerate(courses):
for course in semester:
course["name"] = course["name"].split(':')[0]
course["possible_reqs"] = []
course["reqs_satisfied"] = []
course["reqs_double_counted"] = [] # reqs satisfied for which double counting allowed
course["semester_number"] = sem_num
course["num_settleable"] = 0 # number of reqs to which can be settled. autosettled if 1
if "external" not in course:
course["external"] = False
if "settled" not in course or course["settled"] == None:
course["settled"] = []
elif req["type"] in ["Major", "Degree"]: # filter out irrelevant requirements from list
for path in course["settled"]:
if not path.startswith(REQ_PATH_PREFIX % (req["type"], year, req["code"])):
course["settled"].remove(path)
else: # type must be "Certificate"
for path in course["settled"]:
if not path.startswith(REQ_PATH_PREFIX % (req["type"], year, req["name"])):
course["settled"].remove(path)
return courses
def _format_courses_output(courses):
"""
Enforce the type and order of | |
<filename>acipdt/main.py
import acipdt
import xlrd
import xlwt
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from xlutils.copy import copy
from orderedset import OrderedSet
import sys
import time
import ipaddress
import getpass
import os
# Log levels 0 = None, 1 = Class only, 2 = Line
log_level = 2
# Define the name of the configuration file you will be using.
# This doesn't alter the folder name.
ACI_DEPLOY_FILE = 'aci_deploy.xls'
# Adding these values are NOT secure. Use for testing only.
APICIP = None
APICUSER = None
APICPASS = None
def stdout_log(sheet, line):
if log_level == 0:
return
elif ((log_level == (1) or log_level == (2)) and
(sheet) and (line is None)):
print('*' * 80)
print('Starting work on {} section'.format(sheet))
print('*' * 80)
elif log_level == (2) and (sheet) and (line is not None):
print('Deploying line {} from section {}...'.format(line, sheet))
else:
return
def read_in(usr_path):
try:
wb_path = os.path.join(usr_path, ACI_DEPLOY_FILE)
wb = xlrd.open_workbook(wb_path)
print("Workbook Loaded.")
except Exception as e:
print("Something went wrong logging opening the workbook - ABORT!")
sys.exit(e)
return wb
def findKeys(ws, rows):
func_list = OrderedSet()
for i in range(2, rows):
if (ws.cell(i, 0)).value:
func_list.add((ws.cell(i, 0)).value)
else:
i += 1
return func_list
def countKeys(ws, rows, func):
count = 0
for i in range(2, rows):
if (ws.cell(i, 0)).value == func:
count += 1
else:
i += 1
return count
def findVars(ws, rows, func, count):
var_list = []
var_dict = {}
for i in range(2, rows):
if (ws.cell(i, 0)).value == func:
try:
for x in range(4, 17):
if (ws.cell(i - 1, x)).value:
var_list.append((ws.cell(i - 1, x)).value)
else:
x += 1
except Exception as e:
e = e
pass
break
while count > 0:
var_dict[count] = {}
var_count = 0
for z in var_list:
var_dict[count][z] = ws.cell(i + count - 1, 4 + var_count).value
var_count += 1
var_dict[count]['row'] = i + count - 1
count -= 1
return var_dict
def wb_update(wr_ws, status, i):
# build green and red style sheets for excel
green_st = xlwt.easyxf('pattern: pattern solid;')
green_st.pattern.pattern_fore_colour = 3
red_st = xlwt.easyxf('pattern: pattern solid;')
red_st.pattern.pattern_fore_colour = 2
yellow_st = xlwt.easyxf('pattern: pattern solid;')
yellow_st.pattern.pattern_fore_colour = 5
# if stanzas to catch the status code from the request
# and then input the appropriate information in the workbook
# this then writes the changes to the doc
if status == 200:
wr_ws.write(i, 1, 'Success (200)', green_st)
if status == 400:
print("Error 400 - Bad Request - ABORT!")
print("Probably have a bad URL or payload")
wr_ws.write(i, 1, 'Bad Request (400)', red_st)
pass
if status == 401:
print("Error 401 - Unauthorized - ABORT!")
print("Probably have incorrect credentials")
wr_ws.write(i, 1, 'Unauthorized (401)', red_st)
pass
if status == 403:
print("Error 403 - Forbidden - ABORT!")
print("Server refuses to handle your request")
wr_ws.write(i, 1, 'Forbidden (403)', red_st)
pass
if status == 404:
print("Error 404 - Not Found - ABORT!")
print("Seems like you're trying to POST to a page that doesn't"
" exist.")
wr_ws.write(i, 1, 'Not Found (400)', red_st)
pass
if status == 666:
print("Error - Something failed!")
print("The POST failed, see stdout for the exception.")
wr_ws.write(i, 1, 'Unkown Failure', yellow_st)
pass
if status == 667:
print("Error - Invalid Input!")
print("Invalid integer or other input.")
wr_ws.write(i, 1, 'Unkown Failure', yellow_st)
pass
def pod_policies(apic, cookies, wb, wr_wb):
ws = wb.sheet_by_name('Fabric Pod Policies')
wr_ws = wr_wb.get_sheet(0)
rows = ws.nrows
func_list = findKeys(ws, rows)
podpol = acipdt.FabPodPol(apic, cookies)
stdout_log(wr_ws.name, None)
for func in func_list:
count = countKeys(ws, rows, func)
var_dict = findVars(ws, rows, func, count)
for pos in var_dict:
row_num = var_dict[pos]['row']
del var_dict[pos]['row']
for x in list(var_dict[pos].keys()):
if var_dict[pos][x] == '':
del var_dict[pos][x]
stdout_log(wr_ws.name, row_num)
status = eval("podpol.%s(**var_dict[pos])" % func)
wb_update(wr_ws, status, row_num)
time.sleep(.025)
def access_policies(apic, cookies, wb, wr_wb):
ws = wb.sheet_by_name('Fabric Access Policies')
wr_ws = wr_wb.get_sheet(1)
rows = ws.nrows
func_list = findKeys(ws, rows)
accpol = acipdt.FabAccPol(apic, cookies)
stdout_log(wr_ws.name, None)
for func in func_list:
count = countKeys(ws, rows, func)
var_dict = findVars(ws, rows, func, count)
for pos in var_dict:
row_num = var_dict[pos]['row']
del var_dict[pos]['row']
for x in list(var_dict[pos].keys()):
if var_dict[pos][x] == '':
del var_dict[pos][x]
stdout_log(wr_ws.name, row_num)
status = eval("accpol.%s(**var_dict[pos])" % func)
wb_update(wr_ws, status, row_num)
time.sleep(.025)
def tn_policies(apic, cookies, wb, wr_wb):
ws = wb.sheet_by_name('Tenant Configuration')
wr_ws = wr_wb.get_sheet(2)
rows = ws.nrows
func_list = findKeys(ws, rows)
tnpol = acipdt.FabTnPol(apic, cookies)
stdout_log(wr_ws.name, None)
for func in func_list:
count = countKeys(ws, rows, func)
var_dict = findVars(ws, rows, func, count)
for pos in var_dict:
row_num = var_dict[pos]['row']
del var_dict[pos]['row']
for x in list(var_dict[pos].keys()):
if var_dict[pos][x] == '':
del var_dict[pos][x]
stdout_log(wr_ws.name, row_num)
status = eval("tnpol.%s(**var_dict[pos])" % func)
wb_update(wr_ws, status, row_num)
time.sleep(.025)
def l3_policies(apic, cookies, wb, wr_wb):
ws = wb.sheet_by_name('L3 Out')
wr_ws = wr_wb.get_sheet(3)
rows = ws.nrows
func_list = findKeys(ws, rows)
l3pol = acipdt.FabL3Pol(apic, cookies)
stdout_log(wr_ws.name, None)
for func in func_list:
count = countKeys(ws, rows, func)
var_dict = findVars(ws, rows, func, count)
for pos in var_dict:
row_num = var_dict[pos]['row']
del var_dict[pos]['row']
for x in list(var_dict[pos].keys()):
if var_dict[pos][x] == '':
del var_dict[pos][x]
stdout_log(wr_ws.name, row_num)
status = eval("l3pol.%s(**var_dict[pos])" % func)
wb_update(wr_ws, status, row_num)
time.sleep(.025)
def vmm_policies(apic, cookies, wb, wr_wb):
ws = wb.sheet_by_name('VMM')
wr_ws = wr_wb.get_sheet(4)
rows = ws.nrows
func_list = findKeys(ws, rows)
vmm = acipdt.FabVMM(apic, cookies)
stdout_log(wr_ws.name, None)
for func in func_list:
count = countKeys(ws, rows, func)
var_dict = findVars(ws, rows, func, count)
for pos in var_dict:
row_num = var_dict[pos]['row']
del var_dict[pos]['row']
for x in list(var_dict[pos].keys()):
if var_dict[pos][x] == '':
del var_dict[pos][x]
stdout_log(wr_ws.name, row_num)
status = eval("vmm.%s(**var_dict[pos])" % func)
wb_update(wr_ws, status, row_num)
time.sleep(.025)
def fab_admin_policies(apic, cookies, wb, wr_wb):
ws = wb.sheet_by_name('Fabric Admin')
wr_ws = wr_wb.get_sheet(5)
rows = ws.nrows
func_list = findKeys(ws, rows)
fabadmin = acipdt.FabAdminMgmt(apic, cookies)
stdout_log(wr_ws.name, None)
for func in func_list:
count = countKeys(ws, rows, func)
var_dict = findVars(ws, rows, func, count)
for pos in var_dict:
row_num = var_dict[pos]['row']
del var_dict[pos]['row']
for x in list(var_dict[pos].keys()):
if var_dict[pos][x] == '':
del var_dict[pos][x]
stdout_log(wr_ws.name, row_num)
status = eval("fabadmin.%s(**var_dict[pos])" % func)
wb_update(wr_ws, status, row_num)
time.sleep(.025)
def mpod_policies(apic, cookies, wb, wr_wb):
ws = wb.sheet_by_name('Multipod')
wr_ws = wr_wb.get_sheet(6)
rows = ws.nrows
func_list = findKeys(ws, rows)
mpod = acipdt.Mpod(apic, cookies)
stdout_log(wr_ws.name, None)
for func in func_list:
count = countKeys(ws, rows, func)
var_dict = findVars(ws, rows, func, count)
for pos in var_dict:
row_num = var_dict[pos]['row']
del var_dict[pos]['row']
for x in list(var_dict[pos].keys()):
if var_dict[pos][x] == '':
del var_dict[pos][x]
stdout_log(wr_ws.name, row_num)
status = eval("mpod.%s(**var_dict[pos])" % func)
wb_update(wr_ws, status, row_num)
time.sleep(.025)
def take_snapshot(apic, cookies, snapshot_name):
query = acipdt.Query(apic, cookies)
query_string = 'configSnapshot'
query_payload = query.query_class(query_string)
payload_len = len(query_payload[1]['imdata'])
snap_count = 0
for x in range(0, payload_len):
try:
if (query_payload[1]['imdata'][x]['configSnapshot']['attributes']
['fileName'])[4:17] == snapshot_name:
snap_count += 1
except Exception as e:
e = e
print("It seems the APIC does not support snapshots, moving on.")
return(None)
if snap_count > 0:
print("A snapshot including 'acipdt_backup' already exists. Would you "
"like to delete this snapshot or exit?")
user_input = input("Delete 'd' or Exit 'q' [q]: ")
selection = user_input or 'q'
if selection.lower() == 'd':
del_snap_pol(apic, cookies, snapshot_name)
elif selection.lower() == 'q':
sys.exit()
snapshot = 'true'
status = 'created,modified'
snapshot_args = {}
snapshot_args['name'] = snapshot_name
snapshot_args['snapshot'] = snapshot
snapshot_args['status'] = status
cfgmgmt = acipdt.FabCfgMgmt(apic, cookies)
status = cfgmgmt.backup(**snapshot_args)
if status == 200:
print("Snapshot taken successfully, continuing.")
time.sleep(1)
snap = True
return(snap)
else:
print("Snapshot failed for some reason, do you want to continue?")
while True:
user_input = input("Continue 'y' or 'n' [n]: ")
selection = user_input or 'n'
if selection.lower() == 'y':
snap = None
return(snap)
elif selection.lower() == 'n':
del_snap_pol(apic, cookies, snapshot_name)
sys.exit()
def revert_snapshot(apic, cookies, snapshot_name):
print('Deployment completed, please verify status in workbook.')
while True:
user_input = input("Rollback to previous snapshot 'y' or 'n' [n]: ")
selection = user_input or 'n'
if selection.lower() == 'n':
return
elif selection.lower() == 'y':
query = acipdt.Query(apic, cookies)
query_string = 'configSnapshot'
query_payload = query.query_class(query_string)
payload_len = len(query_payload[1]['imdata'])
for x in range(0, payload_len):
if (query_payload[1]['imdata'][x]['configSnapshot']
['attributes']['fileName'])[4:17] == snapshot_name:
snapshot_name = (query_payload[1]['imdata'][x]
['configSnapshot']['attributes']
['fileName'])
break
cfgmgmt = acipdt.FabCfgMgmt(apic, cookies)
snapshot_args = {}
snapshot_args['name'] = snapshot_name
cfgmgmt.snapback(**snapshot_args)
return
def del_snap_pol(apic, cookies, snapshot_name):
status = 'deleted'
snapshot = 'true'
snapshot_args = {}
snapshot_args['name'] = snapshot_name
snapshot_args['snapshot'] = snapshot
snapshot_args['status'] = status
cfgmgmt = acipdt.FabCfgMgmt(apic, cookies)
status = cfgmgmt.backup(**snapshot_args)
def main():
# Disable urllib3 warnings
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
# Ask user for path to the ACI_DEPLOY_FILE
while True:
print('Please enter the path | |
AC.dt64_2_dt([time2use])[0].strftime('%Y/%m/%d %H:%M')
# Print out status
pstr = "'plotting 2layer @ {:.1f}$^{}$N on {}"
print(pstr.format(lat2use, '{\circ}', dstr))
# Select for level and variable, and average over time
ds_tmp = ds.sel(lat=lat2use, time=time2use)
# Set title
title_str = '[{}] & [{}] @ {:.1f}$^{}$N on {}'
title = title_str.format(LaTeX_spec1, LaTeX_spec2, lat2use,
'{\circ}', dstr)
if not isinstance(extr_title_str, type(None)):
title += extr_title_str
# Save plots
extra_str = 'lat_{}N_dt_{}'.format(lat2use, dstr)
# Update the long_names - var1
attrs = ds_tmp[var2plot1].attrs
attrs['long_name'] = LaTeX_spec1
ds_tmp[var2plot1].attrs = attrs
# Update the long_names - var2
attrs = ds_tmp[var2plot2].attrs
attrs['long_name'] = LaTeX_spec2
ds_tmp[var2plot2].attrs = attrs
# Now call plotter
quick_lat_plt_2layer(ds_tmp, var2plot1=var2plot1,
folder=folder,
var2plot2=var2plot2, title=title,
save_plot=True, extra_str=extra_str
)
plt.close('all')
def plot_CVAO_region_on_global_map(ds, var2use='NOy'):
"""
Plot a global map to show ARNA campaign region
"""
# - extents to use
# extracted data from OPeNDAP
# d = get_analysis_region('OPeNDAP_download_area')
# Local area analysed as Cape Verde
d = get_analysis_region('local_CVAO_area')
x0, x1, y0, y1 = d['x0'], d['x1'], d['y0'], d['y1']
# - Select the data
# Just get an example dataset
ds = ds[[var2use]]
# Select a single level and time
ds = ds.sel(time=ds.time[0])
ds = ds.sel(lev=ds.lev[0])
# Set values region
bool1 = ((ds.lon >= x0) & (ds.lon <= x1)).values
bool2 = ((ds.lat >= y0) & (ds.lat <= y1)).values
# Cut by lon, then lat
ds = ds.isel(lon=bool1)
ds = ds.isel(lat=bool2)
# Set all values to 1
arr = ds[var2use].values
arr[:] = 1
ds[var2use].values = arr
# Plot the data
projection = ccrs.Robinson()
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(111, projection=projection, aspect='auto', alpha=0.5)
LatVar = 'lat'
LonVar = 'lon'
ds[var2use].plot.imshow(x=LonVar, y=LatVar, ax=ax,
transform=ccrs.PlateCarree())
# Beautify the figure/plot
ax.coastlines()
# Force global perspective
ax.set_global() # this will force a global perspective
# Save
savename = 'spatial_plot_Cape_Verde_flying_area'
savename = AC.rm_spaces_and_chars_from_str(savename)
plt.savefig(savename+'.png', dpi=dpi)
def quick_map_plt_2layer(ds, var2plot1=None, var2plot2=None, extra_str='',
projection=ccrs.PlateCarree(), folder=None,
save_plot=True, show_plot=False, savename=None,
units=None, title=None,
LatVar='lat', LonVar='lon', fig=None, ax=None,
extents=None,
add_ARNA_locs=True,
use_local_CVAO_area=True, region='Cape_Verde',
extend='both',
add_flyable_range_as_box=False,
add_flyable_range_as_circle=True,
add_detailed_map=True,
add_max_vals_as_txt=False,
dpi=320):
"""
Plot up a quick spatial plot of data using cartopy
Parameters
-------
ds (xr.Dataset): dataset object holding data to plot
var2plot (str): variable to plot within the dataset
LatVar, LonVar (str): variables to use for latitude and longitude
save_plot (bool): save the plot as a .png ?
show_plot (bool): show the plot on screen
dpi (int): resolution to use for saved image (dots per square inch)
savename (str): name to use for png of saved .png
extra_str (str): extra string to append to save .png
projection (cartopy.crs obj.): projection to use
fig (figure instance): matplotlib figure instance
ax (axis instance): axis object to use
add_ARNA_locs (bool):
use_local_CVAO_area (bool):
Returns
-------
(None)
"""
# Use the 1st data variable if not variable given
if isinstance(var2plot1, type(None)):
pstr = 'WARNING: No variable to plot (var2plot), trying 1st data_var'
print(pstr)
var2plot1 = list(ds.data_vars)[0]
# var2plot1 = 'NOy'
if isinstance(var2plot2, type(None)):
pstr = 'WARNING: No variable to plot (var2plot), trying 1st data_var'
print(pstr)
var2plot2 = list(ds.data_vars)[0]
# var2plot2 = 'PM2.5(dust)'
# Setup figure and axis and plot
if isinstance(fig, type(None)):
fig = plt.figure(figsize=(10, 6))
if isinstance(ax, type(None)):
ax = fig.add_subplot(111, projection=projection, aspect='auto')
# - Plot first var
alpha = 0.5
# Setup plotted range
vmin1, vmax1 = set_limits4ar_plotted_range(var2plot1)
vmin1 = get_vmin_value4var(var2plot1)
units1 = get_species_units(var2plot1)
cmap, ticks, nticks = get_cmap4var(var2plot1)
if isinstance(ticks, type(None)):
cbar_kwargs = {'cmap': cmap, 'extend': extend, }
else:
cbar_kwargs = {'ticks': ticks, 'cmap': cmap, 'extend': extend, }
# Now plot up var1
ds[var2plot1].plot.imshow(x=LonVar, y=LatVar, ax=ax,
transform=ccrs.PlateCarree(),
vmin=vmin1, vmax=vmax1,
zorder=1, alpha=alpha,
cmap=cmap,
cbar_kwargs=cbar_kwargs,
# extend=extend,
)
# Update the units on the colour bar panel
im = ax.images
cb = im[-1].colorbar
try:
LaTeX_spec1 = AC.latex_spec_name(var2plot1)
except KeyError:
LaTeX_spec1 = var2plot1
cb.set_label('{} ({})'.format(LaTeX_spec1, units1))
# - Plot second var
alpha = 0.4
# Now plot up var 2
vmin2, vmax2 = set_limits4ar_plotted_range(var2plot2)
vmin2 = get_vmin_value4var(var2plot2)
units2 = get_species_units(var2plot2)
cmap, ticks, nticks = get_cmap4var(var2plot2)
if isinstance(ticks, type(None)):
cbar_kwargs = {'cmap': cmap, 'extend': extend, }
else:
cbar_kwargs = {'ticks': ticks, 'cmap': cmap, 'extend': extend, }
# Now plot up var2
ds[var2plot2].plot.imshow(x=LonVar, y=LatVar, ax=ax,
transform=ccrs.PlateCarree(),
vmin=vmin2, vmax=vmax2,
zorder=1, alpha=alpha, cmap=cmap,
cbar_kwargs=cbar_kwargs,
# extend=extend,
)
# Update the units on the colour bar panel
im = ax.images
cb = im[-1].colorbar
try:
LaTeX_spec2 = AC.latex_spec_name(var2plot2)
except KeyError:
LaTeX_spec2 = var2plot2
cb.set_label('{} ({})'.format(LaTeX_spec2, units2))
# Update the xaxis ticks (lon) to deg W
# update_lon_units = True
# if update_lon_units:
# xticks = ax.get_xticks()
# xticklabels = ax.get_xticklabels()
# ax.set_xticklabels([str(i)*-1 for i in xticks])
# - Update plot aesthetics
# Add some grid lines
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
linewidth=.5, color='gray', alpha=0.25, linestyle='--')
gl.xlabels_top = False
gl.ylabels_right = False
# Just plot over the CVAO region?
if use_local_CVAO_area and (region != 'Cape_Verde_Flying'):
d = get_analysis_region(region) # 'local_CVAO_area'
extents = (d['x0'], d['x1'], d['y0'], d['y1'])
elif (region == 'Cape_Verde_Flying'):
d = get_analysis_region(region)
extents = (d['x0'], d['x1'], d['y0'], d['y1'])
# Add extra lat and lon grid libnes
if (region == 'Cape_Verde_Flying'):
# Which X tickst to use?
# x axis
xticks = np.arange(ds.lon.values.min(), ds.lon.values.max(), 0.2)
# y axis
yticks = np.arange(ds.lat.values.min(), ds.lat.values.max(), 0.2)
# --- New approach
# from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
# LON_FORMATTER = LONGITUDE_FORMATTER(dms=True)#, auto_hide=True)
# LON_FORMATTER.set_locs(xticks)
# LAT_FORMATTER = LATITUDE_FORMATTER(dms=True)#, auto_hide=True)
# LAT_FORMATTER.set_locs(yticks)
# gl.xformatter = LON_FORMATTER
# gl.yformatter = LAT_FORMATTER
# --- Old approach
# xmajor = np.arange(ds.lon.values.min(), ds.lon.values.max(), 1 )
# xminor = [i for i in xticks if i not in xmajor]
# xminor_locator = mticker.FixedLocator(xminor)
# xmajor_locator = mticker.FixedLocator(xmajor)
# ax.xaxis.set_major_locator(xmajor_locator)
# ax.xaxis.set_minor_locator(xminor_locator)
gl.xlocator = mticker.FixedLocator(xticks) # last working setting...
# ymajor = np.arange(ds.lat.values.min(), ds.lat.values.max(), 1 )
# yminor = [i for i in yticks if i not in ymajor]
gl.ylocator = mticker.FixedLocator(yticks) # last working setting...
# get_labels
# ymajor_locator = mticker.FixedLocator(ymajor)
# yminor_locator = mticker.FixedLocator(yminor)
# ax.yaxis.set_major_locator(ymajor_locator)
# ax.yaxis.set_minor_locator(yminor_locator)
# tight off the main labels.
# gl.xlabels_bottom = False
# gl.ylabels_left = False
gl.xlabels_bottom = True # last working setting...
gl.ylabels_left = True # last working setting...
# Add main labels
# for lon in xmajor:
# buffer = 0.25
# ax.text( y0, lon, '{}'.format(lon), fontsize=10, alpha=0.5,
# horizontalalignment='center' )
# for lat in ymajor:
# buffer = 0.25
# ax.text( lat, x0, '{}'.format(lon), fontsize=10, alpha=0.5,
# horizontalalignment='center' )
# Make axis label text smaller
gl.xlabel_style = {'size': 6, 'rotation': 90}
gl.ylabel_style = {'size': 6, }
# Mark a known place to help us geo-locate ourselves
if add_ARNA_locs:
colours = AC.get_CB_color_cycle()
locs2plot = 'Praia Airport', 'Dakar', 'Sao Vicente Airport',
for loc2plot in locs2plot:
lon, lat, alt = AC.get_loc(loc2plot)
ax.plot(lon, lat, 'bo', markersize=5, markerfacecolor='none',
markeredgewidth=2,
# markeredgecolor=colours[0],
markeredgecolor='black',
transform=ccrs.PlateCarree())
# ax.text(lon, lat+0.25, loc2plot, transform=ccrs.PlateCarree())
# Add a box to show the flyable range
if add_flyable_range_as_box:
# Get the minimum
d = get_max_flying_range4BAE146()
min_lon = d['min_lon']
max_lon = d['max_lon']
min_lat = d['min_lat']
max_lat = d['max_lat']
# Create new lists
lons = [min_lon, min_lon, max_lon, max_lon]
lats = [min_lat, max_lat, max_lat, min_lat]
# Now plot as a linear ring
ring = LinearRing(list(zip(lons, lats)))
ax.add_geometries([ring], ccrs.PlateCarree(),
facecolor='none', edgecolor='grey',
zorder=10, linestyle=':',
)
if add_flyable_range_as_circle:
# n_points = 1000
# Approximate from James' max distance
# ( 16.8331-13 ) *110667.45
locs4circles = 'Dakar', 'Sao Vicente Airport',
for loc in locs4circles:
# Get locations to centre circle on
lon, lat, alt = AC.get_loc(loc)
# Radius in degrees
# radius = 16.8331-13
radius = 21 - 16.8331
# Plot up circle
ax.add_patch(mpatches.Circle(xy=[lon, lat],
radius=radius,
transform=projection,
facecolor='none',
edgecolor='black',
linestyle=':',
linewidth=3.0,
zorder=100
))
# Get limits of plotting data
if isinstance(extents, type(None)):
x0 = float(ds[LonVar].min())
x1 = float(ds[LonVar].max())
y0 = float(ds[LatVar].min())
y1 = float(ds[LatVar].max())
extents = (x0, x1, y0, y1)
ax.set_extent(extents, crs=ccrs.PlateCarree())
# Beautify the figure/plot
if add_detailed_map:
# Add borders for countries
ax.add_feature(cfeature.BORDERS, edgecolor='grey',
facecolor='none', zorder=50)
# Also add minor islands (inc. Cape Verde)
land_10m = cfeature.NaturalEarthFeature('physical', 'land', '10m',
edgecolor=None,
facecolor='none')
ax.add_feature(land_10m, edgecolor='grey', facecolor='none', zorder=50)
# Update the xaxis ticks (lon) to deg W
# update_lon_units = True
# if update_lon_units:
# xticks = ax.get_xticks()
# xticklabels = ax.get_xticklabels()
# ax.set_xticklabels([str(i)*-1 for i in xticks])
# Trun of cartopy axis
# gl.xlabels_bottom = False
#
# Add main labels
# for lon in np.arange(-27, -12, 3):
# buffer = 0.25
# ax.text(x0-buffer, lon, '{}'.format(lon), fontsize=10, alpha=0.5,
# horizontalalignment='center', transform=ccrs.PlateCarree())
# Add the grid box with maximum NOy*Dust (print value)
if (region == 'Cape_Verde_Flying') and | |
max_level:
raise AAAException("Unauthorized role")
registration_code = uuid.uuid4().hex
creation_date = str(datetime.utcnow())
# send registration email
email_text = bottle.template(email_template,
username=username,
email_addr=email_addr,
role=role,
creation_date=creation_date,
registration_code=registration_code
)
self.mailer.send_email(email_addr, subject, email_text)
# store pending registration
self._store.pending_registrations[registration_code] = {
'username': username,
'role': role,
'hash': self._hash(username, password),
'email_addr': email_addr,
'desc': description,
'creation_date': creation_date,
}
self._store.save_pending_registrations()
def validate_registration(self, registration_code):
"""Validate pending account registration, create a new account if
successful.
:param registration_code: registration code
:type registration_code: str.
"""
try:
data = self._store.pending_registrations.pop(registration_code)
except KeyError:
raise AuthException("Invalid registration code.")
username = data['username']
if username in self._store.users:
raise AAAException("User is already existing.")
# the user data is moved from pending_registrations to _users
self._store.users[username] = {
'role': data['role'],
'hash': data['hash'],
'email_addr': data['email_addr'],
'desc': data['desc'],
'creation_date': data['creation_date'],
'last_login': str(datetime.utcnow())
}
self._store.save_users()
def send_password_reset_email(self, username=None, email_addr=None,
subject="Password reset confirmation",
email_template='views/password_reset_email'):
"""Email the user with a link to reset his/her password
If only one parameter is passed, fetch the other from the users
database. If both are passed they will be matched against the users
database as a security check.
:param username: username
:type username: str.
:param email_addr: email address
:type email_addr: str.
:param subject: email subject
:type subject: str.
:param email_template: email template filename
:type email_template: str.
:raises: AAAException on missing username or email_addr,
AuthException on incorrect username/email_addr pair
"""
if username is None:
if email_addr is None:
raise AAAException("At least `username` or `email_addr` must" \
" be specified.")
# only email_addr is specified: fetch the username
for k, v in self._store.users.iteritems():
if v['email_addr'] == email_addr:
username = k
break
else:
raise AAAException("Email address not found.")
else: # username is provided
if username not in self._store.users:
raise AAAException("Nonexistent user.")
if email_addr is None:
email_addr = self._store.users[username].get('email_addr', None)
if not email_addr:
raise AAAException("Email address not available.")
else:
# both username and email_addr are provided: check them
stored_email_addr = self._store.users[username]['email_addr']
if email_addr != stored_email_addr:
raise AuthException("Username/email address pair not found.")
# generate a reset_code token
reset_code = self._reset_code(username, email_addr)
# send reset email
email_text = bottle.template(email_template,
username=username,
email_addr=email_addr,
reset_code=reset_code
)
self.mailer.send_email(email_addr, subject, email_text)
def reset_password(self, reset_code, password):
"""Validate reset_code and update the account password
The username is extracted from the reset_code token
:param reset_code: reset token
:type reset_code: str.
:param password: <PASSWORD>
:type password: str.
:raises: AuthException for invalid reset tokens, AAAException
"""
try:
reset_code = b64decode(reset_code)
username, email_addr, tstamp, h = reset_code.split(':', 3)
tstamp = int(tstamp)
except (TypeError, ValueError):
raise AuthException("Invalid reset code.")
if time() - tstamp > self.password_reset_timeout:
raise AuthException("Expired reset code.")
if not self._verify_password(username, email_addr, h):
raise AuthException("Invalid reset code.")
user = self.user(username)
if user is None:
raise AAAException("Nonexistent user.")
user.update(pwd=password)
def make_auth_decorator(self, username=None, role=None, fixed_role=False, fail_redirect='/login'):
'''
Create a decorator to be used for authentication and authorization
:param username: A resource can be protected for a specific user
:param role: Minimum role level required for authorization
:param fixed_role: Only this role gets authorized
:param fail_redirect: The URL to redirect to if a login is required.
'''
session_manager = self
def auth_require(username=username, role=role, fixed_role=fixed_role,
fail_redirect=fail_redirect):
def decorator(func):
import functools
@functools.wraps(func)
def wrapper(*a, **ka):
session_manager.require(username=username, role=role, fixed_role=fixed_role,
fail_redirect=fail_redirect)
return func(*a, **ka)
return wrapper
return decorator
return(auth_require)
## Private methods
@property
def _beaker_session(self):
"""Get Beaker session"""
return bottle.request.environ.get('beaker.session')
def _setup_cookie(self, username):
"""Setup cookie for a user that just logged in"""
session = self._beaker_session
session['username'] = username
if self.session_domain is not None:
session.domain = self.session_domain
session.save()
def _hash(self, username, pwd, salt=None, algo=None):
"""Hash username and password, generating salt value if required
"""
if algo is None:
algo = self.preferred_hashing_algorithm
if algo == 'PBKDF2':
return self._hash_pbkdf2(username, pwd, salt=salt)
if algo == 'scrypt':
return self._hash_scrypt(username, pwd, salt=salt)
raise RuntimeError("Unknown hashing algorithm requested: %s" % algo)
@staticmethod
def _hash_scrypt(username, pwd, salt=None):
"""Hash username and password, generating salt value if required
Use scrypt.
:returns: base-64 encoded str.
"""
if not scrypt_available:
raise Exception("scrypt.hash required."
" Please install the scrypt library.")
if salt is None:
salt = os.urandom(32)
assert len(salt) == 32, "Incorrect salt length"
cleartext = "%s\0%s" % (username, pwd)
h = scrypt.hash(cleartext, salt)
# 's' for scrypt
return b64encode('s' + salt + h)
@staticmethod
def _hash_pbkdf2(username, pwd, salt=None):
"""Hash username and password, generating salt value if required
Use PBKDF2 from Beaker
:returns: base-64 encoded str.
"""
if salt is None:
salt = os.urandom(32)
assert len(salt) == 32, "Incorrect salt length"
cleartext = "%s\0%s" % (username, pwd)
h = crypto.generateCryptoKeys(cleartext, salt, 10)
if len(h) != 32:
raise RuntimeError("The PBKDF2 hash is %d bytes long instead"
"of 32. The pycrypto library might be missing." % len(h))
# 'p' for PBKDF2
return b64encode('p' + salt + h)
def _verify_password(self, username, pwd, salted_hash):
"""Verity username/password pair against a salted hash
:returns: bool
"""
decoded = b64decode(salted_hash)
hash_type = decoded[0]
salt = decoded[1:33]
if hash_type == 'p': # PBKDF2
h = self._hash_pbkdf2(username, pwd, salt)
return salted_hash == h
if hash_type == 's': # scrypt
h = self._hash_scrypt(username, pwd, salt)
return salted_hash == h
raise RuntimeError("Unknown hashing algorithm: %s" % hash_type)
def _purge_expired_registrations(self, exp_time=96):
"""Purge expired registration requests.
:param exp_time: expiration time (hours)
:type exp_time: float.
"""
for uuid, data in self._store.pending_registrations.items():
creation = datetime.strptime(data['creation_date'],
"%Y-%m-%d %H:%M:%S.%f")
now = datetime.utcnow()
maxdelta = timedelta(hours=exp_time)
if now - creation > maxdelta:
self._store.pending_registrations.pop(uuid)
def _reset_code(self, username, email_addr):
"""generate a reset_code token
:param username: username
:type username: str.
:param email_addr: email address
:type email_addr: str.
:returns: Base-64 encoded token
"""
h = self._hash(username, email_addr)
t = "%d" % time()
reset_code = ':'.join((username, email_addr, t, h))
return b64encode(reset_code)
class User(object):
def __init__(self, username, cork_obj, session=None):
"""Represent an authenticated user, exposing useful attributes:
username, role, level, description, email_addr, session_creation_time,
session_accessed_time, session_id. The session-related attributes are
available for the current user only.
:param username: username
:type username: str.
:param cork_obj: instance of :class:`Cork`
"""
self._cork = cork_obj
assert username in self._cork._store.users, "Unknown user"
self.username = username
user_data = self._cork._store.users[username]
self.role = user_data['role']
self.description = user_data['desc']
self.email_addr = user_data['email_addr']
self.level = self._cork._store.roles[self.role]
if session is not None:
try:
self.session_creation_time = session['_creation_time']
self.session_accessed_time = session['_accessed_time']
self.session_id = session['_id']
except:
pass
def update(self, role=None, pwd=None, email_addr=None):
"""Update an user account data
:param role: change user role, if specified
:type role: str.
:param pwd: change user password, if specified
:type pwd: str.
:param email_addr: change user email address, if specified
:type email_addr: str.
:raises: AAAException on nonexistent user or role.
"""
username = self.username
if username not in self._cork._store.users:
raise AAAException("User does not exist.")
if role is not None:
if role not in self._cork._store.roles:
raise AAAException("Nonexistent role.")
self._cork._store.users[username]['role'] = role
if pwd is not None:
self._cork._store.users[username]['hash'] = self._cork._hash(
username, pwd)
if email_addr is not None:
self._cork._store.users[username]['email_addr'] = email_addr
self._cork._store.save_users()
def delete(self):
"""Delete user account
:raises: AAAException on nonexistent user.
"""
try:
self._cork._store.users.pop(self.username)
except KeyError:
raise AAAException("Nonexistent user.")
self._cork._store.save_users()
class Mailer(object):
def __init__(self, sender, smtp_url, join_timeout=5):
"""Send emails asyncronously
:param sender: Sender email address
:type sender: str.
:param smtp_server: SMTP server
:type smtp_server: str.
"""
self.sender = sender
self.join_timeout = join_timeout
self._threads = []
self._conf = self._parse_smtp_url(smtp_url)
def _parse_smtp_url(self, url):
"""Parse SMTP URL"""
match = re.match(r"""
( # Optional protocol
(?P<proto>smtp|starttls|ssl) # Protocol name
://
)?
( # Optional user:pass@
(?P<user>[^:]*) # Match every char except ':'
(: (?P<pass>.*) )? @ # Optional :pass
)?
(?P<fqdn> # Required FQDN on IP address
()| # Empty string
( # FQDN
[a-zA-Z_\-] # First character cannot be a number
[a-zA-Z0-9_\-\.]{,254}
)
|( # IPv4
([0-9]{1,3}\.){3}
[0-9]{1,3}
)
|( # IPv6
\[ # Square brackets
([0-9a-f]{,4}:){1,8}
[0-9a-f]{,4}
\]
)
)
( # Optional :port
:
(?P<port>[0-9]{,5}) # Up to 5-digits port
)?
[/]?
$
""", url, re.VERBOSE)
if not match:
raise RuntimeError("SMTP URL seems incorrect")
d = match.groupdict()
if d['proto'] is None:
d['proto'] = 'smtp'
if d['port'] is None:
d['port'] = 25
else:
d['port'] = int(d['port'])
if not 0 < d['port'] < 65536:
raise RuntimeError("Incorrect SMTP port")
return d
def send_email(self, email_addr, subject, email_text):
"""Send an email
:param email_addr: email address
:type email_addr: str.
:param subject: subject
:type subject: str.
:param | |
('t_3', 'v_6')},
'>': {('c_1', 'v_1'), ('t_3', 'v_4'), ('t_1', 'v_5'), ('t_2', 'v_1'), ('t_3', 'v_2'), ('t_1', 'v_3'),
('t_1', 'v_4'), ('t_2', 'v_6'), ('c_1', 'v_5'), ('t_2', 'v_3'), ('t_1', 'v_6'), ('c_1', 't_1'),
('t_3', 'v_5'), ('t_1', 'v_2'), ('c_1', 'v_4'), ('t_3', 'v_1'), ('c_1', 't_2'), ('t_2', 'v_4'),
('c_1', 'v_6'), ('t_2', 'v_2'), ('t_3', 'v_6'), ('t_1', 'v_1'), ('c_1', 'v_2'), ('t_3', 'v_3'),
('c_1', 't_3'), ('c_1', 'v_3'), ('t_2', 'v_5')}},
{'DOMAIN': {'v_1', 'v_4', 't_2', 't_1', 'c_1', 'v_2', 't_3', 'v_6', 'v_5', 'v_3'}, 'City': {'c_1'},
'Town': {'t_3', 't_2', 't_1'}, 'Village': {'v_4', 'v_1', 'v_2', 'v_6', 'v_5', 'v_3'},
'Road': {('t_2', 'v_6'), ('v_3', 't_1'), ('t_1', 'v_2'), ('t_3', 'v_4'), ('t_1', 'c_1'), ('v_5', 't_3'),
('c_1', 't_3'), ('c_1', 't_2'), ('t_2', 'v_1'), ('c_1', 't_1'), ('v_6', 't_2'), ('v_2', 't_1'),
('t_2', 'c_1'), ('v_1', 't_2'), ('v_4', 't_3'), ('t_1', 'v_3'), ('t_3', 'c_1'), ('t_3', 'v_5')},
'>': {('c_1', 'v_1'), ('t_3', 'v_4'), ('t_1', 'v_5'), ('t_2', 'v_1'), ('t_3', 'v_2'), ('t_1', 'v_3'),
('t_1', 'v_4'), ('t_2', 'v_6'), ('c_1', 'v_5'), ('t_2', 'v_3'), ('t_1', 'v_6'), ('c_1', 't_1'),
('t_3', 'v_5'), ('t_1', 'v_2'), ('c_1', 'v_4'), ('t_3', 'v_1'), ('c_1', 't_2'), ('t_2', 'v_4'),
('c_1', 'v_6'), ('t_2', 'v_2'), ('t_3', 'v_6'), ('t_1', 'v_1'), ('c_1', 'v_2'), ('t_3', 'v_3'),
('c_1', 't_3'), ('c_1', 'v_3'), ('t_2', 'v_5')}},
{'DOMAIN': {'v_1', 'v_4', 't_2', 't_1', 'c_1', 'v_2', 't_3', 'v_6', 'v_5', 'v_3'}, 'City': {'c_1'},
'Town': {'t_3', 't_2', 't_1'}, 'Village': {'v_4', 'v_1', 'v_2', 'v_6', 'v_5', 'v_3'},
'Road': {('v_3', 't_1'), ('t_1', 'v_2'), ('v_5', 't_2'), ('t_3', 'v_1'), ('t_1', 'c_1'), ('c_1', 't_3'),
('c_1', 't_2'), ('t_2', 'v_4'), ('v_6', 't_3'), ('c_1', 't_1'), ('t_2', 'v_5'), ('t_2', 'c_1'),
('v_2', 't_1'), ('v_1', 't_3'), ('v_4', 't_2'), ('t_1', 'v_3'), ('t_3', 'c_1'), ('t_3', 'v_6')},
'>': {('c_1', 'v_1'), ('t_3', 'v_4'), ('t_1', 'v_5'), ('t_2', 'v_1'), ('t_3', 'v_2'), ('t_1', 'v_3'),
('t_1', 'v_4'), ('t_2', 'v_6'), ('c_1', 'v_5'), ('t_2', 'v_3'), ('t_1', 'v_6'), ('c_1', 't_1'),
('t_3', 'v_5'), ('t_1', 'v_2'), ('c_1', 'v_4'), ('t_3', 'v_1'), ('c_1', 't_2'), ('t_2', 'v_4'),
('c_1', 'v_6'), ('t_2', 'v_2'), ('t_3', 'v_6'), ('t_1', 'v_1'), ('c_1', 'v_2'), ('t_3', 'v_3'),
('c_1', 't_3'), ('c_1', 'v_3'), ('t_2', 'v_5')}},
{'DOMAIN': {'v_1', 'v_4', 't_2', 't_1', 'c_1', 'v_2', 't_3', 'v_6', 'v_5', 'v_3'}, 'City': {'c_1'},
'Town': {'t_3', 't_2', 't_1'}, 'Village': {'v_4', 'v_1', 'v_2', 'v_6', 'v_5', 'v_3'},
'Road': {('t_2', 'v_6'), ('v_3', 't_1'), ('t_1', 'v_2'), ('t_3', 'v_1'), ('t_1', 'c_1'), ('v_5', 't_3'),
('c_1', 't_3'), ('c_1', 't_2'), ('t_2', 'v_4'), ('c_1', 't_1'), ('v_6', 't_2'), ('v_2', 't_1'),
('t_2', 'c_1'), ('v_4', 't_2'), ('v_1', 't_3'), ('t_1', 'v_3'), ('t_3', 'c_1'), ('t_3', 'v_5')},
'>': {('c_1', 'v_1'), ('t_3', 'v_4'), ('t_1', 'v_5'), ('t_2', 'v_1'), ('t_3', 'v_2'), ('t_1', 'v_3'),
('t_1', 'v_4'), ('t_2', 'v_6'), ('c_1', 'v_5'), ('t_2', 'v_3'), ('t_1', 'v_6'), ('c_1', 't_1'),
('t_3', 'v_5'), ('t_1', 'v_2'), ('c_1', 'v_4'), ('t_3', 'v_1'), ('c_1', 't_2'), ('t_2', 'v_4'),
('c_1', 'v_6'), ('t_2', 'v_2'), ('t_3', 'v_6'), ('t_1', 'v_1'), ('c_1', 'v_2'), ('t_3', 'v_3'),
('c_1', 't_3'), ('c_1', 'v_3'), ('t_2', 'v_5')}},
{'DOMAIN': {'v_1', 'v_4', 't_2', 't_1', 'c_1', 'v_2', 't_3', 'v_6', 'v_5', 'v_3'}, 'City': {'c_1'},
'Town': {'t_3', 't_2', 't_1'}, 'Village': {'v_4', 'v_1', 'v_2', 'v_6', 'v_5', 'v_3'},
'Road': {('t_2', 'v_6'), ('v_3', 't_1'), ('t_1', 'v_2'), ('v_5', 't_2'), ('t_3', 'v_1'), ('t_1', 'c_1'),
('t_3', 'v_4'), ('v_4', 't_3'), ('c_1', 't_3'), ('c_1', 't_2'), ('c_1', 't_1'), ('v_6', 't_2'),
('t_2', 'v_5'), ('t_2', 'c_1'), ('v_2', 't_1'), ('v_1', 't_3'), ('t_1', 'v_3'), ('t_3', 'c_1')},
'>': {('c_1', 'v_1'), ('t_3', 'v_4'), ('t_1', 'v_5'), ('t_2', 'v_1'), ('t_3', 'v_2'), ('t_1', 'v_3'),
('t_1', 'v_4'), ('t_2', 'v_6'), ('c_1', 'v_5'), ('t_2', 'v_3'), ('t_1', 'v_6'), ('c_1', 't_1'),
('t_3', 'v_5'), ('t_1', 'v_2'), ('c_1', 'v_4'), ('t_3', 'v_1'), ('c_1', 't_2'), ('t_2', 'v_4'),
('c_1', 'v_6'), ('t_2', 'v_2'), ('t_3', 'v_6'), ('t_1', 'v_1'), ('c_1', 'v_2'), ('t_3', 'v_3'),
('c_1', 't_3'), ('c_1', 'v_3'), ('t_2', 'v_5')}},
{'DOMAIN': {'v_1', 'v_4', 't_2', 't_1', 'c_1', 'v_2', 't_3', 'v_6', 'v_5', 'v_3'}, 'City': {'c_1'},
'Town': {'t_3', 't_2', 't_1'}, 'Village': {'v_4', 'v_1', 'v_2', 'v_6', 'v_5', 'v_3'},
'Road': {('v_3', 't_2'), ('t_1', 'v_4'), ('t_1', 'v_2'), ('t_2', 'v_3'), ('t_1', 'c_1'), ('v_5', 't_3'),
('c_1', 't_3'), ('c_1', 't_2'), ('t_2', 'v_1'), ('v_6', 't_3'), ('c_1', 't_1'), ('v_2', 't_1'),
('t_2', 'c_1'), ('v_1', 't_2'), ('v_4', 't_1'), ('t_3', 'v_5'), ('t_3', 'c_1'), ('t_3', 'v_6')},
'>': {('c_1', 'v_1'), ('t_3', 'v_4'), ('t_1', 'v_5'), ('t_2', 'v_1'), ('t_3', 'v_2'), ('t_1', 'v_3'),
('t_1', 'v_4'), ('t_2', 'v_6'), ('c_1', 'v_5'), ('t_2', 'v_3'), ('t_1', 'v_6'), ('c_1', 't_1'),
('t_3', 'v_5'), ('t_1', 'v_2'), ('c_1', 'v_4'), ('t_3', 'v_1'), ('c_1', 't_2'), ('t_2', 'v_4'),
('c_1', 'v_6'), ('t_2', 'v_2'), ('t_3', 'v_6'), ('t_1', 'v_1'), ('c_1', 'v_2'), ('t_3', 'v_3'),
('c_1', 't_3'), ('c_1', 'v_3'), ('t_2', 'v_5')}},
{'DOMAIN': {'v_1', 'v_4', 't_2', 't_1', 'c_1', 'v_2', 't_3', 'v_6', 'v_5', 'v_3'}, 'City': {'c_1'},
'Town': {'t_3', 't_2', 't_1'}, 'Village': {'v_4', 'v_1', 'v_2', 'v_6', 'v_5', 'v_3'},
'Road': {('t_1', 'v_4'), ('t_1', 'v_2'), ('v_5', 't_2'), ('t_1', 'c_1'), ('t_3', 'v_3'), ('c_1', 't_3'),
('c_1', 't_2'), ('t_2', 'v_1'), ('v_6', 't_3'), ('c_1', 't_1'), ('t_2', 'v_5'), ('t_2', 'c_1'),
('v_1', 't_2'), ('v_2', 't_1'), ('v_4', 't_1'), ('t_3', 'c_1'), ('t_3', 'v_6'), ('v_3', 't_3')},
'>': {('c_1', 'v_1'), ('t_3', 'v_4'), ('t_1', 'v_5'), ('t_2', 'v_1'), ('t_3', 'v_2'), ('t_1', 'v_3'),
('t_1', 'v_4'), ('t_2', 'v_6'), ('c_1', 'v_5'), ('t_2', 'v_3'), ('t_1', 'v_6'), ('c_1', 't_1'),
('t_3', 'v_5'), ('t_1', 'v_2'), ('c_1', 'v_4'), ('t_3', 'v_1'), ('c_1', 't_2'), ('t_2', 'v_4'),
('c_1', 'v_6'), ('t_2', 'v_2'), ('t_3', 'v_6'), ('t_1', 'v_1'), ('c_1', 'v_2'), ('t_3', 'v_3'),
('c_1', 't_3'), ('c_1', 'v_3'), ('t_2', 'v_5')}},
{'DOMAIN': {'v_1', 'v_4', 't_2', 't_1', 'c_1', 'v_2', 't_3', 'v_6', 'v_5', 'v_3'}, 'City': {'c_1'},
'Town': {'t_3', 't_2', 't_1'}, 'Village': {'v_4', 'v_1', 'v_2', 'v_6', 'v_5', 'v_3'},
'Road': {('t_1', 'v_4'), ('t_2', 'v_6'), ('t_1', 'v_2'), ('t_1', 'c_1'), ('t_3', 'v_3'), ('v_5', 't_3'),
('c_1', 't_3'), ('c_1', 't_2'), ('t_2', 'v_1'), ('c_1', 't_1'), ('v_6', 't_2'), ('v_2', 't_1'),
('t_2', 'c_1'), ('v_1', 't_2'), ('v_4', 't_1'), ('t_3', 'v_5'), ('t_3', 'c_1'), ('v_3', 't_3')},
'>': {('c_1', 'v_1'), ('t_3', 'v_4'), ('t_1', 'v_5'), ('t_2', 'v_1'), ('t_3', 'v_2'), ('t_1', 'v_3'),
('t_1', 'v_4'), ('t_2', 'v_6'), ('c_1', 'v_5'), ('t_2', 'v_3'), ('t_1', 'v_6'), ('c_1', 't_1'),
('t_3', 'v_5'), ('t_1', 'v_2'), ('c_1', 'v_4'), ('t_3', 'v_1'), ('c_1', 't_2'), ('t_2', 'v_4'),
('c_1', 'v_6'), ('t_2', 'v_2'), ('t_3', 'v_6'), ('t_1', 'v_1'), ('c_1', 'v_2'), ('t_3', 'v_3'),
('c_1', 't_3'), ('c_1', 'v_3'), ('t_2', 'v_5')}},
{'DOMAIN': {'v_1', 'v_4', 't_2', 't_1', 'c_1', 'v_2', 't_3', 'v_6', 'v_5', 'v_3'}, 'City': {'c_1'},
'Town': {'t_3', 't_2', 't_1'}, 'Village': {'v_4', 'v_1', 'v_2', 'v_6', 'v_5', 'v_3'},
'Road': {('v_3', 't_2'), ('t_1', 'v_4'), ('t_1', 'v_2'), ('t_2', 'v_3'), ('v_5', 't_2'), ('t_3', 'v_1'),
('t_1', 'c_1'), ('c_1', 't_3'), ('c_1', 't_2'), ('v_6', 't_3'), ('c_1', 't_1'), ('t_2', 'v_5'),
('t_2', 'c_1'), ('v_2', 't_1'), ('v_1', 't_3'), ('v_4', 't_1'), ('t_3', 'c_1'), ('t_3', 'v_6')},
'>': {('c_1', 'v_1'), ('t_3', 'v_4'), ('t_1', 'v_5'), ('t_2', 'v_1'), ('t_3', 'v_2'), ('t_1', 'v_3'),
('t_1', 'v_4'), ('t_2', 'v_6'), ('c_1', 'v_5'), ('t_2', 'v_3'), ('t_1', 'v_6'), ('c_1', 't_1'),
('t_3', 'v_5'), ('t_1', 'v_2'), ('c_1', 'v_4'), ('t_3', 'v_1'), ('c_1', 't_2'), ('t_2', 'v_4'),
('c_1', 'v_6'), ('t_2', 'v_2'), ('t_3', 'v_6'), ('t_1', 'v_1'), ('c_1', 'v_2'), ('t_3', 'v_3'),
('c_1', 't_3'), ('c_1', 'v_3'), ('t_2', 'v_5')}},
{'DOMAIN': {'v_1', 'v_4', 't_2', 't_1', 'c_1', 'v_2', 't_3', 'v_6', 'v_5', 'v_3'}, 'City': {'c_1'},
'Town': {'t_3', 't_2', 't_1'}, 'Village': {'v_4', 'v_1', 'v_2', 'v_6', 'v_5', 'v_3'},
'Road': {('v_3', 't_2'), ('t_1', 'v_4'), ('t_2', 'v_6'), ('t_1', 'v_2'), ('t_2', 'v_3'), ('t_3', 'v_1'),
('t_1', 'c_1'), ('v_5', 't_3'), ('c_1', 't_3'), ('c_1', 't_2'), ('c_1', 't_1'), ('v_6', 't_2'),
('v_2', 't_1'), ('t_2', 'c_1'), ('v_1', 't_3'), ('v_4', 't_1'), ('t_3', 'v_5'), ('t_3', 'c_1')},
'>': {('c_1', 'v_1'), ('t_3', 'v_4'), ('t_1', 'v_5'), ('t_2', 'v_1'), ('t_3', 'v_2'), ('t_1', 'v_3'),
('t_1', 'v_4'), ('t_2', 'v_6'), ('c_1', 'v_5'), ('t_2', 'v_3'), ('t_1', 'v_6'), ('c_1', 't_1'),
('t_3', 'v_5'), ('t_1', 'v_2'), ('c_1', 'v_4'), ('t_3', 'v_1'), ('c_1', 't_2'), ('t_2', 'v_4'),
('c_1', 'v_6'), ('t_2', 'v_2'), ('t_3', 'v_6'), ('t_1', 'v_1'), ('c_1', 'v_2'), ('t_3', 'v_3'),
('c_1', 't_3'), ('c_1', 'v_3'), ('t_2', 'v_5')}},
{'DOMAIN': {'v_1', 'v_4', 't_2', 't_1', 'c_1', 'v_2', 't_3', 'v_6', 'v_5', 'v_3'}, 'City': {'c_1'},
'Town': {'t_3', 't_2', 't_1'}, 'Village': {'v_4', 'v_1', 'v_2', 'v_6', 'v_5', 'v_3'},
'Road': {('t_1', 'v_4'), ('t_2', 'v_6'), ('t_1', 'v_2'), ('v_5', 't_2'), ('t_3', 'v_1'), ('t_1', 'c_1'),
('t_3', 'v_3'), ('c_1', 't_3'), ('c_1', 't_2'), ('c_1', 't_1'), ('v_6', 't_2'), ('t_2', 'v_5'),
('t_2', 'c_1'), ('v_2', 't_1'), ('v_1', 't_3'), ('v_4', 't_1'), ('t_3', 'c_1'), ('v_3', 't_3')},
'>': {('c_1', 'v_1'), ('t_3', 'v_4'), ('t_1', 'v_5'), ('t_2', 'v_1'), ('t_3', 'v_2'), ('t_1', 'v_3'),
('t_1', 'v_4'), ('t_2', 'v_6'), ('c_1', 'v_5'), ('t_2', 'v_3'), ('t_1', 'v_6'), ('c_1', 't_1'),
('t_3', 'v_5'), ('t_1', 'v_2'), ('c_1', 'v_4'), ('t_3', 'v_1'), ('c_1', 't_2'), ('t_2', 'v_4'),
('c_1', 'v_6'), ('t_2', 'v_2'), ('t_3', 'v_6'), ('t_1', 'v_1'), ('c_1', 'v_2'), ('t_3', 'v_3'),
('c_1', 't_3'), ('c_1', 'v_3'), ('t_2', 'v_5')}},
{'DOMAIN': {'v_1', 'v_4', 't_2', 't_1', 'c_1', 'v_2', 't_3', 'v_6', 'v_5', 'v_3'}, 'City': {'c_1'},
'Town': {'t_3', 't_2', 't_1'}, 'Village': {'v_4', 'v_1', 'v_2', 'v_6', 'v_5', 'v_3'},
'Road': {('v_3', 't_2'), ('t_1', 'v_2'), ('t_2', 'v_3'), ('v_5', 't_1'), ('t_3', 'v_4'), ('t_1', 'c_1'),
('t_1', 'v_5'), ('c_1', 't_3'), ('c_1', 't_2'), ('t_2', 'v_1'), ('v_6', 't_3'), ('c_1', 't_1'),
('v_2', 't_1'), ('t_2', 'c_1'), ('v_1', 't_2'), ('v_4', 't_3'), ('t_3', 'c_1'), ('t_3', 'v_6')},
'>': {('c_1', | |
roi_h, roi_w, 1) mask of valid pixels
"""
depth_map_shape = depth_map.shape
if len(depth_map_shape) != 2:
raise ValueError('Invalid depth_map_shape', depth_map_shape)
all_inst_depth_crops, all_inst_valid_masks = np_instance_crop(
boxes_2d=boxes_2d,
boxes_3d=boxes_3d,
instance_masks=instance_masks,
input_map=np.expand_dims(depth_map, 2),
roi_size=roi_size,
view_norm=False)
camN_inst_pc_maps = [depth_map_utils.depth_patch_to_pc_map(
inst_depth_crop, box_2d, cam_p, roi_size, depth_map_shape=depth_map.shape[0:2],
use_pixel_centres=use_pixel_centres, use_corr_factors=use_corr_factors)
for inst_depth_crop, box_2d in zip(all_inst_depth_crops, boxes_2d)]
# Get x offset (b_cam) from calibration: cam_mat[0, 3] = (-f_x * b_cam)
x_offset = -cam_p[0, 3] / cam_p[0, 0]
camN_centroids = boxes_3d[:, 0:3] - [x_offset, 0, 0]
if centroid_type == 'middle':
# Move centroid to half the box height
half_h = boxes_3d[:, 5] / 2.0
camN_centroids[:, 1] -= half_h
if not rotate_view:
viewing_angles = np.zeros_like(viewing_angles)
inst_xyz_maps_local = [
apply_view_norm_to_pc_map(inst_pc_map, valid_mask, viewing_angle, centroid, roi_size)
for inst_pc_map, valid_mask, viewing_angle, centroid in zip(
camN_inst_pc_maps, all_inst_valid_masks, viewing_angles, camN_centroids)]
return inst_xyz_maps_local, all_inst_valid_masks
def tf_instance_xyz_crop_from_depth_map(box_idx, tf_boxes_2d, tf_boxes_3d, tf_instance_masks,
tf_depth_map_batched, roi_size, tf_viewing_angles, cam_p,
view_norm=False, centroid_type='bottom', rotate_view=True):
"""Crops the depth map for an instance and returns local instance xyz crops
Args:
box_idx: box index
tf_boxes_2d: (N, 4) 2D boxes [y1, x1, y2, x2]
tf_boxes_3d: (N, 6) 3D boxes
tf_instance_masks: (N, H, W) boolean instance masks
tf_depth_map_batched: (1, H, W, 1) depth map
roi_size: [h, w] roi crop size
tf_viewing_angles: (N) viewing angles
cam_p: (3, 4) Camera projection matrix
view_norm: bool whether to perform any view normalization
centroid_type (string): centroid position (bottom or middle)
rotate_view: bool whether to rotate by viewing angle
Returns:
xyz_out: (N, roi_h, roi_w, 3) instance xyz map in local coordinate frame
valid_pixel_mask: (N, roi_h, roi_w, 1) mask of valid pixels
"""
# TODO: Add other representations (e.g. depth or distance)
with tf.variable_scope('crop_{}'.format(box_idx)):
box_2d = tf_boxes_2d[box_idx]
box_2d_rounded = tf.to_int32(tf.round(box_2d))
instance_mask = tf_instance_masks[box_idx]
depth_map_masked = tf_depth_map_batched * tf.expand_dims(instance_mask, axis=2)
depth_map_cropped = depth_map_masked[:,
box_2d_rounded[0]:box_2d_rounded[2],
box_2d_rounded[1]:box_2d_rounded[3]]
depth_map_resized = tf.image.resize_nearest_neighbor(
depth_map_cropped, roi_size, align_corners=True)
# Convert to xyz map
inst_pc_map = depth_map_utils.tf_depth_patch_to_pc_map(
depth_map_resized, box_2d, cam_p, roi_size, use_pixel_centres=True)
# Calculate valid pixel mask
valid_pixel_mask = tf.reduce_max(
tf.to_float(tf.greater_equal(tf.abs(depth_map_resized), 0.1)), axis=3, keepdims=True)
if view_norm:
# Get viewing angle rotation matrix
viewing_angle = tf_viewing_angles[box_idx]
cam0_centroid = tf_boxes_3d[box_idx, 0:3]
# Get x offset (b_cam) from calibration: cam_mat[0, 3] = (-f_x * b_cam)
x_offset = -cam_p[0, 3] / cam_p[0, 0]
camN_centroid = cam0_centroid - [x_offset, 0, 0]
if centroid_type == 'middle':
# Move centroid to half the box height
half_h = tf_boxes_3d[box_idx, 5] / 2.0
camN_centroid = camN_centroid - [0, half_h, 0]
if rotate_view:
tr_mat = transform_utils.tf_get_tr_mat(-viewing_angle, -camN_centroid)
else:
tr_mat = tf.to_float([
[1.0, 0.0, 0.0, -camN_centroid[0]],
[0.0, 1.0, 0.0, -camN_centroid[1]],
[0.0, 0.0, 1.0, -camN_centroid[2]],
[0.0, 0.0, 0.0, 1.0],
])
# Pad for matrix multiplication
# pc_resized = tf.transpose(tf.reshape(inst_pc_map, [-1, 3]))
pc_resized = tf.reshape(inst_pc_map, [3, -1])
pc_padded = tf.pad(pc_resized, [[0, 1], [0, 0]], constant_values=1.0)
# Transform into local space
xyz_local = tf.transpose(tf.matmul(tr_mat, pc_padded)[0:3])
xyz_local = tf.reshape(xyz_local, (1, *roi_size, 3))
# Only keep valid pixels
xyz_out = xyz_local * valid_pixel_mask
else:
# TODO: Directly reshape?
pc = tf.transpose(tf.reshape(inst_pc_map, [3, -1]))
xyz_out = tf.reshape(pc, (1, *roi_size, 3)) * valid_pixel_mask
# return xyz_masked, xyz_resized, xyz_normalized
return tf.stop_gradient(xyz_out), valid_pixel_mask
def tf_crop_and_resize_instance_masks(instance_masks, boxes_2d, roi_size, box_idx):
"""Crops and resize instance masks using nearest neighbor
Args:
instance_masks: (N, H, W) instance mask
boxes_2d: (N, 4) box 2d
roi_size: ROI size [h, w]
box_idx: Box index
Returns:
instance_maps_cropped_resized: instance mask cropped and resized
"""
box_2d = boxes_2d[box_idx]
box_2d_rounded = tf.to_int32(tf.round(box_2d))
instance_mask = instance_masks[box_idx]
instance_masks_batched = tf.expand_dims(instance_mask, axis=0)
instance_masks_cropped = instance_masks_batched[:,
box_2d_rounded[0]: box_2d_rounded[2],
box_2d_rounded[1]: box_2d_rounded[3]]
instance_maps_cropped_resized = tf.image.resize_nearest_neighbor(
tf.expand_dims(instance_masks_cropped, axis=3), roi_size, align_corners=True)
return instance_maps_cropped_resized
def apply_view_norm_to_pc_map(inst_pc_map, valid_mask_map, viewing_angle, centroid, roi_size):
"""Applies view normalization on instance pc map
Args:
inst_pc_map: (3, H, W) Instance pc map
valid_mask_map: (H, W) Valid pixel mask
viewing_angle: Viewing angle
centroid: Centroid [x, y, z]
roi_size: ROI size [h, w]
Returns:
inst_xyz_map: (H, W, 3) View normalized xyz map
"""
# Apply view normalization
tr_mat = transform_utils.np_get_tr_mat(-viewing_angle, -centroid)
# Move to origin
inst_pc_padded = transform_utils.pad_pc(inst_pc_map.reshape(3, -1))
inst_pc_local = tr_mat.dot(inst_pc_padded)[0:3]
inst_xyz_map = np.reshape(inst_pc_local.T, (*roi_size, 3))
inst_xyz_map = inst_xyz_map * np.expand_dims(valid_mask_map, 2)
return inst_xyz_map
def inst_points_global_to_local(inst_points_global, viewing_angle, centroid):
"""Converts global points to local points in same camera frame."""
# Apply view normalization
rot_mat = transform_utils.np_get_tr_mat(-viewing_angle, -centroid)
# Rotate, then translate
inst_pc_padded = transform_utils.pad_pc(inst_points_global.T)
inst_pc_local = rot_mat.dot(inst_pc_padded)[0:3]
return inst_pc_local.T
def inst_points_local_to_global(inst_points_local, viewing_angle, centroid):
"""Converts local points to global points in same camera frame"""
# Rotate predicted instance points to viewing angle and translate to guessed centroid
rot_mat = transform_utils.np_get_tr_mat(viewing_angle, (0.0, 0.0, 0.0))
t_mat = transform_utils.np_get_tr_mat(0.0, centroid)
inst_points_rotated = transform_utils.apply_tr_mat_to_points(
rot_mat, inst_points_local)
inst_points_global = transform_utils.apply_tr_mat_to_points(t_mat, inst_points_rotated)
return inst_points_global
def tf_inst_xyz_map_local_to_global(inst_xyz_map_local, map_roi_size,
view_angs, centroids):
"""Converts a local instance xyz map to a global instance xyz map
Args:
inst_xyz_map_local: (N, H, W, 3) Local instance xyz map
map_roi_size: Map ROI size
view_angs: Viewing angles
centroids: (N, 3) Centroids
Returns:
inst_xyz_map_global: (N, H, W, 3) Global instance xyz map
"""
num_inst = inst_xyz_map_local.shape[0]
map_roi_h = map_roi_size[0]
map_roi_w = map_roi_size[1]
# Convert prediction maps to point cloud format
inst_pc_map_local = tf.transpose(inst_xyz_map_local, [0, 3, 1, 2])
inst_pc_local = tf.reshape(
inst_pc_map_local, [num_inst, 3, map_roi_h * map_roi_w])
# Transform to predicted global position
rot_mat, _, _ = transform_utils.tf_get_tr_mat_batch(view_angs, tf.zeros_like(centroids))
t_mat, _, _ = transform_utils.tf_get_tr_mat_batch(tf.zeros_like(view_angs), centroids)
# tr_mat, rot_mat, t_mat = transform_utils.tf_get_tr_mat_batch(view_angs, centroids)
inst_pc_local_padded = transform_utils.tf_pad_pc(inst_pc_local)
inst_pc_rotated = tf.matmul(rot_mat, inst_pc_local_padded)
inst_pc_global_padded = tf.matmul(t_mat, inst_pc_rotated)
# Convert to global xyz map
inst_pc_map_global = tf.reshape(inst_pc_global_padded[:, 0:3],
[num_inst, 3, map_roi_h, map_roi_w])
inst_xyz_map_global = tf.transpose(inst_pc_map_global, [0, 2, 3, 1])
return inst_xyz_map_global
def tf_inst_depth_map_local_to_global(inst_depth_map_local, global_depth,
box_2d=None, inst_view_ang=None,
map_roi_size=None, cam_p=None, rotate_view=False):
"""Converts a local instance depth map to a global instance depth map by adding a constant
to it. Optionally performs rotation to undo view normalization. See view_normalization_depth.py
Args:
inst_depth_map_local: Local depth map [N, H, W, 1]
global_depth: Scalar of how much to scale local depth by
box_2d: Box 2D of instance
inst_view_ang: Viewing angle of instance
map_roi_size: [H, W]
cam_p: camera projection matrix
rotate_view: Bool whether to undo view normalization
Returns:
inst_depth_map_global: Global depth map [N, H, W, 1]
"""
if rotate_view:
centre_u = cam_p[0, 2]
focal_length = cam_p[0, 0]
# Use 2D box left and right edges
box_x1 = box_2d[:, 1]
box_x2 = box_2d[:, 3]
# Account for pixel centres
grid_spacing = (box_x2 - box_x1) / map_roi_size[0] / 2.0
box_x1 += grid_spacing
box_x2 -= grid_spacing
# Assume depth of 1.0 to calculate viewing angle
# viewing_angle = atan2(i / f, 1.0)
view_ang_l = tf.atan2((box_x1 - centre_u) / focal_length, 1.0)
view_ang_l = tf.expand_dims(view_ang_l, axis=1)
view_ang_r = tf.atan2((box_x2 - centre_u) / focal_length, 1.0)
view_ang_r = tf.expand_dims(view_ang_r, axis=1)
inst_xz = global_depth / tf.cos(inst_view_ang)
# Calculate depth offset for each edge
l_o = inst_xz / tf.cos(view_ang_l - inst_view_ang)
r_o = inst_xz / tf.cos(view_ang_r - inst_view_ang)
x_l = l_o * tf.sin(view_ang_l - inst_view_ang)
x_r = r_o * tf.sin(view_ang_r - inst_view_ang)
offset_l = tf.squeeze(x_l * tf.sin(inst_view_ang))
offset_r = tf.squeeze(x_r * tf.sin(inst_view_ang))
# Linearly interpolate across
view_ang_depth_offset = \
tf.map_fn(lambda x: tf.linspace(x[0], x[1], map_roi_size[0]),
(-offset_l, -offset_r), dtype=tf.float32)
# Reshape for broadcasting
pred_cen_z_reshaped = tf.reshape(global_depth, [-1, 1, 1, 1])
view_ang_depth_offset_reshaped = \
tf.tile(tf.reshape(view_ang_depth_offset, (-1, map_roi_size[0], 1, 1)),
(1, 1, 48, 1))
# Get global point cloud
inst_depth_map_global = \
(inst_depth_map_local + pred_cen_z_reshaped + view_ang_depth_offset_reshaped)
else:
# Reshape for broadcasting
pred_cen_z_reshaped = tf.reshape(global_depth, [-1, 1, 1, 1])
# Add predicted centroid depth to get global depth
inst_depth_map_global = inst_depth_map_local + pred_cen_z_reshaped
return inst_depth_map_global
def get_exp_proj_uv_map(box_2d, roi_size, round_box_2d=False, use_pixel_centres=False):
"""Get expected grid projection of a 2D box based on roi size, if pixels are evenly spaced.
Points project to the top left of each pixel.
Args:
box_2d: 2D box
roi_size: ROI size [h, w]
use_pixel_centres: (optional) If True, return projections to centre of pixels
Returns:
proj_uv_map: (H, W, 2) Expected box_2d projection uv map
"""
# Grid start and stop
if round_box_2d:
inst_u1, inst_u2 = np.round(box_2d[[1, 3]])
inst_v1, inst_v2 = np.round(box_2d[[0, 2]])
else:
inst_u1, inst_u2 = box_2d[[1, 3]]
inst_v1, inst_v2 = box_2d[[0, 2]]
# Grid spacing
roi_h, roi_w = roi_size
grid_u_spacing = (inst_u2 - inst_u1) / roi_w
grid_v_spacing = (inst_v2 - inst_v1) / roi_h
if use_pixel_centres:
# Grid along u
grid_u_half_spacing = grid_u_spacing / 2.0
grid_u = np.linspace(
inst_u1 + grid_u_half_spacing,
inst_u2 - grid_u_half_spacing,
roi_w)
# Grid along v
grid_v_half_spacing | |
"""
Font Bakery callable is the wrapper for your custom check code.
Separation of Concerns Disclaimer:
While created specifically for running checks on fonts and font-families
this module has no domain knowledge about fonts. It can be used for any
kind of (document) checking. Please keep it so. It will be valuable for
other domains as well.
Domain specific knowledge should be encoded only in the Profile (Checks,
Conditions) and MAYBE in *customized* reporters e.g. subclasses.
"""
import inspect
from functools import wraps, update_wrapper
def cached_getter(func):
"""Decorate a property by executing it at instatiation time and cache the
result on the instance object."""
@wraps(func)
def wrapper(self):
attribute = f'_{func.__name__}'
value = getattr(self, attribute, None)
if value is None:
value = func(self)
setattr(self, attribute, value)
return value
return wrapper
class FontbakeryCallable:
def __init__(self, func):
self._args = None
self._mandatoryArgs = None
self._optionalArgs = None
# must be set by sub class
# this is set by update_wrapper
# self.__wrapped__ = func
# https://docs.python.org/2/library/functools.html#functools.update_wrapper
# Update a wrapper function to look like the wrapped function.
# ... assigns to the wrapper function’s __name__, __module__ and __doc__
update_wrapper(self, func)
def __repr__(self):
return'<{}:{}>'.format(type(self).__name__,
getattr(self, 'id',
getattr(self, 'name',
super(FontbakeryCallable, self).__repr__()
)))
@property
@cached_getter
def args(self):
return self.mandatoryArgs + self.optionalArgs
@property
@cached_getter
def mandatoryArgs(self):
args = list()
# make follow_wrapped=True explicit, even though it is the default!
sig = inspect.signature(self, follow_wrapped=True)
for name, param in sig.parameters.items():
if param.default is not inspect.Parameter.empty\
or param.kind not in (
inspect.Parameter.POSITIONAL_OR_KEYWORD
, inspect.Parameter.POSITIONAL_ONLY):
# has a default i.e. not mandatory or not positional of any kind
print(f'{param.default is inspect.Parameter.empty} param.kind: {param.kind} param.default: {param.default} BREAK')
break
args.append(name)
return tuple(args)
@property
@cached_getter
def optionalArgs(self):
args = list()
# make follow_wrapped=True explicit, even though it is the default!
sig = inspect.signature(self, follow_wrapped=True)
for name, param in sig.parameters.items():
if param.default is inspect.Parameter.empty:
# is a mandatory
continue
if param.kind not in (
inspect.Parameter.POSITIONAL_OR_KEYWORD
, inspect.Parameter.POSITIONAL_ONLY):
# no more positional of any kind
print(f'{param.default is inspect.Parameter.empty} param.kind: {param.kind} param.default: {param.default} BREAK')
break
args.append(name)
return tuple(args)
def __call__(self, *args, **kwds):
""" Each call to __call__ with the same arguments must return
the same result.
"""
return self.__wrapped__(*args, **kwds)
def get_doc_desc(func, description, documentation):
doc = inspect.getdoc(func) or ""
doclines = doc.split('\n')
if not description:
description = []
while len(doclines) and doclines[0]:
# consume until first empty line
description.append(doclines[0])
doclines = doclines[1:]
# This removes line breaks
description = ' '.join(description)
# remove preceding empty lines
while len(doclines) and not doclines[0]:
doclines = doclines[1:]
if not documentation and len(doclines):
documentation = '\n'.join(doclines) or None
return description, documentation
class FontBakeryCondition(FontbakeryCallable):
def __init__(
self,
func,
# id,
name = None, # very short text
description = None, # short text
documentation=None, # long text, markdown?
force=False
):
super(FontBakeryCondition, self).__init__(func)
# self.id = id
self.name = func.__name__ if name is None else name
self.description, self.documentation = get_doc_desc(
func, description, documentation)
self.force = force
class FontBakeryCheck(FontbakeryCallable):
def __init__(
self,
checkfunc,
id,
advancedMessageSetup=None,
description=None, # short text, this is mandatory
documentation=None,
name = None, # very short text
conditions=None,
# arguments_setup=None,
rationale=None, # long text explaining why this check is needed. Using markdown, perhaps?
misc_metadata=None, # miscelaneous free-form metadata fields
# some of them may be promoted to first-class metadata fields
# if they start being used by the check-runner.
# Below are a few candidates for that:
#affects=None, # A list of tuples each indicating Browser/OS/Application
# # and the affected versions range.
#request=None, # An URL to the original request for implementation of this check.
# # This is typically a github issue tracker URL.
#example_failures=None, # A reference to some font or family that originally failed due to
# # the problems that this check tries to detect and report.
#priority=None
):
"""This is the base class for all checks. It will usually
not be used directly to create check instances, rather
decorators which are factories will init this class.
Arguments:
checkfunc: callable, the check implementation itself.
id: use reverse domain name notation as a namespace and a
unique identifier (numbers or anything) but make sure that
it **never** **ever** changes, that it is **unique until
eternity**. This is meant to provide a way to track
burn-down or regressions in a project over time and maybe
to identify changed/updated check implementations for partial
profile re-evaluation (in contrast to full profile evaluation)
if the profile/check changed but not the font.
description: text, used as one line short description
read by humans
name: text, used as a short label read by humans, defaults
to checkfunc.__name__
conditions: a list of condition names that must be all true
in order for this check to be executed. conditions are similar
to checks, because they also inspect the check subject and they
also belong to the profile. However, they do not get reported
directly (there could be checks that report the result of a
condition). Conditions are **probably** registered and
referenced by name (like "isVariableFont"). We may accept a
python function for combining or negating a condition. It
receives the condition values as arguments, queried by name
via inspection, and returns True or False.
TODO: flesh out the format.
NOTE: `arguments_setup` is postponed until we have a case where it's needed.
arguments_setup: describes the arguments and position/keyword
of arguments `checkfunc` expects. Used to override any arguments
inferred via inspection of `checkfunc`.
`CheckRunner._get_check_dependencies` will use this information
to prepare the arguments for this check.
TODO: flesh out the format.
documentation: text, used as a detailed documentation,
read by humans(I suggest to make it markdown formatted).
advancedMessageSetup: depending on the instance of
AdvancedMessageType returned by the check, this is the
counterpart for it. Needed to make sense/use of an
advancedMessage.
TODO: Make a proposal for this.
TODO: This would be used to fix/hotfix issues etc. that means,
advancedMessageSetup would know how to fix an issue by
looking at an advancedMessage.
TODO: The naming is a bit odd.
priority: inherited from our legacy checks. Need to see if we
use this at all now.
"""
super(FontBakeryCheck, self).__init__(checkfunc)
self.id = id
self.name = checkfunc.__name__ if name is None else name
self.conditions = conditions or []
self.rationale = rationale
self.description, self.documentation = get_doc_desc(
checkfunc, description, documentation)
if not self.description:
raise TypeError('{} needs a description.'.format(type(self).__name__))
# self._arguments_setup = arguments_setup
# self._conditions_setup = conditions_setup
self._advancedMessageSetup = advancedMessageSetup
# This was problematic. See: https://github.com/googlefonts/fontbakery/issues/2194
# def __str__(self):
# return self.id
def condition(*args, **kwds):
"""Check wrapper, a factory for FontBakeryCondition
Requires all arguments of FontBakeryCondition but not `func`
which is passed via the decorator syntax.
"""
if len(args) == 1 and len(kwds) == 0 and callable(args[0]):
# used as `@decorator`
func = args[0]
return FontBakeryCondition(func)
else:
# used as `@decorator()` maybe with args
def wrapper(func):
return FontBakeryCondition(func, *args, **kwds)
return wrapper
def check(*args, **kwds):
"""Check wrapper, a factory for FontBakeryCheck
Requires all arguments of FontBakeryCheck but not `checkfunc`
which is passed via the decorator syntax.
"""
def wrapper(checkfunc):
return FontBakeryCheck(checkfunc, *args, **kwds)
return wrapper
# ExpectedValue is not a callable, but it belongs next to check and condition
_NOT_SET = object() # used as a marker
class FontBakeryExpectedValue:
def __init__(self,
name, # unique name in global namespace
description=None, # short text, this is mandatory
documentation=None, # markdown?
default=_NOT_SET, # because None can be a valid default
validator=None, # function, see the docstring of `def validate`
force=False
):
self.name = name
self.description = description
self.documentation = documentation
self._default = (True, default) if default is not _NOT_SET else (False, None)
self._validator = validator
self.force = force
def __repr__(self):
return'<{}:{}>'.format(type(self).__name__, self.name)
@property
def has_default(self):
return self._default[0]
@property
def default(self):
has_default, value = self._default
if not has_default:
raise AttributeError(f'{self} has no default value')
return value
def validate(self, value):
"""
returns (bool valid, string|None message)
If valid is True, message is None or can be ignored.
If valid is False, message should be a string describing what
is wrong with value.
"""
return self._validator(value) if self._validator else (True, None)
class Disabled:
def __init__(self, | |
direction = end - start
length = np.linalg.norm(direction)
if above:
ax.plot([start[0], end[0]], [start[1], end[1]], [start[2], end[2]], color=color)
else:
mid1 = start + 0.4 * direction
mid2 = start + 0.6 * direction
ax.plot([start[0], mid1[0]], [start[1], mid1[1]], [start[2], mid1[2]], color=color)
ax.plot([end[0], mid2[0]], [end[1], mid2[1]], [end[2], mid2[2]], color=color)
if np.linalg.norm(direction / length - unitz) < np.finfo(float).eps:
axis = unitx
else:
axis = unitz
mark = norm_vector(perpendicular_to_vectors(direction, axis)) * 0.03 * length
mark_start1 = start + mark
mark_start2 = start - mark
mark_end1 = end + mark
mark_end2 = end - mark
ax.plot([mark_start1[0], mark_start2[0]],
[mark_start1[1], mark_start2[1]],
[mark_start1[2], mark_start2[2]],
color=color)
ax.plot([mark_end1[0], mark_end2[0]],
[mark_end1[1], mark_end2[1]],
[mark_end1[2], mark_end2[2]],
color=color)
text_location = start + 0.45 * direction
if above:
text_location[2] += 0.3 * length
ax.text(text_location[0], text_location[1], text_location[2], name, zdir="x", **kwargs)
return ax
def plot_box(ax=None, size=np.ones(3), A2B=np.eye(4), ax_s=1, wireframe=True, color="k", alpha=1.0):
"""Plot box.
Parameters
----------
ax : Matplotlib 3d axis, optional (default: None)
If the axis is None, a new 3d axis will be created
size : array-like, shape (3,), optional (default: [1, 1, 1])
Size of the box per dimension
A2B : array-like, shape (4, 4)
Center of the box
ax_s : float, optional (default: 1)
Scaling of the new matplotlib 3d axis
wireframe : bool, optional (default: True)
Plot wireframe of cylinder and surface otherwise
color : str, optional (default: black)
Color in which the cylinder should be plotted
alpha : float, optional (default: 1)
Alpha value of the mesh that will be plotted
Returns
-------
ax : Matplotlib 3d axis
New or old axis
"""
if ax is None:
ax = make_3d_axis(ax_s)
corners = np.array([
[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1]
])
corners = (corners - 0.5) * size
corners = transform(
A2B, np.hstack((corners, np.ones((len(corners), 1)))))[:, :3]
if wireframe:
for i, j in [(0, 1), (0, 2), (1, 3), (2, 3),
(4, 5), (4, 6), (5, 7), (6, 7),
(0, 4), (1, 5), (2, 6), (3, 7)]:
ax.plot([corners[i, 0], corners[j, 0]],
[corners[i, 1], corners[j, 1]],
[corners[i, 2], corners[j, 2]],
c=color, alpha=alpha)
else:
p3c = Poly3DCollection(np.array([
[corners[0], corners[1], corners[2]],
[corners[1], corners[2], corners[3]],
[corners[4], corners[5], corners[6]],
[corners[5], corners[6], corners[7]],
[corners[0], corners[1], corners[4]],
[corners[1], corners[4], corners[5]],
[corners[2], corners[6], corners[7]],
[corners[2], corners[3], corners[7]],
[corners[0], corners[4], corners[6]],
[corners[0], corners[2], corners[6]],
[corners[1], corners[5], corners[7]],
[corners[1], corners[3], corners[7]],
]))
p3c.set_alpha(alpha)
p3c.set_facecolor(color)
ax.add_collection3d(p3c)
return ax
def plot_sphere(ax=None, radius=1.0, p=np.zeros(3), ax_s=1, wireframe=True, n_steps=100, color="k", alpha=1.0):
"""Plot cylinder.
Parameters
----------
ax : Matplotlib 3d axis, optional (default: None)
If the axis is None, a new 3d axis will be created
radius : float, optional (default: 1)
Radius of the sphere
p : array-like, shape (3,), optional (default: [0, 0, 0])
Center of the sphere
ax_s : float, optional (default: 1)
Scaling of the new matplotlib 3d axis
wireframe : bool, optional (default: True)
Plot wireframe of cylinder and surface otherwise
n_steps : int, optional (default: 100)
Number of discrete steps plotted in each dimension
color : str, optional (default: black)
Color in which the cylinder should be plotted
alpha : float, optional (default: 1)
Alpha value of the mesh that will be plotted
Returns
-------
ax : Matplotlib 3d axis
New or old axis
"""
if ax is None:
ax = make_3d_axis(ax_s)
phi, theta = np.mgrid[0.0:np.pi:n_steps * 1j, 0.0:2.0 * np.pi:n_steps * 1j]
x = p[0] + radius * np.sin(phi) * np.cos(theta)
y = p[1] + radius * np.sin(phi) * np.sin(theta)
z = p[2] + radius * np.cos(phi)
if wireframe:
ax.plot_wireframe(x, y, z, rstride=10, cstride=10, color=color, alpha=alpha)
else:
ax.plot_surface(x, y, z, color=color, alpha=alpha, linewidth=0)
return ax
def plot_cylinder(ax=None, length=1.0, radius=1.0, thickness=0.0, A2B=np.eye(4), ax_s=1, wireframe=True, n_steps=100, alpha=1.0, color="k"):
"""Plot cylinder.
Parameters
----------
ax : Matplotlib 3d axis, optional (default: None)
If the axis is None, a new 3d axis will be created
length : float, optional (default: 1)
Length of the cylinder
radius : float, optional (default: 1)
Radius of the cylinder
thickness : float, optional (default: 0)
Thickness of a cylindrical shell. It will be subtracted from the
outer radius to obtain the inner radius. The difference must be
greater than 0.
A2B : array-like, shape (4, 4)
Center of the cylinder
ax_s : float, optional (default: 1)
Scaling of the new matplotlib 3d axis
wireframe : bool, optional (default: True)
Plot wireframe of cylinder and surface otherwise
n_steps : int, optional (default: 100)
Number of discrete steps plotted in each dimension
alpha : float, optional (default: 1)
Alpha value of the mesh that will be plotted
color : str, optional (default: black)
Color in which the cylinder should be plotted
Returns
-------
ax : Matplotlib 3d axis
New or old axis
"""
if ax is None:
ax = make_3d_axis(ax_s)
inner_radius = radius - thickness
if inner_radius <= 0.0:
raise ValueError("Thickness of cylindrical shell results in "
"invalid inner radius: %g" % inner_radius)
axis_start = A2B.dot(np.array([0, 0, -0.5 * length, 1]))[:3]
axis_end = A2B.dot(np.array([0, 0, 0.5 * length, 1]))[:3]
axis = axis_end - axis_start
axis /= length
not_axis = np.array([1, 0, 0])
if (axis == not_axis).all():
not_axis = np.array([0, 1, 0])
n1 = np.cross(axis, not_axis)
n1 /= np.linalg.norm(n1)
n2 = np.cross(axis, n1)
if wireframe:
t = np.linspace(0, length, n_steps)
else:
t = np.array([0, length])
theta = np.linspace(0, 2 * np.pi, n_steps)
t, theta = np.meshgrid(t, theta)
if thickness > 0.0:
X_outer, Y_outer, Z_outer = [
axis_start[i] + axis[i] * t +
radius * np.sin(theta) * n1[i] +
radius * np.cos(theta) * n2[i] for i in [0, 1, 2]]
X_inner, Y_inner, Z_inner = [
axis_end[i] - axis[i] * t +
inner_radius * np.sin(theta) * n1[i] +
inner_radius * np.cos(theta) * n2[i] for i in [0, 1, 2]]
X = np.hstack((X_outer, X_inner))
Y = np.hstack((Y_outer, Y_inner))
Z = np.hstack((Z_outer, Z_inner))
else:
X, Y, Z = [axis_start[i] + axis[i] * t +
radius * np.sin(theta) * n1[i] +
radius * np.cos(theta) * n2[i] for i in [0, 1, 2]]
if wireframe:
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10, alpha=alpha,
color=color)
else:
ax.plot_surface(X, Y, Z, color=color, alpha=alpha, linewidth=0)
return ax
def plot_mesh(ax=None, filename=None, A2B=np.eye(4), s=np.array([1.0, 1.0, 1.0]), ax_s=1, wireframe=False, convex_hull=False, alpha=1.0, color="k"):
"""Plot mesh.
Note that this function requires the additional library 'trimesh'. It will
print a warning if trimesh is not available.
Parameters
----------
ax : Matplotlib 3d axis, optional (default: None)
If the axis is None, a new 3d axis will be created
filename : str, optional (default: None)
Path to mesh file.
A2B : array-like, shape (4, 4)
Pose of the mesh
s : array-like, shape (3,), optional (default: [1, 1, 1])
Scaling of the mesh that will be drawn
ax_s : float, optional (default: 1)
Scaling of the new matplotlib 3d axis
wireframe : bool, optional (default: True)
Plot wireframe of mesh and surface otherwise
convex_hull : bool, optional (default: False)
Show convex hull instead of the original mesh. This can be much
faster.
alpha : float, optional (default: 1)
Alpha value of the mesh that will be plotted
color : str, optional (default: black)
Color in which the cylinder should be plotted
Returns
-------
ax : Matplotlib 3d axis
New or old axis
"""
if ax is None:
ax = make_3d_axis(ax_s)
if filename is None:
warnings.warn(
"No filename given for mesh. When you use the "
"UrdfTransformManager, make sure to set the mesh path or "
"package directory.")
return ax
try:
import trimesh
except ImportError:
warnings.warn(
"Cannot display mesh. Library 'trimesh' not installed.")
return ax
mesh = trimesh.load(filename)
if convex_hull:
mesh = mesh.convex_hull
vertices = mesh.vertices * s
vertices = np.hstack((vertices, np.ones((len(vertices), 1))))
vertices = transform(A2B, vertices)[:, :3]
vectors = np.array([vertices[[i, j, k]] for i, j, k in mesh.faces])
if wireframe:
surface = Line3DCollection(vectors)
surface.set_color(color)
else:
surface = Poly3DCollection(vectors)
surface.set_facecolor(color)
surface.set_alpha(alpha)
ax.add_collection3d(surface)
return ax
def remove_frame(ax, left=0.0, bottom=0.0, right=1.0, top=1.0):
"""Remove axis and scale bbox.
Parameters
----------
ax | |
"""This algorithm implements the Wang Generalization algotithm with constraint checking
This algorithm simplifies lines. It detects for each line the bends. It analyze the bend and
remove the bends that are below a certain diameter. The point and lines that do not need
to be simplified are still used to enforce topology integrity between those feature that need to be simplified
Limits and constraints
Always works better when the line to process meet the OGC simple line.
"""
import math, sys
from shapely.geometry import Point, LineString, LinearRing, Polygon
from shapely.prepared import prep
from shapely import affinity
from lib_geosim import GenUtil, PointSc, LineStringSc, SpatialContainer, GeoSimException
# Internal constant ===> Should be modify with care...
_AREA_CMP_INDEX = .75 # Compactness index factor applied to the adjusted area
#Internal key word constants
_BURNED = "Burned"
_DIAMETER = "diameter"
_SIMPLIFIED = 'Simplified'
_NOT_SIMPLIFIED = 'NotSimplified'
_UNSIMPLIFIABLE = 'Unsimplifiable'
class LineStringSb(LineStringSc):
"""A class to represent a LineString used by the SherBend algorithm
Attributes
----------
coords : List
A list of coordinates (x,y)
original_type: str
The original type of the feature
min_adj_are : float
The minimal adjusted area below which the vends are deleted
properties : dict
The dictionary of the properties (attributes of the features)
fast_access : Boolean
A flag to indicate if we keep a copy od the coordinate in order to accelrate the access becase
the access to the C function is slow
"""
def __init__(self, coords, original_type, min_adj_area, layer_name, properties, fast_access=True):
super().__init__(coords)
self.sb_original_type = original_type
self.sb_layer_name = layer_name
self.sb_properties = properties
self.sb_min_adj_area = min_adj_area
self._sb_fast_access = fast_access
if self._sb_fast_access:
self.__lst_coords = list(super().coords)
# Declaration of the instance variable
self.sb_geom_type = self.geom_type # variable defined to avoid slower C calls with geom_type
self.sb_is_simplest = False # The line is not at its simplest form
self.sb_bends = [] # Holder for the bend of the line
# Is the line string closed
@property
def sb_is_closed(self):
"""This method tests if a line is closed (first/last coordinates are the same)
Parameters
----------
None
Returns
-------
bool
True: the line is closed or False the line is open
"""
try:
return self._sb_is_closed
except AttributeError:
# A closed line need at least 4 vertex to be valid
if len(self.coords) >= 4 and GenUtil.distance(self.coords[0], self.coords[-1]) <= GenUtil.ZERO:
self._sb_is_closed = True
else:
self._sb_is_closed = False
return self._sb_is_closed
@property
def coords(self):
"""This method keeps a copy of the coordinate in a list.
This methods allows a faster acces than to always access the coordinates from the C call
of shapely. the drawback more memory space
Parameters
----------
None
Returns
-------
list
Coordinate of the LineString
"""
if self._sb_fast_access:
return self.__lst_coords
else:
return super().coords
@coords.setter
def coords(self, coords):
"""Set the coordinate of a LineString
Parameters
----------
coords : list
List of x,y coordinates
Returns
-------
None
"""
# Access the coord attribute in the parent class
super(LineStringSb, self.__class__).coords.fset(self, coords) # Odd writing but it's needed...
if self._sb_fast_access:
self.__lst_coords = list(super().coords)
# Delete variable that are now outdated. so they will be computed next time it will be accessed
try:
del self._vertex_orientation
except AttributeError:
pass
@property
def vertex_orientation(self):
"""This method calculates the orientation of the vertex
List containing the orientation at each vertex of the line.
-1: anti clockwise, +1 Clockwise; 0 Straight line
For closed line the first and last vertice bear the same value
For open line the first and last value are None
Parameters
----------
None
Returns
-------
None
"""
try:
return self._vertex_orientation
except AttributeError:
self._vertex_orientation = []
for i in range(1, len(self.coords) - 1): # '1' and 'cnt-1' to 'forget' first and last vertice
orient = GenUtil.orientation(self.coords[i-1], self.coords[i], self.coords[i+1])
self._vertex_orientation.append(orient)
if self.is_closed:
# Case of a closed line or polygon; we do not copy the first and lat even if they are the same
orient = GenUtil.orientation(self.coords[-2], self.coords[0], self.coords[1])
self._vertex_orientation = [orient] + self._vertex_orientation
else:
# Case of an open line; the first and last are None
orient = None
self._vertex_orientation = [orient] + self._vertex_orientation + [orient]
return self._vertex_orientation
def _remove_colinear_vertex(self):
"""This method remove the co linear vertex in the line string. Also handles closed line
Parameters
----------
None
Returns
-------
None
"""
if len(self.coords) <= 2:
# Nothing to do with a line with 2 points
pass
else:
# Detect the position of the colinear vertex
vertex_to_del = [i for i, orient in (enumerate(self.vertex_orientation)) if orient == 0]
if len(vertex_to_del) >= 1:
# Delete the co linear vertex
lst_coords = list(self.coords)
for i in reversed(vertex_to_del):
del(lst_coords[i])
if vertex_to_del[0] == 0:
# When delete the first vertex than we need to recopy the "new first" to the last vertice
lst_coords = lst_coords + [lst_coords[0]]
self.coords = lst_coords
def _rotate_start_bend(self):
"""Rotate a closed line string so the start of the line is also the start of a clockwise bend
To be done on closed line only
Parameters
----------
None
Returns
-------
None
"""
rotate = None
max_v = len(self.vertex_orientation)
for i in range(max_v):
j = (i+1) % max_v
if self.vertex_orientation[i] == GenUtil.CLOCKWISE and \
self.vertex_orientation[j] == GenUtil.ANTI_CLOCKWISE:
rotate = i
break
# Rotate the frist last vertex to the position of the biggest bend
if rotate is None:
# All the bend are clockwise. Nothing to do
pass
elif rotate == 0:
# The line string does not to be rotated
pass
else:
lst_coord = self.coords[rotate:] + self.coords[1:rotate+1]
self.coords = lst_coord # Update the LineString coordinate
def _extract_coords(self, i,j):
"""Extract the coordinate between index [i,j]
If j is lower than i act like a circular array and avoid duplication of first/last vertice
Parameters
----------
i,j : int
Index used to extract a sub list
Returns
-------
List
list of (x,y) coordinates
"""
if i <= j:
lst_coords = self.coords[i:j+1]
else:
lst_coords = self.coords[i:] + self.coords[0:j+1]
return lst_coords
def _change_inflexion(self, i):
"""Flag if there is an inflexion between at the specified vertices.
There is inflexion when a change of orientation occurs from clock wise to anti clocwise or vice cersa
Parameters
----------
i : int
Index of for vertex orientation
Returns
-------
bool
Flag indicating if an inflexion occurs or not
"""
max_v = len(self.vertex_orientation)
if (self.vertex_orientation[i] == GenUtil.ANTI_CLOCKWISE and
self.vertex_orientation[(i+1) % max_v] == GenUtil.CLOCKWISE) or \
(self.vertex_orientation[i] == GenUtil.CLOCKWISE and
self.vertex_orientation[(i+1) % max_v] == GenUtil.ANTI_CLOCKWISE):
inflexion = True
else:
inflexion = False
return inflexion
def _add_bends(self, inflexions):
"""Add Bend to the line from the inflexion list
Parameters
----------
inflexions : List
List of the inflexions in the list
Returns
-------
None
"""
for k in range(len(inflexions) - 1):
i = inflexions[k][0]
j = inflexions[k + 1][1]
self.sb_bends.append(Bend(i, j, self._extract_coords(i, j)))
def _create_bends(self):
"""Create the bends in the line
Parameters
----------
None
Returns
-------
None
"""
# Delete any actual bend information
self.sb_bends = []
# Remove the colinear vertice in order to facilitate bend detection (moreover colinaer vertice are useless)
self._remove_colinear_vertex()
inflexions = []
max = len(self.vertex_orientation)
if self.is_closed:
# Rotate the line to position at the start of a bend
self._rotate_start_bend()
# The vertex_oriention list is considered a circular list
for i in range(max):
j = (i + 1) % max
if self._change_inflexion(i):
inflexions.append((i, j))
# Create the bend from the inflexion point
if inflexions:
if len(inflexions) >= 3:
# If there is more than 23 inflexions we add another circular inflexion
i = inflexions[-1][0]
j = inflexions[0][1]
inflexions.append((i, j))
# Transform the inflexion into bends
self._add_bends(inflexions)
else:
# The vertex_oriention list is not considered a circular list
if max == 3:
# Special case there is only one bend to simplify
j = len(self.coords)-1
self.sb_bends.append(Bend(0, j, self._extract_coords(0, j)))
elif max >= 4:
for i in range(1, max-2):
if self._change_inflexion(i):
inflexions.append((i, i+1))
# Add inflexion to add the first and last bend
inflexions = [(0, None)] + inflexions + [(None, max-1)]
# Transform inflexion into bends
self._add_bends(inflexions)
return
def _sort_bends(self):
"""Sort the bends by order of ascending min_adj_are
Parameters
----------
None
Returns
-------
None
"""
lst_bends = []
for i, bend in | |
# -*- coding: utf-8 -*-
"""
Loads, parses and classifies the text from manuscripts.
Notes:
* The first ms you load becomes your base text.
* I'm not currently doing anything with the book's title, e.g. κατα ιωαννην
* I'm not handling gap tags very smartly
"""
from collections import defaultdict
import logging
logger = logging.getLogger('XmlMss')
import xml.etree.ElementTree as ET
# What tags do we just ignore?
ignore_tags = ['lb', # Line break
'cb', # Column break
'pb', # Page break
'fw', # Other text, e.g. running titles
'pc', # Punctuation
'space', # White space
'gap', # Lacuna, illegible etc.
'seg', # Marginal text
'note', # Notes
'num', # (Mostly) paratextual numbners
'unclear', # TODO - should these be ignored?
'supplied', # for supplied tags outside words...
]
class Snippet(object):
"""
An object representing a text snippet, either a verse or a sub-part of
a verse. This will contain the text and associated hand name/type
for all hands active in this snippet.
"""
def __init__(self, word_sep=True):
self._readings = {} # {('hand_name', 'hand_type'): text, ...}
self._snippets = []
self._word_sep = word_sep
def add_reading(self, text, hand_name='firsthand', hand_type='orig'):
assert not self._snippets, self
if hand_name is None:
if hand_type == 'orig':
print("WARNING: Assuming hand None:orig is firsthand")
hand_name = 'firsthand'
elif hand_type == 'corr':
print("WARNING: Assuming hand None:corr is corrector")
hand_name = 'corrector'
assert hand_name, (text, hand_name, hand_type)
assert hand_type, (text, hand_name, hand_type)
key = (hand_name, hand_type)
if key in self._readings:
# Duplicate hand discovered - recurse
return self.add_reading(text, hand_name, "{}:dup".format(hand_type))
self._readings[key] = text
def add_snippet(self, snippet):
assert not self._readings, self
self._snippets.append(snippet)
def _post_process(self, text):
"""
Take some text and process it - e.g. rationalise out final nu.
Get rid of any double spaces.
TODO: should this do anything else? Nomina sacra for example?
XXX: Is this a good idea at all? It's standard...
"""
# Final nu
text = text.replace('¯', 'ν')
while ' ' in text:
text = text.replace(' ', ' ')
return text
def get_hands(self):
"""
Return a list of (name, type) tuples of all hands found recursively
"""
all_hands = set()
for s in self._snippets:
all_hands.update(s.get_hands())
for (hand_name, hand_type) in list(self._readings.keys()):
all_hands.add((hand_name, hand_type))
return all_hands
def get_text(self, hand_name='firsthand', hand_type='orig', order_of_hands=['firsthand']):
"""
Return the text of a particular hand. If the hand isn't present in this
place, then we search backwards from that hand in order_of_hands to find
a hand that is present, and return that text.
"""
assert hand_name in order_of_hands, (hand_name, hand_type, order_of_hands)
if self._snippets:
# Find our text recursively
ret = []
for s in self._snippets:
ret.append(s.get_text(hand_name, hand_type, order_of_hands))
return self._post_process(''.join(ret))
elif not self._readings:
# Empty snippet - return empty string
return ""
else:
# Return the required reading's text
key = (hand_name, hand_type)
if key in self._readings:
# This hand exists here
ret = self._readings[key]
else:
# Special case for firsthand corrections...
if hand_name == 'firsthand':
if hand_type == 'alt':
return self.get_text(hand_name, 'corr', order_of_hands)
elif hand_type == 'corr':
return self.get_text(hand_name, 'orig', order_of_hands)
hand_idx = order_of_hands.index(hand_name)
# Find hand names that exist here... Note, order_of_hands doesn't
# have the hand_type, so we can't use that right now...
present_hands_keys = list(self._readings.keys())
present_hands = [x[0] for x in present_hands_keys]
hands_to_try = list(reversed(order_of_hands[:hand_idx]))
if not hands_to_try:
hands_to_try = ['firsthand']
for hand in hands_to_try:
if hand in present_hands:
if hand == 'firsthand':
# look for firsthand_corr first...
key = ('firsthand', 'corr')
if key not in present_hands_keys:
key = ('firsthand', 'orig')
else:
key = present_hands_keys[present_hands.index(hand)]
ret = self._readings[key]
break
else:
import pdb
pdb.set_trace()
print("NO BREAK")
# Run any required post processing on the text
ret = self._post_process(ret)
if self._word_sep is True:
# If this is a new word, then add a space
ret = " " + ret
return ret
def __repr__(self):
return "<Snippet: {} | {}>".format(self._snippets, self._readings)
def is_empty(self):
return True if (self._readings or self._snippets) else False
word_ignore_tags = ['note', 'pc', 'seg']
class Verse(object): # flake8: noqa
"""
Takes an ElementTree element representing a verse and parses it.
"""
def __init__(self, element, number, chapter):
self.element = element
self.chapter = chapter
self.num = number
# Note - we can have multiple different texts if correctors have been at work.
self.snippet = self._parse(self.element)
def get_texts(self):
"""
Return the texts in a list of (text, hand)
"""
ret = []
hands = self.snippet.get_hands()
for n, t in hands:
if n == 'firsthand':
if t == 'orig':
hand = n
else:
hand = "firsthand({})".format(t)
else:
hand = n
assert hand
assert hand.split('(')[0] in self.chapter.manuscript.order_of_hands, (hand, self.chapter.manuscript.order_of_hands)
reading = self.snippet.get_text(n, t, self.chapter.manuscript.order_of_hands).strip()
if reading:
ret.append((reading, hand))
return ret
def _parse(self, element):
"""
Parse this element, and recursively call myself on its children.
@returns: a Snippet object
"""
tag = element.tag.split('}')[1]
if tag in ignore_tags:
return Snippet()
parser = getattr(self, '_parse_%s' % (tag, ), None)
if parser:
my_snippet = parser(element)
else:
my_snippet = Snippet()
for i in element.getchildren():
my_snippet.add_snippet(self._parse(i))
return my_snippet
def _word_reader(self, el, top=False):
"""
This calls itself recursively to extract the text from a word element
in the right order. We don't want any spaces in here, so we will
pass word_sep=False into snippets.
@param el: the element in question
@param top: (bool) is this the top <w> tag?
@returns: a Snippet object or None
"""
ret = Snippet(word_sep=top)
tag = el.tag.split('}')[1]
if tag == 'w' and not top:
# nested word tags without numbers should be ignored
if el.attrib.get('n'):
logger.warning("Nested <w> tags at {}:{}".format(
self.chapter.num, self.num))
return ret
if tag not in word_ignore_tags:
if el.text is not None:
t = el.text.strip().lower()
s = Snippet(word_sep=False)
if t == 'om':
s.add_reading('')
else:
s.add_reading(t)
ret.add_snippet(s)
if tag == 'gap':
# Gap tags matter - put in a space for now
gap = Snippet()
gap.add_reading(" ")
ret.add_snippet(gap)
for c in el.getchildren():
ret.add_snippet(self._word_reader(c))
# We always want the tail, because of the way elementtree puts it on
# the end of a closing tag, rather than in the containing tag...
if el.tail is not None:
s = Snippet(word_sep=False)
s.add_reading(el.tail.strip().lower())
ret.add_snippet(s)
if top is True:
# Add a space after every word
space = Snippet()
space.add_reading(" ")
ret.add_snippet(space)
return ret
def _parse_w(self, el):
"""
Parse a <w> tag
"""
ret = self._word_reader(el, top=True)
if el.tail and el.tail.strip():
print(("WARNING: Word {} ({}:{}) has a tail".format(el.attrib.get('n'), self.chapter.num, self.num)))
return ret
def _parse_app(self, el):
"""
This bit has been corrected - there will be more than one
reading.
"""
ret = Snippet()
for ch in el.getchildren():
tag = ch.tag.split('}')[1]
if tag in ignore_tags:
continue
if not ch.tag.endswith("}rdg"):
print((ch, ch.attrib, ch.text))
raise ValueError("I only want rdg tags in an app")
# Now parse the rdg tag to get its text
ch_snippet = self._parse(ch)
hand = ch.attrib.get('hand')
if hand == '*':
# Occasionally firsthand is named '*' in the XML
hand = 'firsthand'
typ = ch.attrib.get('type')
text = ch_snippet.get_text(order_of_hands = self.chapter.manuscript.order_of_hands)
if text == "" and hand == typ == None:
print("WARNING: Empty rdg tag")
else:
ret.add_reading(text, hand, typ)
return ret
class Chapter(object):
"""
Takes an ElementTree element representing a chapter and provides
useful methods for interrogating it.
"""
def __init__(self, element, num, manuscript):
self.verses = defaultdict(list)
self.num = num
self.manuscript = manuscript
self.parse_element(element)
def parse_element(self, element):
"""
Parse the XML element and children to get the verses.
This function can be called multiple times, for example in
commentary mss where a chapter turns up more than once.
"""
for i in element.getchildren():
if i.tag == "{http://www.tei-c.org/ns/1.0}ab":
# This is a verse
if 'n' not in i.attrib:
import pdb; pdb.set_trace()
v = i.attrib['n']
if v.startswith('B'):
# e.g. B04K12V17
v = v.split('V')[-1]
v = int(v)
v_obj = Verse(i, v, self)
self.verses[v].append(v_obj)
class Manuscript(object):
"""
Fetches a manuscript from a file and parses it.
"""
def __init__(self, name, filepath):
self.name = name
self.filepath = filepath
self.tree = None
self.chapters = {}
self.ms_desc = {}
self.order_of_hands = []
# Book identification - FIXME, am I limited to one book per ms?
self.book = None
self.num = None
self._load_xml()
self._parse_tree()
def _load_xml(self):
"""
Load the file from disk.
"""
| |
<reponame>chianfern/rmf_traffic_editor
import fiona
import gzip
import json
import math
import numpy as np
import os
import sqlite3
import tempfile
import yaml
from ament_index_python.packages import get_package_share_directory
from pyproj import Transformer
from pyproj.crs import CRS
from xml.etree.ElementTree import Element, ElementTree, SubElement, parse
from .coordinate_system import CoordinateSystem
from .edge_type import EdgeType
from .etree_utils import indent_etree
from .geopackage import GeoPackage
from .level import Level
from .lift import Lift
from .material_utils import copy_texture
from .param_value import ParamValue
from .passthrough_transform import PassthroughTransform
from .vertex import Vertex
from .web_mercator_transform import WebMercatorTransform
from .wgs84_transform import WGS84Transform
class Building:
def __init__(self, data, data_format='yaml'):
if data_format == 'yaml':
self.parse_yaml(data)
elif data_format == 'geojson':
self.parse_geojson(data)
else:
raise ValueError(f'unknown data format: {data_format}')
def parse_yaml(self, yaml_node):
if 'building_name' in yaml_node:
self.name = yaml_node['building_name']
else:
self.name = yaml_node['name']
print(f'building name: {self.name}')
self.params = {}
if 'parameters' in yaml_node and yaml_node['parameters']:
for param_name, param_yaml in yaml_node['parameters'].items():
self.params[param_name] = ParamValue(param_yaml)
if 'map_version' in yaml_node:
self.map_version = yaml_node['map_version']
else:
self.map_version = None
cs_name = yaml_node.get('coordinate_system', 'reference_image')
print(f'coordinate system: {cs_name}')
self.coordinate_system = CoordinateSystem[cs_name]
self.global_transform = None
if self.coordinate_system == CoordinateSystem.reference_image:
pass
elif self.coordinate_system == CoordinateSystem.web_mercator:
if 'generate_crs' not in self.params:
raise ValueError('generate_crs must be defined for global nav')
crs_name = self.params['generate_crs'].value
self.global_transform = WebMercatorTransform(crs_name)
origin_name = 'origin'
if 'generate_origin_vertex' in self.params:
origin_name = self.params['generate_origin_vertex'].value
# this is weird, but we have to pre-parse the level vertices
# in order to find the offset vertex :|
origin_found = False
for level_name, level_yaml in yaml_node['levels'].items():
for vertex in level_yaml['vertices']:
if vertex[3] == origin_name:
origin_found = True
break
if origin_found:
# transform the origin to the target frame
x = float(vertex[0])
# TODO: revisit this y inversion...
y = -float(vertex[1]) # invert due to historical reasons
self.global_transform.set_offset(
self.global_transform.transform_point((x, y)))
break
elif self.coordinate_system == CoordinateSystem.cartesian_meters:
if 'offset_x' in self.params:
offset_x = self.params['offset_x'].value
else:
offset_x = 0
if 'offset_y' in self.params:
offset_y = self.params['offset_y'].value
else:
offset_y = 0
if 'generate_crs' in self.params:
crs_name = self.params['generate_crs'].value
else:
crs_name = ''
self.global_transform = \
PassthroughTransform(offset_x, offset_y, crs_name)
elif self.coordinate_system == CoordinateSystem.wgs84:
if 'generate_crs' not in self.params:
# todo: automatically add a reasonable CRS in traffic-editor
raise ValueError('generate_crs must be defined in wgs84 maps')
crs_name = self.params['generate_crs'].value
if 'suggested_offset_x' in self.params:
offset_x = self.params['suggested_offset_x'].value
else:
offset_x = 0
if 'suggested_offset_y' in self.params:
offset_y = self.params['suggested_offset_y'].value
else:
offset_y = 0
self.global_transform = \
WGS84Transform(crs_name, (offset_x, offset_y))
self.levels = {}
self.model_counts = {}
for level_name, level_yaml in yaml_node['levels'].items():
self.levels[level_name] = Level(level_name)
self.levels[level_name].parse_yaml(
level_yaml,
self.coordinate_system,
self.model_counts,
self.global_transform)
if 'reference_level_name' in yaml_node:
self.reference_level_name = yaml_node['reference_level_name']
else:
self.reference_level_name = next(iter(self.levels))
self.ref_level = self.levels[self.reference_level_name] # save typing
# we only need to calculate offsets/scales if we're in pixel space
if self.coordinate_system == CoordinateSystem.reference_image:
self.calculate_level_offsets_and_scales()
self.transform_all_vertices()
self.lifts = {}
if 'lifts' in yaml_node:
for lift_name, lift_yaml in yaml_node['lifts'].items():
if 'reference_floor_name' in lift_yaml:
ref_level_name = lift_yaml['reference_floor_name']
transform = self.levels[ref_level_name].transform
else:
transform = self.ref_level.transform
self.lifts[lift_name] = \
Lift(lift_yaml, lift_name, transform, self.levels,
self.coordinate_system)
self.set_lift_vert_lists()
def parse_geojson(self, json_node):
self.levels = {}
self.lifts = {}
self.name = json_node.get('site_name', 'no_name')
print(f'name: {self.name}')
if 'features' not in json_node:
return
self.coordinate_system = CoordinateSystem.cartesian_meters
if 'preferred_crs' not in json_node:
# todo: calculate based on UTM grid
print('CRS not specified. TODO: infer one.')
return
crs_name = json_node.get('preferred_crs', '')
offset_x = json_node.get('suggested_offset_x', 0)
offset_y = json_node.get('suggested_offset_y', 0)
self.global_transform = \
PassthroughTransform(offset_x, offset_y, crs_name)
# project from WGS 84 to whatever is requested by this file
transformer = Transformer.from_crs('EPSG:4326', crs_name)
# Spin through all items and see how many levels we have.
# todo: encode level polygons and names in GeoJSON files.
# For now, just compute a bounding box and expand it a bit
for feature in json_node['features']:
if 'feature_type' not in feature:
continue
if feature['feature_type'] == 'rmf_vertex':
self.parse_geojson_vertex(feature, transformer)
for level_name in self.levels:
self.levels[level_name].build_spatial_index()
# now spin through and find the lanes, and assign them to vertices
# using the rtree that was just built
for feature in json_node['features']:
if 'feature_type' not in feature:
continue
if feature['feature_type'] == 'rmf_lane':
self.parse_geojson_lane(feature, transformer)
self.transform_all_vertices()
for level_name, level in self.levels.items():
print(f'level {level_name}:')
print(f' bbox: {level.bbox}')
print(f' {len(level.vertices)} vertices')
print(f' {len(level.lanes)} lanes')
def parse_geojson_lane(self, feature, transformer):
if 'geometry' not in feature:
return
geometry = feature['geometry']
if 'type' not in geometry:
return
if geometry['type'] != 'LineString':
return
if 'coordinates' not in geometry:
return
start_lon = geometry['coordinates'][0][0]
start_lat = geometry['coordinates'][0][1]
end_lon = geometry['coordinates'][1][0]
end_lat = geometry['coordinates'][1][1]
start_y, start_x = transformer.transform(start_lat, start_lon)
end_y, end_x = transformer.transform(end_lat, end_lon)
if 'properties' in feature:
props = feature['properties']
level_idx = props.get('level_idx', 0)
# todo: look up the real level name somewhere
level_name = f'level_{level_idx}'
level = self.levels[level_name]
level.add_edge_from_coords(
EdgeType.LANE,
(start_x, start_y),
(end_x, end_y),
props)
def parse_geojson_vertex(self, feature, transformer):
if 'geometry' not in feature:
return
geometry = feature['geometry']
if 'type' not in geometry:
return
if geometry['type'] != 'Point':
return
if 'coordinates' not in geometry:
return
lon = geometry['coordinates'][0]
lat = geometry['coordinates'][1]
y, x = transformer.transform(lat, lon)
level_idx = 0
vertex_name = ''
if 'properties' in feature:
props = feature['properties']
level_idx = props.get('level_idx', 0)
vertex_name = props.get('name', '')
# todo: look up the real level name somewhere
level_name = f'level_{level_idx}'
if level_name not in self.levels:
level = Level(level_name)
level.bbox = [[x, y], [x, y]]
level.transform = self.global_transform
self.levels[level_name] = level
level = self.levels[level_name]
level.bbox[0][0] = min(level.bbox[0][0], x)
level.bbox[0][1] = min(level.bbox[0][1], y)
level.bbox[1][0] = max(level.bbox[1][0], x)
level.bbox[1][1] = max(level.bbox[1][1], y)
# todo: parse all remaining params from json properties
vertex_params = {}
level.vertices.append(
Vertex(
[x, y, 0, vertex_name, vertex_params],
self.coordinate_system
)
)
def __str__(self):
s = ''
for level_name, level in self.levels.items():
s += f'{level_name}: ({len(level.vertices)} vertices) '
return s
def set_lift_vert_lists(self):
lift_vert_lists = {}
for lift_name, lift in self.lifts.items():
lift_vert_lists[lift_name] = lift.get_lift_vertices()
for level_name, level in self.levels.items():
level.set_lift_vert_lists(lift_vert_lists, self.lifts)
def transform_all_vertices(self):
""" Transform all vertices on all levels to a unified system """
for level_name, level in self.levels.items():
level.transform_all_vertices()
def calculate_level_offsets_and_scales(self):
# calculate all level offsets relative to reference_level_name
print(f'calculating levels relative to {self.reference_level_name}')
# first calculate scale of the reference level using its measurements
self.ref_level.calculate_scale_using_measurements()
# now calculate every other level's scale and offsets
for level_name, level in self.levels.items():
if level_name == self.reference_level_name:
continue
self.calculate_level_offset_and_scale(level_name)
def calculate_level_offset_and_scale(self, level_name):
print(f'calculating level {level_name} offset and scale...')
level = self.levels[level_name]
# find which fiducials are in common between ref_level and level
fiducials = []
for ref_fiducial in self.ref_level.fiducials:
for fiducial in level.fiducials:
if ref_fiducial.name == fiducial.name:
fiducials.append((ref_fiducial, fiducial))
print(f' {len(fiducials)} common fiducials:')
level.transform.set_from_fiducials(
fiducials,
self.ref_level.transform.scale)
def generate_nav_graphs(self):
""" Returns a dict of all non-empty nav graphs """
print("generating nav data")
nav_graphs = {}
# at the moment, graphs are numbered 0..9
# iterate through and generate any non-empty graphs
for i in range(0, 9):
g = {}
g['building_name'] = self.name
g['levels'] = {}
if self.coordinate_system == CoordinateSystem.web_mercator:
g['crs_name'] = self.global_transform.crs_name
g['offset'] = [*self.global_transform.offset]
elif self.coordinate_system == CoordinateSystem.cartesian_meters:
if 'generate_crs' in self.params:
g['crs_name'] = self.params['generate_crs'].value
tx, ty = self.global_transform.x, self.global_transform.y
g['offset'] = [tx, ty]
elif self.coordinate_system == CoordinateSystem.wgs84:
g['crs_name'] = self.params['generate_crs'].value
tx, ty = self.global_transform.x, self.global_transform.y
g['offset'] = [tx, ty]
empty = True
for level_name, level in self.levels.items():
level_graph = level.generate_nav_graph(i)
g['levels'][level_name] = level_graph
if level_graph['lanes']:
empty = False
if not empty:
nav_graphs[f'{i}'] = g
return nav_graphs
def generate_sdf_world(self, options):
""" Return an etree of this Building in SDF starting from a template"""
print(f'generator options: {options}')
if 'gazebo' in options:
template_name = 'gz_world.sdf'
elif 'ignition' in options:
template_name = 'ign_world.sdf'
else:
raise RuntimeError("expected either gazebo or ignition in options")
template_path = os.path.join(
get_package_share_directory('rmf_building_map_tools'),
f'templates/{template_name}')
tree = parse(template_path)
sdf = tree.getroot()
world = sdf.find('world')
for level_name, level in self.levels.items():
level.generate_sdf_models(world) # todo: a better name
level.generate_doors(world, options)
level_include_ele = SubElement(world, 'include')
level_model_name = f'{self.name}_{level_name}'
name_ele = SubElement(level_include_ele, 'name')
name_ele.text = level_model_name
uri_ele = SubElement(level_include_ele, 'uri')
uri_ele.text = f'model://{level_model_name}'
pose_ele = SubElement(level_include_ele, 'pose')
if self.coordinate_system == CoordinateSystem.wgs84:
tx = -self.global_transform.x
ty = -self.global_transform.y
else:
tx = 0
ty = 0
pose_ele.text = f'{tx} {ty} {level.elevation} 0 0 0'
for lift_name, lift in self.lifts.items():
if not lift.level_doors:
print(f'[{lift_name}] is not serving any floor, ignoring.')
continue
lift.generate_shaft_doors(world)
lift.generate_cabin(world, options)
charger_waypoints_ele = SubElement(
world,
'rmf_charger_waypoints',
{'name': 'charger_waypoints'})
for level_name, level in self.levels.items():
for vertex in level.transformed_vertices:
if 'is_charger' in vertex.params:
| |
<gh_stars>0
import os
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from CustomButton import CustomButton
from Flag import Flag
from arrow import Arrow
from Mitigation_01 import MitigationWindow
def resource_path(relative_path):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
source1 = resource_path("x_button.png")
class MainLeft(QWidget):
qss = """
QWidget#main {
background: rgb(128, 128, 128);
border: 2px solid rgb(0, 0, 0);
}
QWidget {
background: rgb(128, 128, 128);
border: 0px solid rgb(0, 0, 0);
}
"""
def __init__(self, parent=None):
super(MainLeft, self).__init__()
self.setAttribute(Qt.WA_StyledBackground, True) # 상위 스타일 상속
self.parent = parent
self.shmem = parent.shmem
self.setStyleSheet(self.qss)
# 크기 조정
self.setMinimumHeight(900 - 40)
self.setMinimumWidth(int(1920 * (2 / 3)))
# 레이어 셋업
layout = QVBoxLayout(self)
layout.setContentsMargins(5, 0, 5, 0)
label2 = FlowChartArea(self)
label2.setObjectName("main")
layout.addWidget(label2)
self.setLayout(layout)
class FlowChartArea(QWidget,QThread):
qss = """
QWidget#scroll {
background: rgb(128, 128, 128);
border: 2px solid rgb(0, 0, 0);
}
QWidget {
background: rgb(128, 128, 128);
border: 0px solid rgb(0, 0, 0);
}
"""
def __init__(self, parent=None):
super(FlowChartArea, self).__init__()
self.setAttribute(Qt.WA_StyledBackground, True)
self.parent = parent
self.shmem = parent.shmem
self.scroll = QScrollArea()
self.scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
flowchart = FlowChart(self)
self.scroll.setWidget(flowchart)
layout = QVBoxLayout()
layout.addWidget(self.scroll)
self.setLayout(layout)
# 자동 스크롤
def paintEvent(self, e):
if Flag.PAGE1:
vbar = self.scroll.verticalScrollBar()
vbar.setValue((vbar.maximum())*8/20)
Flag.PAGE1 = False
if Flag.PAGE2:
vbar = self.scroll.verticalScrollBar()
vbar.setValue((vbar.maximum()))
Flag.PAGE2 = False
if Flag.PAGE3:
vbar = self.scroll.verticalScrollBar()
vbar.setValue((vbar.minimum()))
Flag.PAGE3 = False
class FlowChart(QWidget):
def __init__(self, parent=None):
super(FlowChart, self).__init__()
self.parent = parent
self.shmem = parent.shmem
self.setGeometry(0, 0, 1210, 2070) # 1900*(3/4) = 1425
# Arrow
self.line1 = Arrow(self, x=270, y=100, x2=270, y2=123, type=1)
self.line1 = Arrow(self, x=270, y=210, x2=270, y2=243, type=1)
self.line1 = Arrow(self, x=270, y=370, x2=270, y2=403, type=1)
self.line1 = Arrow(self, x=270, y=530, x2=270, y2=563, type=1)
self.line1 = Arrow(self, x=270, y=690, x2=270, y2=723, type=1)
self.line1 = Arrow(self, x=270, y=850, x2=270, y2=883, type=1)
self.line1 = Arrow(self, x=270, y=1010, x2=270, y2=1043, type=1)
self.line1 = Arrow(self, x=270, y=1170, x2=270, y2=1203, type=1)
self.line1 = Arrow(self, x=270, y=130, x2=270, y2=1363, type=1)
self.line1 = Arrow(self, x=270, y=1750, x2=270, y2=1893, type=1)
#아니오
self.line1 = Arrow(self, x=270, y=315, x2=663, y2=315, type=3)
self.line1 = Arrow(self, x=270, y=475, x2=663, y2=475, type=3)
self.line1 = Arrow(self, x=270, y=635, x2=663, y2=635, type=3)
self.line1 = Arrow(self, x=270, y=795, x2=663, y2=795, type=3)
self.line1 = Arrow(self, x=270, y=955, x2=663, y2=955, type=3)
self.line1 = Arrow(self, x=270, y=1115, x2=663, y2=1115, type=3)
self.line1 = Arrow(self, x=270, y=1275, x2=663, y2=1275, type=3)
#돌아오기
self.line1 = Arrow(self, x=895, y=396, x2=280, y2=396, type=2)
self.line1 = Arrow(self, x=895, y=556, x2=280, y2=556, type=2)
self.line1 = Arrow(self, x=895, y=716, x2=280, y2=716, type=2)
self.line1 = Arrow(self, x=895, y=876, x2=280, y2=876, type=2)
self.line1 = Arrow(self, x=895, y=1036, x2=280, y2=1036, type=2)
self.line1 = Arrow(self, x=895, y=1196, x2=280, y2=1196, type=2)
self.line1 = Arrow(self, x=895, y=1356, x2=280, y2=1356, type=2)
self.line1 = Arrow(self, x=1200, y=233, x2=280, y2=233, type=2)
# CustomButton
self.btn_1 = CustomButton(self, page=1, num=1, x=70, y=30, w=400, h=70, text='TSC “완화” 절차서 사용시작',type=0)
self.btn_2 = CustomButton(self, page=1, num=2, x=70, y=130, w=400, h=90, text='안전 변수<br/>R02, P09, H04 감시 시작', type=0)
self.btn_3 = CustomButton(self, page=1, num=3, x=70, y=250, w=400, h=130, text='발전소 부지 경계 선량<br/>< 5분동안 0.5mSv/h', type=2)
self.btn_4 = CustomButton(self, page=1, num=4, x=70, y=410, w=400, h=130, text='격납건물 압력<br/>< 4.97 psig', type=2)
self.btn_5 = CustomButton(self, page=1, num=5, x=70, y=570, w=400, h=130, text='격납건물 수소농도<br/>< [H02]%', type=2)
self.btn_6 = CustomButton(self, page=1, num=6, x=70, y=730, w=400, h=130, text='노심출구온도<br/>< 371.1°C', type=2)
self.btn_7 = CustomButton(self, page=1, num=7, x=70, y=890, w=400, h=130, text='RCS 압력<br/><28.12kg/cm2', type=2)
self.btn_8 = CustomButton(self, page=1, num=8, x=70, y=1050, w=400, h=130, text='모든 증기발생기 수위<br/>> 74% NR', type=2)
self.btn_9 = CustomButton(self, page=1, num=9, x=70, y=1210, w=400, h=130, text='격납건물 수위<br/>> 27.1%', type=2)
self.btn_10 = CustomButton(self, page=1, num=10, x=20, y=1370, w=500, h=500, text='● 노심출구온도 < 371.1°C<br/><br/>그리고 안정 또는 감소<br/>●발전소부지 경계 선량 <[R01]<br/><br/>그리고 안정 또는 감소<br/>● 격납건물 압력 < [P11]<br/><br/>그리고 안정 또는 감소<br/>●격납건물 수소농도 < [H02]<br/><br/>그리고 안정 또는 감소', type=2)
self.btn_11 = CustomButton(self, page=1, num=11, x=70, y=1900, w=400, h=90, text='종료-01<br/>“중대사고관리 종료“ 수행', type=1)
self.btn_3_1 = CustomButton(self, page=1, num=31, x=670, y=270, w=450, h=90, text='완화-01<br/>“핵분열생성물 방출 제어“ 수행')
self.btn_4_1 = CustomButton(self, page=1, num=41, x=670, y=430, w=450, h=90, text='완화-02<br/>“격납건물 상태제어“ 수행', type=1)
self.btn_5_1 = CustomButton(self, page=1, num=51, x=670, y=590, w=450, h=90, text='완화-03<br/>“격납건물내 수소 제어“ 수행', type=1)
self.btn_6_1 = CustomButton(self, page=1, num=61, x=670, y=750, w=450, h=90, text='완화-04<br/>“원자로 냉각재 계통 냉각수 주입“ 수행', type=1)
self.btn_7_1 = CustomButton(self, page=1, num=71, x=670, y=910, w=450, h=90, text='완화-05<br/>“원자로 냉각재 계통 감압“ 수행', type=1)
self.btn_8_1 = CustomButton(self, page=1, num=81, x=670, y=1070, w=450, h=90, text='완화-06<br/>“증기발생기 급수 주입“ 수행', type=1)
self.btn_9_1 = CustomButton(self, page=1, num=91, x=670, y=1230, w=450, h=90, text='완화-07<br/>“격납건물 냉각수 주입“ 수행', type=1)
def paintEvent(self, event):
p = QPainter(self)
p.setPen(QPen(Qt.black))
p.setFont(QFont('맑은 고딕', 14))
p.drawLine(895, 350, 895, 396)
p.drawText(470, 305, "아니오")
p.drawText(240, 403, "예")
p.drawLine(895, 500, 895, 556)
p.drawText(470, 465, "아니오")
p.drawText(240, 563, "예")
p.drawLine(895, 666, 895, 716)
p.drawText(470, 625, "아니오")
p.drawText(240, 723, "예")
p.drawLine(895, 820, 895, 876)
p.drawText(470, 785, "아니오")
p.drawText(240, 883, "예")
p.drawLine(895, 990, 895, 1036)
p.drawText(470, 945, "아니오")
p.drawText(240, 1043, "예")
p.drawLine(895, 1140, 895, 1196)
p.drawText(470, 1105, "아니오")
p.drawText(240, 1203, "예")
p.drawLine(895, 1300, 895, 1356)
p.drawText(470, 1265, "아니오")
p.drawText(240, 1363, "예")
p.drawLine(270, 1620, 1200, 1620)
p.drawLine(1200, 233, 1200, 1620)
current = 0
# Popup open
if Flag.btn_clicked[1]:
self.popup = CustomPopup(p_number=1, p_title="TSC “완화” 절차서 사용시작", p_content='\nTSC “완화” 절차서를 시작합니다.')
Flag.btn_clicked[1] = False
self.btn_1.color()
Flag.color[1] = 2
Flag.close[1] = 0
# 현재 실행중인 버튼 병행처리
current = self.together(1)
self.change(current)
show = self.popup.showModal()
if Flag.btn_yes[1] == 0 and Flag.close[1] == 0: #yes # 완료된 버튼 팝업 생성 방지
self.btn_1.complete()
Flag.color[1] = 3
Flag.btn_clicked[2] = True
self.btn_2.color()
Flag.color[2] = 2
if Flag.btn_clicked[2]:
self.popup = CustomPopup(p_number=2, p_title="안전 변수 R02, P09, H04 감시 시작", p_content='\n안전 변수 R02, P09, H04 감시를 시작합니다.')
Flag.btn_clicked[2] = False
self.btn_2.color()
Flag.color[2] = 2
Flag.close[2] = 0
# 현재 실행중인 버튼 병행처리
current = self.together(2)
self.change(current)
show = self.popup.showModal()
if Flag.btn_yes[2] == 0 and Flag.close[2] == 0: # 완료된 버튼 팝업 생성 방지
self.btn_2.complete()
Flag.color[2] = 3
Flag.btn_clicked[3] = True
self.btn_3.color()
Flag.color[3] = 2
if Flag.btn_clicked[3]:
self.popup = CustomPopup(p_number=3, p_title="발전소 부지 경계 선량 확인", p_content="\n발전소 부지 경계 선량 5분동안 < 0.5mSv/h", p_label1="현재 발전소 부지 경계 선량", p_value1=Flag.value1_1) #단위 추가 필요 "%d"%~
Flag.btn_clicked[3] = False
self.btn_3.color()
Flag.color[3] = 2
Flag.close[3] = 0 # 팝업 닫기
# 현재 실행중인 버튼 병행처리
current = self.together(3)
self.change(current)
show = self.popup.showModal()
if Flag.btn_yes[3] == 0 and Flag.close[3] == 0: #yes
self.btn_3.complete()
Flag.color[3] = 3
Flag.btn_clicked[4] = True
self.btn_3_1.complete()
self.btn_4.color()
Flag.color[31] = 3
Flag.color[4] = 2
elif Flag.btn_yes[3] == 1 and Flag.close[3] == 0: #no
self.btn_3.complete()
Flag.color[3] = 3
Flag.btn_clicked_1[31] = True
self.btn_3_1.color()
Flag.color[31] = 2
if Flag.btn_clicked[4]:
self.popup = CustomPopup(p_number=4, p_title="격납건물 압력 확인", p_content="\n격납건물 압력 < 4.97 psig", p_label1="현재 격납건물 압력", p_value1=Flag.value1_2)
Flag.btn_clicked[4] = False
self.btn_4.color()
Flag.color[4] = 2
Flag.close[4] = 0
# 현재 실행중인 버튼 병행처리
current = self.together(4)
self.change(current)
show = self.popup.showModal()
if Flag.btn_yes[4] == 0 and Flag.close[4] == 0: # yes
self.btn_4.complete()
Flag.color[4] = 3
Flag.btn_clicked[5] = True
self.btn_4_1.complete()
self.btn_5.color()
Flag.color[41] = 3
Flag.color[5] = 2
elif Flag.btn_yes[4] == 1 and Flag.close[4] == 0: # no
self.btn_4.complete()
Flag.color[4] = 3
Flag.btn_clicked_1[41] = True
self.btn_4_1.color()
Flag.color[41] = 2
if Flag.btn_clicked[5]:
self.popup = CustomPopup(p_number=5, p_title="격납건물 수소농도 확인", p_content="\n격납건물 수소농도 < [H02]%", p_label1="현재 격납건물 수소농도", p_value1=Flag.value2_4)
Flag.PAGE1 = True
Flag.btn_clicked[5] = False
self.btn_5.color()
Flag.color[5] = 2
Flag.close[5] = 0
# 현재 실행중인 버튼 병행처리
current = self.together(5)
self.change(current)
show = self.popup.showModal()
if Flag.btn_yes[5] == 0 and Flag.close[5] == 0: # yes
self.btn_5.complete()
Flag.color[5] = 3
Flag.btn_clicked[6] = True
self.btn_5_1.complete()
self.btn_6.color()
Flag.color[51] = 3
Flag.color[6] = 2
elif Flag.btn_yes[5] == 1 and Flag.close[5] == 0: # no
self.btn_5.complete()
Flag.color[5] = 3
Flag.btn_clicked_1[51] = True
self.btn_5_1.color()
Flag.color[51] = 2
if Flag.btn_clicked[6]:
self.popup = CustomPopup(p_number=6, p_title="노심출구온도 확인", p_content="\n노심출구온도 < 371.1°C", p_label1="현재 노심출구온도", p_value1=Flag.value1_3)
Flag.btn_clicked[6] = False
Flag.PAGE1 = True
self.btn_6.color()
Flag.color[6] = 2
Flag.close[6] = 0
# 현재 실행중인 버튼 병행처리
current = self.together(6)
self.change(current)
show = self.popup.showModal()
if Flag.btn_yes[6] == 0 and Flag.close[6] == 0: # yes
self.btn_6.complete()
Flag.color[6] = 3
Flag.btn_clicked[7] = True
self.btn_6_1.complete()
self.btn_7.color()
Flag.color[61] = 3
Flag.color[7] = 2
elif Flag.btn_yes[6] == 1 and Flag.close[6] == 0: # no
self.btn_6.complete()
Flag.color[6] = 3
Flag.btn_clicked_1[61] = True
self.btn_6_1.color()
Flag.color[61] = 2
if Flag.btn_clicked[7]:
| |
<reponame>kdart/pycopia3
#!/usr/bin/python3.4
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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.
r"""
Implements a Windows version of a client responder. This should run with the
native Python for Windows.
Install on a Windows server:
Place the following lines in c:\autoexec.bat::
PATH=%PATH%;C:\Python26;C:\Python26\Scripts
Now run (all on one line)::
C:\Python26>python.exe %PYTHONLIB%\site-packages\pycopia\remote\WindowsServer.py
--username DOMAIN\Administrator --password xxxxxxxx install
OR, for system process that can interact with console::
C:\Python26>python.exe %PYTHONLIB%\site-packages\pycopia\remote\WindowsServer.py
--interactive install
Note: if you get an error about an account not existing, you may need
to supply the username like this:
.\Administrator
If a username was supplied to run as, go to the Service Manger from the
Windows control panel, and perform the following.
- Select "Remote Agent Server" from the list. Right-clieck and select "properties".
- Select the "Log On" tab.
- Click the "This account:" radio button.
- Enter DOMAIN\Administrator in the account box (or something else appropriate).
- Enter the proper password (twice).
- Click "Apply". You should confirm a message saying user is
enabled to log in as a service.
- Click "General" tab.
- You may now start the service.
You may also need to disable the Windows firewall for this to function
properly. This service is a massive security hole, so only run it on
a throw-away test machine on an isolated network.
"""
import os, sys, shutil, errno
import threading
# Pycopia imports
from pycopia.aid import IF
from pycopia.anypath import cygwin2nt, nt2cygwin
from pycopia import shparser
# returnable objects
from pycopia.remote.WindowsObjects import ExitStatus
# Windows stuff
import msvcrt
import win32api
import win32file
import win32net
import win32process
import win32event
# constants
import pywintypes
import win32con
import win32netcon
# some constants that the API forgot...
USE_WILDCARD = -1
USE_DISKDEV = 0
USE_SPOOLDEV = 1
USE_CHARDEV = 2
USE_IPC = 3
def setConfig():
Pyro.config.PYRO_STORAGE = "C:\\tmp\\"
Pyro.config.PYRO_LOGFILE = "C:\\tmp\\agent_svc.log"
Pyro.config.PYRO_TRACELEVEL=3
Pyro.config.PYRO_USER_LOGFILE = "C:\\tmp\\agent_user.log"
Pyro.config.PYRO_USER_TRACELEVEL = 3
Pyro.config.PYRO_PORT = 7867 # don't conflict with cygwin Pyro
import Pyro
import Pyro.util
setConfig()
Log=Pyro.util.Log
import Pyro.core
import Pyro.naming
from Pyro.ext.BasicNTService import BasicNTService, getRegistryParameters
_EXIT = False
UserLog = Pyro.util.UserLogger()
# msg, warn, or error methods
class WindowsFile(file):
"""A file object with some extra methods that match those in UserFile
(which has Posix extensions)."""
def locking(self, mode, nbytes):
return msvcrt.locking(self.fileno(), mode, nbytes)
def __repr__(self):
return "WindowsFile(%r, %r)" % (self.name, self.mode)
def lock_exclusive(self, length, start=0, whence=0, nb=0):
"""Locking method compatible with Posix files."""
if nb:
mode = msvcrt.LK_NBLCK
else:
mode = msvcrt.LK_LOCK
orig = self.tell()
self.seek(start, whence)
try:
msvcrt.locking(self.fileno(), mode, length)
finally:
self.seek(orig)
lock = lock_exclusive
def unlock(self, length, start=0, whence=0):
"""Posix compatible unlock."""
orig = self.tell()
self.seek(start, whence)
try:
msvcrt.locking(self.fileno(), msvcrt.LK_UNLCK, length)
finally:
self.seek(orig)
def get_osfhandle(self):
return msvcrt.get_osfhandle(self.fileno())
split_command_line = shparser.get_command_splitter()
# quick hack ... Windows sucks. No signal handling or anything useful, so it has to be faked.
class WindowsProcess(object):
def __init__(self, cmdline, logfile=None, env=None, callback=None, merge=True, pwent=None, async=False):
self.deadchild = False
self.exitstatus = None
self.cmdline = cmdline
self._callback = callback
self._buf = ""
self._log = logfile
if merge:
self.child_stdin, self.child_stdout = os.popen2(cmdline, "t", -1)
self.child_stderr = None
else:
self.child_stdin, self.child_stdout, self.child_stderr = os.popen3(cmdline, "t", -1)
self.childpid, self.handle = self._scan_for_self()
# since the Python popenX functions do not provide the PID, it must be
# scanned for in this ugly manner. 8-(
def _scan_for_self(self):
win32api.Sleep(2000) # sleep to give time for process to be seen in system table.
basename = self.cmdline.split()[0]
pids = win32process.EnumProcesses()
if not pids:
UserLog.warn("WindowsProcess", "no pids", pids)
for pid in pids:
try:
handle = win32api.OpenProcess(
win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ,
pywintypes.FALSE, pid)
except pywintypes.error as err:
UserLog.warn("WindowsProcess", str(err))
continue
try:
modlist = win32process.EnumProcessModules(handle)
except pywintypes.error as err:
UserLog.warn("WindowsProcess",str(err))
continue
for mod in modlist:
mname = win32process.GetModuleFileNameEx(handle, mod)
if mname.find(basename) >= 0:
return int(pid), handle
raise WindowsError("could not find process for %r" % (basename,))
def write(self, data):
return self.child_stdin.write(data)
def kill(self):
handle = win32api.OpenProcess(
win32con.PROCESS_VM_READ | win32con.PROCESS_TERMINATE, pywintypes.FALSE, self.childpid)
win32process.TerminateProcess(handle, 3)
def read(self, amt=1048576):
bs = len(self._buf)
while bs < amt:
c = self._read(4096)
if not c:
break
self._buf += c
bs = len(self._buf)
data = self._buf[:amt]
self._buf = self._buf[amt:]
return data
def readerr(self, amt=-1):
if self.child_stderr:
return self.child_stderr.read(amt)
def _read(self, amt):
data = self.child_stdout.read(amt)
if self._log:
self._log.write(data)
return data
def close(self):
if win32process.GetExitCodeProcess(self.handle) == win32con.STILL_ACTIVE:
self.kill()
self.child_stdin.close()
self.child_stdin = None
if self.child_stderr:
self.child_stdin.close()
self.child_stdin = None
es = ExitStatus(self.cmdline, self.child_stdout.close())
if self.exitstatus is None:
self.exitstatus = es
self.child_stdout = None
self.dead()
return self.exitstatus
def poll(self):
es = win32process.GetExitCodeProcess(self.handle)
if es == win32con.STILL_ACTIVE:
return None
else:
self.exitstatus = ExitStatus(self.cmdline, es)
self.dead()
return self.exitstatus
# called when process determined to be daed
def dead(self):
if not self.deadchild:
self.deadchild = True
if self._callback:
self._callback(self)
# check if still running
def alive(self):
es = win32process.GetExitCodeProcess(self.handle)
if es == win32con.STILL_ACTIVE:
return True
else:
return False
# wait until finished
def wait(self):
# let python read until EOF for a wait
try:
self._buf += self.child_stdout.read()
self.close()
except: # closed file?
pass
return self.exitstatus
def status(self):
return self.exitstatus
def isdead(self):
return self.deadchild
# considered true if child alive, false if child dead
def __bool__(self):
return not self.deadchild
# A server that performs filer client operations. This mostly delegates to the
# os module. But some special methods are provided for common functions.
class Win32Agent(Pyro.core.SynchronizedObjBase):
def __init__(self):
Pyro.core.SynchronizedObjBase.__init__(self)
self._files = {}
self._procs = {}
self._dirstack = []
def platform(self):
return sys.platform
def whatami(self):
"""Return agent implementation (class name)."""
return self.__class__.__name__
# Since file objects are not pickle-able, a handle is returned. Use the
# handle for subsequent file operations on f* methods.
def fopen(self, fname, mode="r", bufsize=-1):
"Opens a file object and returns a handle to it."
fname = cygwin2nt(fname)
fo = WindowsFile(fname, mode, bufsize)
UserLog.msg("fopen", fname)
handle = fo.fileno()
self._files[handle] = fo
return handle
def CreateFile(self, fname, mode="r", bufsize=-1):
"Open a file the same way a File Directory migration engine would."
fname = cygwin2nt(fname)
UserLog.msg("CreateFile", fname)
if mode == "r":
wmode = win32file.GENERIC_READ
elif mode == "w":
wmode = win32file.GENERIC_WRITE
elif mode in ( 'r+', 'w+', 'a+'):
wmode = win32file.GENERIC_READ | win32file.GENERIC_WRITE
else:
raise ValueError("invalid file mode")
h = win32file.CreateFile(
fname, # CTSTR lpFileName,
wmode, # DWORD dwDesiredAccess,
win32file.FILE_SHARE_DELETE | win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, # DWORD dwShareMode,
None, # LPSECURITY_ATTRIBUTES lpSecurityAttributes,
win32file.OPEN_EXISTING, # DWORD dwCreationDisposition,
win32file.FILE_ATTRIBUTE_NORMAL, # DWORD dwFlagsAndAttributes,
0, # HANDLE hTemplateFile
)
self._files[int(h)] = h
return int(h)
def fclose(self, handle):
"Closes a file object given the handle."
fo = self._files.get(handle, None)
if fo:
if type(fo) is WindowsFile:
fo.close()
del self._files[handle]
else:
fo.Close() # pyHANDLE from CreateFile
def fread(self, handle, amt=-1):
"Reads from the file object given the handle and amount to read."
fo = self._files.get(handle, None)
if fo:
if type(fo) is WindowsFile:
return fo.read(amt)
else:
return win32file.ReadFile(fo, amt, None)
def fwrite(self, handle, data):
"Writes to a file object given the handle."
fo = self._files.get(handle, None)
if fo:
if type(fo) is WindowsFile:
return fo.write(data)
else:
return win32file.WriteFile(fo, data, None)
def fsync(self, handle):
"fsync the file object."
fo = self._files.get(handle, None)
if fo:
fo.flush()
return os.fsync(fo.fileno())
def fseek(self, handle, pos, how=0):
"Seek in the file object."
fo = self._files.get(handle, None)
if fo:
if type(fo) is WindowsFile:
return fo.seek(pos, how)
else:
win32file.SetFilePointer(fo, pos, how)
def ftell(self, handle):
"Tell where the seek pointer is in the file object."
fo = self._files.get(handle, None)
if fo:
if type(fo) is WindowsFile:
return fo.tell()
def fflush(self, handle):
"""Flush the file object buffer."""
fo = self._files.get(handle, None)
if fo:
return fo.flush()
def fileno(self, handle):
"Return the file objects file descriptor."
fo = self._files.get(handle, None)
if fo:
return fo.fileno()
def get_handle_info(self, handle):
fo = self._files.get(handle, None)
if fo:
return repr(fo) # XXX
else:
return None
def flock(self, handle, length=0, start=0, whence=0, nonblocking=False):
"""Lock the file with the given range."""
fo = self._files.get(handle, None)
if fo:
return fo.lock_exclusive(length, start, whence, nonblocking)
def funlock(self, handle, length, start=0, whence=0):
fo = self._files.get(handle, None)
if fo:
fo.unlock(length, start, whence)
| |
"""
Classes related to DiamondFire (DF) variable types.
"""
import typing
import math
import re
import collections
import operator
import json
import nbtlib as nbt
from nbtlib.tag import Base
from .. import constants
from ..enums import (
Material, HideFlags, SoundType, ParticleType, CustomSpawnEggType, PotionEffect, Color, Enchantments,
IfVariableType, BlockType, ItemEqComparisonMode)
from .subcollections import Lore
from .dataclass import Enchantment, Tag
from .abc import DFType, Itemable
from ..utils import remove_u200b_from_doc, clamp, select_dict, nbt_to_python, serialize_tag, dumps_json
from ..schemas import ItemSchema, ItemTagSchema, ItemDisplaySchema, ItemEnchantmentSchema
from ..constants import (
DEFAULT_VAL, DEFAULT_SOUND_PITCH, DEFAULT_SOUND_VOL, MAX_PITCH_DEGREES, MAX_YAW_DEGREES,
MAX_ITEM_STACK_SIZE, MIN_ITEM_STACK_SIZE
)
if typing.TYPE_CHECKING:
from ..codeblocks import IfVariable
from ..typings import Numeric, Locatable, ItemParam
class Item(DFType, Itemable): # TODO: Bonus Item classes - WrittenBook, for example, or Chest/EnderChest
"""Represents a Minecraft Item stack.
Parameters
----------\u200b
material : :class:`Material`
Instance of the Materials enum; represents what this item actually is.
amount : :class:`int`
The amount of items in this item stack, between 1 and 64. By default, 1.
name : Optional[Union[:class:`str`, :class:`DFText`]]
An optional custom name to be given to this item, as a `:class:`str`` or :class:`DFText`. Default: None
lore : Union[`Lore`, Optional[Iterable[:class:`str`]]]
A Lore for this item (either Lore instance or list of `:class:`str``). Default: empty Lore instance.
enchantments : Optional[Iterable[:class:`~py2df.classes.dataclass.Enchantment`]]
A list of :class:`~py2df.classes.dataclass.Enchantment` instances.
damage : :class:`int`
The damage of this item (i.e., amount of uses so far). Defaults to 0 (not used).
unbreakable : :class:`bool`
Whether or not this item is unbreakable. Defaults to False.
hide_flags : Optional[Union[:class:`~py2df.enums.misc_mc_enums.HideFlags`, :class:`int`]]
Flags to be hidden, such as unbreakability. See the enum documentation for more info.
Other Parameters
----------------\u200b
leather_armor_color : Optional[:class:`int`]
If this is a piece of leather armor, specify its color through an integer. Tip: Use
``0x......`` for hexadecimal colors.
entity_tag : Optional[Union[:class:`dict`, :class:`str`, :class:`nbtlib.Compound`]]
An optional TAG_Compound (NBT) representing Entity NBT tags applied on entities that are spawned
through this item. Applies to the materials: (X)_SPAWN_EGG; TROPICAL_FISH_BUCKET; ARMOR_STAND. Default:
None (Note: If this is given a string, it must be a valid SNBT string)
extra_tags : Optional[Union[:class:`dict`, :class:`str`]]
Any extra NBT tags you'd like to give your item, either as a :class:`dict` of NBT tags or a valid NBT
:class:`str`. Please ensure those tags do not conflict with the previous ones to avoid spooky errors in
DiamondFire. Default: ``None``.
(Please ensure this is a valid TAG_Compound in NBT, a.k.a. `:class:`dict` in pythonic language.)
.. container:: comparisons
.. describe:: a == b, a != b
Checks if every attribute except :attr:`amount` is equal between the two items.
.. describe:: a > b, a < b, a >= b, a <= b
Compares the items' amounts, **if they are equal** (otherwise raises a TypeError).
.. container:: operations
.. describe:: a + b, a - b, a * b, a ** b, a / b, a // b
Executes the given operation between the items' amounts.
.. note::
The resulting item is a copy of the one that comes first**, with its 'amount' set to the result
of the operation.
.. warning::
Raises a :exc:`ValueError` if there was an attempt to set to a stack outside of the bounds 1 <= n <= 64.
.. describe:: +a, abs(a), ceil(a), floor(a)
Returns `a` (self).
.. describe:: hash(a)
Returns an unique hash representing its material, name, damage, unbreakability and which flags are hidden.
Attributes
-------------\u200b
material : :class:`~py2df.enums.materials.Material`
Tells what kind of item this is.
amount : :class:`int`
The amount there is in this Item stack. (From 1 to 64 - any number outside those bounds will error!)
name : :class:`str`
The item's name.
lore : :class:`~py2df.classes.subcollections.Lore`
The item's lore, as an instance of Lore.
enchantments : List[:class:`~py2df.classes.dataclass.Enchantment`]
A list containing instances of Enchantment.
damage : :class:`int`
How broken this item is (0 = not broken at all; the higher, the closer to breaking it is). The max
amount this attribute can have depends on the item's durability, for which there are many lists online.
unbreakable : :class:`bool`
If True, this item cannot lose durability, and remains at damage = 0.
hide_flags : Union[:class:`~py2df.enums.misc_mc_enums.HideFlags`, :class:`int`]
Flags to be hidden. Use the :class:`~py2df.enums.misc_mc_enums.HideFlags` enum for this.
One flag is of the form ``HideFlags.FLAG_NAME``, while, to use more than one, use the OR (bar) operator
(``HideFlags.FLAG_NAME | HideFlags.OTHER_FLAG_NAME | ...``). For all flags, use :data:`~.ALL_HIDE_FLAGS`.
For all flags except `x`, use ``~x``.
leather_armor_color : :class:`int`
An integer that represents the color of a leather armor. Tip: write `0x......` for a
hexadecimal representation. (This is not present in non-leather armor items.)
entity_tag : Optional[:class:`nbtlib.Compound`]
Entity NBT. Any NBT that
modifies entities generated by either spawn eggs, the armor stand item or tropical fish buckets.
(For other :class:`Material`s, this attribute should always be None.)
extra_tags : Optional[:class:`nbtlib.Compound`]
Extra NBT, representing any extra tags not covered here.
"""
__slots__ = (
"material", "_amount", "name", "lore", "enchantments", "damage", "unbreakable", "hide_flags",
"leather_armor_color", "entity_tag", "extra_tags"
)
def __init__(
self, material: Material, amount: int = 1,
*, name: typing.Optional[typing.Union[str, "DFText"]] = None,
lore: typing.Union[Lore, typing.Optional[typing.Iterable[str]]] = Lore(),
enchantments: typing.Optional[typing.Iterable[Enchantment]] = None,
damage: int = 0, unbreakable: bool = False, hide_flags: typing.Optional[typing.Union[HideFlags, int]] = None,
leather_armor_color: typing.Optional[int] = None,
entity_tag: typing.Optional[typing.Union[dict, str]] = None,
extra_tags: typing.Optional[typing.Union[dict, str]] = None
):
"""
Parameters
----------
material : :class:`Material`
Instance of the Materials enum; represents what this item actually is.
amount : :class:`int`
The amount of items in this item stack, between 1 and 64. By default, 1.
name : Optional[Union[:class:`str`, :class:`DFText`]]
An optional custom name to be given to this item, as a `:class:`str`` or :class:`DFText`. Default: None
lore : Union[`Lore`, Optional[Iterable[:class:`str`]]]
A Lore for this item (either Lore instance or list of `:class:`str``). Default: empty Lore instance.
enchantments : Optional[Iterable[:class:`~py2df.classes.dataclass.Enchantment`]]
A list of :class:`~py2df.classes.dataclass.Enchantment` instances.
damage : :class:`int`
The damage of this item (i.e., amount of uses so far). Defaults to 0 (not used).
unbreakable : :class:`bool`
Whether or not this item is unbreakable. Defaults to False.
hide_flags : Optional[:class:`~py2df.enums.misc_mc_enums.HideFlags`]
Flags to be hidden, such as unbreakability. See the enum documentation for more info.
"""
self.material: Material = material
self._amount: int = 1
self.amount = amount
self.name: str = str(name) if name else None
self.lore: Lore = Lore(lore)
if enchantments and any(type(i) != Enchantment for i in enchantments):
raise TypeError("Non-Enchantment instance found in given 'enchantments' arg.")
self.enchantments = list(enchantments) if enchantments else []
self.damage: int = int(damage)
self.unbreakable: bool = bool(unbreakable)
self.hide_flags: HideFlags = HideFlags(hide_flags) if hide_flags else None
if self.material in (
Material.LEATHER_HELMET, Material.LEATHER_CHESTPLATE, Material.LEATHER_LEGGINGS, Material.LEATHER_BOOTS
):
self.leather_armor_color: typing.Optional[int] = int(leather_armor_color) \
if leather_armor_color is not None else None
else:
self.leather_armor_color: typing.Optional[int] = None
if entity_tag and "SPAWN_EGG" in self.material.value.upper() or self.material in (
Material.ARMOR_STAND, Material.TROPICAL_FISH_BUCKET
):
if isinstance(entity_tag, (str, collections.UserString)):
entity_tag = nbt.parse_nbt(str(entity_tag))
self.entity_tag: typing.Optional[nbt.Compound] = nbt.Compound(entity_tag)
else:
self.entity_tag: typing.Optional[nbt.Compound] = None
if extra_tags:
if isinstance(extra_tags, (str, collections.UserString)):
extra_tags = nbt.parse_nbt(str(extra_tags))
self.extra_tags: typing.Optional[nbt.Compound] = nbt.Compound(extra_tags)
else:
self.extra_tags = None
@property
def amount(self) -> int:
return self._amount
@amount.setter
def amount(self, new_amt: int) -> None:
i_n_amt = int(new_amt)
if i_n_amt > MAX_ITEM_STACK_SIZE:
raise ValueError(f"Maximum item stack size is {MAX_ITEM_STACK_SIZE}.")
if i_n_amt < MIN_ITEM_STACK_SIZE:
raise ValueError(f"Minimum item stack size is {MIN_ITEM_STACK_SIZE}.")
self._amount = i_n_amt
def as_nbt(self) -> nbt.Compound:
"""Produces a NBT representation of this Item.
Returns
-------
:class:`nbtlib.Compound`
A NBT Tag_Compound (dictionary-like structure) representing this item.
"""
tag = ItemTagSchema()
if self.damage > 0:
tag["Damage"] = int(self.damage)
if self.unbreakable:
tag["Unbreakable"] = 1
if self.entity_tag: # custom entity-related nbt
ent_t = self.entity_tag
if isinstance(ent_t, str) or isinstance(ent_t, collections.UserString):
tag["EntityTag"] = nbt.parse_nbt(ent_t)
else: # must be a nbtlib.Compound or dict already
tag["EntityTag"] = ent_t
if self.enchantments:
tag["Enchantments"] = [
ItemEnchantmentSchema(
id=f"minecraft:{enchant.ench_type.value}", lvl=enchant.level
) for enchant in self.enchantments
]
if any([self.leather_armor_color is not None, self.name, self.lore]):
display = ItemDisplaySchema()
if self.name:
display["Name"] = dumps_json(str(self.name), ensure_ascii=False)
if self.lore:
display["Lore"] = self.lore.as_json_data()
if self.leather_armor_color is not None:
display["color"] = int(self.leather_armor_color)
tag["display"] = display
if self.hide_flags and self.hide_flags.value:
tag["HideFlags"] = int(typing.cast(int, self.hide_flags.value))
if self.extra_tags:
ext_t = self.extra_tags
tag.update(
serialize_tag(
ext_t
) if | |
<reponame>entityoneuk/lusid-python-tools<gh_stars>1-10
import argparse
import copy
import csv
import os
import numpy as np
import lusid
from collections.abc import Mapping
import pandas as pd
from detect_delimiter import detect
import requests
import json
import inspect
import functools
from pathlib import Path
import re
from lusidtools.cocoon.dateorcutlabel import DateOrCutLabel
import lusid.models as models
import logging
import time as default_time
from lusidtools.cocoon.validator import Validator
import types
import typing
def checkargs(function: typing.Callable) -> typing.Callable:
"""
This can be used as a decorator to test the type of arguments are correct. It checks that the provided arguments
match any type annotations and/or the default value for the parameter.
Parameters
----------
function : typing.Callable
The function to wrap with annotated types, all parameters must be annotated with a type
Returns
-------
_f : typing.Callable
The wrapped function
"""
@functools.wraps(function)
def _f(*args, **kwargs):
# Get all the function arguments in order
function_arguments = inspect.signature(function).parameters
# Collect each non keyword argument value and key it by the argument name
keyed_arguments = {
list(function_arguments.keys())[i]: args[i] for i in range(0, len(args))
}
# Update this with the keyword argument values
keyed_arguments.update(kwargs)
# For each argument raise an error if it is of the incorrect type and if it has an invalid default value
for argument_name, argument_value in keyed_arguments.items():
if argument_name not in list(function_arguments.keys()):
raise ValueError(
f"The argument {argument_name} is not a valid keyword argument for this function, valid arguments"
+ f" are {str(list(function_arguments.keys()))}"
)
# Get the arguments details
argument_details = function_arguments[argument_name]
# Assume that there is no default value for this parameter
is_default_value = False
# If there is a default value
if argument_details.default is not argument_details.empty:
# Check to see if the argument value matches the default
if argument_details.default is None:
is_default_value = argument_value is argument_details.default
else:
is_default_value = argument_value == argument_details.default
# If the argument value is of the wrong type e.g. list instead of dict then throw an error
if (
not isinstance(argument_value, argument_details.annotation)
and argument_details.annotation is not argument_details.empty
):
# Only exception to this is if it matches the default value which may be of a different type e.g. None
if not is_default_value:
raise TypeError(
f"""The value provided for {argument_name} is of type {type(argument_value)} not of
type {argument_details.annotation}. Please update the provided value to be of type
{argument_details.annotation}"""
)
return function(*args, **kwargs)
return _f
def make_code_lusid_friendly(raw_code) -> str:
"""
This function takes a column name and converts it to a LUSID friendly code creating LUSID objects. LUSID allows
for up to 64 characters which can be lowercase and uppercase letters, numbers, a dash ("-") or an underscore ("_").
The complete restrictions are here: https://support.lusid.com/what-is-a-code
Parameters
----------
raw_code : any
A raw column header which needs special characters stripped out
Returns
-------
friendly_code : str
A LUSID friendly code with special characters removed
"""
# Convert any type to a string
try:
raw_code = str(raw_code)
except Exception as exception:
raise ValueError(
f"Could not convert value of {raw_code} with type {type(raw_code)} to a string. "
+ "Please convert to a format which can be cast to a string and try again"
) from exception
# Check that it does not exceed the max length
max_length = 64
if len(raw_code) > max_length:
raise ValueError(
f"""The name {raw_code} is {len(raw_code)} characters long and exceeds the limit of {max_length}
for a code. Please shorten it by {len(raw_code) - 64} characters."""
)
# Specifically convert known unfriendly characters with a specific string and remove the rest completely
friendly_code = re.sub(
r"[^\w]",
"",
raw_code.replace("%", "Percentage")
.replace("&", "and")
.replace(".", "_")
.replace("-", "_")
.strip(),
)
return friendly_code
@checkargs
def populate_model(
model_object_name: str,
required_mapping: dict,
optional_mapping: dict,
row: pd.Series,
properties,
identifiers: dict = None,
sub_holding_keys=None,
) -> typing.Callable:
"""
This function populates the provided LUSID model object in lusid.models with values from a Pandas Series
Parameters
----------
model_object_name : str
The name of the model object to populate
required_mapping : dict
The required mapping between the row columns and the model attributes
optional_mapping : dict
The optional mapping between the row columns and the model attributes
row : pd.Series
The row from the provided pd.DataFrame to use to populate the model
properties
The properties for this model
identifiers : dict
The identifiers for this model
sub_holding_keys
The sub holding keys to use
Returns
-------
set_attributes : typing.Callable
The function to set the attributes for the model
"""
# Check that the provided model name actually exists
model_object = getattr(lusid.models, model_object_name, None)
if model_object is None:
raise TypeError("The provided model_object is not a lusid.model object")
# Expand the mapping out from being a dot separated flat dictionary e.g. transaction_price.price to being nested
update_dict(required_mapping, optional_mapping)
mapping_expanded = expand_dictionary(required_mapping)
# Set the attributes on the model
return set_attributes_recursive(
model_object=model_object,
mapping=mapping_expanded,
row=row,
properties=properties,
identifiers=identifiers,
sub_holding_keys=sub_holding_keys,
)
@checkargs
def set_attributes_recursive(
model_object,
mapping: dict,
row: pd.Series,
properties=None,
identifiers: dict = None,
sub_holding_keys=None,
):
"""
This function takes a lusid.model object name and an expanded mapping between its attributes and the provided
row of data and constructs a populated model
Parameters
----------
model_object : lusid.models
The object from lusid.models to populate
mapping : dict
The expanded dictionary mapping the Series columns to the LUSID model attributes
row : pd.Series
The current row of the DataFrame being worked on
properties : any
The properties to use on this model
identifiers : any
The instrument identifiers to use on this model
sub_holding_keys
The sub holding keys to use on this model
Returns
-------
new model_object : lusid.models
An instance of the model object with populated attributes
"""
# Get the object attributes
obj_attr = model_object.openapi_types
obj_init_values = {}
# Additional attributes which are used on most models but will be populated outside the provided mapping
additional_attributes = {
"instrument_identifiers": identifiers,
"properties": properties,
"sub_holding_keys": sub_holding_keys,
"identifiers": identifiers,
}
# Generate the intersection between the available attributes and the provided attributes
provided_attributes = set(list(mapping.keys()) + list(additional_attributes.keys()))
available_attributes = set(list(obj_attr.keys()))
populate_attributes = provided_attributes.intersection(available_attributes)
# Used to check if all attributes are none
total_count = 0
none_count = 0
# For each of the attributes to populate
for key in list(populate_attributes):
# If it is an additional attribute, populate it with the provided values and move to the next attribute
if key in list(additional_attributes.keys()):
obj_init_values[key] = additional_attributes[key]
continue
# This block keeps track of the number of missing (non-additional) attributes
else:
total_count += 1
if mapping[key] is None:
none_count += 1
# Get the attribute type
attribute_type = obj_attr[key]
# If this is the last object and there is no more nesting set the value from the row
if not isinstance(mapping[key], dict):
# If this exists in the mapping with a value and there is a value in the row for it
if mapping[key] is not None and not pd.isna(row[mapping[key]]):
# Converts to a date if it is a date field
if "date" in key or "created" in key or "effective_at" in key:
obj_init_values[key] = str(DateOrCutLabel(row[mapping[key]]))
else:
obj_init_values[key] = row[mapping[key]]
# if there is more nesting call the function recursively
else:
# Ensure that that if there is a complex attribute type e.g. dict(str, InstrumentIdValue) it is extracted
attribute_type, nested_type = extract_lusid_model_from_attribute_type(
attribute_type
)
# Call the function recursively
value = set_attributes_recursive(
model_object=getattr(lusid.models, attribute_type),
mapping=mapping[key],
row=row,
)
obj_init_values[key] = [value] if nested_type == "list" else value
"""
If all attributes are None propagate None rather than a model filled with Nones. For example if a CorporateActionSourceId
has no scope or code return build a model with CorporateActionSourceId = None rather than CorporateActionSourceId =
lusid.models.ResourceId(scope=None, code=None)
"""
if total_count == none_count:
return None
# Create an instance of and populate the model object
return model_object(**obj_init_values)
@checkargs
def update_dict(orig_dict: dict, new_dict) -> None:
"""
This is used to update a dictionary with another dictionary. Using the default Python update method does not merge
nested dictionaries. This method allows for this. This modifies the original dictionary in place.
Parameters
----------
orig_dict : dict
The original dictionary to update
new_dict : dict
The new dictionary to merge with the original
Returns
-------
orig_dict | |
that someone is a particular role
# (there are no examples of this right now, but it could be possible in the future). For example,
# if !shoot was rewritten so that there was a "gunner" and "sharpshooter" template, one could
# prove they are sharpshooter -- and therefore prove should they miss that the target is werekitten,
# as opposed to the possiblity of them being a wolf with 1 bullet who stole the gun from a dead gunner --
# by using !sharpshooter shoot target.
command(*keys, exclusive=True, pm=True, chan=False, playing=True)(fn)
# event_listener decorator wraps callback in handle_error, which we don't want for the init event
# (as no IRC connection exists at this point)
events.add_listener("init", setup_role_commands, priority=10000)
@event_listener("chan_join", priority=1)
def on_join(evt, var, chan, user):
if user is users.Bot:
plog("Joined {0}".format(chan))
# FIXME: kill all of this off along with var.USERS
elif not users.exists(user.nick):
users.add(user.nick, ident=user.ident,host=user.host,account=user.account,inchan=(chan is channels.Main),modes=set(),moded=set())
else:
baduser = users.get(user.nick)
baduser.ident = user.ident
baduser.host = user.host
baduser.account = user.account
if not baduser.inchan:
# Will be True if the user joined the main channel, else False
baduser.inchan = (chan is channels.Main)
if chan is not channels.Main:
return
return_to_village(var, user, show_message=True)
@command("goat")
def goat(var, wrapper, message):
"""Use a goat to interact with anyone in the channel during the day."""
if wrapper.source in var.LAST_GOAT and var.LAST_GOAT[wrapper.source][0] + timedelta(seconds=var.GOAT_RATE_LIMIT) > datetime.now():
wrapper.pm(messages["command_ratelimited"])
return
target = re.split(" +",message)[0]
if not target:
wrapper.pm(messages["not_enough_parameters"])
return
victim, _ = users.complete_match(users.lower(target), wrapper.target.users)
if not victim:
wrapper.pm(messages["goat_target_not_in_channel"].format(target))
return
var.LAST_GOAT[wrapper.source] = [datetime.now(), 1]
goatact = random.choice(messages["goat_actions"])
wrapper.send(messages["goat_success"].format(wrapper.source, goatact, victim))
@command("fgoat", flag="j")
def fgoat(var, wrapper, message):
"""Forces a goat to interact with anyone or anything, without limitations."""
nick = message.split(' ')[0].strip()
victim, _ = users.complete_match(users.lower(nick), wrapper.target.users)
if victim:
togoat = victim
else:
togoat = message
goatact = random.choice(messages["goat_actions"])
wrapper.send(messages["goat_success"].format(wrapper.source, goatact, togoat))
@handle_error
def return_to_village(var, target, *, show_message, new_user=None):
# Note: we do not manipulate or check target.disconnected, as that property
# is used to determine if they are entirely dc'ed rather than just maybe using
# a different account or /parting the channel. If they were dced for real and
# rejoined IRC, the join handler already took care of marking them no longer dced.
with var.GRAVEYARD_LOCK:
if target in var.DISCONNECTED:
del var.DISCONNECTED[target]
if new_user is None:
new_user = target
var.LAST_SAID_TIME[target.nick] = datetime.now()
var.DCED_LOSERS.discard(target)
if target.nick in var.DCED_PLAYERS:
var.PLAYERS[target.nick] = var.DCED_PLAYERS.pop(target.nick)
if new_user is not target:
# different users, perform a swap. This will clean up disconnected users.
target.swap(new_user)
if target.nick != new_user.nick:
# have a nickchange, update tracking vars
rename_player(var, new_user, target.nick)
if show_message:
if not var.DEVOICE_DURING_NIGHT or var.PHASE != "night":
channels.Main.mode(("+v", new_user))
if target.nick == new_user.nick:
channels.Main.send(messages["player_return"].format(new_user))
else:
channels.Main.send(messages["player_return_nickchange"].format(new_user, target))
else:
# this particular user doesn't exist in var.DISCONNECTED, but that doesn't
# mean that they aren't dced. They may have rejoined as a different nick,
# for example, and we want to mark them as back without requiring them to do
# a !swap.
if var.ACCOUNTS_ONLY or target.account:
userlist = users._get(account=target.account, allow_multiple=True) # FIXME
else: # match host (hopefully the ircd uses vhosts to differentiate users)
userlist = users._get(host=target.host, allow_multiple=True)
userlist = [u for u in userlist if u in var.DISCONNECTED]
if len(userlist) == 1:
return_to_village(var, userlist[0], show_message=show_message, new_user=target)
def rename_player(var, user, prefix):
nick = user.nick
event = Event("rename_player", {})
event.dispatch(var, prefix, nick)
if user in var.ALL_PLAYERS:
if var.PHASE in var.GAME_PHASES:
for k,v in list(var.PLAYERS.items()):
if prefix == k:
var.PLAYERS[nick] = var.PLAYERS.pop(k)
for dictvar in (var.FINAL_ROLES,):
if prefix in dictvar.keys():
dictvar[nick] = dictvar.pop(prefix)
with var.GRAVEYARD_LOCK: # to be safe
if prefix in var.LAST_SAID_TIME.keys():
var.LAST_SAID_TIME[nick] = var.LAST_SAID_TIME.pop(prefix)
if prefix in getattr(var, "IDLE_WARNED", ()):
var.IDLE_WARNED.remove(prefix)
var.IDLE_WARNED.add(nick)
if prefix in getattr(var, "IDLE_WARNED_PM", ()):
var.IDLE_WARNED_PM.remove(prefix)
var.IDLE_WARNED_PM.add(nick)
if var.PHASE == "join":
if prefix in var.GAMEMODE_VOTES:
var.GAMEMODE_VOTES[nick] = var.GAMEMODE_VOTES.pop(prefix)
@event_listener("account_change")
def account_change(evt, var, user):
if user not in channels.Main.users:
return # We only care about game-related changes in this function
if user.account is None and var.ACCOUNTS_ONLY and user in get_players():
leave(var, "account", user)
if var.PHASE == "join":
user.send(messages["account_midgame_change"], notice=True)
else:
channels.Main.mode(["-v", user.nick])
user.send(messages["account_reidentify"].format(user.account), notice=True)
# if they were gone, maybe mark them as back
return_to_village(var, user, show_message=True)
@event_listener("nick_change")
def nick_change(evt, var, user, old_rawnick):
nick = users.parse_rawnick_as_dict(old_rawnick)["nick"] # FIXME: We won't need that when all variables hold User instances
if user not in var.DISCONNECTED and user in get_players() and re.search(var.GUEST_NICK_PATTERN, user.nick):
if var.PHASE != "join":
channels.Main.mode(["-v", user.nick])
temp = users.FakeUser(None, nick, user.ident, user.host, user.realname, user.account)
leave(var, "badnick", temp) # pass in a fake user with the old nick (since the user holds the new nick)
return # Don't do anything else; they're using a guest/away nick
if user not in channels.Main.users:
return
rename_player(var, user, nick)
# perhaps mark them as back
return_to_village(var, user, show_message=True)
@event_listener("cleanup_user")
def cleanup_user(evt, var, user):
var.LAST_GOAT.pop(user, None)
@event_listener("nick_change")
def update_users(evt, var, user, old_rawnick): # FIXME: This is a temporary hack while var.USERS still exists
nick = users.parse_rawnick_as_dict(old_rawnick)["nick"]
if nick in var.USERS:
var.USERS[user.nick] = var.USERS.pop(nick)
@event_listener("chan_part")
def left_channel(evt, var, chan, user, reason):
leave(var, "part", user, chan)
@event_listener("chan_kick")
def channel_kicked(evt, var, chan, actor, user, reason):
leave(var, "kick", user, chan)
@event_listener("server_quit")
def quit_server(evt, var, user, reason):
leave(var, "quit", user, reason)
def leave(var, what, user, why=None):
if what in ("part", "kick") and why is not channels.Main:
return
if why and why == botconfig.CHANGING_HOST_QUIT_MESSAGE:
return
if var.PHASE == "none":
return
ps = get_players()
# Only mark living players as disconnected, unless they were kicked
if user.nick in var.PLAYERS and (what == "kick" or user in ps): # FIXME: Convert var.PLAYERS
var.DCED_LOSERS.add(user)
var.DCED_PLAYERS[user.nick] = var.PLAYERS.pop(user.nick) # FIXME: Convert var.PLAYERS and var.DCED_PLAYERS
if user not in ps or user in var.DISCONNECTED:
return
# If we got that far, the player was in the game. This variable tracks whether or not we want to kill them off.
killplayer = True
population = ""
if var.PHASE == "join":
lpl = len(ps) - 1
if lpl < var.MIN_PLAYERS:
with var.WARNING_LOCK:
from pregame import START_VOTES
START_VOTES.clear()
if lpl <= 0:
population = " " + messages["no_players_remaining"]
else:
population = " " + messages["new_player_count"].format(lpl)
reveal = ""
if get_main_role(user) == "person" or var.ROLE_REVEAL not in ("on", "team"):
reveal = "_no_reveal"
grace_times = {"part": var.PART_GRACE_TIME, "quit": var.QUIT_GRACE_TIME, "account": var.ACC_GRACE_TIME, "leave": 0}
reason = what
if reason == "badnick":
reason = "quit"
elif reason == "kick":
reason = "leave"
if reason in grace_times and (grace_times[reason] <= 0 or var.PHASE == "join"):
# possible message keys (for easy grep):
# "quit_death", "quit_death_no_reveal", "leave_death", "leave_death_no_reveal", "account_death", "account_death_no_reveal"
msg = messages["{0}_death{1}".format(reason, reveal)]
elif what != "kick": # There's time for the player to rejoin the game
user.send(messages["part_grace_time_notice"].format(botconfig.CHANNEL, var.PART_GRACE_TIME))
msg = messages["player_missing"]
population = ""
killplayer = False
channels.Main.send(msg.format(user, get_reveal_role(user)) + population)
var.SPECTATING_WOLFCHAT.discard(user)
var.SPECTATING_DEADCHAT.discard(user)
leave_deadchat(var, user)
if what not in ("badnick", "account") and user.nick in var.USERS: # FIXME: Need to move mode toggling somewhere saner
var.USERS[user.nick]["modes"] = set()
var.USERS[user.nick]["moded"] = set()
if killplayer:
add_dying(var, user, "bot", what, death_triggers=False)
kill_players(var)
else:
temp = user.lower()
var.DISCONNECTED[user] = (datetime.now(), what)
@command("quit", "leave", pm=True, phases=("join", "day", "night"))
def leave_game(var, wrapper, message):
"""Quits the game."""
if wrapper.target is channels.Main:
if wrapper.source not in get_players():
return
if var.PHASE == "join":
lpl = len(get_players()) - 1
if lpl == 0:
population = " " + messages["no_players_remaining"]
else:
population = " " + messages["new_player_count"].format(lpl)
else:
if not message.startswith("-force"):
wrapper.pm(messages["leave_game_ingame_safeguard"].format(botconfig.CMD_CHAR))
return
population = ""
elif wrapper.private:
if var.PHASE in var.GAME_PHASES and wrapper.source not in get_players() and wrapper.source in var.DEADCHAT_PLAYERS:
leave_deadchat(var, wrapper.source)
return
else:
return
if get_main_role(wrapper.source) != "person" and var.ROLE_REVEAL in ("on", "team"):
role = get_reveal_role(wrapper.source)
an = "n" if role.startswith(("a", "e", "i", "o", "u")) else ""
if var.DYNQUIT_DURING_GAME:
lmsg = random.choice(messages["quit"]).format(wrapper.source.nick, an, role)
channels.Main.send(lmsg)
else:
channels.Main.send((messages["static_quit"] + "{2}").format(wrapper.source.nick, role, population))
else:
# DYNQUIT_DURING_GAME should not have any effect during the join phase, so only check if we aren't in that
if var.PHASE != "join" and not var.DYNQUIT_DURING_GAME:
channels.Main.send((messages["static_quit_no_reveal"] + "{1}").format(wrapper.source.nick, population))
else:
lmsg = random.choice(messages["quit_no_reveal"]).format(wrapper.source.nick) + population
channels.Main.send(lmsg)
if var.PHASE != "join":
var.DCED_LOSERS.add(wrapper.source)
if var.LEAVE_PENALTY:
add_warning(wrapper.client, wrapper.source.nick, var.LEAVE_PENALTY, users.Bot.nick, messages["leave_warning"], expires=var.LEAVE_EXPIRY) # FIXME
if wrapper.source.nick in var.PLAYERS:
var.DCED_PLAYERS[wrapper.source.nick] = var.PLAYERS.pop(wrapper.source.nick)
add_dying(var, wrapper.source, "bot", "quit", death_triggers=False)
kill_players(var)
def begin_day():
# Reset nighttime variables
var.GAMEPHASE = "day"
| |
where you want to move the event to.
Moves an event to a different folder (calendar). ::
event = service.calendar().get_event(id='KEY HERE')
event.move_to(folder_id='NEW CALENDAR KEY HERE')
"""
if not folder_id:
raise TypeError(u"You can't move an event to a non-existant folder")
if not isinstance(folder_id, BASESTRING_TYPES):
raise TypeError(u"folder_id must be a string")
if not self.id:
raise TypeError(u"You can't move an event that hasn't been created yet.")
self.refresh_change_key()
response_xml = self.service.send(soap_request.move_event(self, folder_id))
new_id, new_change_key = self._parse_id_and_change_key_from_response(response_xml)
if not new_id:
raise ValueError(u"MoveItem returned success but requested item not moved")
self._id = new_id
self._change_key = new_change_key
self.calendar_id = folder_id
return self
def get_master(self):
"""
get_master()
:raises InvalidEventType: When this method is called on an event that is not a Occurrence type.
This will return the master event to the occurrence.
**Examples**::
event = service.calendar().get_event(id='<event_id>')
print event.type # If it prints out 'Occurrence' then that means we could get the master.
master = event.get_master()
print master.type # Will print out 'RecurringMaster'.
"""
if self.type != 'Occurrence':
raise InvalidEventType("get_master method can only be called on a 'Occurrence' event type")
body = soap_request.get_master(exchange_id=self._id, format=u"AllProperties")
response_xml = self.service.send(body)
return Exchange2010CalendarEvent(service=self.service, xml=response_xml)
def get_occurrence(self, instance_index):
"""
get_occurrence(instance_index)
:param iterable instance_index: This should be tuple or list of integers which correspond to occurrences.
:raises TypeError: When instance_index is not an iterable of ints.
:raises InvalidEventType: When this method is called on an event that is not a RecurringMaster type.
This will return a list of occurrence events.
**Examples**::
master = service.calendar().get_event(id='<event_id>')
# The following will return the first 20 occurrences in the recurrence.
# If there are not 20 occurrences, it will only return what it finds.
occurrences = master.get_occurrence(range(1,21))
for occurrence in occurrences:
print occurrence.start
"""
if not all([isinstance(i, int) for i in instance_index]):
raise TypeError("instance_index must be an interable of type int")
if self.type != 'RecurringMaster':
raise InvalidEventType("get_occurrance method can only be called on a 'RecurringMaster' event type")
body = soap_request.get_occurrence(exchange_id=self._id, instance_index=instance_index, format=u"AllProperties")
response_xml = self.service.send(body)
items = response_xml.xpath(u'//m:GetItemResponseMessage/m:Items', namespaces=soap_request.NAMESPACES)
events = []
for item in items:
event = Exchange2010CalendarEvent(service=self.service, xml=deepcopy(item))
if event.id:
events.append(event)
return events
def conflicting_events(self):
"""
conflicting_events()
This will return a list of conflicting events.
**Example**::
event = service.calendar().get_event(id='<event_id>')
for conflict in event.conflicting_events():
print conflict.subject
"""
if not self.conflicting_event_ids:
return []
body = soap_request.get_item(exchange_id=self.conflicting_event_ids, format="AllProperties")
response_xml = self.service.send(body)
items = response_xml.xpath(u'//m:GetItemResponseMessage/m:Items', namespaces=soap_request.NAMESPACES)
events = []
for item in items:
event = Exchange2010CalendarEvent(service=self.service, xml=deepcopy(item))
if event.id:
events.append(event)
return events
def refresh_change_key(self):
body = soap_request.get_item(exchange_id=self._id, format=u"IdOnly")
response_xml = self.service.send(body)
self._id, self._change_key = self._parse_id_and_change_key_from_response(response_xml)
return self
def _parse_id_and_change_key_from_response(self, response):
id_elements = response.xpath(u'//m:Items/t:CalendarItem/t:ItemId', namespaces=soap_request.NAMESPACES)
if id_elements:
id_element = id_elements[0]
return id_element.get(u"Id", None), id_element.get(u"ChangeKey", None)
else:
return None, None
def _parse_response_for_get_event(self, response):
result = self._parse_event_properties(response)
organizer_properties = self._parse_event_organizer(response)
if organizer_properties is not None:
if 'email' not in organizer_properties:
organizer_properties['email'] = None
result[u'organizer'] = ExchangeEventOrganizer(**organizer_properties)
attendee_properties = self._parse_event_attendees(response)
result[u'_attendees'] = self._build_resource_dictionary([ExchangeEventResponse(**attendee) for attendee in attendee_properties])
resource_properties = self._parse_event_resources(response)
result[u'_resources'] = self._build_resource_dictionary([ExchangeEventResponse(**resource) for resource in resource_properties])
result['_conflicting_event_ids'] = self._parse_event_conflicts(response)
return result
def _parse_event_properties(self, response):
property_map = {
u'subject': {
u'xpath': u'//m:Items/t:CalendarItem/t:Subject',
},
u'location':
{
u'xpath': u'//m:Items/t:CalendarItem/t:Location',
},
u'availability':
{
u'xpath': u'//m:Items/t:CalendarItem/t:LegacyFreeBusyStatus',
},
u'start':
{
u'xpath': u'//m:Items/t:CalendarItem/t:Start',
u'cast': u'datetime',
},
u'end':
{
u'xpath': u'//m:Items/t:CalendarItem/t:End',
u'cast': u'datetime',
},
u'html_body':
{
u'xpath': u'//m:Items/t:CalendarItem/t:Body[@BodyType="HTML"]',
},
u'text_body':
{
u'xpath': u'//m:Items/t:CalendarItem/t:Body[@BodyType="Text"]',
},
u'_type':
{
u'xpath': u'//m:Items/t:CalendarItem/t:CalendarItemType',
},
u'reminder_minutes_before_start':
{
u'xpath': u'//m:Items/t:CalendarItem/t:ReminderMinutesBeforeStart',
u'cast': u'int',
},
u'is_all_day':
{
u'xpath': u'//m:Items/t:CalendarItem/t:IsAllDayEvent',
u'cast': u'bool',
},
u'recurrence_end_date':
{
u'xpath': u'//m:Items/t:CalendarItem/t:Recurrence/t:EndDateRecurrence/t:EndDate',
u'cast': u'date_only_naive',
},
u'recurrence_interval':
{
u'xpath': u'//m:Items/t:CalendarItem/t:Recurrence/*/t:Interval',
u'cast': u'int',
},
u'recurrence_days':
{
u'xpath': u'//m:Items/t:CalendarItem/t:Recurrence/t:WeeklyRecurrence/t:DaysOfWeek',
},
}
result = self.service._xpath_to_dict(element=response, property_map=property_map, namespace_map=soap_request.NAMESPACES)
try:
recurrence_node = response.xpath(u'//m:Items/t:CalendarItem/t:Recurrence', namespaces=soap_request.NAMESPACES)[0]
except IndexError:
recurrence_node = None
if recurrence_node is not None:
if recurrence_node.find('t:DailyRecurrence', namespaces=soap_request.NAMESPACES) is not None:
result['recurrence'] = 'daily'
elif recurrence_node.find('t:WeeklyRecurrence', namespaces=soap_request.NAMESPACES) is not None:
result['recurrence'] = 'weekly'
elif recurrence_node.find('t:AbsoluteMonthlyRecurrence', namespaces=soap_request.NAMESPACES) is not None:
result['recurrence'] = 'monthly'
elif recurrence_node.find('t:AbsoluteYearlyRecurrence', namespaces=soap_request.NAMESPACES) is not None:
result['recurrence'] = 'yearly'
return result
def _parse_event_organizer(self, response):
organizer = response.xpath(u'//m:Items/t:CalendarItem/t:Organizer/t:Mailbox', namespaces=soap_request.NAMESPACES)
property_map = {
u'name':
{
u'xpath': u't:Name'
},
u'email':
{
u'xpath': u't:EmailAddress'
},
}
if organizer:
return self.service._xpath_to_dict(element=organizer[0], property_map=property_map, namespace_map=soap_request.NAMESPACES)
else:
return None
def _parse_event_resources(self, response):
property_map = {
u'name':
{
u'xpath': u't:Mailbox/t:Name'
},
u'email':
{
u'xpath': u't:Mailbox/t:EmailAddress'
},
u'response':
{
u'xpath': u't:ResponseType'
},
u'last_response':
{
u'xpath': u't:LastResponseTime',
u'cast': u'datetime'
},
}
result = []
resources = response.xpath(u'//m:Items/t:CalendarItem/t:Resources/t:Attendee', namespaces=soap_request.NAMESPACES)
for attendee in resources:
attendee_properties = self.service._xpath_to_dict(element=attendee, property_map=property_map, namespace_map=soap_request.NAMESPACES)
attendee_properties[u'required'] = True
if u'last_response' not in attendee_properties:
attendee_properties[u'last_response'] = None
if u'email' in attendee_properties:
result.append(attendee_properties)
return result
def _parse_event_attendees(self, response):
property_map = {
u'name':
{
u'xpath': u't:Mailbox/t:Name'
},
u'email':
{
u'xpath': u't:Mailbox/t:EmailAddress'
},
u'response':
{
u'xpath': u't:ResponseType'
},
u'last_response':
{
u'xpath': u't:LastResponseTime',
u'cast': u'datetime'
},
}
result = []
required_attendees = response.xpath(u'//m:Items/t:CalendarItem/t:RequiredAttendees/t:Attendee', namespaces=soap_request.NAMESPACES)
for attendee in required_attendees:
attendee_properties = self.service._xpath_to_dict(element=attendee, property_map=property_map, namespace_map=soap_request.NAMESPACES)
attendee_properties[u'required'] = True
if u'last_response' not in attendee_properties:
attendee_properties[u'last_response'] = None
if u'email' in attendee_properties:
result.append(attendee_properties)
optional_attendees = response.xpath(u'//m:Items/t:CalendarItem/t:OptionalAttendees/t:Attendee', namespaces=soap_request.NAMESPACES)
for attendee in optional_attendees:
attendee_properties = self.service._xpath_to_dict(element=attendee, property_map=property_map, namespace_map=soap_request.NAMESPACES)
attendee_properties[u'required'] = False
if u'last_response' not in attendee_properties:
attendee_properties[u'last_response'] = None
if u'email' in attendee_properties:
result.append(attendee_properties)
return result
def _parse_event_conflicts(self, response):
conflicting_ids = response.xpath(u'//m:Items/t:CalendarItem/t:ConflictingMeetings/t:CalendarItem/t:ItemId', namespaces=soap_request.NAMESPACES)
return [id_element.get(u"Id") for id_element in conflicting_ids]
class Exchange2010FolderService(BaseExchangeFolderService):
def folder(self, id=None, **kwargs):
return Exchange2010Folder(service=self.service, id=id, **kwargs)
def get_folder(self, id):
"""
:param str id: The Exchange ID of the folder to retrieve from the Exchange store.
Retrieves the folder specified by the id, from the Exchange store.
**Examples**::
folder = service.folder().get_folder(id)
"""
return Exchange2010Folder(service=self.service, id=id)
def new_folder(self, **properties):
"""
new_folder(display_name=display_name, folder_type=folder_type, parent_id=parent_id)
:param str display_name: The display name given to the new folder.
:param str folder_type: The type of folder to create. Possible values are 'Folder',
'CalendarFolder', 'ContactsFolder', 'SearchFolder', 'TasksFolder'.
:param str parent_id: The parent folder where the new folder will be created.
Creates a new folder with the given properties. Not saved until you call the create() method.
**Examples**::
folder = service.folder().new_folder(
display_name=u"New Folder Name",
folder_type="CalendarFolder",
parent_id='calendar',
)
folder.create()
"""
return Exchange2010Folder(service=self.service, **properties)
def find_folder(self, parent_id):
"""
find_folder(parent_id)
:param str parent_id: The parent folder to list.
This method will return a list of sub-folders to a given parent folder.
**Examples**::
# Iterate through folders within the default 'calendar' folder.
folders = service.folder().find_folder(parent_id='calendar')
for folder in folders:
print(folder.display_name)
# Delete all folders within the 'calendar' folder.
folders = service.folder().find_folder(parent_id='calendar')
for folder in folders:
folder.delete()
"""
body = soap_request.find_folder(parent_id=parent_id, format=u'AllProperties')
response_xml = self.service.send(body)
return self._parse_response_for_find_folder(response_xml)
def _parse_response_for_find_folder(self, response):
result = []
folders = response.xpath(u'//t:Folders/t:*', namespaces=soap_request.NAMESPACES)
for folder in folders:
result.append(
Exchange2010Folder(
service=self.service,
xml=etree.fromstring(etree.tostring(folder)) # Might be a better way to do this
)
)
return result
class Exchange2010Folder(BaseExchangeFolder):
def _init_from_service(self, id):
body = soap_request.get_folder(folder_id=id, format=u'AllProperties')
response_xml = self.service.send(body)
properties = self._parse_response_for_get_folder(response_xml)
self._update_properties(properties)
return self
def _init_from_xml(self, xml):
properties = self._parse_response_for_get_folder(xml)
self._update_properties(properties)
return self
def create(self):
"""
Creates a folder in Exchange. ::
calendar = service.folder().new_folder(
display_name=u"New Folder Name",
folder_type="CalendarFolder",
parent_id='calendar',
)
calendar.create()
"""
self.validate()
body = soap_request.new_folder(self)
response_xml = self.service.send(body)
self._id, self._change_key = self._parse_id_and_change_key_from_response(response_xml)
return self
def delete(self):
"""
Deletes a folder from the Exchange store. ::
folder = service.folder().get_folder(id)
print("Deleting folder: %s" % folder.display_name)
folder.delete()
"""
if not self.id:
raise TypeError(u"You can't delete a folder that hasn't been created yet.")
body = soap_request.delete_folder(self)
response_xml = self.service.send(body) # noqa
# TODO: verify deletion
self._id = None
self._change_key = None
return None
def move_to(self, folder_id):
"""
:param str folder_id: The Folder ID of what will be the new parent folder, of this folder.
Move folder to a different location, specified by folder_id::
folder = service.folder().get_folder(id)
folder.move_to(folder_id="ID of new location's folder")
"""
if not folder_id:
raise TypeError(u"You can't move to a non-existant folder")
if not isinstance(folder_id, BASESTRING_TYPES):
raise TypeError(u"folder_id must be a string")
if not self.id:
raise TypeError(u"You can't move a folder that hasn't been created yet.")
response_xml = self.service.send(soap_request.move_folder(self, folder_id)) # noqa
result_id, result_key = self._parse_id_and_change_key_from_response(response_xml)
if self.id != result_id:
raise ValueError(u"MoveFolder returned success but requested folder not moved")
self.parent_id = folder_id
return self
def _parse_response_for_get_folder(self, response):
FOLDER_PATH = u'//t:Folder | //t:CalendarFolder | //t:ContactsFolder | //t:SearchFolder | //t:TasksFolder'
path = response.xpath(FOLDER_PATH, namespaces=soap_request.NAMESPACES)[0]
result = | |
+ str(fid_lookup))
fid_disp = re.sub(r"^.*\.([^\.]+)\.([^\.]+)$", r"\1.\2", fid_lookup)
func_disp = feature_id_to_function[genome_ref][fid_lookup]
genome_sci_name = genome_ref_to_sci_name[genome_ref]
html_report_chunk += ['<tr bgcolor="' + row_color + '">']
#html_report_chunk += ['<tr bgcolor="'+'white'+'">'] # DEBUG
# add overlap bar
# coverage graphic (with respect to hit seq)
html_report_chunk += ['<td valign=middle align=center style="border-right:solid 1px ' +
border_body_color + '; border-bottom:solid 1px ' + border_body_color + '">']
html_report_chunk += ['<table style="height:' + str(bar_height) + 'px; width:' + str(
bar_width) + 'px" border=0 cellpadding=0 cellspacing=0>']
full_len_pos = bar_width
aln_beg_pos = int(float(bar_width) * float(int(h_beg) - 1) / float(int(h_len) - 1))
aln_end_pos = int(float(bar_width) * float(int(h_end) - 1) / float(int(h_len) - 1))
cell_pix_height = str(int(round(float(bar_height) / 3.0, 0)))
cell_color = ['', '', '']
cell_width = []
cell_width.append(aln_beg_pos)
cell_width.append(aln_end_pos - aln_beg_pos)
cell_width.append(bar_width - aln_end_pos)
for row_i in range(3):
html_report_chunk += ['<tr style="height:' + cell_pix_height + 'px">']
unalign_color = row_color
if row_i == 1:
unalign_color = bar_line_color
cell_color[0] = unalign_color
cell_color[1] = bar_color
cell_color[2] = unalign_color
for col_i in range(3):
cell_pix_width = str(cell_width[col_i])
cell_pix_color = cell_color[col_i]
html_report_chunk += ['<td style="height:' + cell_pix_height +
'px; width:' + cell_pix_width + 'px" bgcolor="' + cell_pix_color + '"></td>']
html_report_chunk += ['</tr>']
html_report_chunk += ['</table>']
html_report_chunk += ['</td>']
# add other cells
# fid
html_report_chunk += ['<td style="border-right:solid 1px ' + border_body_color + '; border-bottom:solid 1px ' +
border_body_color + '"><font color="' + text_color + '" size=' + text_fontsize + '>' + str(fid_disp) + '</font></td>']
# html_report_chunk += ['<td style="border-right:solid 1px '+border_body_color+'; border-bottom:solid 1px '+border_body_color+'"><font color="'+text_color+'" size='+text_fontsize+'>'+str(hit_accession)+'</font></td>']
# func
html_report_chunk += ['<td style="border-right:solid 1px ' + border_body_color + '; border-bottom:solid 1px ' +
border_body_color + '"><font color="' + text_color + '" size=' + text_fontsize + '>' + func_disp + '</font></td>']
# sci name
html_report_chunk += ['<td style="border-right:solid 1px ' + border_body_color + '; border-bottom:solid 1px ' +
border_body_color + '"><font color="' + text_color + '" size=' + text_fontsize + '>' + genome_sci_name + '</font></td>']
# ident
# if 'ident_thresh' in filtering_fields[hit_id]:
# this_cell_color = reject_cell_color
# else:
# this_cell_color = row_color
# html_report_chunk += ['<td align=center bgcolor="'+this_cell_color+'" style="border-right:solid 1px '+border_body_color+'; border-bottom:solid 1px '+border_body_color+'"><font color="'+text_color+'" size='+text_fontsize+'>'+str(identity)+'%</font></td>']
# aln len
if 'overlap_perc' in filtering_fields[hit_id]:
this_cell_color = reject_cell_color
else:
this_cell_color = row_color
html_report_chunk += ['<td align=center bgcolor="' + str(this_cell_color) + '" style="border-right:solid 1px ' + border_body_color + '; border-bottom:solid 1px ' +
border_body_color + '"><font color="' + text_color + '" size=' + text_fontsize + '>' + str(aln_len) + ' (' + str(aln_len_perc) + '%)</font></td>']
# evalue
html_report_chunk += ['<td align=center style="border-right:solid 1px ' + border_body_color + '; border-bottom:solid 1px ' +
border_body_color + '"><font color="' + text_color + '" size=' + text_fontsize + '><nobr>' + str(e_value) + '</nobr></font></td>']
# bit score
if 'bitscore' in filtering_fields[hit_id]:
this_cell_color = reject_cell_color
else:
this_cell_color = row_color
html_report_chunk += ['<td align=center bgcolor="' + str(this_cell_color) + '" style="border-right:solid 1px ' + border_body_color + '; border-bottom:solid 1px ' +
border_body_color + '"><font color="' + text_color + '" size=' + text_fontsize + '><nobr>' + str(bit_score) + '</nobr></font></td>']
# bias
# html_report_chunk += ['<td align=center style="border-right:solid 1px '+border_body_color+'; border-bottom:solid 1px '+border_body_color+'"><font color="'+text_color+'" size='+text_fontsize+'><nobr>'+str(bias)+'</nobr><br><nobr>('+str(bias_best_dom)+')</nobr></font></td>']
# aln coords only for hit seq
html_report_chunk += ['<td align=center style="border-right:solid 1px ' + border_body_color + '; border-bottom:solid 1px ' + border_body_color +
'"><font color="' + text_color + '" size=' + text_fontsize + '><nobr>' + str(h_beg) + '-' + str(h_end) + '</nobr></font></td>']
# close chunk
html_report_chunk += ['</tr>']
# attach chunk
if total_hit_cnts[msa_i] == 0:
self.log(console, "NO HITS FOR MSA[" + str(msa_i) + "] " +
input_msa_names[msa_i] + ". NOT ADDING TO HTML HIT REPORT.")
html_report_chunk_str = '<tr><td colspan=table_col_width><blockquote><i>no hits found</i></td></tr>'
else:
html_report_chunk_str = "\n".join(html_report_chunk)
html_report_chunks[msa_i] = html_report_chunk_str
#self.log(console, "HTML_REPORT_CHUNK: '"+str(html_report_chunk_str)+"'") # DEBUG
#### Create and Upload output objects if coalesce_output is true
##
if 'coalesce_output' in params and int(params['coalesce_output']) == 1:
output_name = params['output_filtered_name']
if len(invalid_msgs) == 0:
if not hit_accept_something:
self.log(console, "No Object to Upload for all MSAs") # DEBUG
else:
self.log(console, "Uploading results Object") # DEBUG
if many_type_name == 'SequenceSet': # input many SequenceSet -> save SequenceSet
output_sequenceSet['sequences'] = coalesced_sequenceObjs
new_obj_info = ws.save_objects({
'workspace': params['workspace_name'],
'objects': [{
'type': 'KBaseSequences.SequenceSet',
'data': output_sequenceSet,
'name': output_name,
'meta': {},
'provenance': provenance
}]
})[0]
else: # input FeatureSet, Genome, and GenomeSet -> upload FeatureSet output
output_featureSet['element_ordering'] = coalesce_featureIds_element_ordering
output_featureSet['elements'] = dict()
for f_i, fId in enumerate(output_featureSet['element_ordering']):
output_featureSet['elements'][fId] = []
output_featureSet['elements'][fId].append(coalesce_featureIds_genome_ordering[f_i])
new_obj_info = ws.save_objects({
'workspace': params['workspace_name'],
'objects': [{
'type': 'KBaseCollections.FeatureSet',
'data': output_featureSet,
'name': output_name,
'meta': {},
'provenance': provenance
}]
})[0]
[OBJID_I, NAME_I, TYPE_I, SAVE_DATE_I, VERSION_I, SAVED_BY_I, WSID_I,
WORKSPACE_I, CHSUM_I, SIZE_I, META_I] = range(11) # object_info tuple
objects_created_refs.append(str(new_obj_info[WSID_I]) + '/' + str(new_obj_info[OBJID_I]))
#### Set paths for output HTML
##
html_output_dir = os.path.join(self.output_dir, 'html_output')
if not os.path.exists(html_output_dir):
os.makedirs(html_output_dir)
html_search_file = search_tool_name + '_Search.html'
html_search_path = os.path.join(html_output_dir, html_search_file)
html_profile_file = search_tool_name + '_Profile.html'
html_profile_path = os.path.join(html_output_dir, html_profile_file)
#### Build Search output report (and assemble html chunks)
##
self.log(console, "BUILDING SEARCH REPORT ") # DEBUG
if len(invalid_msgs) == 0:
# build html report
if many_type_name == 'Genome':
feature_id_to_function = GenomeToFASTA_retVal['feature_id_to_function']
genome_ref_to_sci_name = GenomeToFASTA_retVal['genome_ref_to_sci_name']
elif many_type_name == 'GenomeSet':
feature_id_to_function = GenomeSetToFASTA_retVal['feature_id_to_function']
genome_ref_to_sci_name = GenomeSetToFASTA_retVal['genome_ref_to_sci_name']
elif many_type_name == 'FeatureSet':
feature_id_to_function = FeatureSetToFASTA_retVal['feature_id_to_function']
genome_ref_to_sci_name = FeatureSetToFASTA_retVal['genome_ref_to_sci_name']
sp = ' '
head_color = "#eeeeff"
border_head_color = "#ffccff"
accept_row_color = 'white'
#reject_row_color = '#ffeeee'
reject_row_color = '#eeeeee'
reject_cell_color = '#ffcccc'
text_fontsize = "2"
text_color = '#606060'
header_tab_fontsize = "3"
header_tab_color = '#606060'
border_body_color = "#cccccc"
bar_width = 100
bar_height = 15
bar_color = "lightblue"
bar_line_color = "#cccccc"
bar_fontsize = "1"
bar_char = "."
cellpadding = "3"
cellspacing = "2"
border = "0"
table_col_width = 8
html_report_lines = []
html_report_lines += ['<html>']
html_report_lines += ['<head>']
html_report_lines += ['<title>KBase HMMER Custom Model Search Hits</title>']
html_report_lines += ['</head>']
html_report_lines += ['<body bgcolor="white">']
if many_type_name == 'GenomeSet':
html_report_lines += ['<a href="' + html_profile_file + '"><font color="' + header_tab_color + '" size=' + header_tab_fontsize +
'>TABULAR PROFILE</font></a> | <font color="' + header_tab_color + '" size=' + header_tab_fontsize + '><b>SEARCH HITS</b></font>']
html_report_lines += ['<p>']
html_report_lines += ['<table cellpadding=' + cellpadding +
' cellspacing = ' + cellspacing + ' border=' + border + '>']
html_report_lines += ['<tr bgcolor="' + head_color + '">']
html_report_lines += ['<td style="border-right:solid 2px ' + border_head_color + '; border-bottom:solid 2px ' + border_head_color +
'"><font color="' + text_color + '" size=' + text_fontsize + '>' + 'ALIGNMENT COVERAGE (HIT SEQ)' + '</font></td>']
html_report_lines += ['<td style="border-right:solid 2px ' + border_head_color + '; border-bottom:solid 2px ' +
border_head_color + '"><font color="' + text_color + '" size=' + text_fontsize + '>' + 'GENE ID' + '</font></td>']
html_report_lines += ['<td style="border-right:solid 2px ' + border_head_color + '; border-bottom:solid 2px ' +
border_head_color + '"><font color="' + text_color + '" size=' + text_fontsize + '>' + 'FUNCTION' + '</font></td>']
html_report_lines += ['<td style="border-right:solid 2px ' + border_head_color + '; border-bottom:solid 2px ' +
border_head_color + '"><font color="' + text_color + '" size=' + text_fontsize + '>' + 'GENOME' + '</font></td>']
# html_report_lines += ['<td align=center style="border-right:solid 2px '+border_head_color+'; border-bottom:solid 2px '+border_head_color+'"><font color="'+text_color+'" size='+text_fontsize+'>'+'IDENT'+'%</font></td>']
html_report_lines += ['<td align=center style="border-right:solid 2px ' + border_head_color + '; border-bottom:solid 2px ' +
border_head_color + '"><font color="' + text_color + '" size=' + text_fontsize + '>' + 'ALN_LEN' + '</font></td>']
html_report_lines += ['<td align=center style="border-right:solid 2px ' + border_head_color + '; border-bottom:solid 2px ' +
border_head_color + '"><font color="' + text_color + '" size=' + text_fontsize + '>' + 'E-VALUE' + '</font></td>']
html_report_lines += ['<td align=center style="border-right:solid 2px ' + border_head_color + '; border-bottom:solid 2px ' +
border_head_color + '"><font color="' + text_color + '" size=' + text_fontsize + '>' + 'BIT SCORE' + '</font></td>']
html_report_lines += ['<td align=center style="border-right:solid 2px ' + border_head_color + '; border-bottom:solid 2px ' +
border_head_color + '"><font color="' + text_color + '" size=' + text_fontsize + '>' + '<nobr>H_BEG-H_END</nobr>' + '</font></td>']
# html_report_lines += ['<td align=center style="border-right:solid 2px '+border_head_color+'; border-bottom:solid 2px '+border_head_color+'"><font color="'+text_color+'" size='+text_fontsize+'>'+'MIS MATCH'+'</font></td>']
# html_report_lines += ['<td align=center style="border-right:solid 2px '+border_head_color+'; border-bottom:solid 2px '+border_head_color+'"><font color="'+text_color+'" size='+text_fontsize+'>'+'GAP OPEN'+'</font></td>']
html_report_lines += ['</tr>']
for msa_i, input_msa_name in enumerate(input_msa_names):
html_report_lines | |
<reponame>LauraOlivera/gammapy<gh_stars>0
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Spectral models for Gammapy."""
import operator
import numpy as np
import scipy.optimize
import scipy.special
import astropy.units as u
from astropy import constants as const
from astropy.table import Table
from astropy.utils.decorators import classproperty
from astropy.visualization import quantity_support
from gammapy.maps import MapAxis, RegionNDMap
from gammapy.modeling import Parameter, Parameters
from gammapy.utils.integrate import trapz_loglog
from gammapy.utils.interpolation import (
ScaledRegularGridInterpolator,
interpolation_scale,
)
from gammapy.utils.scripts import make_path
from .core import Model
from gammapy.utils.roots import find_roots
def scale_plot_flux(flux, energy_power=0):
"""Scale flux to plot
Parameters
----------
flux : `Map`
Flux map
energy_power : int, optional
Power of energy to multiply flux axis with
Returns
-------
flux : `Map`
Scaled flux map
"""
energy = flux.geom.get_coord(sparse=True)["energy"]
try:
eunit = [_ for _ in flux.unit.bases if _.physical_type == "energy"][0]
except IndexError:
eunit = energy.unit
y = flux * np.power(energy, energy_power)
return y.to_unit(flux.unit * eunit ** energy_power)
def integrate_spectrum(func, energy_min, energy_max, ndecade=100):
"""Integrate 1d function using the log-log trapezoidal rule.
Internally an oversampling of the energy bins to "ndecade" is used.
Parameters
----------
func : callable
Function to integrate.
energy_min : `~astropy.units.Quantity`
Integration range minimum
energy_max : `~astropy.units.Quantity`
Integration range minimum
ndecade : int, optional
Number of grid points per decade used for the integration.
Default : 100
"""
num = np.max(ndecade * np.log10(energy_max / energy_min))
energy = np.geomspace(energy_min, energy_max, num=int(num), axis=-1)
integral = trapz_loglog(func(energy), energy, axis=-1)
return integral.sum(axis=0)
class SpectralModel(Model):
"""Spectral model base class."""
_type = "spectral"
def __call__(self, energy):
kwargs = {par.name: par.quantity for par in self.parameters}
kwargs = self._convert_evaluate_unit(kwargs, energy)
return self.evaluate(energy, **kwargs)
@classproperty
def is_norm_spectral_model(cls):
"""Whether model is a norm spectral model"""
return "Norm" in cls.__name__
@staticmethod
def _convert_evaluate_unit(kwargs_ref, energy):
kwargs = {}
for name, quantity in kwargs_ref.items():
if quantity.unit.physical_type == "energy":
quantity = quantity.to(energy.unit)
kwargs[name] = quantity
return kwargs
def __add__(self, model):
if not isinstance(model, SpectralModel):
model = ConstantSpectralModel(const=model)
return CompoundSpectralModel(self, model, operator.add)
def __mul__(self, other):
if isinstance(other, SpectralModel):
return CompoundSpectralModel(self, other, operator.mul)
else:
raise TypeError(f"Multiplication invalid for type {other!r}")
def __radd__(self, model):
return self.__add__(model)
def __sub__(self, model):
if not isinstance(model, SpectralModel):
model = ConstantSpectralModel(const=model)
return CompoundSpectralModel(self, model, operator.sub)
def __rsub__(self, model):
return self.__sub__(model)
def _propagate_error(self, epsilon, fct, **kwargs):
"""Evaluate error for a given function with uncertainty propagation.
Parameters
----------
fct : `~astropy.units.Quantity`
Function to estimate the error.
epsilon : float
Step size of the gradient evaluation. Given as a
fraction of the parameter error.
**kwargs : dict
Keyword argument
Returns
-------
f_cov : `~astropy.units.Quantity`
Error of the given function.
"""
eps = np.sqrt(np.diag(self.covariance)) * epsilon
n, f_0 = len(self.parameters), fct(**kwargs)
shape = (n, len(np.atleast_1d(f_0)))
df_dp = np.zeros(shape)
for idx, parameter in enumerate(self.parameters):
if parameter.frozen or eps[idx] == 0:
continue
parameter.value += eps[idx]
df = fct(**kwargs) - f_0
df_dp[idx] = df.value / eps[idx]
parameter.value -= eps[idx]
f_cov = df_dp.T @ self.covariance @ df_dp
f_err = np.sqrt(np.diagonal(f_cov))
return u.Quantity([f_0.value, f_err], unit=f_0.unit)
def evaluate_error(self, energy, epsilon=1e-4):
"""Evaluate spectral model with error propagation.
Parameters
----------
energy : `~astropy.units.Quantity`
Energy at which to evaluate
epsilon : float
Step size of the gradient evaluation. Given as a
fraction of the parameter error.
Returns
-------
dnde, dnde_error : tuple of `~astropy.units.Quantity`
Tuple of flux and flux error.
"""
return self._propagate_error(epsilon=epsilon, fct=self, energy=energy)
def integral(self, energy_min, energy_max, **kwargs):
r"""Integrate spectral model numerically if no analytical solution defined.
.. math::
F(E_{min}, E_{max}) = \int_{E_{min}}^{E_{max}} \phi(E) dE
Parameters
----------
energy_min, energy_max : `~astropy.units.Quantity`
Lower and upper bound of integration range.
**kwargs : dict
Keyword arguments passed to :func:`~gammapy.utils.integrate.integrate_spectrum`
"""
if hasattr(self, "evaluate_integral"):
kwargs = {par.name: par.quantity for par in self.parameters}
kwargs = self._convert_evaluate_unit(kwargs, energy_min)
return self.evaluate_integral(energy_min, energy_max, **kwargs)
else:
return integrate_spectrum(self, energy_min, energy_max, **kwargs)
def integral_error(self, energy_min, energy_max, epsilon=1e-4, **kwargs):
"""Evaluate the error of the integral flux of a given spectrum in
a given energy range.
Parameters
----------
energy_min, energy_max : `~astropy.units.Quantity`
Lower and upper bound of integration range.
epsilon : float
Step size of the gradient evaluation. Given as a
fraction of the parameter error.
Returns
-------
flux, flux_err : tuple of `~astropy.units.Quantity`
Integral flux and flux error betwen energy_min and energy_max.
"""
return self._propagate_error(
epsilon=epsilon,
fct=self.integral,
energy_min=energy_min,
energy_max=energy_max,
**kwargs,
)
def energy_flux(self, energy_min, energy_max, **kwargs):
r"""Compute energy flux in given energy range.
.. math::
G(E_{min}, E_{max}) = \int_{E_{min}}^{E_{max}} E \phi(E) dE
Parameters
----------
energy_min, energy_max : `~astropy.units.Quantity`
Lower and upper bound of integration range.
**kwargs : dict
Keyword arguments passed to func:`~gammapy.utils.integrate.integrate_spectrum`
"""
def f(x):
return x * self(x)
if hasattr(self, "evaluate_energy_flux"):
kwargs = {par.name: par.quantity for par in self.parameters}
kwargs = self._convert_evaluate_unit(kwargs, energy_min)
return self.evaluate_energy_flux(energy_min, energy_max, **kwargs)
else:
return integrate_spectrum(f, energy_min, energy_max, **kwargs)
def energy_flux_error(self, energy_min, energy_max, epsilon=1e-4, **kwargs):
"""Evaluate the error of the energy flux of a given spectrum in
a given energy range.
Parameters
----------
energy_min, energy_max : `~astropy.units.Quantity`
Lower and upper bound of integration range.
epsilon : float
Step size of the gradient evaluation. Given as a
fraction of the parameter error.
Returns
-------
energy_flux, energy_flux_err : tuple of `~astropy.units.Quantity`
Energy flux and energy flux error betwen energy_min and energy_max.
"""
return self._propagate_error(
epsilon=epsilon,
fct=self.energy_flux,
energy_min=energy_min,
energy_max=energy_max,
**kwargs,
)
def reference_fluxes(self, energy_axis):
"""Get reference fluxes for a given energy axis.
Parameters
----------
energy_axis : `MapAxis`
Energy axis
Returns
-------
fluxes : dict of `~astropy.units.Quantity`
Reference fluxes
"""
energy = energy_axis.center
energy_min, energy_max = energy_axis.edges_min, energy_axis.edges_max
return {
"e_ref": energy,
"e_min": energy_min,
"e_max": energy_max,
"ref_dnde": self(energy),
"ref_flux": self.integral(energy_min, energy_max),
"ref_eflux": self.energy_flux(energy_min, energy_max),
"ref_e2dnde": self(energy) * energy ** 2,
}
def _get_plot_flux(self, energy, sed_type):
flux = RegionNDMap.create(region=None, axes=[energy])
flux_err = RegionNDMap.create(region=None, axes=[energy])
if sed_type in ["dnde", "norm"]:
flux.quantity, flux_err.quantity = self.evaluate_error(energy.center)
elif sed_type == "e2dnde":
flux.quantity, flux_err.quantity = energy.center ** 2 * self.evaluate_error(energy.center)
elif sed_type == "flux":
flux.quantity, flux_err.quantity = self.integral_error(energy.edges_min, energy.edges_max)
elif sed_type == "eflux":
flux.quantity, flux_err.quantity = self.energy_flux_error(energy.edges_min, energy.edges_max)
else:
raise ValueError(f"Not a valid SED type: '{sed_type}'")
return flux, flux_err
def plot(
self,
energy_bounds,
ax=None,
sed_type="dnde",
energy_power=0,
n_points=100,
**kwargs,
):
"""Plot spectral model curve.
kwargs are forwarded to `matplotlib.pyplot.plot`
By default a log-log scaling of the axes is used, if you want to change
the y axis scaling to linear you can use::
from gammapy.modeling.models import ExpCutoffPowerLawSpectralModel
from astropy import units as u
pwl = ExpCutoffPowerLawSpectralModel()
ax = pwl.plot(energy_bounds=(0.1, 100) * u.TeV)
ax.set_yscale('linear')
Parameters
----------
ax : `~matplotlib.axes.Axes`, optional
Axis
energy_bounds : `~astropy.units.Quantity`
Plot energy bounds passed to MapAxis.from_energy_bounds
sed_type : {"dnde", "flux", "eflux", "e2dnde"}
Evaluation methods of the model
energy_power : int, optional
Power of energy to multiply flux axis with
n_points : int, optional
Number of evaluation nodes
**kwargs : dict
Keyword arguments forwared to `~matplotlib.pyplot.plot`
Returns
-------
ax : `~matplotlib.axes.Axes`, optional
Axis
"""
from gammapy.estimators.flux_map import DEFAULT_UNIT
import matplotlib.pyplot as plt
ax = plt.gca() if ax is None else ax
if self.is_norm_spectral_model:
sed_type = "norm"
energy_min, energy_max = energy_bounds
energy = MapAxis.from_energy_bounds(
energy_min, energy_max, n_points,
)
kwargs.setdefault("yunits", DEFAULT_UNIT[sed_type] * energy.unit ** energy_power)
flux, _ = self._get_plot_flux(sed_type=sed_type, energy=energy)
flux = scale_plot_flux(flux, energy_power=energy_power)
with quantity_support():
ax.plot(energy.center, flux.quantity[:, 0, 0], **kwargs)
self._plot_format_ax(ax, energy_power, sed_type)
return ax
def plot_error(
self,
energy_bounds,
ax=None,
sed_type="dnde",
energy_power=0,
n_points=100,
**kwargs,
):
"""Plot spectral model error band.
.. note::
This method calls ``ax.set_yscale("log", nonpositive='clip')`` and
``ax.set_xscale("log", nonposx='clip')`` to create a log-log representation.
The additional argument ``nonposx='clip'`` avoids artefacts in the plot,
when the error band extends to negative values (see also
https://github.com/matplotlib/matplotlib/issues/8623).
When you call ``plt.loglog()`` or ``plt.semilogy()`` explicitely in your
plotting code and the error band extends to negative values, it is not
shown correctly. To circumvent this issue also use
``plt.loglog(nonposx='clip', nonpositive='clip')``
or ``plt.semilogy(nonpositive='clip')``.
Parameters
----------
ax : `~matplotlib.axes.Axes`, optional
Axis
energy_bounds : `~astropy.units.Quantity`
Plot energy bounds passed to MapAxis.from_energy_bounds
sed_type : {"dnde", "flux", "eflux", "e2dnde"}
Evaluation methods of the model
energy_power : int, optional
Power of energy to multiply flux axis with
n_points : int, optional
Number of evaluation nodes
**kwargs : dict
Keyword arguments forwarded to `matplotlib.pyplot.fill_between`
Returns
-------
ax : `~matplotlib.axes.Axes`, optional
Axis
"""
from gammapy.estimators.flux_map import DEFAULT_UNIT
import matplotlib.pyplot as plt
ax = plt.gca() if ax is None else ax
if self.is_norm_spectral_model:
sed_type = "norm"
energy_min, energy_max | |
import numpy as np
import joblib
import torch
from torch import nn
from torch.autograd import Variable
from .gru import GRUCell, GRUODECell
class ForecastRNN(nn.Module):
"""
Helper for pytorch reimplementation
Uses variable sized/depth GRU with linear layer to get output right
"""
def __init__(self, input_dim, output_dim, hidden_size, depth, output_len=-1, cuda=False):
super(ForecastRNN, self).__init__()
self.cuda = cuda
# gru forward: seq and output has the same size
# each output unit o[t] is based on i[0:t]
self.rnn = nn.GRU(input_size=input_dim,
hidden_size=hidden_size,
num_layers=depth,
dropout=0.,
bidirectional=False, # would bidirectional help forecasting?
batch_first=True)
self.sm = nn.LogSoftmax(dim=1)
self.input_dim = input_dim
self.output_dim = output_dim
self.output_len = output_len
if self.cuda:
self.rnn = self.rnn.cuda()
self.sm = self.sm.cuda()
self.float = torch.cuda.FloatTensor # not sure I need this
else:
self.float = torch.FloatTensor
@staticmethod
def _dist_to_bins(dist):
return torch.max(dist, dim=-1)[1]
@staticmethod
def _get_sequence_info(seq):
"""
gets info on fed sequence
"""
if type(seq) == torch.nn.utils.rnn.PackedSequence:
pack = True
batch_size = seq.batch_sizes[0]
sequence_length = len(seq.batch_sizes)
else:
pack = False
batch_size = seq.size(0)
sequence_length = seq.size(1)
return pack, batch_size, sequence_length
def _rnn_forward(self, seq, pack, batch_size):
"""
Helper function for forward that computes up to output layer
"""
h = Variable(torch.zeros(self.rnn.num_layers,
batch_size, # not sure if need to reshape for batch_first
self.rnn.hidden_size).type(self.float),
requires_grad=False)
# predict within the sequence
out, h = self.rnn.forward(seq, h)
# print(seq)
# print(out)
if pack:
out, lens = nn.utils.rnn.pad_packed_sequence(out, batch_first=True, padding_value=-1)
else:
lens = None
# out has dim (batch_size, sequence_length, hidden_size)
out_flat = out.contiguous().view(-1, self.rnn.hidden_size)
# print(out_flat.shape)
return out_flat, h, lens
def _extract_final_dist(self, pack, batch_size, y, lens):
"""
Given y (possibly with padding), get distribution
for final prediction at t+1
prediction must be of size (batch_size, 1[, output_len], output_length)
"""
if type(self) is RecursiveRNN:
output_len = 1
else:
output_len = self.decoding_steps
single_view = 1, 1, output_len, self.output_dim
batch_view = batch_size, 1, output_len, self.output_dim
if pack:
# need to handle uneven lengths
final_dist = []
for i in range(batch_size):
final_dist.append(y[i, lens[i]-1].view(single_view))
final_dist = torch.cat(final_dist).view(batch_view)
else:
final_dist = y[:, -1].contiguous().view(batch_view)
return final_dist
def forward(self, seq, glucose_dat, pred_len=0):
raise NotImplementedError
class RecursiveRNN(ForecastRNN):
"""
Designed to handle uneven batch sizes
"""
def __init__(self, input_dim, output_dim, hidden_size, depth, cuda):
super(RecursiveRNN, self).__init__(input_dim=input_dim,
output_dim=output_dim,
hidden_size=hidden_size,
depth=depth,
cuda=cuda)
self.output = nn.Linear(hidden_size, output_dim)
if self.cuda:
self.output = self.output.cuda()
def _hidden_state_to_output(self, out_flat, batch_size, sequence_length):
"""
Given output from RNN layer, translate to output
"""
return self.sm(self.output(out_flat)).contiguous().view(batch_size, sequence_length, 1, self.output_dim)
def forward(self, seq, glucose_dat, pred_len=0, **kwargs):
"""
pred_len is number of recursive forecasts to make
Note: there is padding in form of -1, need to remove for
accurate loss
bins reverse probability predictions to real values
returns:
curr_dist: (batch_size, sequence_length-1, 1[output_len], output_dim)
curr_pred: (batch_size, sequence_length-1, 1[pred_dim])
future_dist: (batch_size, 1[tiled preds], pred_len+1, output_dim)
future_pred: (batch_size, 1[tiled preds], pred_len+1)
"""
pack, batch_size, sequence_length = self._get_sequence_info(seq)
out_flat, h, lens = self._rnn_forward(seq, pack, batch_size)
y = self._hidden_state_to_output(out_flat, batch_size, sequence_length)
final_dist = self._extract_final_dist(pack, batch_size, y, lens)
if y.data.shape[1] == 1:
# only 1 input, no within series predictions
curr_dist = None
else:
curr_dist = y[:, :-1]
curr_pred = self._dist_to_bins(curr_dist)
future_dist = [final_dist]
future_pred = [self._dist_to_bins(future_dist[-1])]
for i in range(pred_len):
if self.cuda:
pred_vals = glucose_dat.bins_to_values(future_pred[-1].data.cpu().numpy())
else:
pred_vals = glucose_dat.bins_to_values(future_pred[-1].data.numpy())
out, h = self.rnn.forward(Variable(torch.from_numpy(pred_vals).type(self.float)), h)
out_flat = out.contiguous().view(-1, self.rnn.hidden_size)
y_f = self._hidden_state_to_output(out_flat, batch_size, 1)
future_dist.append(y_f)
future_pred.append(self._dist_to_bins(future_dist[-1]))
return curr_dist, curr_pred, torch.cat(future_dist, dim=2), torch.cat(future_pred, dim=2)
class MultiOutputRNN(ForecastRNN):
"""
Designed to handle uneven batch sizes
"""
def __init__(self,
input_dim,
output_dim,
output_len,
hidden_size,
depth,
cuda,
autoregressive=False,
args=None,):
super(MultiOutputRNN, self).__init__(input_dim=input_dim,
output_dim=output_dim,
hidden_size=hidden_size,
depth=depth,
output_len=output_len,
cuda=cuda)
self.ar = autoregressive
self.seq = args.sequence
self.polynomial = args.polynomial
self.degree = args.degree
self.network = args.network
self.args = args
if self.polynomial:
self.decoding_steps = self.degree+1
self.polyval_layer = nn.Linear(self.decoding_steps*output_dim, output_len*output_dim)
else:
self.decoding_steps = self.output_len
if self.seq:
# TODO: add neural ODE block
if self.network == 'grutorch':
self.decoder = nn.GRU(input_size=hidden_size,
hidden_size=hidden_size,
num_layers=1,
dropout=0.,
bidirectional=False,
batch_first=False)
elif self.network == 'gru':
self.decoder = GRUCell(input_size=hidden_size,
hidden_size=hidden_size,
bias=True)
elif self.network == 'odenet':
self.decoder = GRUODECell(input_size=hidden_size,
hidden_size=hidden_size,
bias=True,
args=self.args)
if self.cuda:
self.decoder.cuda()
self.output = nn.Linear(hidden_size, output_dim)
elif self.ar:
output = [nn.Linear(hidden_size, output_dim)]
for i in range(self.decoding_steps-1):
output.append(nn.Linear(hidden_size + output_dim, output_dim))
self.output = nn.ModuleList(output)
else:
output = [nn.Linear(hidden_size, output_dim) for i in range(self.decoding_steps)]
self.output = nn.ModuleList(output)
if self.cuda:
self.output = self.output.cuda()
def _hidden_state_to_output(self, out_flat, batch_size, sequence_length):
"""
Given output from RNN layer, translate to output
y has size (batch_size, sequence_length, output_len, output_dim)
might want to change
"""
if self.seq:
y = []
encoded = out_flat[None, :]
# print(encoded.shape)
hidden = Variable(torch.zeros(encoded.data.shape))
if self.cuda:
hidden = hidden.cuda()
for i in range(self.decoding_steps):
# size of encoded [batch*inputlength, hidden_size]
# for encoded, batch*inputlength elements are independent (here 128 x 101)
if self.network == 'odenet':
encoded = self.decoder(encoded)
else:
encoded, hidden = self.decoder(encoded, hidden)
pred = self.sm(self.output(encoded[0])).contiguous()
y.append(pred.view(batch_size,
sequence_length,
1,
self.output_dim))
return torch.cat(y, dim=2)
else:
y = []
for i in range(len(self.output)):
if self.ar:
if i == 0:
pred = self.sm(self.output[0](out_flat)).contiguous()
y.append(pred.view(batch_size,
sequence_length,
1,
self.output_dim))
else:
fused_state = torch.cat((out_flat, pred), dim=1)
pred = self.sm(self.output[i](fused_state)).contiguous()
y.append(pred.view(batch_size,
sequence_length,
1,
self.output_dim))
else:
y.append(self.sm(self.output[i](out_flat)).contiguous().view(batch_size,
sequence_length,
1,
self.output_dim))
return torch.cat(y, dim=2)
def poly_to_val(self, poly):
return poly
def forward(self, seq, glucose_dat, **kwargs):
"""
prediction into future is based on output size
Note: there is padding in form of -1, need to remove for
accurate loss
bins reverse probability predictions to real values
"""
pack, batch_size, sequence_length = self._get_sequence_info(seq)
out_flat, h, lens = self._rnn_forward(seq, pack, batch_size)
y = self._hidden_state_to_output(out_flat, batch_size, sequence_length)
final_dist = self._extract_final_dist(pack, batch_size, y, lens)
if y.data.shape[1] <= self.output_len:
# curr_dist contains dists ENTIRELY within signal
# note that this reduces training size
curr_dist = None
else:
curr_dist = y[:, :-self.output_len]
curr_pred = self._dist_to_bins(curr_dist)
future_dist = [final_dist]
future_pred = self._dist_to_bins(future_dist[-1])
if self.polynomial:
curr_real_pred = self.poly_to_val(curr_pred)
future_real_pred = self.poly_to_val(future_pred)
return (curr_dist,
curr_pred,
torch.cat(future_dist, dim=0),
future_pred)
def sort_batch(batch_x, batch_y, batch_y_real, lens):
"""
Sorts minibatch by length in decreasing order
to accomodate pack_padded_sequence
"""
dat_x, dat_y, dat_y_real, dat_l = batch_x.numpy(), batch_y.numpy(), batch_y_real.numpy(), lens.numpy()
sort_x = dat_x[(dat_l*-1).argsort()] # -1 to get descending order
sort_y = dat_y[(dat_l*-1).argsort()]
sort_y_real = dat_y_real[(dat_l*-1).argsort()]
sort_l = dat_l[(dat_l*-1).argsort()]
return sort_x, sort_y, sort_y_real, sort_l
def convert_batch(batch_x, batch_y, batch_y_real, batch_l, cuda, real_values=False):
"""
Given batches in numpy form,
convert to proper type for model input
"""
if cuda:
float_type = torch.cuda.FloatTensor
long_type = torch.cuda.LongTensor
else:
float_type = torch.FloatTensor
long_type = torch.LongTensor
new_batch_x = Variable(torch.from_numpy(batch_x).type(float_type), requires_grad=False)
if real_values:
new_batch_y = Variable(torch.from_numpy(batch_y).type(float_type), requires_grad=False)
new_batch_y_real = new_batch_y
else:
new_batch_y = Variable(torch.from_numpy(batch_y).type(long_type), requires_grad=False)
new_batch_y_real = Variable(torch.from_numpy(batch_y_real).type(long_type), requires_grad=False)
new_batch_l = list(batch_l)
return new_batch_x, new_batch_y, new_batch_y_real, new_batch_l
def remove_prediction_padding(prediction_distribution,
target_value,
loss_weight,
target_real_value):
"""
Masks prediction for artificial targets and flattens
"""
# assuming target value will have all -1 or no -1
missing_indicator = torch.min(target_value, dim=2)[0] != -1
prediction_nopad = torch.masked_select(
prediction_distribution,
missing_indicator[:, :, None, None]).view(-1, prediction_distribution.shape[-1])
target_nopad = torch.masked_select(
target_value,
missing_indicator[:, :, None])
target_real_nopad = torch.masked_select(
target_real_value,
missing_indicator[:, :, None])
loss_weight_nopad = torch.masked_select(
loss_weight,
missing_indicator[:, :, None])
return prediction_nopad, target_nopad, target_real_nopad, loss_weight_nopad
def remove_prediction_padding_old(prediction_distribution,
target_value,
loss_weight,
target_real_value):
"""
Masks prediction for artificial targets
"""
prediction_distribution = prediction_distribution.contiguous().view(-1, 361)
target_value = target_value.contiguous().view(-1)
loss_weight = loss_weight.contiguous().view(-1)
inter = (target_value != -1).view(-1, 1)
mask = inter.expand(prediction_distribution.size(0), prediction_distribution.size(1))
ret = [prediction_distribution[mask].view(-1, prediction_distribution.size(1)),
target_value[(target_value != -1)],
None]
if loss_weight is not None:
ret.append(loss_weight[(target_value != -1)])
else:
ret.append(None)
return ret
def get_loss(inp, # input
out,
out_real,
lens,
cuda,
gn, # model
glucose_dat,
criterion,
base=1,
value_weight=0,
value_ratio=0):
"""
Simple helper function that calculates model loss.
Basically to save some space
"""
batch_size_val = inp.size(0)
output_dim = gn.output_dim
weight_vec = torch.Tensor([base ** i for i in reversed(range(out.size(-1)))])
weight_vec = (weight_vec/weight_vec.sum()) * weight_vec.numel() # consistent weighting on output length
loss_weight = weight_vec.expand(out.shape)
inp_s, out_s, out_real_s, lens_s = sort_batch(inp, out, out_real, lens)
inp_s, out_s, out_real_s, lens_s = convert_batch(batch_x=inp_s,
batch_y=out_s,
batch_y_real=out_real_s,
batch_l=lens_s,
cuda=cuda,
real_values=glucose_dat.real_values)
# print(inp_s.shape)
# pack is used to produce different input for different x position
x = nn.utils.rnn.pack_padded_sequence(inp_s.view(batch_size_val,
glucose_dat.max_pad,
1),
list(np.array(lens_s)),
batch_first=True)
if cuda:
loss_weight = Variable(loss_weight.cuda())
else:
loss_weight = Variable(loss_weight)
if glucose_dat.real_values:
yd_p, y_p, yd_f, y_f = gn(x, | |
0.05*len(EDFEnergyProfile)
#If threshold jump observed, save current intersect region index (k)
if Intersections[j]+RegionThreshold < Intersections[j+1]:
IntersectionRegions.append(Intersections[k:j])
k = j+1
#Save final intersect region index
elif j == len(Intersections)-2:
IntersectionRegions.append(Intersections[k:j])
#endif
#endfor
Intersections = list()
#If odd number of intersections, likely that low energy one was missed
if len(IntersectionRegions) % 2 == 1: Intersections.append(1.0)
#For all intersection regions identify the central index
for j in range(0,len(IntersectionRegions)):
try:
RegionCentralIndex = int(len(IntersectionRegions[j])/2.0)
Intersections.append( IntersectionRegions[j][RegionCentralIndex] )
except:
#If no intersections, assume a single zero energy intersection
if j == 0: Intersections.append(0.0)
#endtry
#endfor
#Extrema represent FWHM of EDF, mean energy lies between extrema
FWHM_eV.append([min(Intersections)*deV,max(Intersections)*deV])
MeanEnergyIndex = (max(Intersections)+min(Intersections))/2
#endif
#Mean energy obtained as ion energy with population fraction most closely matching IEDF average
#OLD MEAN ENERGY DEFINITION - MEAN DEFINED BY FRACTION NOT BY ENERGY
if GlobMeanCalculation == 'MeanFraction':
BinAveragedFraction = sum(EDFprofile)/len(EDFprofile)
ResidualArray = list()
#Calculate Residuals using EDF_threshold as upper energy percentile
for j in range(IndexRange[0],IndexRange[1]):
ResidualArray.append(abs(EDFprofile[j]-BinAveragedFraction))
#endfor
#Capture mean/residual intersections, sort high energy intersection indices first
NumIntersections = int(len(EDFprofile)/8)
Intersections = np.argsort(ResidualArray)[:NumIntersections]
Intersections = sorted(Intersections,reverse=False)
#Index k defines the IEDF array lower energy edge corresponding to the threshold
IntersectionRegions,k = list(),0
for j in range(0,len(Intersections)-1):
RegionThreshold = 0.05*len(EDFprofile)
#If threshold jump observed, save current intersect region index (k)
if Intersections[j]+RegionThreshold < Intersections[j+1]:
IntersectionRegions.append(Intersections[k:j])
k = j+1
#Save final intersect region index
elif j == len(Intersections)-2:
IntersectionRegions.append(Intersections[k:j])
#endif
#endfor
Intersections = list()
#If odd number of intersections, likely that low energy one was missed
if len(IntersectionRegions) % 2 == 1: Intersections.append(1.0)
#For all intersection regions identify the central index
for j in range(0,len(IntersectionRegions)):
try:
RegionCentralIndex = int(len(IntersectionRegions[j])/2.0)
Intersections.append( IntersectionRegions[j][RegionCentralIndex] )
except:
#If no intersections, assume a single zero energy intersection
if j == 0: Intersections.append(0.0)
#endtry
#endfor
#Extrema represent FWHM of EDF, mean energy lies between extrema
FWHM_eV.append([min(Intersections)*deV,max(Intersections)*deV])
MeanEnergyIndex = (max(Intersections)+min(Intersections))/2
#endif
Mean_eV.append( MeanEnergyIndex*deV )
# #Median energy calculated as EDF index representing midpoint of equal integrated energies
# RisingSum,FallingSum,AbsDiff = 0.0,0.0,list()
# for j in range(0,len(EDFprofile)):
# Rising_j, Falling_j = j, (len(EDFprofile)-1-2)-j
# RisingSum += EDFprofile[Rising_j]*(Rising_j*deV)
# FallingSum += EDFprofile[Falling_j]*(Falling_j*deV)
# AbsDiff.append(abs(RisingSum-FallingSum))
# #endif
# #endfor
# MedianIndex = AbsDiff.index(min(AbsDiff))
# Median_eV.append( MedianIndex*deV ) #### NB: MEDIANS' ALL FUCKED UP BRAH! ####
# #Particle energy variance analysis: Returns FWHM of energy distribution.
# Take mean and draw line at y = mean
# Calculate where y = mean intercepts EDFprofile
# If only one intercept, first intercept is x = 0
# Integrate EDFprofile indices between intercepts
# Save in 1D array, can be used to get energy spread percentage.
#==========#
#==========#
if IDEBUG == True:
fig2,ax2 = figure()
try: BinAveragedValue = BinAveragedEnergy #MeanEnergy Value
except: BinAveragedValue = BinAveragedFraction #MeanFraction Value
Ylims = [0,max(EDFEnergyProfile)]
fig2,ax2 = figure()
ax2.plot(EDFEnergyProfile, 'k-', lw=2)
ax2.plot(ResidualArray, 'r-', lw=2)
ax2.plot((0,len(EDFEnergyProfile)),(BinAveragedValue,BinAveragedValue),'b--',lw=2)
ax2.plot((max(Intersections),max(Intersections)),(Ylims[0],Ylims[1]),'b--',lw=2)
ax2.plot((min(Intersections),min(Intersections)),(Ylims[0],Ylims[1]),'b--',lw=2)
ax2.plot((MeanEnergyIndex,MeanEnergyIndex),(Ylims[0],Ylims[1]),'m--',lw=2)
ax2.legend(['Integrated Energy','abs(ResidualArray)','BinAveragedEnergy/Fraction'])
# plt.savefig(DirIEDFTrends+'_DebugOutput.png')
#endif
#endfor
#Write data to ASCII format datafile if requested.
if write_ASCII == True:
if i == 0:
DirASCII = CreateNewFolder(DirTrends,'Trend_Data')
DirASCIIIEDF = CreateNewFolder(DirASCII,'IEDF_Data')
#endif
WriteDataToFile(Legendlist+['\n']+Total_eV, DirASCIIIEDF+variablelist[i]+'_Total', 'w')
WriteDataToFile(Legendlist+['\n']+Range_eV, DirASCIIIEDF+variablelist[i]+'_Range', 'w')
WriteDataToFile(Legendlist+['\n']+Mode_eV, DirASCIIIEDF+variablelist[i]+'_Mode', 'w')
WriteDataToFile(Legendlist+['\n']+Mean_eV, DirASCIIIEDF+variablelist[i]+'_Mean', 'w')
#endif
##IEDF PROFILES##
#===============#
#Apply image options to IEDF plot generated in the above loop.
Title = Dirlist[l][2::]+'\n'+variablelist[i]+' Angular Energy Distribution Function Profiles'
Xlabel,Ylabel = 'Energy [eV]',variablelist[i]+' EDF [$\\theta$ Integrated]'
ImageCrop = [ [0,GlobRange_eV[1]], [] ] #[[X1,X2],[Y1,Y2]]
ImageOptions(fig,ax,Xlabel,Ylabel,Title,Legendlist,Crop=ImageCrop,Rotate=False)
plt.savefig(DirIEDFTrends+variablelist[i]+'_EDFprofiles'+ext)
plt.close('all')
##ENERGY ANALYSIS##
#=================#
#Plot IEDF average energies with respect to simulation folder names.
fig,ax = figure()
TrendPlotter(ax,Mean_eV,Legendlist,NormFactor=0)
TrendPlotter(ax,Mode_eV,Legendlist,NormFactor=0)
## TrendPlotter(ax,Range_eV[0],Legendlist,NormFactor=0)
## TrendPlotter(ax,Range_eV[1],Legendlist,NormFactor=0)
Title = Dirlist[l][2::]+'\n'+'Average '+variablelist[i]+' Energies'
Legend = ['EDF Mean Energy','EDF Mode Energy','EDF Min Energy','EDF Max Energy']
Xlabel,Ylabel = 'Varied Property',variablelist[i]+' Energy [eV]'
ImageCrop = [[],[0,max(Mean_eV+Mode_eV)*1.15]] #[[X1,X2],[Y1,Y2]]
ImageOptions(fig,ax,Xlabel,Ylabel,Title,Legend,Crop=ImageCrop,Rotate=False)
plt.savefig(DirIEDFTrends+variablelist[i]+'_AverageEnergies'+ext)
plt.close('all')
#endfor
#endif
if any([savefig_IEDFangular, savefig_IEDFtrends, savefig_EEDF]) == True:
print('--------------------------------')
print('# EEDF/IEDF Processing Complete.')
print('--------------------------------')
#endif
#=====================================================================#
#=====================================================================#
#====================================================================#
#GENERAL TREND PLOTTING ANALYSIS#
#====================================================================#
#====================================================================#
#COMPARATIVE TRENDS -- MULTI-FOLDER#
#====================================================================#
if savefig_trendphaseaveraged == True or print_generaltrends == True:
#Create trend folder for outputs - Assumes that scanned variable is within trimmed foler name
TrendVariable = list(filter(lambda x: x.isalpha(), FolderNameTrimmer(Dirlist[0]))) #List of discrete chars
TrendVariable = ''.join(TrendVariable) #Single string of chars
DirTrends = CreateNewFolder(os.getcwd()+'/',TrendVariable+' Trends')
#For each requested comparison variable.
for k in tqdm(range(0,len(Variables))):
#Create processlist for largest output, only compare variables shared between all folders.
processlist,Variablelist = VariableEnumerator(Variables,max(rawdata_2D),max(header_2Dlist))
processlist,Variablelist = VariableInterpolator(processlist,Variablelist,Comparisonlist)
#Create Y-axis legend for each variable to be plotted.
YaxisLegend = VariableLabelMaker(Variablelist)
#Loop escape if variables that do not exist have been requested.
if k >= 1 and k > len(Variablelist)-1:
break
#endif
#Create fig of desired size and refresh legendlist.
fig,ax = figure(image_aspectratio,1)
Legendlist = list()
##AXIAL TRENDS##
#===============#
#Perform trend analysis on requested axial profiles.
for j in range(0,len(heightlineouts)):
#Create folder for axial trends if needed.
DirAxialTrends = CreateNewFolder(DirTrends,'Axial Trends')
#Take Trend at Given Location or Default to Min/Max Trends.
if len(ProbeLoc) == 2:
#Append requested position to the legendlist.
R,Z = ProbeLoc[0],ProbeLoc[1]
Location = '(R'+str(round(R*dr[l],1))+'cm, Z'+str(round(Z*dz[l],1))+'cm)'
Legendlist.append(Location)
#Take trend at given location if specified.
Xaxis,Trend = TrendAtGivenLocation([R,Z],processlist[k],Variablelist[k])
elif len(ProbeLoc) == 1:
#Append requested position to the legendlist.
R,Z = ProbeLoc[0],heightlineouts[j]
Location = '(R'+str(round(R*dr[l],1))+'cm, Z'+str(round(Z*dz[l],1))+'cm)'
Legendlist.append(Location)
#Take trend at given location if specified.
Xaxis,Trend = TrendAtGivenLocation([R,Z],processlist[k],Variablelist[k])
else:
#Obtain min/max trend values for requested profile over all folders.
Xaxis,MaxTrend,MinTrend = MinMaxTrends(heightlineouts[j],'Axial',k)
Trend = MaxTrend
#Append the radial position to the legendlist.
Legendlist.append( 'R='+str(round((heightlineouts[j]*dr[l]), 2))+'cm' )
#endif
#Plot trends for each variable over all folders, applying image options.
TrendPlotter(ax,Trend,Xaxis,NormFactor=0)
Title='Trend in max '+Variablelist[k]+' with changing '+TrendVariable+' \n'+Dirlist[l][2:-1]
Xlabel,Ylabel = 'Varied Property','Max '+YaxisLegend[k]
ImageOptions(fig,ax,Xlabel,Ylabel,Title,Legendlist,Crop=False)
#Write data to ASCII format datafile if requested.
if write_ASCII == True:
if j == 0:
DirASCII = CreateNewFolder(DirTrends,'Trend_Data')
DirASCIIAxial = CreateNewFolder(DirASCII,'Axial_Data')
WriteDataToFile(Xaxis+['\n'], DirASCIIAxial+Variablelist[k]+'_Trends', 'w')
#endif
WriteDataToFile(Trend+['\n'], DirASCIIAxial+Variablelist[k]+'_Trends', 'a')
#endif
#Save one image per variable with data from all simulations.
if len(heightlineouts) > 0:
plt.savefig(DirAxialTrends+'Axial Trends in '+Variablelist[k]+ext)
plt.close('all')
#endif
##RADIAL TRENDS##
#===============#
#Create fig of desired size and refresh legendlist.
fig,ax = figure(image_aspectratio,1)
Legendlist = list()
#Perform trend analysis on requested radial profiles.
for j in range(0,len(radialineouts)):
#Create folder for axial trends if needed.
DirRadialTrends = CreateNewFolder(DirTrends,'Radial Trends')
#Take Trend at Given Location or Default to Min/Max Trends.
if len(ProbeLoc) == 2:
#Append requested position to the legendlist.
R,Z = ProbeLoc[0],ProbeLoc[1]
Location = '(R'+str(round(R*dr[l],1))+'cm, Z'+str(round(Z*dz[l],1))+'cm)'
Legendlist.append(Location)
#Take trend at given location if specified.
Xaxis,Trend = TrendAtGivenLocation([R,Z],processlist[k],Variablelist[k])
elif len(ProbeLoc) == 1:
#Append requested position to the legendlist.
R,Z = radialineouts[j],ProbeLoc[0],
Location = '(R'+str(round(R*dr[l],1))+'cm, Z'+str(round(Z*dz[l],1))+'cm)'
Legendlist.append(Location)
#Take trend at given location if specified.
Xaxis,Trend = TrendAtGivenLocation([R,Z],processlist[k],Variablelist[k])
else:
#Obtain min/max trend values for requested profile over all folders.
Xaxis,MaxTrend,MinTrend = MinMaxTrends(radialineouts[j],'Radial',k)
Trend = MaxTrend
#Append the axial position to the legendlist.
Legendlist.append( 'Z='+str(round((radialineouts[j]*dz[l]), 2))+'cm' )
#endif
#Plot trends for each variable over all folders, applying image options.
TrendPlotter(ax,Trend,Xaxis,NormFactor=0)
Title='Trend in max '+Variablelist[k]+' with changing '+TrendVariable+' \n'+Dirlist[l][2:-1]
Xlabel,Ylabel = 'Varied Property','Max '+YaxisLegend[k]
ImageOptions(fig,ax,Xlabel,Ylabel,Title,Legendlist,Crop=False)
#Write data to ASCII format datafile if requested.
if write_ASCII == True:
if j == 0:
DirASCII = CreateNewFolder(DirTrends,'Trend_Data')
DirASCIIRadial = CreateNewFolder(DirASCII,'Radial_Data')
WriteDataToFile(Xaxis+['\n'], DirASCIIRadial+Variablelist[k]+'_Trends', 'w')
#endif
WriteDataToFile(Trend+['\n'], DirASCIIRadial+Variablelist[k]+'_Trends', 'a')
#endif
#Save one image per variable with data from all simulations.
if len(radialineouts) > 0:
plt.savefig(DirRadialTrends+'Radial Trends in '+Variablelist[k]+ext)
plt.close('all')
#endif
#endfor
#endif
#=====================================================================#
# DC-BIAS CALCULATOR #
#=====================================================================#
if savefig_trendphaseaveraged == True or print_DCbias == True:
#Create Trend folder to keep output plots.
TrendVariable = list(filter(lambda x: x.isalpha(), FolderNameTrimmer(Dirlist[0]))) #List of discrete chars
TrendVariable = ''.join(TrendVariable) #Single string of chars
DirTrends = CreateNewFolder(os.getcwd()+'/',TrendVariable+' Trends')
#Initiate lists required for storing data.
Xaxis = list()
DCbias = list()
#For all folders.
for l in range(0,numfolders):
#Create processlist for each folder as required.
Process,Variable = VariableEnumerator(['P-POT'],rawdata_2D[l],header_2Dlist[l])
#Update X-axis with folder information.
Xaxis.append( FolderNameTrimmer(Dirlist[l]) )
#Locate powered electrode for bias extraction.
Rlineoutloc = WaveformLoc(electrodeloc,'2D')[0]
Zlineoutloc = WaveformLoc(electrodeloc,'2D')[1]
#Obtain radial and axial profiles for further processing.
try: Rlineout = ExtractRadialProfile(Data[l],Process[0],Variable[0],Rlineoutloc,R_mesh[l], ISYMlist[l])
except: Rlineout = float('NaN')
#endtry
try: Zlineout = ExtractAxialProfile(Data[l],Process[0],Variable[0],Zlineoutloc,R_mesh[l],Z_mesh[l],ISYMlist[l])
except: Zlineout = float('NaN')
#endtry
#Obtain DCbias on axis and across the centre radius of the mesh.
AxialDCbias = DCbiasMagnitude(Zlineout[::-1])
RadialDCbias = DCbiasMagnitude(Rlineout)
#Choose axial or radial DCbias based on user input, else autoselect most probable.
if DCbiasaxis == 'Radial':
DCbias.append(RadialDCbias)
elif DCbiasaxis == 'Axial':
DCbias.append(AxialDCbias)
elif DCbiasaxis == 'Auto':
#Compare Axial and Radial DCbias, if same pick Axial, if not pick the largest.
if AxialDCbias != RadialDCbias:
if abs(AxialDCbias) > abs(RadialDCbias):
DCbias.append(AxialDCbias)
else:
DCbias.append(RadialDCbias)
#endif
else:
DCbias.append(AxialDCbias)
#endif
#endif
#Display DCbias to terminal if requested.
if print_DCbias == True:
print(Dirlist[l])
print('DC Bias:',round(DCbias[l],5),'V')
#endif
#endfor
#Write data to ASCII format datafile if requested.
if write_ASCII == True:
DirASCII = CreateNewFolder(DirTrends,'Trend_Data')
DCASCII = [Xaxis,DCbias]
WriteDataToFile(DCASCII, DirASCII+'DCbias_Trends')
#endif
#Plot and beautify the DCbias, applying normalization if requested.
fig,ax = figure(image_aspectratio,1)
TrendPlotter(ax,DCbias,Xaxis,NormFactor=0)
#Apply image options and axis labels.
Title = 'Trend in DCbias with changing '+TrendVariable+' \n'+Dirlist[l][2:-1]
Xlabel,Ylabel = 'Varied Property','DC bias [V]'
ImageOptions(fig,ax,Xlabel,Ylabel,Title,Crop=False)
plt.savefig(DirTrends+'Powered Electrode DCbias'+ext)
plt.close('all')
#endif
#====================================================================#
#POWER DEPOSITED DIAGNOSTIC#
#====================================================================#
if savefig_trendphaseaveraged == True or print_totalpower == True:
#Create Trend folder to keep output plots.
TrendVariable = list(filter(lambda x: x.isalpha(), FolderNameTrimmer(Dirlist[0]))) #List of discrete chars
TrendVariable = ''.join(TrendVariable) #Single string of chars
DirTrends = CreateNewFolder(os.getcwd()+'/',TrendVariable+' Trends')
#Create required lists.
RequestedPowers,DepositedPowerList = list(),list()
Xaxis,Powers = list(),list()
#Update X-axis with folder information.
for l in range(0,numfolders): Xaxis.append( FolderNameTrimmer(Dirlist[l]) )
#Create list of requested power variables and ensure they also exist in all compared folders
for i in range(0,len(Variables)):
if 'POW-' in Variables[i] and Variables[i] in Comparisonlist:
RequestedPowers.append(Variables[i])
#endif
#endfor
#For each different power deposition mechanism requested.
for k in range(0,len(RequestedPowers)):
#For all folders.
for l in range(0,numfolders):
#Create extract data for the neutral flux and neutral velocity.
processlist,Variablelist = VariableEnumerator(RequestedPowers,rawdata_2D[l],header_2Dlist[l])
#Extract full 2D power density image. [W/m3]
PowerDensity = ImageExtractor2D(Data[l][processlist[k]])
PowerDensity = VariableUnitConversion(PowerDensity,Variablelist[k])
#=====#=====#
#Cylindrical integration of power per unit volume ==> total coupled power.
if IXZlist[l] == 0:
Power = 0 #[W]
#For each axial slice
for j in range(0,Z_mesh[l]):
#For each radial slice
for i in range(0,R_mesh[l]-1):
#Calculate radial plane volume of a ring at radius [i], correcting for central r=0.
InnerArea = np.pi*( (i*(dr[l]/100))**2 ) #[m^2]
OuterArea = np.pi*( ((i+1)*(dr[l]/100))**2 ) #[m^2]
RingVolume = (OuterArea-InnerArea)*(dz[l]/100) #[m^3]
#Calculate Power by multiplying power density for ring[i] by volume of ring[i]
Power += PowerDensity[j][i]*RingVolume #[W]
#endfor
#endfor
DepositedPowerList.append(Power)
#Display power to terminal if requested.
if print_totalpower == True:
print(Dirlist[l])
print(RequestedPowers[k]+' Deposited:',round(Power,4),'W')
#endif
#=====#=====#
#Cartesian integration of power per unit volume ==> total coupled power.
elif IXZlist[l] == 1:
Power = 0 #[W]
#For each axial slice
for j in range(0,Z_mesh[l]):
#For each radial slice
for i in range(0,R_mesh[l]-1):
#Calculate cell area, all cells have the same area in a cartesian grid
CellArea = (dr[l]/100.)*(dz[l]/100.) #[m^2]
CellVolume = CellArea*(dy[l]/100.) #[m^3]
#Calculate Power by multiplying power density for ring[i] by volume of ring[i]
Power += PowerDensity[j][i]*CellVolume #[W]
#endfor
#endfor
DepositedPowerList.append(Power)
#Display power | |
backgroundColor: A tuple indicating the color of the level's background.
playerStartPositions: A list of four tuples indicating which columns and rows each player starts on.
blackHolePositions: A list of four tuples indicating which columns and rows each black hole sprite
starts on.
itemTiles: A list of tuples indicating which columns and rows can have items spawned on them.
This should include every tile that a player can reach, except those tiles that the players start
on.
levelBorderRects: A list of rect objects that form the boundaries of the level.
"""
super().__init__(rubberTilesHorizontal, rubberTilesVertical, goldTilesHorizontal, goldTilesVertical)
self.standardImage = getImage(c.BACKGROUND_FOLDER, "background_3A.png")
self.lightImage = getImage(c.BACKGROUND_FOLDER, "background_3B.png")
self.image = self.standardImage
self.backgroundColor = c.DARK_BLUE
self.playerStartPosition = [(5, 1), (5, 6), (1, 3), (9, 3)]
self.blackHolePositions = [(4, 4), (6, 4)]
self.itemTiles = [(x, y) for x in range(1, 10) for y in range(0, 8) if (x, y) not in self.playerStartPosition
and (x, y) not in self.blackHolePositions and (x, y) not in [(4, 0), (5, 0), (6, 0),
(4, 7), (5, 7), (6, 7)]]
self.levelBorderRects = [pygame.Rect(0, 0, 512, 36), pygame.Rect(0, 0, 39, 448), pygame.Rect(477, 0, 39, 448),
pygame.Rect(0, 426, 512, 36), pygame.Rect(190, 0, 134, 84),
pygame.Rect(190, 380, 134, 84)]
class BoardFourLevel(Level):
"""Create a new object of the fourth variant of levels.
Attributes:
rubberTilesHorizontal: A list of tuples indicating which columns and rows to place horizontal rubber
traps.
rubberTilesVertical: A list of tuples indicating which columns and rows to place vertical rubber traps.
goldTilesHorizontal: A list of tuples indicating which columns and rows to place horizontal gold sprites.
goldTilesVertical: A list of tuples indicating which columns and rows to place vertical gold sprites.
"""
def __init__(self, rubberTilesHorizontal, rubberTilesVertical, goldTilesHorizontal, goldTilesVertical):
"""Init BoardFourLevel using the lists of tuples rubberTilesHorizontal, rubberTilesVertical,
goldTilesHorizontal, and goldTilesVertical.
Instance variables:
standardImage: The image to be drawn for the level during standard gameplay.
lightImage: A lighter variant of standardImage, designed to be used when an ItemClock object is
active, or to give the illusion of the level flashing.
image: The current image to be drawn for the level.
Defaults to the standardImage.
backgroundColor: A tuple indicating the color of the level's background.
playerStartPositions: A list of four tuples indicating which columns and rows each player starts on.
blackHolePositions: A list of four tuples indicating which columns and rows each black hole sprite
starts on.
itemTiles: A list of tuples indicating which columns and rows can have items spawned on them.
This should include every tile that a player can reach, except those tiles that the players start
on.
levelBorderRects: A list of rect objects that form the boundaries of the level.
"""
super().__init__(rubberTilesHorizontal, rubberTilesVertical, goldTilesHorizontal, goldTilesVertical)
self.standardImage = getImage(c.BACKGROUND_FOLDER, "background_4A.png")
self.lightImage = getImage(c.BACKGROUND_FOLDER, "background_4B.png")
self.image = self.standardImage
self.backgroundColor = c.PURPLE
self.playerStartPosition = [(4, 0), (6, 0), (1, 7), (9, 7)]
self.blackHolePositions = [(2, 2), (8, 2), (4, 6), (6, 6)]
self.itemTiles = [(x, y) for x in range(0, 11) for y in range(0, 8) if (x, y) not in self.playerStartPosition
and (x, y) not in self.blackHolePositions and (x, y) not in [(5, 0), (0, 1), (5, 1), (10, 1),
(0, 2), (10, 2), (0, 3),
(10, 3), (0, 4), (10, 4),
(0, 5), (10, 5), (0, 6), (5, 6),
(10, 6), (5, 7)]]
self.levelBorderRects = [pygame.Rect(0, 0, 512, 36), pygame.Rect(238, 0, 36, 132),
pygame.Rect(238, 346, 36, 132), pygame.Rect(0, 426, 512, 36),
pygame.Rect(0, 92, 38, 280), pygame.Rect(476, 92, 38, 280)]
class BoardFiveLevel(Level):
"""Create a new object of the fifth variant of levels.
Attributes:
rubberTilesHorizontal: A list of tuples indicating which columns and rows to place horizontal rubber
traps.
rubberTilesVertical: A list of tuples indicating which columns and rows to place vertical rubber traps.
goldTilesHorizontal: A list of tuples indicating which columns and rows to place horizontal gold sprites.
goldTilesVertical: A list of tuples indicating which columns and rows to place vertical gold sprites.
"""
def __init__(self, rubberTilesHorizontal, rubberTilesVertical, goldTilesHorizontal, goldTilesVertical):
"""Init BoardFiveLevel using the lists of tuples rubberTilesHorizontal, rubberTilesVertical,
goldTilesHorizontal, and goldTilesVertical.
Instance variables:
standardImage: The image to be drawn for the level during standard gameplay.
lightImage: A lighter variant of standardImage, designed to be used when an ItemClock object is
active, or to give the illusion of the level flashing.
image: The current image to be drawn for the level.
Defaults to the standardImage.
backgroundColor: A tuple indicating the color of the level's background.
activeRubberTraps: A list of tuples indicating which columns and rows have horizontal rubber traps
which begin the game in an active state.
playerStartPositions: A list of four tuples indicating which columns and rows each player starts on.
blackHolePositions: A list of four tuples indicating which columns and rows each black hole sprite
starts on.
itemTiles: A list of tuples indicating which columns and rows can have items spawned on them.
This should include every tile that a player can reach, except those tiles that the players start
on.
levelBorderRects: A list of rect objects that form the boundaries of the level.
"""
super().__init__(rubberTilesHorizontal, rubberTilesVertical, goldTilesHorizontal, goldTilesVertical)
self.standardImage = getImage(c.BACKGROUND_FOLDER, "background_5A.png")
self.lightImage = getImage(c.BACKGROUND_FOLDER, "background_5B.png")
self.image = self.standardImage
self.backgroundColor = c.DARK_ORANGE
self.activeRubberTraps = [(1, 4), (9, 4)]
self.playerStartPosition = [(1, 0), (9, 0), (4, 7), (6, 7)]
self.blackHolePositions = [(2, 4), (4, 4), (6, 4), (8, 4)]
self.itemTiles = [(x, y) for x in range(0, 11) for y in range(0, 8) if (x, y) not in self.playerStartPosition
and (x, y) not in self.blackHolePositions and (x, y) not in [(0, 0), (5, 0), (10, 0),
(0, 7), (5, 7), (10, 7)]]
self.levelBorderRects = [pygame.Rect(0, 0, 512, 36), pygame.Rect(238, 0, 40, 84), pygame.Rect(0, 426, 512, 36),
pygame.Rect(238, 380, 40, 84), pygame.Rect(0, 0, 36, 84), pygame.Rect(478, 0, 36, 84),
pygame.Rect(0, 380, 36, 84), pygame.Rect(478, 380, 36, 84)]
class BonusLevel(Level):
"""Create a new object of the sixth, bonus variant of levels.
Note that since the bonus level layout is unique, the arguments that are usually passed to the other level
variants are instead created as constant instance variables in the bonus level __init__ method.
"""
def __init__(self):
"""Init BonusLevel.
Instance variables:
goldTilesHorizontal: A list of tuples indicating which columns and rows to place horizontal gold
sprites.
goldTilesVertical: A list of tuples indicating which columns and rows to place vertical gold sprites.
standardImage: The image to be drawn for the level during standard gameplay.
lightImage: A lighter variant of standardImage, designed to be used when an ItemClock object is
active, or to give the illusion of the level flashing.
image: The current image to be drawn for the level.
Defaults to the standardImage.
backgroundColor: A tuple indicating the color of the level's background.
playerStartPositions: A list of four tuples indicating which columns and rows each player starts on.
levelBorderRects: A list of rect objects that form the boundaries of the level.
"""
goldTilesHorizontal = [(2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (2, 2), (3, 2), (4, 2), (5, 2),
(6, 2), (7, 2), (8, 2), (2, 3), (8, 3), (2, 4), (8, 4), (2, 5), (8, 5), (2, 6), (3, 6),
(4, 6), (5, 6), (6, 6), (7, 6), (8, 6), (2, 7), (3, 7), (4, 7), (5, 7), (6, 7), (7, 7),
(8, 7)]
goldTilesVertical = [(2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (2, 2), (3, 2), (8, 2),
(9, 2), (2, 3), (3, 3), (8, 3), (9, 3), (2, 4), (3, 4), (8, 4), (9, 4), (2, 5), (3, 5),
(8, 5), (9, 5), (2, 6), (3, 6), (4, 6), (5, 6), (6, 6), (7, 6), (8, 6), (9, 6)]
super().__init__([], [], goldTilesHorizontal, goldTilesVertical)
self.standardImage = getImage(c.BACKGROUND_FOLDER, "background_6A.png")
self.lightImage = getImage(c.BACKGROUND_FOLDER, "background_6B.png")
self.image = self.standardImage
self.backgroundColor = c.DARK_RED
self.playerStartPosition = [(4, 1), (6, 1), (3, 6), (7, 6)]
self.levelBorderRects = [pygame.Rect(0, 0, 512, 36), pygame.Rect(188, 186, 136, 94),
pygame.Rect(0, 426, 512, | |
<reponame>zjzh/nova<filename>nova/virt/libvirt/vif.py
# Copyright (C) 2011 <NAME>
# Copyright (C) 2011 Nicira, Inc
# Copyright 2011 OpenStack Foundation
# All Rights Reserved.
# Copyright 2016 Red Hat, 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.
"""VIF drivers for libvirt."""
import os
import typing as ty
import os_vif
from os_vif import exception as osv_exception
from os_vif.objects import fields as osv_fields
from os_vif.objects import vif as osv_vifs
from oslo_concurrency import processutils
from oslo_log import log as logging
from oslo_utils import strutils
import nova.conf
from nova import exception
from nova.i18n import _
from nova.network import model as network_model
from nova.network import os_vif_util
from nova import objects
from nova.pci import utils as pci_utils
import nova.privsep.linux_net
from nova import profiler
from nova import utils
from nova.virt.libvirt import config as vconfig
from nova.virt.libvirt import designer
from nova.virt.libvirt import host as libvirt_host
from nova.virt import osinfo
LOG = logging.getLogger(__name__)
CONF = nova.conf.CONF
SUPPORTED_VIF_MODELS = {
'qemu': [
network_model.VIF_MODEL_VIRTIO,
network_model.VIF_MODEL_NE2K_PCI,
network_model.VIF_MODEL_PCNET,
network_model.VIF_MODEL_RTL8139,
network_model.VIF_MODEL_E1000,
network_model.VIF_MODEL_E1000E,
network_model.VIF_MODEL_LAN9118,
network_model.VIF_MODEL_SPAPR_VLAN,
network_model.VIF_MODEL_VMXNET3,
],
'kvm': [
network_model.VIF_MODEL_VIRTIO,
network_model.VIF_MODEL_NE2K_PCI,
network_model.VIF_MODEL_PCNET,
network_model.VIF_MODEL_RTL8139,
network_model.VIF_MODEL_E1000,
network_model.VIF_MODEL_E1000E,
network_model.VIF_MODEL_SPAPR_VLAN,
network_model.VIF_MODEL_VMXNET3,
],
'lxc': [],
'parallels': [
network_model.VIF_MODEL_VIRTIO,
network_model.VIF_MODEL_RTL8139,
network_model.VIF_MODEL_E1000,
],
}
def is_vif_model_valid_for_virt(virt_type, vif_model):
if vif_model is None:
return True
if virt_type not in SUPPORTED_VIF_MODELS:
raise exception.UnsupportedVirtType(virt=virt_type)
return vif_model in SUPPORTED_VIF_MODELS[virt_type]
def set_vf_interface_vlan(pci_addr, mac_addr, vlan=0):
vlan_id = int(vlan)
pf_ifname = pci_utils.get_ifname_by_pci_address(pci_addr,
pf_interface=True)
vf_ifname = pci_utils.get_ifname_by_pci_address(pci_addr)
vf_num = pci_utils.get_vf_num_by_pci_address(pci_addr)
nova.privsep.linux_net.set_device_macaddr_and_vlan(
pf_ifname, vf_num, mac_addr, vlan_id)
# Bring up/down the VF's interface
# TODO(edand): The mac is assigned as a workaround for the following issue
# https://bugzilla.redhat.com/show_bug.cgi?id=1372944
# once resolved it will be removed
port_state = 'up' if vlan_id > 0 else 'down'
nova.privsep.linux_net.set_device_macaddr(vf_ifname, mac_addr,
port_state=port_state)
def set_vf_trusted(pci_addr, trusted):
"""Configures the VF to be trusted or not
:param pci_addr: PCI slot of the device
:param trusted: Boolean value to indicate whether to
enable/disable 'trusted' capability
"""
pf_ifname = pci_utils.get_ifname_by_pci_address(pci_addr,
pf_interface=True)
vf_num = pci_utils.get_vf_num_by_pci_address(pci_addr)
nova.privsep.linux_net.set_device_trust(
pf_ifname, vf_num, trusted)
@utils.synchronized('lock_vlan', external=True)
def ensure_vlan(vlan_num, bridge_interface, mac_address=None, mtu=None,
interface=None):
"""Create a vlan unless it already exists."""
if interface is None:
interface = 'vlan%s' % vlan_num
if not nova.privsep.linux_net.device_exists(interface):
LOG.debug('Starting VLAN interface %s', interface)
nova.privsep.linux_net.add_vlan(bridge_interface, interface,
vlan_num)
# (danwent) the bridge will inherit this address, so we want to
# make sure it is the value set from the NetworkManager
if mac_address:
nova.privsep.linux_net.set_device_macaddr(
interface, mac_address)
nova.privsep.linux_net.set_device_enabled(interface)
# NOTE(vish): set mtu every time to ensure that changes to mtu get
# propagated
nova.privsep.linux_net.set_device_mtu(interface, mtu)
return interface
@profiler.trace_cls("vif_driver")
class LibvirtGenericVIFDriver(object):
"""Generic VIF driver for libvirt networking."""
def __init__(self, host: libvirt_host.Host = None):
super().__init__()
self.host = host
def get_vif_devname(self, vif):
if 'devname' in vif:
return vif['devname']
return ("nic" + vif['id'])[:network_model.NIC_NAME_LEN]
def get_vif_model(self, image_meta=None, vif_model=None):
model = vif_model
# If the user has specified a 'vif_model' against the
# image then honour that model
if image_meta:
model = osinfo.HardwareProperties(image_meta).network_model
# If the virt type is KVM/QEMU/VZ(Parallels), then use virtio according
# to the global config parameter
if (model is None and CONF.libvirt.virt_type in
('kvm', 'qemu', 'parallels') and
CONF.libvirt.use_virtio_for_bridges):
model = network_model.VIF_MODEL_VIRTIO
return model
def get_base_config(
self, instance, mac, image_meta, flavor, virt_type, vnic_type,
):
# TODO(sahid): We should rewrite it. This method handles too
# many unrelated things. We probably need to have a specific
# virtio, vhost, vhostuser functions.
conf = vconfig.LibvirtConfigGuestInterface()
# Default to letting libvirt / the hypervisor choose the model
model = None
driver = None
vhost_queues = None
rx_queue_size = None
# NOTE(stephenfin): Skip most things here as only apply to virtio
# devices
if vnic_type in network_model.VNIC_TYPES_DIRECT_PASSTHROUGH:
designer.set_vif_guest_frontend_config(
conf, mac, model, driver, vhost_queues, rx_queue_size)
return conf
rx_queue_size = CONF.libvirt.rx_queue_size
# if model has already been defined,
# image_meta contents will override it
model = self.get_vif_model(image_meta=image_meta, vif_model=model)
if not is_vif_model_valid_for_virt(virt_type, model):
raise exception.UnsupportedHardware(model=model, virt=virt_type)
# The rest of this only applies to virtio
if model != network_model.VIF_MODEL_VIRTIO:
designer.set_vif_guest_frontend_config(
conf, mac, model, driver, vhost_queues, rx_queue_size)
return conf
# Workaround libvirt bug, where it mistakenly enables vhost mode, even
# for non-KVM guests
if virt_type == 'qemu':
driver = 'qemu'
if virt_type in ('kvm', 'parallels'):
vhost_drv, vhost_queues = self._get_virtio_mq_settings(
image_meta, flavor)
# TODO(sahid): It seems that we return driver 'vhost' even
# for vhostuser interface where for vhostuser interface
# the driver should be 'vhost-user'. That currently does
# not create any issue since QEMU ignores the driver
# argument for vhostuser interface but we should probably
# fix that anyway. Also we should enforce that the driver
# use vhost and not None.
driver = vhost_drv or driver
if driver == 'vhost' or driver is None:
# vhost backend only supports update of RX queue size
if rx_queue_size:
# TODO(sahid): Specifically force driver to be vhost
# that because if None we don't generate the XML
# driver element needed to set the queue size
# attribute. This can be removed when get_base_config
# will be fixed and rewrite to set the correct
# backend.
driver = 'vhost'
designer.set_vif_guest_frontend_config(
conf, mac, model, driver, vhost_queues, rx_queue_size)
return conf
def get_base_hostdev_pci_config(self, vif):
conf = vconfig.LibvirtConfigGuestHostdevPCI()
pci_slot = vif['profile']['pci_slot']
designer.set_vif_host_backend_hostdev_pci_config(conf, pci_slot)
return conf
def _get_virtio_mq_settings(self, image_meta, flavor):
"""A methods to set the number of virtio queues,
if it has been requested in extra specs.
"""
driver = None
vhost_queues = None
if self._requests_multiqueue(image_meta):
driver = 'vhost'
max_tap_queues = self._get_max_tap_queues()
if max_tap_queues:
vhost_queues = (max_tap_queues if flavor.vcpus > max_tap_queues
else flavor.vcpus)
else:
vhost_queues = flavor.vcpus
return (driver, vhost_queues)
def _requests_multiqueue(self, image_meta):
"""Check if multiqueue property is set in the image metadata."""
if not isinstance(image_meta, objects.ImageMeta):
image_meta = objects.ImageMeta.from_dict(image_meta)
img_props = image_meta.properties
if img_props.get('hw_vif_multiqueue_enabled'):
return True
return False
def _get_max_tap_queues(self):
# Note(sean-k-mooney): some linux distros have backported
# changes for newer kernels which make the kernel version
# number unreliable to determine the max queues supported
# To address this without making the code distro dependent
# we introduce a new config option and prefer it if set.
if CONF.libvirt.max_queues:
return CONF.libvirt.max_queues
# NOTE(kengo.sakai): In kernels prior to 3.0,
# multiple queues on a tap interface is not supported.
# In kernels 3.x, the number of queues on a tap interface
# is limited to 8. From 4.0, the number is 256.
# See: https://bugs.launchpad.net/nova/+bug/1570631
kernel_version = int(os.uname().release.split(".")[0])
if kernel_version <= 2:
return 1
elif kernel_version == 3:
return 8
elif kernel_version == 4:
return 256
else:
return None
def get_bridge_name(self, vif):
return vif['network']['bridge']
def get_veth_pair_names(self, iface_id):
return (("qvb%s" % iface_id)[:network_model.NIC_NAME_LEN],
("qvo%s" % iface_id)[:network_model.NIC_NAME_LEN])
def get_config_802qbg(self, instance, vif, image_meta, flavor, virt_type):
conf = self.get_base_config(
instance, vif['address'], image_meta, flavor, virt_type,
vif['vnic_type'])
params = vif["qbg_params"]
designer.set_vif_host_backend_802qbg_config(
conf, vif['network'].get_meta('interface'),
params['managerid'],
params['typeid'],
params['typeidversion'],
params['instanceid'])
designer.set_vif_bandwidth_config(conf, flavor)
return conf
def get_config_802qbh(self, instance, vif, image_meta, flavor, virt_type):
conf = self.get_base_config(
instance, vif['address'], image_meta, flavor, virt_type,
vif['vnic_type'])
profile = vif["profile"]
vif_details = vif["details"]
net_type = 'direct'
if vif['vnic_type'] == network_model.VNIC_TYPE_DIRECT:
net_type = 'hostdev'
designer.set_vif_host_backend_802qbh_config(
conf, net_type, profile['pci_slot'],
vif_details[network_model.VIF_DETAILS_PROFILEID])
designer.set_vif_bandwidth_config(conf, flavor)
return conf
def get_config_hw_veb(self, instance, vif, image_meta, flavor, virt_type):
conf = self.get_base_config(
instance, vif['address'], image_meta, flavor, virt_type,
vif['vnic_type'])
profile = vif["profile"]
vif_details = vif["details"]
net_type = 'direct'
if vif['vnic_type'] in [network_model.VNIC_TYPE_DIRECT,
network_model.VNIC_TYPE_ACCELERATOR_DIRECT]:
net_type = 'hostdev'
designer.set_vif_host_backend_hw_veb(
conf, net_type, profile['pci_slot'],
vif_details[network_model.VIF_DETAILS_VLAN])
designer.set_vif_bandwidth_config(conf, flavor)
return conf
def get_config_hostdev_physical(
self, instance, vif, image_meta, flavor, virt_type,
):
return self.get_base_hostdev_pci_config(vif)
def get_config_macvtap(self, instance, vif, image_meta, flavor, virt_type):
conf = self.get_base_config(
instance, vif['address'], image_meta, flavor, virt_type,
vif['vnic_type'])
vif_details = vif['details']
macvtap_src = vif_details.get(network_model.VIF_DETAILS_MACVTAP_SOURCE)
macvtap_mode = vif_details.get(network_model.VIF_DETAILS_MACVTAP_MODE)
phys_interface = vif_details.get(
network_model.VIF_DETAILS_PHYS_INTERFACE)
missing_params = []
if macvtap_src is None:
missing_params.append(network_model.VIF_DETAILS_MACVTAP_SOURCE)
if macvtap_mode is None:
missing_params.append(network_model.VIF_DETAILS_MACVTAP_MODE)
if phys_interface is None:
missing_params.append(network_model.VIF_DETAILS_PHYS_INTERFACE)
if len(missing_params) > 0:
raise exception.VifDetailsMissingMacvtapParameters(
vif_id=vif['id'],
missing_params=missing_params)
designer.set_vif_host_backend_direct_config(
conf, macvtap_src, macvtap_mode)
designer.set_vif_bandwidth_config(conf, flavor)
return conf
def get_config_iovisor(self, instance, vif, image_meta, flavor, virt_type):
conf = self.get_base_config(
instance, vif['address'], image_meta, flavor, virt_type,
vif['vnic_type'])
dev = self.get_vif_devname(vif)
designer.set_vif_host_backend_ethernet_config(conf, dev)
designer.set_vif_bandwidth_config(conf, flavor)
return conf
def get_config_midonet(self, instance, vif, image_meta, flavor, virt_type):
conf = | |
from enum import Enum
import random
from copy import deepcopy
class Role(Enum):
NOTHING = 0
VILLAGER = 1
WEREWOLF = 2
SEER = 3
TROUBLEMAKER = 4
ROBBER = 5
HUNTER = 6
TANNER = 7
MINION = 8
MASON = 9
DRUNK = 10
INSOMNIAC = 11
DOPPELGANGER = 12
class Card():
def __init__(self, role, alt_role=Role.NOTHING):
self.role = role
self.alt_role = alt_role # Used for classes with multiple roles, such as Doppelganger
self.tokens = [] # Token mechanics not implemented
def to_string(self, alt=False):
name_string = self.role.name
if self.alt_role != Role.NOTHING and alt:
name_string += "-" + self.alt_role.name
return name_string
''' Returns a list of player ids that match a role in a given list of cards
' alt: (bool) Whether the alternative role of the class should be considered
'''
def players_with_role(role, pCards, alt=False):
if alt:
return[id for id, card in enumerate(pCards) if role in (card.role, card.alt_role)]
return [id for id, card in enumerate(pCards) if card.role == role]
'''
' WerewolfGame
' Stores information about the state of a werewolf game, handles state transitions
'''
class WerewolfGame:
def __init__(self):
# Card arrays are lists of Card objects. Order of cards is important(!),
# As it determines which player holds which card
self.playerCards = []
self.centerCards = []
self.startPlayerCards = []
self.NIGHT_PRIORITIES = (Role.DOPPELGANGER, Role.WEREWOLF, Role.MINION, Role.MASON,
Role.SEER, Role.ROBBER, Role.TROUBLEMAKER, Role.DRUNK, Role.INSOMNIAC)
self.current_turn = Role.NOTHING
self.unfinished_players = []
# Optional rules, disabled by default
self.house_rules = {
"minionkill": False, # If there are no werewolves and a minion gets killed, the villagers win
"tannerwinsteal": False, # If a tanner dies, everyone else loses
"doubletransform": False # If a doppelganger picks another doppelganger during the night, they will copy their transformation (if any)
}
'''
' setup_game: Randomly deals cards to each player and sets center cards
' player_count (int): How many players will participate
' roles (list of Roles): List of roles to be used in game. Repeating a role
' implies that multiple cards will have the same role. Any roles left over
' after dealing player cards will be used as center cards.
'''
def setup_game(self, player_count, roles):
if player_count < 3:
raise ValueError("Not enough players to start game (need at least 3).")
if len(roles) < player_count:
raise ValueError('Not enough cards for all players.')
for i in range(player_count):
self.playerCards.append(Card(role=roles.pop(random.randint(0, len(roles) - 1))))
self.startPlayerCards = deepcopy(self.playerCards)
# Order of center cards should be randomized too
while roles:
self.centerCards.append(Card(role=roles.pop(random.randint(0, len(roles)-1))))
self.current_turn = Role.NOTHING
'''
' Returns a dict with current game state
' Cards are represented with strings describing of their names
'''
def get_state(self):
pCards = []
cCards = []
spCards = []
inPlay = []
for pCard in self.playerCards:
pCards.append(pCard.to_string(alt=True))
for cCard in self.centerCards:
cCards.append(cCard.to_string(alt=True))
for spCard in self.startPlayerCards:
spCards.append(spCard.to_string(alt=True))
# Cards in play must be sorted, otherwise it inadvertently reveals which players hold which cards
inPlay.sort()
return {"pCards": pCards,
"cCards": cCards,
"startPCards": spCards,
"turn": self.current_turn.name,
"waiting": self.unfinished_players
}
def print_status(self):
if len(self.playerCards) > 0:
for i, playerCard in enumerate(self.playerCards):
print(f"Player {i} is: {playerCard.to_string()}")
else:
print("No players are in the game")
if len(self.centerCards) > 0:
for i, cCard in enumerate(self.centerCards):
print(f"Center card {i}: {cCard.to_string()}")
else:
print("There are no center cards")
'''
' do_doppelganger
' target: target player's id (int)
' implements the first stage of the doppelganger action (transformation)
' the new form of the doppelganger is stored as alt_role in the Card object
' The new form is also returned as Role object
'
' Note: when implementing the secondary actions SEER, ROBBER, TROUBLEMAKER and DRUNK
' use their respective functions with the doppel_pass set to True.
'''
def do_doppelganger(self, player_id, target):
if self.current_turn != Role.DOPPELGANGER:
raise ValueError('It is not the doppelganger turn')
if not(player_id in self.unfinished_players):
raise ValueError('Player does not have the right to make this move')
card = self.playerCards[target]
new_role = card.role
if new_role==Role.DOPPELGANGER and self.house_rules["doubletransform"]:
if card.alt_role != Role.NOTHING:
new_role = card.alt_role
self.startPlayerCards[player_id].alt_role = new_role
self.playerCards[player_id].alt_role = new_role
if not new_role in (Role.SEER, Role.ROBBER, Role.TROUBLEMAKER, Role.DRUNK):
self.unfinished_players.remove(player_id)
return card.to_string()
'''
' do_werewolf
' player_id, choice should be ints
' returns a list of other players' ids that are also werewolves (empty if alone)
'''
def do_werewolf(self, player_id):
if self.current_turn != Role.WEREWOLF:
raise ValueError('It is not the werewolf turn')
if not(player_id in self.unfinished_players):
raise ValueError('Player does not have the right to make this move')
others = players_with_role(Role.WEREWOLF, self.startPlayerCards, alt=True)
others.remove(player_id)
# If there are no other wolves, lone wolf must first make their solo move before being finished
if others:
self.unfinished_players.remove(player_id)
return others
'''
' do_solo_werewolf
' used when a player is the only werewolf, to see a center card
' choice should correspond to a center card
' returns the primary role of the card viewed
'''
def do_solo_werewolf(self, player_id, choice=0):
if self.current_turn != Role.WEREWOLF:
raise ValueError('It is not the werewolf turn')
wolves = players_with_role(Role.WEREWOLF, self.startPlayerCards, alt=True)
if (player_id in self.unfinished_players) and len(wolves)==1 and len(self.centerCards)>choice>=0:
self.unfinished_players.remove(player_id)
return self.centerCards[choice].role
raise ValueError('Invalid move')
'''
' do_minion
' returns a list of werewolves' player ids
'''
def do_minion(self, player_id):
if self.current_turn != Role.MINION:
raise ValueError('It is not the minion turn')
if player_id not in self.unfinished_players:
raise ValueError('Player does not have the right to make this move')
self.unfinished_players.remove(player_id)
return players_with_role(Role.WEREWOLF, self.startPlayerCards, alt=True)
'''
' do_mason
' returns a list of other masons' ids
'''
def do_mason(self, player_id):
if self.current_turn != Role.MASON:
raise ValueError('It is not the mason turn')
if player_id not in self.unfinished_players:
raise ValueError('Player does not have the right to make this move')
self.unfinished_players.remove(player_id)
others = players_with_role(Role.MASON, self.startPlayerCards, alt=True)
others.remove(player_id)
return others
'''
' choices: list of ints matching card ids
' return list of roles (string) that were seen
'''
def do_seer(self, player_id, see_center, choices, doppel_pass=False):
if self.current_turn != Role.SEER and not doppel_pass:
raise ValueError('It is not the seer turn')
if not(player_id in self.unfinished_players):
raise ValueError('Player does not have the right to make this move')
try:
if see_center:
if len(self.centerCards) > 1:
result = [self.centerCards[choices[0]].role, self.centerCards[choices[1]].role]
elif len(self.centerCards) == 1:
result = [self.centerCards[choices[0]].role]
else:
raise ValueError('Invalid selection: no center cards')
elif choices[0] != player_id:
result = [self.playerCards[choices[0]].role]
else:
raise ValueError('Player may not look at their own card')
self.unfinished_players.remove(player_id)
return result
except IndexError:
raise ValueError('Invalid selection')
'''
' Target should be an id (int)
' returns the newly acquired role (string)
'''
def do_robber(self, player_id, target, doppel_pass=False):
if self.current_turn != Role.ROBBER and not doppel_pass:
raise ValueError('It is not the robber turn')
if not(player_id in self.unfinished_players):
raise ValueError('Player does not have the right to make this move')
if player_id == target:
raise ValueError("Robber cannot rob self")
try:
new_role = self.playerCards[target].role
self.swapPlayerCards(player_id, target)
self.unfinished_players.remove(player_id)
return new_role
except IndexError:
raise ValueError("Invalid selection")
'''
' Choices should be a list/tuple that has a length of exactly 2
' (the ids of players whose cards are to be swapped)
'''
def do_troublemaker(self, player_id, choices, doppel_pass=False):
if self.current_turn != Role.TROUBLEMAKER and not doppel_pass:
raise ValueError('It is not the troublemaker turn')
if not(player_id in self.unfinished_players):
raise ValueError('Player does not have the right to make this move')
if len(self.playerCards) < 3:
# Troublemaker has no legal swaps, turn is skipped
self.unfinished_players.remove(player_id)
return
if (player_id in choices) or (len(choices) != 2) or (choices[0] == choices[1]):
raise ValueError('Invalid cards selected')
try:
self.swapPlayerCards(choices[0], choices[1])
self.unfinished_players.remove(player_id)
except IndexError:
raise ValueError("Invalid selection")
'''
' do_drunk
' target should be the id of a center card
' returns nothing
'''
def do_drunk(self, player_id, target, doppel_pass=False):
if self.current_turn != Role.DRUNK and not doppel_pass:
raise ValueError('It is not the drunk turn')
if not(player_id in self.unfinished_players):
raise ValueError('Player does not have the right to make this move')
self.swapWithCenterCard(player_id, target)
self.unfinished_players.remove(player_id)
'''
' do_insomniac
' returns the name of the role (string) that the insomniac's card has
'''
def do_insomniac(self, player_id):
if self.current_turn != Role.INSOMNIAC:
raise ValueError('It is not the insomniac turn')
if not(player_id in self.unfinished_players):
raise ValueError('Player does not have the right to make this move')
self.unfinished_players.remove(player_id)
return self.playerCards[player_id].role.name
| |
"""
Implements indexing on a dbarray. dbarray indexing maps a raw bracket index to
a set of maximal C-contiguous simple index bounds containing the indexed data.
The dbindx an index of a dbarray. A dbindex is created from either a bracketed
expression, i.e., dbarray[raw_idx], or from explicit dbindex creation functions.
"""
# TODO: indexed_shape
# TODO: ellipsis, None, newaxis, fancy
import numpy as np
def unravel_index(db_shape, raw_idx):
"""
Converts a raw bracked index expression to the corresponding set of dbarray
index bounds and the shape of the resulting indexed array; i.e., performs
dbarray[raw_idx] where dbarray has shape db_shape.
Supported raw_idx types are int, slice, tuple, np.ellipsis, np.newaxis, int
array, boolean array, and array-like.
Indexing type is determined by the value of raw_idx and corresponds to one
of the numpy indexing types: basic indexing or advanced (fancy) indexing.
Numpy field access (and structured arrays generally) is not supported.
Args:
db_shape (tuple): shape of dbarray being indexed.
raw_idx (one of supported raw index types): indices to retrieve or set
Returns:
index_bounds (list): a list of tuples of index bounds for each maximal
C-contiguous block of data in dbarray[raw_idx]. Each tuple (start, stop)
indicates the index of the first and last elements of the contigous
block.
indexed_shape (tuple): the shape of dbarray[raw_idx]
"""
# first format index and determine the type of index
idx, idx_type = to_dbindex(raw_idx)
if idx_type == "basic":
# basic indexing
index_bounds = simple_index(db_shape, idx)
else:
# fancy indexing
indexed_shape, index_bounds = fancy_index(db_shape, idx)
maximal_index_bounds = merge_contiguous(index_bounds)
# TODO: replace
return (3,3,3), maximal_index_bounds
def to_dbindex(raw_idx):
"""
Given a raw index, returns the formatted index and the type of indexing.
Also checks that raw index is valid.
Args:
raw_idx (one of dbindex_types): a raw index of a dbarray.
Returns:
idx, idx_type (tuple): a formatted index value and the type index
"""
# a dbindex can be one of the following types
dbindex_types = [int, slice, tuple, type(Ellipsis), type(None), np.ndarray]
# coerce array-likes into np.ndarrays and check that arrays are of bools
# or ints
if not any([isinstance(raw_idx, t) for t in dbindex_types]):
# try to cast np.ndarray
try:
raw_idx = np.array(raw_idx)
except Exception:
raise TypeError, "dbarray index of unsupported type"
if isinstance(raw_idx, np.ndarray):
# array index must be of integers or bools
assert(raw_idx.dtype in [int, bool])
array_in_tuple = False
if isinstance(raw_idx, tuple):
raw_idx_list = list(raw_idx)
# any tuple elements that are array-like must be of ints or bools
for e_idx, e in enumerate(raw_idx):
if not any([isinstance(e, t) for t in dbindex_types]):
# either array-like
try:
raw_idx_list[e_idx] = np.array(e)
array_in_tuple = True
except Exception:
# or invalid
raise TypeError, "dbarray index of unsupported type"
raw_idx = tuple(raw_idx_list)
idx = raw_idx
# determine indexing type
idx_type = "fancy" if isinstance(idx, np.ndarray) or array_in_tuple else "basic"
assert(any([isinstance(idx, t) for t in dbindex_types])), "Error in index formatting"
return idx, idx_type
def merge_contiguous(index_bounds):
"""
Combines any contiguous index bounds.
Args:
index_bounds (list): a list of bounding index tuples for each
potentially non-maximal C-contiguous block of data selected.
Returns:
maximal_index_bounds (list): a list of bounds equivalent to
index_bounds, but such that each bounded area is maximal, i.e., no
pairs of consecutive bounds can be merged to form a single bounds.
"""
# combine any contiguous index bounds
maximal_index_bounds = []
if len(index_bounds) < 2:
# nothing to merge
return index_bounds
else:
# for the first element compare the consecutive bounds in index_bounds
if index_bounds[0][1] != index_bounds[1][0]:
# not contiguous
maximal_index_bounds += [index_bounds[0], index_bounds[1]]
else:
# contiguous
maximal_index_bounds.append((index_bounds[0][0],
index_bounds[1][1]))
for i in range(1, len(index_bounds) - 1):
# compare to last element of maximal_index_bounds
if maximal_index_bounds[-1][1] != index_bounds[i+1][0]:
# not contiguous
maximal_index_bounds.append(index_bounds[i+1])
else:
# contiguous
last_bounds = maximal_index_bounds.pop()
maximal_index_bounds.append((last_bounds[0],
index_bounds[i+1][1]))
return maximal_index_bounds
def positivize_idx(axis_len, idx_1d):
"""
Standardizes a 1d index by converting a negative scalar to a
corresponding positive scalar. Also checks bounds.
"""
if isinstance(idx_1d, tuple):
# numerical index
if idx_1d < 0:
# convert to positive index
standardized_idx = idx_1d + axis_len
else:
standardized_idx = idx_1d
if standardized_idx < 0 or standardized_idx > axis_len - 1:
# out of bounds
raise IndexError, ("Index {} out of bounds for axis with length {}"
).format(idx_1d, axis_len)
else:
# None, etc.
standardized_idx = idx_1d
return standardized_idx
def simple_index(db_shape, idx):
"""
Implements numpy basic slicing.
Returns a list of one tuple for each C-contiguous section of the dbarray
described by the index. Each tuple contains the index in the dbarray of the
first and last elements of the contiguous secion. Sections appear in the
order they occur in the resulting indexed array.
Args:
db_shape (tuple): shape of a dbarray to be indexed
idx (one of supported_index_types): an index of a dbarray
Returns:
indexed_shape (tuple): the shape of dbarray[raw_idx]
index_bounds (list): a list of bounding index tuples for each
C-contiguous block of data in the indexed result.
"""
# number of dimensions to slice in
ndim = len(db_shape)
index_bounds = []
if isinstance(idx, int):
# indexing by a scalar
idx = positivize_idx(db_shape[0], idx)
if ndim == 1:
# result is single value
return [((idx,), (idx,))]
elif ndim == 2:
# slice is 1D array
return [((idx, 0), (idx, db_shape[1] - 1))]
else:
# slice is n-dim array, n > 1; recurse down
sub_idx = to_dbindex(slice(None))[0]
sub_shape = db_shape[1:]
sub_bounds = simple_index(sub_shape, sub_idx)
return [((idx,) + start_idx, (idx,) + end_idx) for
start_idx, end_idx in sub_bounds]
elif isinstance(idx, slice):
# parse slice values to scalars
if idx == slice(None):
# select all
last_idx = tuple((i - 1 for i in db_shape))
return [((0,) * ndim, last_idx)]
else:
if ndim == 1:
start = idx.start if not idx.start is None else 0
stop = idx.stop if not idx.stop is None else db_shape[0]
if idx.step is None:
# simple slice of 1D array
start = positivize_idx(db_shape[0], start)
stop = positivize_idx(db_shape[0], stop - 1)
return [((start,), (stop,))]
else:
# subselection along first axis; slice non-contiguous
step = idx.step if not idx.step is None else 1
first_axis_idxs = range(start, stop, step)
index_bounds = []
for first_idx in first_axis_idxs:
index_bounds += [((first_idx,), (first_idx,))]
return index_bounds
else:
# slice along first axis, full slice from higher axes
sub_idx = to_dbindex(slice(None))[0]
sub_shape = db_shape[1:]
sub_bounds = simple_index(sub_shape, sub_idx)
if idx.step is None:
# simple slice of 1D array
first_axis_start = idx.start if not idx.start is None else 0
first_axis_stop = (idx.stop - 1 if not idx.stop is None else
db_shape[0] - 1)
first_axis_start = positivize_idx(db_shape[0],
first_axis_start)
first_axis_stop = positivize_idx(db_shape[0],
first_axis_stop)
return [((first_axis_start,) + start_idx,
(first_axis_stop,) + end_idx) for start_idx,
end_idx in sub_bounds]
else:
# subselection along first axis
index_bounds = []
start = idx.start if not idx.start is None else 0
stop = idx.stop if not idx.stop is None else db_shape[0]
step = idx.step if not idx.step is None else 1
start = positivize_idx(db_shape[0], start)
stop = positivize_idx(db_shape[0], stop)
first_axis_idxs = range(start, stop, step)
for first_idx in first_axis_idxs:
index_bounds += [((first_idx,) + start_idx, (first_idx,)
+ end_idx) for start_idx, end_idx in
sub_bounds]
return index_bounds
else:
# indexing by a tuple
if len(idx) > ndim:
# too many indices; out of bounds
raise IndexError, (("Too many indices for array with dimension {}")
.format(ndim))
# get bounds on first axis
first_axis_idxs = simple_index((db_shape[0],), to_dbindex(idx[0])[0])
if ndim == 1:
# no subaxes
return first_axis_idxs
else:
if len(idx) > 1:
# next get bounds on subaxes
sub_idx = idx[1:]
else:
# no bounds on subaxes
sub_idx = slice(None)
sub_shape = db_shape[1:]
sub_bounds = simple_index(sub_shape, to_dbindex(sub_idx)[0])
# combine first axis bounds with subaxis bounds
index_bounds = []
for first_axis_start, first_axis_stop in first_axis_idxs:
index_bounds += [(first_axis_start + sub_axis_start,
first_axis_stop + sub_axis_stop) for sub_axis_start,
sub_axis_stop in sub_bounds]
return index_bounds
def fancy_index(db_shape, idx):
"""
Implements numpy fancy slicing.
Returns a list of one tuple for each C-contiguous section of the dbarray
described by | |
<gh_stars>1-10
import argparse
import torch
import pickle
import math
import constant as Constants
import numpy as np
import matplotlib.pyplot as plt
import random
from tqdm import tqdm
from plot import display_multi_poses, display_pose
from sklearn.decomposition import PCA
from sklearn import preprocessing
def loadpickle(path, data_size):
'''
load train and val dataset
param:
file path
data_size
return:
data
'''
with open(path, 'rb') as f:
data = pickle.load(f)
# retrict loaded data size
if data_size < len(data):
dataset = data[:data_size]
else:
dataset = data[:]
return dataset
def get_data(data, sampling_rate):
x_train = []
y_train = []
x_tmp = []
y_tmp = []
# the poses in the dataset has been captured with 12fps
# sampling_rate = math.ceil(12 / sampling_rate)
for data in data:
if len(data['clips'])>0:
for clip in data['clips']:
# get words in a clip
words = clip['words']
# assign temp word list
sentence = []
for word in words:
w = word[0] # get a word
if w != '':
sentence.append(w) # full sentence
# add indexed words to x_train
x_tmp.append(sentence)
# add skeletons in a clip to y_train
y_tmp.append(clip['skeletons'])
pair_list = list(zip(x_tmp, y_tmp))
for pair in pair_list:
sentence = pair[0]
poses = pair[1]
tmp_poses = []
dist1_list = []
dist2_list = []
for p in poses:
if not(0 in p):
p = np.array(p) * -1 # rotate whole pose
p += 1500 # make it positive number
tmp_poses.append(p)
# sampling 10fps
tmp_poses = tmp_poses[::sampling_rate]
# selecte dataset with below condition;
# 1. pose seq must be longer than word seq
# 2. word seq has more than 12 (6*2)
if (2 * len(sentence) < len(tmp_poses)) and (len(sentence) > 6*2):
x_train.append(sentence)
y_train.append(tmp_poses)
print('[INFO] dataset desc.')
print("\tparis: {}".format(len(x_train)))
print("\tmax seq in x: {}".format(len(max(x_train, key=len))))
print("\tmin seq in x: {}".format(len(min(x_train, key=len))))
print("\tmax seq in y: {}".format(len(max(y_train, key=len))))
print("\tmin seq in y: {}\n".format(len(min(y_train, key=len))))
return x_train, y_train
def build_vocab_idx(word_insts, min_word_count):
# word to index dictionary
word2idx = {
Constants.BOS_WORD: Constants.BOS,
Constants.EOS_WORD: Constants.EOS,
Constants.PAD_WORD: Constants.PAD,
Constants.UNK_WORD: Constants.UNK,
}
full_vocab = set(w for sent in word_insts for w in sent)
print('[INFO] Original Vocabulary size: {}'.format(len(full_vocab)))
word_count = {w: 0 for w in full_vocab}
# count word frequency in the given dataset
for sent in word_insts:
for word in sent:
word_count[word] += 1
ignored_word_count = 0
for word, count in word_count.items():
if word not in word2idx:
if count > min_word_count:
word2idx[word] = len(word2idx) # add word to dictioary with index
else:
ignored_word_count += 1
print('[INFO] Trimmed vocabulary size: {}\n\teach with minum occurrence: {}'.format(len(word2idx), min_word_count))
print('[INFO] Ignored word count: {}'.format(ignored_word_count))
return word2idx
def convert_instance_to_idx_seq(word_insts, word2idx):
'''
note:
mapping word to idx seq
return unk seq if there is unknown seq
'''
return [ [word2idx.get(w, Constants.UNK) for w in s] for s in word_insts ]
def run_PCA_train_tgt(tgt_insts, lengths, n_components):
pca = PCA(n_components=n_components)
pca_tgt = pca.fit_transform(tgt_insts)
ori_tgt = []
# initial index of expanded pose array
start = 0
for l in lengths:
# create empty array to store pca poses
pca_skel = np.zeros((1, n_components))
sel_p = pca_tgt[start:start+l]
for i in range(sel_p.shape[0]):
sel_p[i][2] = 0.00
# stack
ori_tgt.append(sel_p)
# change index
start = l
return pca, ori_tgt
def run_PCA_val_tgt(pca, tgt_insts, lengths, n_components):
pca_tgt = pca.transform(tgt_insts)
ori_tgt = []
# initial index of expanded pose array
start = 0
for l in lengths:
# create empty array to store pca poses
pca_skel = np.zeros((1, n_components))
sel_p = pca_tgt[start:start+l]
for i in range(sel_p.shape[0]):
sel_p[i][2] = 0.00
# stack
ori_tgt.append(sel_p)
# change index
start = l
return ori_tgt
def tgt_insts_normalize(tgt_insts):
'''
param:
motion inputs list
motion inputs list and normalize the values,
noramlizer - min_max etc
return:
expanded normalized motion list,
motion lengths list
'''
def get_distance(x1, y1, x2, y2):
return math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
def get_theta(var_x, var_y, fix_x, fix_y):
return math.atan2(var_y - fix_y, var_x - fix_x)
def get_new_cor(theta, dist, point):
return dist * np.array([math.cos(theta),
math.sin(theta)]) + np.array([point[0], point[1]])
def length_norm(var_x, var_y, fix_x, fix_y, expanded_len):
angle = get_theta(var_x, var_y, fix_x, fix_y)
new_cor = get_new_cor(
angle,
expanded_len,
[fix_x, fix_y])
# get change ratio between original dist and expected dist
ratio = expanded_len / get_distance(var_x, var_y, fix_x, fix_y)
# print("old cor: {:0.2f}, {:0.2f}".format(var_x, var_y))
# print("new cor: {:0.2f}, {:0.2f}".format(new_cor[0], new_cor[1]))
return new_cor, ratio
# ------------------- Fitering poses --------------------- #
tmp = []
length = []
# expand poses list
for pose in tgt_insts:
p_count = 0
for p in pose:
if 1.3*get_distance(p[6], p[7], p[3], p[4]) >= get_distance(p[0], p[1], p[3], p[4]) and \
1.3*get_distance(p[15], p[16], p[3], p[4]) >= get_distance(p[0], p[1], p[3], p[4]):
if get_distance(p[6], p[7], p[3], p[4]) < 1.3*get_distance(p[15], p[16], p[3], p[4]) and \
1.3*get_distance(p[6], p[7], p[3], p[4]) > get_distance(p[15], p[16], p[3], p[4]):
if (p[6] > p[3]) and (p[15] < p[3]): # rotated motion
if p[1] > p[4]:
tmp.append(p)
p_count += 1
length.append(p_count)
# convert list to np array
tmp = np.array(tmp)
# normalized with specific scale
normalized = preprocessing.normalize(tmp, norm='l2') * 100
print('[INFO] Filtered poses: {}'.format(len(normalized)))
# save explanded pose pickle
print('[INFO] Save l2 noramlized pose.')
torch.save(normalized, './processed_data/l2_norm.pickle')
# get mean dist of each shoulders
mean_val_pose = np.mean(normalized, axis=0)
rig_sh_len_mean = get_distance(mean_val_pose[3], mean_val_pose[4], mean_val_pose[6], mean_val_pose[7])
lef_sh_len_mean = get_distance(mean_val_pose[3], mean_val_pose[4], mean_val_pose[15], mean_val_pose[16])
for pose in normalized:
# ------------------- re-coordinate neck --------------------- #
neck_diff_x = 0 - pose[3]
neck_diff_y = 0 - pose[4]
pose[3] = 0
pose[4] = 0
for i in range(len(pose)):
if (i % 3 == 0) and not(i == 3): # x
pose[i] += neck_diff_x
elif (i % 3 == 1) and not(i == 4): # y
pose[i] += neck_diff_y
# save explanded pose pickle
print('[INFO] Save neck re-cordination.')
torch.save(normalized, './processed_data/neck_loc.pickle')
# exit(-1)
for pose in normalized:
# ------------------- normalize shoulder --------------------- #
rig_new_cor, rig_ratio = length_norm(pose[6], pose[7], pose[3], pose[4], rig_sh_len_mean)
lef_new_cor, lef_ratio = length_norm(pose[15], pose[16], pose[3], pose[4], lef_sh_len_mean)
rig_diff_x = rig_new_cor[0] - pose[6]
rig_diff_y = rig_new_cor[1] - pose[7]
lef_diff_x = lef_new_cor[0] - pose[15]
lef_diff_y = lef_new_cor[1] - pose[16]
# shoudler re-loc
pose[6] = rig_new_cor[0]
pose[7] = rig_new_cor[1]
pose[15] = lef_new_cor[0]
pose[16] = lef_new_cor[1]
# rest of cor re-loc
pose[9] += rig_diff_x
pose[10] += rig_diff_y
pose[12] += rig_diff_x
pose[13] += rig_diff_y
pose[18] += lef_diff_x
pose[19] += lef_diff_y
pose[21] += lef_diff_x
pose[22] += lef_diff_y
# ------------------- normalize neck --------------------- #
neck_new_cor, _ = length_norm(pose[0], pose[1], pose[3], pose[4],
get_distance(pose[0], pose[1], pose[3], pose[4]) * rig_ratio)
# neck_new_cor, _ = length_norm(pose[0], pose[1], pose[3], pose[4],
# neck_len_mean)
pose[0] = neck_new_cor[0]
pose[1] = neck_new_cor[1]
# right arm
rig_arm_new_cor, _ = length_norm(pose[9], pose[10], pose[6], pose[7],
get_distance(pose[9], pose[10], pose[6], pose[7]) * rig_ratio)
rig_diff_x = rig_arm_new_cor[0] - pose[9]
rig_diff_y = rig_arm_new_cor[1] - pose[10]
pose[9] = rig_arm_new_cor[0]
pose[10] = rig_arm_new_cor[1]
# re-locate right hand coordination
pose[12] += rig_diff_x
pose[13] += rig_diff_y
# right hand
rig_hand_new_cor, _ = length_norm(pose[12], pose[13], pose[9], pose[10],
get_distance(pose[12], pose[13], pose[9], pose[10]) * rig_ratio)
pose[12] = rig_hand_new_cor[0]
pose[13] = rig_hand_new_cor[1]
# left arm
lef_arm_new_cor, _ = length_norm(pose[18], pose[19], pose[15], pose[16],
get_distance(pose[18], pose[19], pose[15], pose[16]) * lef_ratio)
lef_diff_x = lef_arm_new_cor[0] - pose[18]
lef_diff_y = lef_arm_new_cor[1] - pose[19]
pose[18] = lef_arm_new_cor[0]
pose[19] = lef_arm_new_cor[1]
# re-locate left hand coordination
pose[21] += lef_diff_x
pose[22] += lef_diff_y
# left hand
lef_hand_new_cor, _ = length_norm(pose[21], pose[22], pose[18], pose[19],
get_distance(pose[21], pose[22], pose[18], pose[19]) * lef_ratio)
pose[21] = lef_hand_new_cor[0]
pose[22] = lef_hand_new_cor[1]
# save explanded pose pickle
print('[INFO] Save shoulder norm pose.')
torch.save(normalized, './processed_data/sh_norm.pickle')
# exit(-1)
return normalized, length
def build_emb_table(emb_path, target_vocab):
def load_emb_file(emb_path):
vects = []
idx = 0
word2idx = dict()
idx2word = dict()
with open(emb_path, 'r') as f:
for l in tqdm(f):
line = l.split()
word = line[0]
w_vec = np.array(line[1:]).astype(np.float)
vects.append(w_vec)
word2idx[word] = idx
idx2word[idx] = word
idx += 1
return np.array(vects), word2idx, idx2word
vects, word2idx, idx2word = load_emb_file(emb_path)
dim = vects.shape[1]
emb_tb = np.zeros((len(target_vocab), dim))
for k, v in target_vocab.items():
try:
emb_tb[v] = vects[word2idx[k]]
except KeyError:
emb_tb[v] = np.random.normal(scale=0.6, size=(dim, ))
return emb_tb
def main():
def get_distance(x1, y1, x2, y2):
return math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
parser = | |
self.font_text, text = "Blood Pressure", padx = 4, pady = 4)
self.Pressure_Label.grid(row = 10, column = 0, sticky = "ew")
self.Pressure_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Pressure, width = 10)
self.Pressure_Entry.grid(row = 10, column = 1, sticky = "ew")
self.Pulse_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Pulse", padx = 4, pady = 4)
self.Pulse_Label.grid(row = 10, column = 2, sticky = "ew")
self.Pulse_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Pulse, width = 10)
self.Pulse_Entry.grid(row = 10, column = 3, sticky = "ew")
self.Temperature_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Temperature", padx = 4, pady = 4)
self.Temperature_Label.grid(row = 10, column = 4, sticky = "ew")
self.Temperature_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Temperature, width = 10)
self.Temperature_Entry.grid(row = 10, column = 5, sticky = "ew")
self.Breath_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Breath", padx = 4, pady = 4)
self.Breath_Label.grid(row = 10, column = 6, sticky = "ew")
self.Breath_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Breath, width = 10)
self.Breath_Entry.grid(row = 10, column = 7, sticky = "ew")
self.Urin_Exp_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Urine/day", padx = 4, pady = 4)
self.Urin_Exp_Label.grid(row = 10, column = 8, sticky = "ew")
self.Urin_Exp_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Urin_Exp, width = 15)
self.Urin_Exp_Entry.grid(row = 10, column = 9, sticky = "ew")
##############################Meditation###############################
self.Meditation = tk.Label(self.RightFrame, font = self.font_title, text = "Meditation", padx = 4, pady = 4)
self.Meditation.grid(row = 11, column = 0, columnspan = 10, sticky = "w")
self.Cyanosis_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Cyanosis", padx = 4, pady = 4)
self.Cyanosis_Label.grid(row = 12, column = 0, sticky = "ew")
self.Cyanosis_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Cyanosis, width = 10)
self.Cyanosis_Entry.grid(row = 12, column = 1, sticky = "ew")
self.Elevate_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Elevate", padx = 4, pady = 4)
self.Elevate_Label.grid(row = 12, column = 2, sticky = "ew")
self.Elevate_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Elevate, width = 10)
self.Elevate_Entry.grid(row = 12, column = 3, sticky = "ew")
self.Pallor_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Pallor", padx = 4, pady = 4)
self.Pallor_Label.grid(row = 12, column = 4, sticky = "ew")
self.Pallor_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Pallor, width = 10)
self.Pallor_Entry.grid(row = 12, column = 5, sticky = "ew")
self.Dryness_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Dryness", padx = 4, pady = 4)
self.Dryness_Label.grid(row = 12, column = 6, sticky = "ew")
self.Dryness_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Dryness, width = 10)
self.Dryness_Entry.grid(row = 12, column = 7, sticky = "ew")
self.Edema_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Edema", padx = 4, pady = 4)
self.Edema_Label.grid(row = 12, column = 8, sticky = "ew")
self.Edema_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Edema, width = 15)
self.Edema_Entry.grid(row = 12, column = 9, sticky = "ew")
self.Hair_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Hair", padx = 4, pady = 4)
self.Hair_Label.grid(row = 12, column = 10, sticky = "ew")
self.Hair_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Hair, width = 15)
self.Hair_Entry.grid(row = 12, column = 11, sticky = "ew")
##############################Changes###############################
self.Changes = tk.Label(self.RightFrame, font = self.font_title, text = "Changes", padx = 4, pady = 4)
self.Changes.grid(row = 13, column = 0, columnspan = 10, sticky = "w")
self.Sleep_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Sleep", padx = 4, pady = 4)
self.Sleep_Label.grid(row = 14, column = 0, sticky = "ew")
self.Sleep_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Sleep, width = 10)
self.Sleep_Entry.grid(row = 14, column = 1, sticky = "ew")
self.Constipation_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Constipation", padx = 4, pady = 4)
self.Constipation_Label.grid(row = 14, column = 2, sticky = "ew")
self.Constipation_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Constipation, width = 10)
self.Constipation_Entry.grid(row = 14, column = 3, sticky = "ew")
self.Diarrhea_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Diarrhea", padx = 4, pady = 4)
self.Diarrhea_Label.grid(row = 14, column = 4, sticky = "ew")
self.Diarrhea_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Diarrhea, width = 10)
self.Diarrhea_Entry.grid(row = 14, column = 5, sticky = "ew")
self.Vomiting_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Vomiting", padx = 4, pady = 4)
self.Vomiting_Label.grid(row = 14, column = 6, sticky = "ew")
self.Vomiting_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Vomiting, width = 10)
self.Vomiting_Entry.grid(row = 14, column = 7, sticky = "ew")
self.Urin_Color_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Urine Color", padx = 4, pady = 4)
self.Urin_Color_Label.grid(row = 14, column = 8, sticky = "ew")
self.Urin_Color_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Urin_Color, width = 15)
self.Urin_Color_Entry.grid(row = 14, column = 9, sticky = "ew")
self.Urin_Number_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Urine Number", padx = 4, pady = 4)
self.Urin_Number_Label.grid(row = 14, column = 10, sticky = "ew")
self.Urin_Number_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Urin_Number, width = 15)
self.Urin_Number_Entry.grid(row = 14, column = 11, sticky = "ew")
##############################Symptoms###############################
self.Symptoms = tk.Label(self.RightFrame, font = self.font_title, text = "Current Symptoms", padx = 4, pady = 4)
self.Symptoms.grid(row = 15, column = 0, columnspan = 10, sticky = "w")
self.Current_sym1_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Current_sym1, width = 15)
self.Current_sym1_Entry.grid(row = 16, column = 1, columnspan = 4, sticky = "ew")
self.Current_sym2_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Current_sym2, width = 15)
self.Current_sym2_Entry.grid(row = 16, column = 5, columnspan = 4, sticky = "ew")
self.Current_sym3_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Current_sym3, width = 15)
self.Current_sym3_Entry.grid(row = 17, column = 1, columnspan = 4, sticky = "ew")
self.Current_sym4_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Current_sym4, width = 15)
self.Current_sym4_Entry.grid(row = 17, column = 5, columnspan = 4, sticky = "ew")
##############################Special Cases###############################
self.Special = tk.Label(self.RightFrame, font = self.font_title, text = "Special Cases", padx = 4, pady = 4)
self.Special.grid(row = 18, column = 0, columnspan = 10, sticky = "w")
self.Lab = tk.Label(self.RightFrame, font = self.font_title, text = "* Lab Tests", padx = 4, pady = 4)
self.Lab.grid(row = 19, column = 0, columnspan = 10, sticky = "w")
self.Uria_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Uria", padx = 4, pady = 4)
self.Uria_Label.grid(row = 20, column = 0, sticky = "ew")
self.Uria_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Uria, width = 10)
self.Uria_Entry.grid(row = 20, column = 1, sticky = "ew")
self.Humo_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Humo", padx = 4, pady = 4)
self.Humo_Label.grid(row = 20, column = 2, sticky = "ew")
self.Humo_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Humo, width = 10)
self.Humo_Entry.grid(row = 20, column = 3, sticky = "ew")
self.Krea_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Krea", padx = 4, pady = 4)
self.Krea_Label.grid(row = 20, column = 4, sticky = "ew")
self.Krea_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Krea, width = 10)
self.Krea_Entry.grid(row = 20, column = 5, sticky = "ew")
self.Na_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Na", padx = 4, pady = 4)
self.Na_Label.grid(row = 20, column = 6, sticky = "ew")
self.Na_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.Na, width = 10)
self.Na_Entry.grid(row = 20, column = 7, sticky = "ew")
self.K_Label = tk.Label(self.RightFrame, font = self.font_text, text = "K", padx = 4, pady = 4)
self.K_Label.grid(row = 20, column = 8, sticky = "ew")
self.K_Entry = tk.Entry(self.RightFrame, font = self.font_text, textvariable = self.K, width = 15)
self.K_Entry.grid(row = 20, column = 9, sticky = "ew")
self.Ca_Label = tk.Label(self.RightFrame, font = self.font_text, text = "Ca", padx = 4, pady = 4)
self.Ca_Label.grid(row = 21, column = 0, | |
<gh_stars>0
import re
import logging
import datetime
import requests
from .write import Write
from .trigger import run_task
from .proxies import get_proxy
from .user_agent import get_user_agent
from .exceptions import DownloadValueError, HTTPIgnoreCodeError
logger = logging.getLogger(__name__)
class Download:
def __init__(self, scraper, task, headers=None, proxy=None, ignore_codes=(),
triggered_kwargs={}, **kwargs):
"""Base Download class to inherent from
Args:
scraper (scraperx.Scraper): The Scraper class. Scraper Will take care of
passing itself in here.
tasks (dict): Task to be processed.
headers (dict, optional): Headers to be set for all requests. Defaults to None.
proxy (str, optional): Full url of a proxy to use for all requests. Defaults to None.
ignore_codes (tuple, optional): Tuple of http status codes to not re-try on.
Defaults to ().
triggered_kwargs (dict, optional): Dict of keyword arguments to pass into the
scrapers Extract class. Defaults to {}.
**kwargs: Arbitrary keyword arguments.
"""
self.scraper = scraper
self._triggered_kwargs = triggered_kwargs
self.task = task
self._ignore_codes = ignore_codes
# Set timestamps
self.time_downloaded = datetime.datetime.utcnow().isoformat() + 'Z'
self.date_downloaded = str(datetime.datetime.utcnow().date())
logger.info("Start Download",
extra={'task': self.task,
'scraper_name': self.scraper.config['SCRAPER_NAME'],
'time_started': self.time_downloaded,
})
self._manifest = {'source_files': [],
'time_downloaded': self.time_downloaded,
'date_downloaded': self.date_downloaded,
}
# Set up a requests session
self.session = requests.Session()
self._init_headers(headers)
self._init_proxy(proxy)
self._init_http_methods()
def download(self):
"""Scrapers download class should override this method if more then the default is needed.
The default download method does::
r = self.request_get(self.task['url'])
self.save_request(r)
"""
r = self.request_get(self.task['url'])
self.save_request(r)
def _get_proxy(self, country=None):
"""Get a new proxy to use for a request
Users scraper should override this if a custom way to get a proxy is needed.
The default way can be found under `scraperx.proxy.get_proxy`
Args:
country (str, optional): 2 letter country code to get the proxy for.
If None it will get any proxy. Defaults to None.
Returns:
str|None: Full url of the proxy or None if no proxy is available
"""
try:
return self.get_proxy(self.scraper, country=country)
except AttributeError:
return get_proxy(self.scraper, country=country)
def _get_user_agent(self, device_type):
"""Get a new user-agent to use for a request
Users scraper should override this if a custom way to get a user-agent is needed.
The default way can be found under `scraperx.user_agent.get_user_agent`
Args:
device_type (str): A way to pick the correct user-agent.
The options for the default function is `desktop` or `mobile`
Returns:
str: A User-Agent string
"""
try:
return self.get_user_agent(self.scraper, device_type)
except AttributeError:
return get_user_agent(self.scraper, device_type)
def run(self):
"""Starts downloading data based on the task
Will trigger the extract task after its complete
"""
try:
self.download()
except (requests.exceptions.HTTPError, HTTPIgnoreCodeError):
# The status code was logged during the request, no need to repeat
pass
except DownloadValueError:
# The status code was logged during the request, no need to repeat
pass
except Exception:
logger.exception("Download Exception",
extra={'task': self.task,
'scraper_name': self.scraper.config['SCRAPER_NAME']})
else:
if self._manifest['source_files']:
self._save_metadata()
run_task(self.scraper,
self.task,
task_cls=self.scraper.extract,
download_manifest=self._manifest,
**self._triggered_kwargs,
triggered_kwargs=self._triggered_kwargs)
else:
# If it got here and there is not saved file then thats an issue
logger.error("No source file saved",
extra={'task': self.task,
'scraper_name': self.scraper.config['SCRAPER_NAME'],
'manifest': self._manifest,
})
logger.debug('Download finished',
extra={'task': self.task,
'scraper_name': self.scraper.config['SCRAPER_NAME'],
'time_finished': datetime.datetime.utcnow().isoformat() + 'Z',
})
def save_request(self, r, content=None, source_file=None, content_type=None, **save_kwargs):
"""Save the data from the request into a file and save the request data in the metadata file
This is needed to pass the source file into the extract class
Args:
r (requests.request): Response from the requests lib
content (str|bytes, optional): The data of the source to be saved.
If saving a binary file, set to r.contents.
Defaults to r.text.
source_file (str, optional): Path to a saved file if already saved. Defaults to None.
content_type (str, optional): Mimetype of the file.
If None, a best guess will be made. Defaults to None.
**saved_kwargs: Keyword arguments that will be passed into
`scraperx.save_to.SaveTo.save` function
Returns:
str: Path to the source file that was saved
"""
if content is None:
content = r.text
if source_file is None:
source_file = Write(self.scraper, content)\
.write_file(content_type=content_type)\
.save(self, **save_kwargs)
self._manifest['source_files'].append(
{
'file': source_file,
'request': {
'url': r.url,
'method': r.request.method,
'status_code': r.status_code,
'headers': {
'request': dict(r.request.headers),
'response': dict(r.headers),
},
},
}
)
return source_file
def _save_metadata(self):
"""Save the metadata of the download portion of the scraper to a json file.
This is used to pass to the extract class as well as debugging if
anything goes wrong with the request.
Saves a file ending in `_metadata.json` in the same path as the first source file saved.
"""
if self.scraper.config['DOWNLOADER_SAVE_METADATA']:
metadata = self._get_metadata()
if metadata['download_manifest']['source_files']:
metadata_file = Write(self.scraper, metadata).write_json_lines()
filename = metadata['download_manifest']['source_files'][0]['file']
logger.debug("Saving metadata file",
extra={'task': self.task,
'scraper_name': self.scraper.config['SCRAPER_NAME']})
metadata_file.save(self, filename=filename + '_metadata.json')
def _get_metadata(self):
"""Create the dict of metadata to be saved
Returns:
dict: Data to be saved in the metadata file
"""
metadata = {'task': self.task,
'scraper': self.scraper.config['SCRAPER_NAME'],
'download_manifest': self._manifest,
}
return metadata
def _format_proxy(self, proxy):
"""Format the proxy in a way the requests lib can handle
Args:
proxy (str|dict): Full url of the proxy or a dict that the
requests library can use when setting a proxy
Returns:
dict: This is what the requests library uses when setting a proxy
"""
logger.debug(f"Setting proxy {proxy}",
extra={'task': self.task,
'scraper_name': self.scraper.config['SCRAPER_NAME']})
if isinstance(proxy, dict) and 'http' in proxy and 'https' in proxy:
# Nothing more to do
return proxy
return {'http': proxy,
'https': proxy
}
def _init_headers(self, headers):
"""Set headers for all requests
If no user-agent is passed in, one will be provided.
This is the only header that this will set by default
Args:
headers (dict): Dict of headers to set for all requests
"""
# Set headers from init, then update with task headers
self.session.headers = {} if headers is None else headers
self.session.headers.update(self.task.get('headers', {}))
# Set a UA if the scraper did not set one
if 'user-agent' not in map(str.lower, self.session.headers.keys()):
self._set_session_ua()
def _init_proxy(self, proxy):
"""Set the default proxy for all requests.
Only sets a proxy if a proxy file is set or a custom `self.get_proxy()` is set
Args:
proxy (str): Full url of proxy
"""
proxy_str = proxy
if self.task.get('proxy') is not None:
proxy_str = self.task.get('proxy')
# If no proxy has been passed in, try and set one
if not proxy_str:
proxy_str = self._get_proxy(country=self.task.get('proxy_country'))
self.session.proxies = self._format_proxy(proxy_str)
def _init_http_methods(self):
# Create http methods
self.request_get = self._set_http_method('GET')
self.request_post = self._set_http_method('POST')
# Not sure if these are needed, but it doesn't hurt to have them
self.request_head = self._set_http_method('HEAD')
self.request_put = self._set_http_method('PUT')
self.request_patch = self._set_http_method('PATCH')
self.request_delete = self._set_http_method('DELETE')
def _set_http_method(self, http_method):
def make_request(url, max_tries=3, _try_count=1, custom_source_checks=(), **r_kwargs):
"""Makes the requests to get the source file
Must be accessed using::
self.request_get()
self.request_post()
self.request_head()
self.request_put()
self.request_patch()
self.request_delete()
Args:
max_tries (int, optional): Max times to try to get a source file.
Each time `self.new_profile` will be called which will
try and get a new proxy and new user-agent. Defaults to 3.
_try_count (int, optional): Used to keep track of current number of tries.
Defaults to 1.
custom_source_checks (list, optional): List of tuples, each inner tuple has 3 parts
`(regex, http_status_code, message)`
regex (str): A regex to try and match something in the source file
http status code (int): If regex gets a match, set the request status
code to this value
message (str): Custom status message to set to know this is not a normal
status code being thrown
Defaults to ().
**r_kwargs: Keyword Arguments to be passed to requests.Session().requests
Raises:
ValueError: If max_tries is 0 or negative.
HTTPIgnoreCodeError: If an ignore_code is found
DownloadValueError: If the download failed for any reason and
max_tries was reached
Returns:
object: requests library object
"""
if max_tries < 1:
# TODO: Find a better error to raise
raise ValueError("max_tries must be >= 1")
proxy_used = self.session.proxies.get('http')
if 'proxy' in r_kwargs:
# Proxy is not a valid arg to pass in, so fix it
r_kwargs['proxies'] = self._format_proxy(r_kwargs['proxy'])
proxy_used = r_kwargs['proxies'].get('http')
del r_kwargs['proxy']
elif 'proxies' in r_kwargs:
# Make sure they are in the correct format
r_kwargs['proxies'] = self._format_proxy(r_kwargs['proxies'])
proxy_used = r_kwargs['proxies'].get('http')
time_of_request = datetime.datetime.utcnow().isoformat() + 'Z'
try:
r = self.session.request(http_method, url, **r_kwargs)
if custom_source_checks:
for re_text, status_code, message in custom_source_checks:
if re.search(re_text, r.text):
r.status_code = status_code
r.reason = message
| |
#!/usr/local/bin/python2.6 -tt
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 re
from t_output import CompositeOutput
from t_output_aggregator import create_scope_factory
from t_output_aggregator import OutputContext
from t_output_aggregator import Primitive
from t_output_aggregator import PrimitiveFactory
from t_output_aggregator import Scope
# ---------------------------------------------------------------
# Scope
# ---------------------------------------------------------------
class CppScope (Scope):
# Make sure the line is flagged only when an open brace was printed and
# while it wasn't closed
def acquire(self):
print >>self._out, ' {',
self._out.flag_this_line()
self._out.indent(2)
def release(self):
self._out.unindent(2)
if not self._out.on_flagged_line:
self._out.line_feed()
self._out.flag_this_line(False)
self._out.write('}')
# ---------------------------------------------------------------
# PrimitiveFactory and primitives
# ---------------------------------------------------------------
class Definition(Primitive):
def _write(self, context):
# TODO error in case badly formatted (str(self) doesn't contain
# {name})
fields = {}
if 'symbol_name' in self:
fields['symbol_name'] = self.symbol_name
if 'result_type' in self:
fields['result_type'] = self.result_type
fields['symbol_scope'] = ''
tpl_default_n = 0
tpl_default_list = []
while 'tpl_default_' + str(tpl_default_n) in self:
s = 'tpl_default_' + str(tpl_default_n)
tpl_default_list.append(s)
fields[s] = '= ' + str(getattr(self, s))
tpl_default_n = tpl_default_n + 1
if 'name' not in self:
if not self.in_header:
raise AttributeError('Cannot find mandatory keyword "name"'
' inside defn: ' + repr(self))
txt = str(self)
else:
fields['name'] = self.name
fields['unqualified_name'] = self.name
# if we're in a class, define the {class} field to its name
if 'abspath' in self.parent.opts:
fields['class'] = self.parent.opts.abspath
txt = str(self).format(**fields)
if self.in_header:
context.h.double_space()
else:
context.h.line_feed()
if 'modifiers' in self:
txtsplit = txt.split('\n')
# Ensure that templates end up before static or other modifiers
if len(txtsplit) > 1:
txt = txtsplit[0] + '\n' + self.modifiers + \
' ' + "\n".join(txtsplit[1:])
else:
txt = self.modifiers + ' ' + txt
context.h.write(txt)
write_defn = True
if self.pure_virtual:
context.h.write(" = 0;")
write_defn = False
elif self.override:
context.h.write(" override")
elif self.default:
context.h.write(" = default;")
write_defn = False
elif self.delete:
context.h.write(" = delete;")
write_defn = False
elif self.no_except:
context.h.write(" noexcept")
if not self.in_header and write_defn:
# no custom epilogue? we'll just set our own haha
if 'epilogue' not in self:
self.epilogue = '\n\n'
print >>context.h, ';',
if not 'abspath' in self.parent.opts:
# We're not inside of a class so just ignore namespacing
# Use previously defined txt
pass
else:
for i in tpl_default_list:
fields[i] = ''
fields['symbol_scope'] = self.parent.opts.abspath + '::'
fields['name'] = ''.join((self.parent.opts.abspath,
'::', self.name))
txt = str(self).format(**fields)
if self.no_except:
txt += ' noexcept'
decl_output = self.output or context.impl
# make sure this parameter is set and not assumed
self.in_header = False
# delegate writing of the implementation signature til we
# actually open its scope
self.impl_signature = txt
# self.in_header => write the declaration in the header as well
else:
decl_output = context.h
if self.init_dict:
if 'value' in self:
raise AttributeError("Can't have both value and init_dict"
" in a defn. It's either a constructor"
" or it has a value.")
init_txt = ' : \n ' + ',\n '.join("{0}({1})".format(*x)
for x in self.init_dict.iteritems())
if not self.in_header:
decl_output.write(self.impl_signature)
self._opts['impl_signature'] = ''
decl_output.write(init_txt)
if 'value' in self:
# well, we don't have to store the self.impl_signature
# anymore.
decl_output.line_feed()
decl_output.write(self.impl_signature)
del self._opts['impl_signature']
decl_output.write(self.value)
# set its scope's output to decl_output (self.output will get
# passed to the scope into self.scope.opts.output.. jsyk).
self.output = decl_output
def enter_scope_callback(self, context, scope):
if not scope.opts.in_header:
scope.opts.output.line_feed()
scope.opts.output.write(scope.opts.impl_signature)
class Class(Primitive):
# String Format: type folly abspath::name
# Example: class FOLLY_DEPRECATE("msg") classname::function : extrastuff
_pattern_type = "(?P<type>class |struct )"
_pattern_folly = "(?P<folly>\w+\(.*?\) )*"
_pattern_name = "(?:\s*(?P<name>\w+))"
_pattern_scope = "(?:\s*::{pname})*".format(pname=_pattern_name)
_pattern_abspath = "(?P<abspath>\w+{pscope})".format(pscope=_pattern_scope)
_pattern = "{ptype}{pfolly}{pabspath}".format(
ptype=_pattern_type,
pfolly=_pattern_folly,
pabspath=_pattern_abspath)
_classRegex = re.compile(_pattern, re.S)
def _write(self, context):
# deduce name
m = self._classRegex.match(str(self))
if not m:
raise SyntaxError("C++ class/struct incorrectly defined")
self.name, self.abspath = m.group('name', 'abspath')
if 'abspath' in self.parent.opts and self.parent.opts.abspath:
self.abspath = '::'.join((self.parent.opts.abspath, self.abspath))
# this is magic! Basically what it does it it checks if we're
# already on an empty line. If we are not then we introduce a
# newline before the class defn
context.h.double_space()
if context.impl:
context.impl.double_space()
print >>context.h, self,
# the scope of this will be written to output_h
self.output = context.h
# no custom epilogue? we'll just set our own haha
if 'epilogue' not in self:
self.epilogue = ';'
# basically force two newlines after a class definition if it's
# toplevel (not within another class)
if not issubclass(self.parent.opts.type, Class):
self.epilogue += '\n\n'
class Label(Primitive):
def _write(self, context):
assert issubclass(self.parent.opts.type, Class), \
'Declaring a label not inside a class'
context.output.line_feed()
context.output.unindent(1)
print >>context.output, self
context.output.indent(1)
class Extern(Primitive):
def _write(self, context):
context.h.line_feed()
context.impl.line_feed()
print >>context.h, "extern {0};".format(str(self)),
self.output = context.impl
print >>context.impl, str(self),
if 'value' in self:
print >>context.impl, self.value,
else:
print >>context.impl, ';',
# the epilogue for the scope (which will be in output_cpp)
self.epilogue = ";\n\n"
class ImplOnlyStatement(Primitive):
def _write(self, context):
# set the scope's output to cpp
self.output = context.impl
self.output.line_feed()
self.output.write(str(self))
self.epilogue = ";\n\n"
class SameLineStmt(Primitive):
def _write(self, context):
txt = ' ' + str(self)
context.output.write(txt)
class Case(Primitive):
def _write(self, context):
# should assert issubclass(self.parent.opts.type, Switch), but cbb
# plus we don't have a 'Switch' type so maybe some other time
context.output.line_feed()
if str(self) == 'default':
print >>context.output, 'default:',
else:
print >>context.output, 'case {0}:'.format(str(self)),
def enter_scope_callback(self, context, scope):
context.output.line_feed()
print >>context.output, '{',
context.output.indent(2)
return dict(physical_scope=False)
def exit_scope_callback(self, context, scope):
context.output.line_feed()
if 'nobreak' not in self or not self.nobreak:
print >>context.output, 'break;'
context.output.unindent(2)
print >>context.output, '}',
return dict(physical_scope=False)
class Statement(Primitive):
def _write(self, context):
txt = str(self)
# statements always start on new lines
context.output.line_feed()
context.output.write(txt)
class Catch(Primitive):
def _write(self, context):
txt = str(self)
context.output.line_feed()
context.output.unindent(2)
if len(txt) == 0:
print >> context.output, "} catch {"
else:
print >> context.output, "} catch(" + txt + ") {"
context.output.indent(2)
def enter_scope_callback(self, context, scope):
return dict(physical_scope=False)
def exit_scope_callback(self, context, scope):
context.output.line_feed()
return dict(physical_scope=False)
class Namespace(Primitive):
def __init__(self, parent, path):
super(Namespace, self).__init__(parent, text=None, path=path)
self.epilogue = None
def _write(self, context):
path = filter(None, self.path)
if path:
parts = [r'namespace {0} {{'.format(i) for i in path]
text = ' '.join(parts) + '\n'
self.epilogue = '}' * len(path) + ' // ' + '::'.join(path)
context.outputs.line_feed()
print >>context.outputs, text
def enter_scope_callback(self, context, scope):
return dict(physical_scope=False)
def exit_scope_callback(self, context, scope):
if scope.opts.epilogue:
# namespaces don't have physical_scope cause they have an ending
# text hardcoded into .epilogue by the write_primitive method
context.outputs.double_space()
# => write the epilogue statement for all outputs
print >>context.outputs, scope.opts.epilogue,
return dict(physical_scope=False)
class CppPrimitiveFactory(PrimitiveFactory):
# TODO enforce somehow that each PrimitiveFactory subclass defines a types
# staticvar (method_name => class to instantiate with default parameters)
types = dict(case=Case, defn=Definition, cls=Class, label=Label,
catch=Catch,
extern=Extern, impl=ImplOnlyStatement, sameLine=SameLineStmt)
def namespace(self, ns):
path = ns.split('.')
return Namespace(self._scope(), path)
def stmt(self, text='\n'):
'non-special statement, default to newline'
return Statement(self._scope(), text)
__call__ = stmt
# ---------------------------------------------------------------
# OutputContext
# ---------------------------------------------------------------
class CppOutputContext(OutputContext):
def __init__(self, output_cpp, output_h, output_tcc, header_path,
additional_outputs=[], custom_protocol_h=None,
is_types_context=False):
self.omit_include = False
self._output_cpp = output_cpp
self._output_h = output_h
self._output_tcc = output_tcc
self._additional_outputs = additional_outputs
self._custom_protocol_h = custom_protocol_h
self._header_path = header_path
self._add_common_service_includes_to_tcc = not is_types_context
outputs = [output_h]
if output_cpp:
outputs.append(output_cpp)
if output_tcc:
outputs.append(output_tcc)
outputs.extend(additional_outputs)
for output in outputs:
output.make_scope = create_scope_factory(CppScope, output)
# shorthand to write to all outputs at the same time
self._all_outputs = CompositeOutput(*outputs)
# start writing in the header
self.output = output_h
@property
def h(self):
return self._output_h
@property
def additional_outputs(self):
return self._additional_outputs
@property
def custom_protocol_h(self):
return self._custom_protocol_h
@property
def impl(self):
return self._output_cpp
@property
def tcc(self):
return self._output_tcc
@property
def output(self):
return self._output_crt
@output.setter
def output(self, output):
self._output_crt = output
@property
def outputs(self):
return self._all_outputs
def _enter_scope_handler(self, scope, physical_scope=True):
if scope.parent is None:
# | |
<reponame>NMTHydro/Recharge<filename>utils/EC_and_Soil_Moisture_Analysis/EC_analysis.py
# ===============================================================================
# Copyright 2018 gabe-parrish
#
# 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.
# ===============================================================================
# ============= standard library imports ========================
import os
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from datetime import datetime as dt
from datetime import date
# ============= local library imports ===========================
"""5) VARIABLE LIST
-- TIMEKEEPING
TIMESTAMP_START (YYYYMMDDHHMM): ISO timestamp start of averaging period - short format [YEAR, DTIME, DOY, HRMIN]
TIMESTAMP_END (YYYYMMDDHHMM): ISO timestamp end of averaging period - short format [YEAR, DTIME, DOY, HRMIN]
-- GASES
CO2_1 (umolCO2 mol-1): Carbon Dioxide (CO2) mole fraction (CO2 layer 1 - Top) [CO2top]
CO2_2 (umolCO2 mol-1): Carbon Dioxide (CO2) mole fraction (CO2 layer 2) [CO2]
H2O (mmolH2O mol-1): Water (H2O) vapor mole fraction [H2O]
FC (umolCO2 m-2 s-1): Carbon Dioxide (CO2) flux [FC]
SC (umolCO2 m-2 s-1): Carbon Dioxide (CO2) storage flux [SFC]
-- HEAT
G (W m-2): Soil heat flux [FG]
H (W m-2): Sensible heat flux [H]
LE (W m-2): Latent heat flux [LE]
SH (W m-2): Heat storage in the air [SH]
SLE (W m-2): Latent heat storage flux [SLE]
-- MET_WIND
WD (Decimal degrees): Wind direction [WD]
WS (m s-1): Wind speed [WS]
USTAR (m s-1): Friction velocity [UST]
ZL (adimensional): Stability parameter [ZL]
-- MET_ATM
PA (kPa): Atmospheric pressure [PRESS]
RH (%): Relative humidity, range 0-100 [RH]
TA (deg C): Air temperature [TA]
VPD_PI (hPa): Vapor Pressure Deficit (as measured/calculated by tower teams) [VPD]
-- MET_SOIL
SWC_1 (%): Soil water content (volumetric), range 0-100 (SWC layer 1 - upper) [SWC1]
SWC_2 (%): Soil water content (volumetric), range 0-100 (SWC layer 2 - lower) [SWC2]
TS_1 (deg C): Soil temperature (TS layer 1 - upper) [TS1]
TS_2 (deg C): Soil temperature (TS layer 2 - lower) [TS2]
-- MET_RAD
APAR (umol m-2 s-1): Absorbed PAR [APAR]
FAPAR (%): Fraction of absorbed PAR, range 0-100 [APARpct]
NETRAD (W m-2): Net radiation [Rn]
PPFD_IN (umolPhoton m-2 s-1): Photosynthetic photon flux density, incoming [PAR]
PPFD_OUT (umolPhoton m-2 s-1): Photosynthetic photon flux density, outgoing [PARout]
PPFD_DIF (umolPhoton m-2 s-1): Photosynthetic photon flux density, diffuse incoming [PARdif]
SW_IN (W m-2): Shortwave radiation, incoming [Rg]
SW_OUT (W m-2): Shortwave radiation, outgoing [RgOut]
SW_DIF (W m-2): Shortwave radiation, diffuse incoming [Rgdif]
LW_IN (W m-2): Longwave radiation, incoming [Rgl]
LW_OUT (W m-2): Longwave radiation, outgoing [RglOut]
-- MET_PRECIP
P (mm): Precipitation [PREC]
-- PRODUCTS
NEE_PI (umolCO2 m-2 s-1): Net Ecosystem Exchange (as measured/calculated by tower teams) [NEE]
RECO_PI (umolCO2 m-2 s-1): Ecosystem Respiration (as measured/calculated by tower teams) [RE]
GPP_PI (umolCO2 m-2 s-1): Gross Primary Productivity (as measured/calculated by tower teams) [GPP]"""
def closure_check(ec_dataset, Rn, LE, H, timeseries, daily_average=False):
""""""
if not daily_average:
try:
G = ec_dataset['FG']
# TODO - If there is no ground heat flux, average over 24 hours to negate impact of G. Ask Dan the proper way.
except:
KeyError
print 'No ground heat flux at this station. Consider averaging over a daily period.'
G = 0
try:
stored_H = ec_dataset['SH']
stored_LE = ec_dataset['SLE']
except:
KeyError
print 'No sensible or latent heat storage terms'
stored_H = 0
stored_LE = 0
# Todo - Get Dan's help with this.
closure_error = abs((((Rn-G) - (LE + H)) - (stored_H + stored_LE))/Rn) * 100
print 'median closure error: {}, average closure error {}'.format(
np.median(closure_error.values), np.mean(closure_error.values))
plotter1(timeseries, closure_error)
else:
print 'IGNORE G as we are averaging over a daily time period. We wont bother with stored H or stored LE either'
closure_error = abs(((Rn) - (LE + H)) / Rn) * 100
print 'median closure error: {}, average closure error {}'.format(
np.median(closure_error.values), np.mean(closure_error.values))
plotter1(timeseries, closure_error, daily_average=True)
def plotter1(x, y, daily_average=False):
"""
Plots parameters via a timeseries
:param x:
:param y:
:param daily_average:
:return:
"""
if not daily_average:
x = x.values
y = y.values
plt.plot_date(x, y, fillstyle='none')
plt.show()
else:
y = y.values
plt.plot_date(x, y, fillstyle='none')
plt.show()
def monthly_time_parse(timeseries):
timeseries = pd.to_datetime(timeseries)
mtime_list = []
for i in timeseries:
year = i.year
month = i.month
mtime = date(year, month, 1)
mtime_list.append(mtime)
# get rid of duplicates.
mtime_set = set(mtime_list)
print 'len mtime_set', len(mtime_set)
print 'mtime set \n', mtime_set
# change back to a list and sort
mtime = sorted(list(mtime_set))
print 'mtime sorted\n ', mtime
return mtime
def check_energybal(ec_dataset, timeseries=None, dailyaverage=False, monthlyaverage=False, monthly_cumulative=False):
"""
:param ec_dataset: the full dataset from the EC tower
:param timeseries: a series of datetimes
:return: a plot of the energy balance closure over time for the Eddy Covariance tower.
"""
# if not dailyaverage:
# Rn = ec_dataset['NETRAD']
# H = ec_dataset['H']
# LE = ec_dataset['LE']
# closure_check(ec_dataset, Rn, H, LE, timeseries)
# ===== daily averaging =====
if dailyaverage:
timeseries = timeseries.values
Rn = ec_dataset['NETRAD'].values
H = ec_dataset['H'].values
LE = ec_dataset['LE'].values
# indexed_datetimes = pd.DataFrame(pd.DatetimeIndex(timeseries))
# recreate a dataframe of the variables you want to time average on a dialy timestep
halfhour_data = pd.DataFrame({'timeseries':timeseries, 'Rn':Rn, 'LE':LE, 'H':H})
# resample the dataframe by making the timeseries column into the index and using .resample('d') for day
halfhour_data = halfhour_data.set_index(pd.DatetimeIndex(halfhour_data['timeseries']))
daily_time = halfhour_data.resample('d').mean()
# Get the values of the datetime index as an array
timeseries_daily = daily_time.index.values
# Net Radiation
Rn_av = daily_time['Rn']
# Heat
H_av = daily_time['H']
LE_av = daily_time['LE']
closure_check(ec_dataset, Rn_av, H_av, LE_av, timeseries_daily, daily_average=True)
# ===== monthly averaging =====
elif monthlyaverage:
timeseries = timeseries.values
Rn = ec_dataset['NETRAD'].values
H = ec_dataset['H'].values
LE = ec_dataset['LE'].values
# indexed_datetimes = pd.DataFrame(pd.DatetimeIndex(timeseries))
# recreate a dataframe of the variables you want to time average on a monthly timestep
halfhour_data = pd.DataFrame({'timeseries': timeseries, 'Rn': Rn, 'LE': LE, 'H': H})
# resample the dataframe by making the timeseries column into the index and using .resample('d') for day
halfhour_data = halfhour_data.set_index(pd.DatetimeIndex(halfhour_data['timeseries']))
monthly_time = halfhour_data.resample('m').mean()
# Get the values of the datetime index as an array
timeseries_daily = monthly_time.index.values
# Net Radiation
Rn_av = monthly_time['Rn']
# Heat
H_av = monthly_time['H']
LE_av = monthly_time['LE']
# closure_check(ec_dataset, Rn_av, H_av, LE_av, timeseries_daily, daily_average=True)
# ===== cumulative monthly =====
elif monthly_cumulative:
timeseries = timeseries.tolist()
# print 'timeseries\n', timeseries
Rn = ec_dataset['NETRAD'].values
H = ec_dataset['H'].values
LE = ec_dataset['LE'].values
# indexed_datetimes = pd.DataFrame(pd.DatetimeIndex(timeseries))
# recreate a dataframe of the variables you want to time average on a monthly timestep
halfhour_data = pd.DataFrame({'timeseries': timeseries, 'Rn': Rn, 'LE': LE, 'H': H})
# set the timeseries column to the index so groupby function can group by year and month of the index.
halfhour_data = halfhour_data.set_index(pd.DatetimeIndex(halfhour_data['timeseries']))
halfhour_data['mmh20'] = halfhour_data['LE'] * 7.962e-4
monthly_cumulative = halfhour_data.groupby([lambda x: x.year, lambda x: x.month]).sum()
print 'monthly cumulative \n', monthly_cumulative
print 'cum index', monthly_cumulative.index
# last_month = (halfhour_data.index[-1].year, halfhour_data.index[-1].month)
# last_date = date(last_month[0], last_month[1], 1)
# monthly_time_series = []
# for year in monthly_cumulative.index.levels[0]:
# for month in monthly_cumulative.index.levels[1]:
# # print year, month, 1
# year_month = date(year, month, 1)
# if year_month <= last_date:
# monthly_time_series.append(year_month)
# # TODO - NEEDS TO STOP AT 2018 04
monthly_list = monthly_time_parse(timeseries)
# print 'the monthly cumulatives \n', monthly_cumulative.index.values.tolist
# print 'the time series \n', monthly_time_series
print 'length of the month', len(monthly_list)
print 'lenght of the monthly cumulatives', len(monthly_cumulative.LE)
# try plotting
plt.plot(monthly_list, monthly_cumulative.mmh20)
plt.scatter(monthly_list, monthly_cumulative.mmh20)
plt.show()
# # Get the values of the datetime index as an array
# timeseries_daily = monthly_time.index.values
#
# # Net Radiation
# Rn_av = monthly_time['Rn']
#
# # Heat
# H_av = monthly_time['H']
# LE_av = monthly_time['LE']
def analyze(path, x, y):
"""
:param path: path to a csv containing Ameriflux Dataset
:param x: string corresponding to a dependent variable, usually a timeseries
:param y: string corresponding to a dependent variable, usually a timeseries
:return:
"""
# Get the data from the path and turn the path into a data frame
ec_dataset = pd.read_csv(path, header=2)
# print ec_dataset.head()
print ec_dataset[ec_dataset[y] != -9999].head()
ec_dataset = ec_dataset[ec_dataset[y] != -9999]
if x.startswith("TIMESTAMP"):
a = ec_dataset[x].apply(lambda b: dt.strptime(str(b), '%Y%m%d%H%M'))
else:
a = ec_dataset[x]
b = ec_dataset[y]
unconverted_LE = ec_dataset[y]
| |
one sensor's reading.
df_sensor = get_Yahoo_record(filepath, ['value', 'anomaly'])
# Create first Dataframe, if nothing so far.
if df is None:
df = df_sensor.rename(columns={'value': sensor_id})
else:
if np.any(df['datetime'] != df_sensor['datetime']):
raise ValueError('Join between non-matching dates.')
df[sensor_id] = df_sensor['value']
df['anomaly'] = df['anomaly'] | df_sensor['anomaly']
return df
# Extracts the data present in this directory as the Yahoo dataset. Results are cached.
@cache('temp/cachedir/')
def get_Yahoo_data(directory):
df = load_Yahoo_as_df(directory)
times = df['datetime'].apply(mdates.date2num).to_numpy()
df.drop(['datetime', 'anomaly'], axis=1, inplace=True)
values = df.to_numpy()
sensor_ids = df.columns.to_numpy()
return values, sensor_ids, times
# Returns the times marked as anomalies (label 1), by taking the logical OR over individual sensor anomaly flags.
def get_Yahoo_anomalies(directory):
df = load_Yahoo_as_df(directory)
labels = df['anomaly'].to_numpy()
times = df['datetime'].apply(mdates.date2num).to_numpy()
return times[labels == 1]
# Cannot handle missing data! Use get_ELS_data() below instead.
# Extracts the quantity with no interpolation across any dimensions from the given ELS .DAT file. Results are cached.
@cache('temp/cachedir/')
def get_ELS_data_no_interpolation(els_data_file, quantity, start_time, end_time):
"""
:param els_data_file: The path of the ELS data file. Note that headers must be present in the same directory as well.
:param quantity: The quantity to be extracted.
:param start_time: Start time (as a datetime.datetime object) for readings.
:param end_time: End time (as a datetime.datetime object) for readings.
:return: 3-tuple of (counts, energy_range, times)
"""
# Check input arguments - data file should exist.
if not os.path.exists(els_data_file):
raise OSError('Could not find %s.' % els_data_file)
if start_time > end_time:
raise ValueError('Start time larger than end time.')
# If we have to get all anodes, we will have to jump in and out to get all anodes.
if quantity == 'anodes_all':
return get_all_anode_ELS_data(els_data_file, start_time, end_time)
data = ELS(els_data_file)
# Convert dates to floats for matplotlib
mds = mdates.date2num(data.start_date)
# D for data.
D, scalelabel = parse_quantity(data, quantity)
# If a datetime object, convert to a matplotlib float date.
try:
xmin = mdates.date2num(start_time)
xmax = mdates.date2num(end_time)
except AttributeError:
xmin = start_time
xmax = end_time
# Check if our time range has atleast some overlap with data.
if xmin > np.max(mds):
raise ValueError('Start time after any data.')
if xmax < np.min(mds):
raise ValueError('End time before any data.')
# Prune to desired date range.
keep = np.where((mds >= xmin) & (mds <= xmax))[0]
mds = mds[keep]
D = D[keep[:, None], :]
data.dim1_e = data.dim1_e[keep[:, None], :]
data.dim1_e_upper = data.dim1_e_upper[keep[:, None], :]
data.dim1_e_lower = data.dim1_e_lower[keep[:, None], :]
print 'Data start time:', datetime.strftime(mdates.num2date(np.min(mds)), '%d-%m-%Y/%H:%M')
print 'Data end time:', datetime.strftime(mdates.num2date(np.max(mds)), '%d-%m-%Y/%H:%M')
if not (len(mds) == len(data.dim1_e) == len(D)):
raise ValueError('Invalid number of columns.')
counts = D
energy_ranges = data.dim1_e
times = mds
# Squeeze out superfluous dimensions.
counts, energy_ranges, times = np.squeeze(counts), np.squeeze(energy_ranges), np.squeeze(times)
return counts, energy_ranges, times
# Extracts ELS data from all anodes.
def get_all_anode_ELS_data(els_data_file, start_time, end_time):
samples, energy_ranges, times = zip(*[get_ELS_data(els_data_file, 'anode' + str(anode_number), start_time, end_time) for anode_number in range(1, 9)])
# Validate times.
times = np.array(times)
if not np.allclose(np.tile(times[0], (8, 1)), times, 0.00000001):
raise ValueError('Invalid times.')
# Validate energy ranges.
energy_ranges = np.array(energy_ranges)
if not np.allclose(np.tile(energy_ranges[0], (8, 1)), energy_ranges):
raise ValueError('Invalid energy ranges.')
# Stack up counts.
samples = np.hstack(samples)
# Return just one of the energy ranges and times, since they're all the same.
return samples, energy_ranges[0], times[0]
# Extracts the quantity from the given ELS .DAT file. Results are cached.
@cache('temp/cachedir/')
def get_ELS_data(els_data_file, quantity, start_time, end_time, blur_sigma=0, bin_selection='all', filter='no_filter', filter_size=1):
"""
:param els_data_file: The path of the ELS data file. Note that the .LBL file must be present in the same directory.
:param quantity: The quantity to be extracted.
:param start_time: Start time (as a datetime.datetime object/matplotlib float date) for readings.
:param end_time: End time (as a datetime.datetime object/matplotlib float date) for readings.
:param blur_sigma: Parameter sigma (in timesteps) for the Gaussian kernel.
:param bin_selection: Selection of ELS bins.
:param filter: Filter to be applied bin-wise after the Gaussian blur.
:param filter_size: Size of the filter to be applied after the Gaussian blur.
:return: 3-tuple of (counts, energy_ranges, times)
"""
# Obtain the raw counts.
counts, energy_ranges, times = get_ELS_data_no_interpolation(els_data_file, quantity, start_time, end_time)
# The common energy range, fixed across all files. These are the bin centres of the 32-bin timesteps in the original CAPS ELS data.
common_energy_range = np.array([
2.39710098e+04, 1.75067754e+04, 1.27858037e+04, 9.34583984e+03,
6.82949463e+03, 4.98947949e+03, 3.64505884e+03, 2.66262939e+03,
1.94540930e+03, 1.42190784e+03, 1.03906091e+03, 7.59045593e+02,
5.54588379e+02, 4.04940857e+02, 2.96158539e+02, 2.16495728e+02,
1.58241898e+02, 1.15493149e+02, 8.43917389e+01, 6.18861465e+01,
4.50986481e+01, 3.29373093e+01, 2.40994759e+01, 1.76704102e+01,
1.27102909e+01, 9.25298405e+00, 6.92527056e+00, 4.90834713e+00,
3.74522614e+00, 2.58445168e+00, 1.41556251e+00, 5.79999983e-01,
])
# Rebin counts at each time-step.
new_counts = rebin_to_common_range(counts, energy_ranges, common_energy_range)
# Interpolate (and resample) counts across each bin independently as a function of time.
new_counts, new_times = interpolate_timesteps(new_counts, times, time_resolution_s=2)
# We might have negative values after interpolation. Clip these to 0, so that they make physical sense.
new_counts[new_counts < 0] = 0
# Smooth along time dimension.
new_counts = gaussian_blur(new_counts, blur_sigma)
# If we have to ignore the unpaired bin, remove it now.
if bin_selection == 'ignore_unpaired':
new_counts = new_counts[:, :-1]
common_energy_range = common_energy_range[:-1]
elif bin_selection == 'center':
new_counts = new_counts[:, 15:-7]
common_energy_range = common_energy_range[15:-7]
# Apply the filter.
new_counts = Filter(filter, filter_size).filter(new_counts)
# Since we have the same energy ranges at each timestep, we repeat the common energy range.
new_energy_ranges = np.repeat(common_energy_range[:, np.newaxis], new_counts.shape[0], axis=1).T
# Print bin-wise statistics.
for bin_dimension in range(new_counts.shape[1]):
bin_counts = new_counts[:, bin_dimension]
valid_indices = ~np.isnan(bin_counts)
bin_mean = np.mean(bin_counts[valid_indices])
bin_std = np.std(bin_counts[valid_indices])
print 'Bin %d: Mean = %0.2f, Standard Dev. = %0.2f' % (bin_dimension, bin_mean, bin_std)
# The new time-series has a common energy range of 32 bins across all timesteps, and is regularly sampled.
return new_counts, new_energy_ranges, new_times
# Interpolate the counts as a function of the energy range at each time-step, with linear spline interpolation.
def rebin_to_common_range(counts, energy_ranges, common_energy_range):
# Rebin at each time-step using valid (not 'NaN') entries.
new_counts = np.full((counts.shape[0], common_energy_range.shape[0]), np.nan)
for index, (timestep_counts, timestep_energy_range) in enumerate(zip(counts, energy_ranges)):
valid_bins = ~np.isnan(timestep_energy_range)
# How many valid counts do we have?
num_valid_bins = np.sum(valid_bins)
corresponding_counts = timestep_counts[valid_bins]
# If we have 32 bins, keep them as is.
if num_valid_bins == 32:
new_counts[index] = corresponding_counts
# If we have 63 bins, combine all the adjacent bins, except the last, which is as is.
# Note that the last bin is the one with the lowest mean energy.
elif num_valid_bins == 63:
new_counts[index, :-1] = (corresponding_counts[0:-1:2] + corresponding_counts[1:-1:2])/2
new_counts[index, -1] = corresponding_counts[-1]
# Otherwise, we'll fill this timestep in later.
else:
pass
return new_counts
# Interpolate (and resample) counts across each bin independently as a function of time, with linear spline interpolation.
def interpolate_timesteps(counts, times, time_resolution_s=2):
time_resolution_days = time_resolution_s / (60 * 60 * 24)
resampled_times = np.arange(times[0], times[-1], time_resolution_days)
resampled_counts = np.zeros((resampled_times.shape[0], counts.shape[1]))
# Rebin along each dimension using valid (not 'NaN') entries.
for bin_dimension in range(counts.shape[1]):
bin_counts = counts[:, bin_dimension]
valid_indices = ~np.isnan(bin_counts)
valid_counts = bin_counts[valid_indices]
valid_times = times[valid_indices]
interpolated_counts_function = scipy.interpolate.interp1d(valid_times, valid_counts, kind='slinear', fill_value='extrapolate', assume_sorted=True)
resampled_counts[:, bin_dimension] = interpolated_counts_function(resampled_times)
return resampled_counts, resampled_times
# Outdated. No longer used in get_ELS_data().
# Fill in missing timesteps with extra entries, so that the time-series appears regularly sampled.
def interpolate_timesteps_duplication(counts, energy_ranges, times):
# Obtain the time-resolution of sampling.
time_differences = np.diff(times)
time_resolution = np.min(time_differences)
new_times = times
new_counts = counts
new_energy_ranges = energy_ranges
inserted = 0
# Add in extra entries wherever we have undersampled - that is, whenever we have a timestamp difference >= 2 * minimum timestamp difference (time resolution).
for index in np.where(time_differences >= 2 * time_resolution)[0]:
# Fill in samples between this timestamp and the next timestamp at steps with size equal to the time resolution.
for new_index, timestep in enumerate(np.arange(times[index] + time_resolution, times[index + 1] - time_resolution, time_resolution), start=index + inserted + 1):
new_times = np.insert(new_times, new_index, timestep)
new_counts = np.insert(new_counts, new_index, counts[index], axis=0)
new_energy_ranges = np.insert(new_energy_ranges, new_index, energy_ranges[index], axis=0)
inserted += 1
return new_counts, new_energy_ranges, new_times
# Takes the average of the energies with the num_rank highest counts at each timestep.
def ranked_average_energy(counts, energies, num_rank=5):
"""
:param counts: counts corresponding to energies
:param energies: energy values
:return: numpy array of average of energies chosen
>>> | |
<reponame>kenneth2001/Virus
import asyncio
import requests
from bs4 import BeautifulSoup
from datetime import date, datetime
import discord
import numpy as np
from urllib.error import HTTPError
import yt_dlp as youtube_dl
from discord.ext import commands
import os
from pytz import timezone
from yt_dlp.utils import DownloadError, ExtractorError
from util.log import pretty_output, pretty_print
from util.preprocessing import load_config, load_gif, load_user
import secrets
try:
print('LOADING config.txt')
TOKEN, TIMEZONE, MODE = load_config('config/config.txt')
print('LOADED config.txt\n')
except:
print('ERROR LOADING config.txt\n')
tz = timezone(TIMEZONE)
token = TOKEN #os.environ['token']
# 0: local, 1: repl.it
# For setting up bot on replit.com
if MODE == 1:
from util.keep_alive import keep_alive
os.environ['MPLCONFIGDIR'] = '/tmp/' #"/home/runner/Virus-demo/tmp"
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
elif MODE == 0:
import matplotlib.pyplot as plt
import sympy
else:
print('UNDEFINED MODE')
exit()
try:
print('LOADING gif.json')
gif = load_gif('config/gif.json')
print('LOADED gif.json\n')
except:
print('ERROR LOADING gif.json\n')
try:
print('LOADING user.json')
user = load_user('config/user.json')
print('LOADED user.json\n')
except:
print('ERROR LOADING user.json\n')
ytdl_format_options = {
'format': 'bestaudio/best',
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0'
}
ffmpeg_options = {
'options': '-vn',
"before_options": "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5"
}
# channel_var stores all variable for differnet channels
# key: serverid
# value: 1. activated[bool] - indicate whether the music playing function is activated
# 2. bully[dict] - list of user being bullied
# 3. ctx[object]
# 4. log[list] - log of user entering / leaving voice channels
# 5. playing[bool] - indicate whether the bot is playing music
# 6. queue[list] - list of music to be played
channel_var = {}
# return gif link
def send_gif(msg):
if msg in gif.keys():
return gif[msg]
# Wong Tai Sin Fortune Sticks (黃大仙求籤)
def get_stick(tag):
num = np.random.randint(1, 101)
URL = f'https://andy.hk/divine/wongtaisin/{num}'
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
result = soup.find(id='content')
job_elements = result.find("div", class_="inner-padding col-md-5 col-md-offset-7")
stick_no = job_elements.find('h2', class_='id-color text-center').text
stick_author = job_elements.find_all('h4', class_='text-center')[0].text
stick_content = job_elements.find_all('h4', class_='text-center')[1].text
stick_explain = job_elements.text.split('仙機:')[1].split('解說及記載:')[0]
stick_story = job_elements.text.split('仙機:')[1].split('解說及記載:')[1].split('■')[0]
text = tag + '求得' + stick_no + '\n' + stick_author + '\n\n籤文:\n' + stick_content + '\n\n仙機:' + stick_explain + '\n解說及記載' + stick_story
return text
client = commands.Bot(command_prefix='#', help_command=None)
@client.event
async def on_connect():
print("Bot activated successfully")
async def initialize(server_id: int, ctx: object=None):
"""Initializing channel_var
Args:
server_id (int)
ctx (object, optional): Defaults to None.
"""
global channel_var
info = channel_var.get(server_id, -1)
if info != -1:
if channel_var[server_id]['ctx'] == None and ctx != None:
channel_var[server_id]['ctx'] = ctx
return
else:
channel_var[server_id] = {'ctx':ctx, 'queue':[], 'activated':False, 'playing':True, 'log':[], 'bully':{}}
@client.event
async def on_voice_state_update(member, before, after):
server_id = member.guild.id
await initialize(server_id)
global channel_var
if before.channel is None and after.channel is not None:
channel_var[server_id]['log'].append([datetime.now(tz).strftime('%Y-%m-%d %H:%M:%S'), '*' + str(member) + '* Entered `' + str(after.channel) + '`'])
if before.channel is not None and after.channel is None:
channel_var[server_id]['log'].append([datetime.now(tz).strftime('%Y-%m-%d %H:%M:%S'), '*' + str(member) + '* Leaved `' + str(before.channel) + '`'])
if before.channel is not None and after.channel is not None:
channel_var[server_id]['log'].append([datetime.now(tz).strftime('%Y-%m-%d %H:%M:%S'), '*' + str(member) + '* Leaved `' + str(before.channel)+ '`, Joined `' + str(after.channel) + '`'])
@client.command(name='log')
async def log(ctx):
await initialize(ctx.guild.id, ctx)
global channel_var
if len(channel_var[ctx.guild.id]['log']) == 0:
return
embed = discord.Embed(color = discord.Colour.red())
embed.set_author(name='Log (Recent 20 records)')
for field in channel_var[ctx.guild.id]['log'][-20:]:
embed.add_field(name=field[0], value=field[1], inline=False)
await ctx.send(embed=embed)
async def play_music(ctx):
while not client.is_closed():
global channel_var
if not len(channel_var[ctx.guild.id]['queue']) == 0 and ctx is not None:
server = ctx.message.guild
voice_channel = server.voice_client
if (voice_channel and voice_channel.is_connected() and not voice_channel.is_playing() and channel_var[ctx.guild.id]['playing']) == True:
server = ctx.message.guild
voice_channel = server.voice_client
try:
link = channel_var[ctx.guild.id]['queue'][0][1]
title = channel_var[ctx.guild.id]['queue'][0][2]
player = discord.FFmpegPCMAudio(link, **ffmpeg_options)
voice_channel.play(player)
await ctx.send(f'**Now playing:** {title}')
except DownloadError:
await ctx.send(f'**Download error:** {title}')
del(channel_var[ctx.guild.id]['queue'][0])
await asyncio.sleep(1)
@client.command(name='play')
async def play(ctx, *url):
url = ' '.join(url)
await initialize(ctx.guild.id, ctx)
global channel_var
def music(link):
with youtube_dl.YoutubeDL(ytdl_format_options) as ydl:
info = ydl.extract_info(link, download=False)
# Handle if the url is a playlist
if 'entries' in info:
info = info['entries'][0]
LINK = info['webpage_url']
URL = info['url']
TITLE = info['title']
return LINK, URL, TITLE
if not ctx.message.author.voice: # handle if message author is not inside any voice channel
await ctx.send("**You are not connected to a voice channel**")
return
elif ctx.message.guild.voice_client: # if bot is inside any voice channel
if ctx.message.guild.voice_client.channel != ctx.message.author.voice.channel: # if bot is not inside the author's channel
channel = ctx.message.author.voice.channel
user = await ctx.guild.fetch_member(client.user.id)
ctx.voice_client.pause()
await user.move_to(channel)
ctx.voice_client.resume()
else: # if bot is not inside any voice channel
channel = ctx.message.author.voice.channel
await channel.connect() # connect to message author's channel
server = ctx.message.guild
voice_channel = server.voice_client
if url is None or url == '':
if len(channel_var[ctx.guild.id]['queue']) == 0:
return
else:
try:
link, player_link, title = music(url)
channel_var[ctx.guild.id]['queue'].append([link, player_link, title])
except ExtractorError:
await ctx.send('**Error:** ' + url)
except HTTPError:
await ctx.send('**Error:** ' + url)
except DownloadError:
await ctx.send('**Error:** ' + url)
# activate music playing function
if channel_var[ctx.guild.id]['activated'] == False:
channel_var[ctx.guild.id]['activated'] = True
await play_music(ctx)
@client.command(name='debug')
async def debug(ctx):
def check(m):
return m.author == ctx.message.author
func_token = secrets.token_hex(10)
print("Token:", func_token)
await ctx.send('**Please type in the token displayed in console**')
msg = await client.wait_for("message", check=check)
if msg.content == func_token:
pretty_print(channel_var)
pretty_output(channel_var, filename='tmp.json')
await ctx.send(file=discord.File('tmp.json'))
else:
await ctx.send("**Only admin can use this command**")
@client.command(name='queue')
async def queue_(ctx):
await initialize(ctx.guild.id, ctx)
global channel_var
if len(channel_var[ctx.guild.id]['queue']) == 0:
await ctx.send('**Queue is empty!**')
else:
async with ctx.typing():
await ctx.send('\n'.join([f'{idx}. {item[2]}\n{item[0]}' for idx, item in enumerate(channel_var[ctx.guild.id]['queue'], start=1)]))
@client.command(name='stop')
async def stop(ctx):
voice_client = ctx.message.guild.voice_client
await voice_client.disconnect()
@client.command(name='gpa')
async def gpa(ctx):
x = round(np.random.uniform(3,4) - np.random.normal(0, 1), 2)
text = 4.0 if x > 4 else x
if text >= 3.8:
text = "Predicted GPA: " + str(text)
elif text >= 3.0:
text = "Predicted GPA: " + str(text)
elif text >= 2.5:
text = "Predicted GPA: " + str(text)
else:
text = "Predicted GPA: " + str(text)
tag = "<@" + str(ctx.message.author.id) + ">"
await ctx.message.channel.send(str(text)+tag)
@client.command(name='pause')
async def pause(ctx):
await initialize(ctx.guild.id, ctx)
global channel_var
channel_var[ctx.guild.id]['playing'] = False
if ctx.voice_client is not None:
ctx.voice_client.pause()
await ctx.send('**Paused**')
@client.command(name='resume')
async def resume(ctx):
await initialize(ctx.guild.id, ctx)
global channel_var
channel_var[ctx.guild.id]['playing'] = True
if ctx.voice_client is not None:
ctx.voice_client.resume()
await ctx.send('**Resumed**')
@client.command(name='skip')
async def skip(ctx):
await initialize(ctx.guild.id, ctx)
global channel_var
if ctx.voice_client is not None:
ctx.voice_client.stop()
await ctx.send('**Skipped**')
@client.listen()
async def on_message(message):
author = message.author
author_id = str(message.author.id)
tag = "<@" + str(message.author.id) + ">"
msg = message.content.lower()
if author == client.user:
return
#print('Debugging:', author, msg)
today = date.today()
if user.get(author_id, -1) != -1:
if user[author_id]['date'] != today:
user[author_id]['date'] = today
await message.channel.send(user[author_id]['text'] + tag)
if message.content.startswith('#hello'):
await message.channel.send("Hello World!")
gif = send_gif(msg)
if gif is not None:
await message.channel.send(gif)
@client.command(name='help')
async def help(ctx):
embed = discord.Embed(title="Virus", url="https://github.com/kenneth2001/virus", description="Discord Bot developed by YeeKiiiiii 2021", color=discord.Colour.blue())
embed.set_author(name="Virus", url="https://github.com/kenneth2001/virus", icon_url="https://user-images.githubusercontent.com/24566737/132656284-f0ff6571-631c-4cef-bed7-f575233cbf5f.png")
embed.add_field(name=':musical_note: __Music__', value="""1. `#play [url]` Play music, tested platform: Youtube, Soundcloud
2. `#pause` Pause music
3. `#resume` Resume music
4. `#skip` Play next song
5. `#queue` Display the queue
6. `#stop` Kick the bot from voice channel""", inline=False)
embed.add_field(name=':pencil2: __Graph (Developing)__', value="""1. `#plot` Create simple scatter/line plot""", inline=False)
embed.add_field(name=':black_joker: __Kidding__', value="""1. `#joke [userid] [times] [duration]`
Move a specified user into random voice channels randomly and repeatly
2. `#leavemealone` Stop yourself from being bullied
3. `#save [userid]` Recuse your friend from cyber-bullying""", inline=False)
embed.add_field(name=':man_office_worker: __Other__', value="""1. `#stick` Fortune sticks from Wong Tai Sin
2. `#gpa` Get prediction of your GPA (Maximum: 4.0)
3. `#help` Display a list of all commands aviliable
4. `#credit` Display information of the bot developer
5. `#hello` Return 'hello world'
6. `#ping` Return latency
7. `#log` Display the previous 20 in/out user
8. `#clear` Delete previous 30 messages sent by this bot / started with '#'
9. `#debug` Check parameters (for debugging)""", inline=False)
embed.add_field(name=':new: __New Features (Experimental)__', value="""1. `#when` Return the start time of the bot
2. `#dm [userid] [message]` Send message to any user privately""" )
embed.add_field(name=':frame_with_picture: __GIF__', value="Automatically return GIF if the message matches the following keywords\n`" + '` `'.join(gif.keys()) +'`', inline=False)
embed.set_footer(text="Last updated on 25 December 2021")
await ctx.send(embed=embed)
@client.command(name='ping')
async def ping(ctx):
await ctx.send(f'In {round(client.latency * 1000)}ms')
@client.command(name='stick')
async def stick(ctx):
tag = "<@" + str(ctx.message.author.id) + ">"
text = get_stick(tag)
await ctx.send(text)
@client.command(name='credit')
async def credit(ctx):
await ctx.send('Created By kenneth\nLast Update On 18/9/2021\nhttps://github.com/kenneth2001')
@client.command(name='clear')
async def clear(ctx):
def is_bot(m):
try:
return m.author | |
0x1B, 0x2B, 0x03, 0x02, 0x10, 0x06, 0x03, 0x02, 0x1C, 0x27, 0x07, 0x14, 0x36, 0x0B, 0x03, 0x02, 0x37, 0x08, 0x27, 0x13, 0x10, 0x2B, 0x03, 0x02, 0x20, 0x0D, 0x03, 0x02, 0x36, 0x0C, 0x0C, 0x37, 0x37, 0x03, 0x02, 0x37, 0x17, 0x2C, 0x03, 0x02,
#"Sidewalk crouches at her feet"
0x37, 0x0C, 0x21, 0x2E, 0x17, 0x17, 0x2A, 0x03, 0x02, 0x08, 0x27, 0x20, 0x32, 0x0C, 0x2B, 0x03, 0x02, 0x1A, 0x0D, 0x03, 0x02, 0x1B, 0x34, 0x03, 0x02, 0x28, 0x13, 0x0D, 0x03, 0x02,
#"Like a dog that begs for something sweet"
0x2D, 0x06, 0x2A, 0x03, 0x02, 0x07, 0x14, 0x36, 0x03, 0x02, 0x21, 0x17, 0x22, 0x03, 0x02, 0x36, 0x1A, 0x0D, 0x03, 0x02, 0x3F, 0x07, 0x22, 0x2B, 0x03, 0x02, 0x28, 0x17, 0x17, 0x33, 0x03, 0x02, 0x37, 0x0F, 0x10, 0x1D, 0x0C, 0x2C, 0x03, 0x02, 0x37, 0x2E, 0x13, 0x0D, 0x03, 0x02,
#"Do you hope to make her see, you fool?"
0x21, 0x1F, 0x03, 0x02, 0x19, 0x1F, 0x03, 0x02, 0x1B, 0x35, 0x09, 0x03, 0x02, 0x0D, 0x1F, 0x03, 0x02, 0x10, 0x14, 0x36, 0x2A, 0x03, 0x02, 0x1B, 0x34, 0x03, 0x02, 0x37, 0x13, 0x03, 0x02, 0x04, 0x19, 0x1F, 0x03, 0x02, 0x28, 0x1F, 0x2D, 0x03, 0x02, 0x04, 0x04, 0x03,
#"Do you hope to pluck this dusky jewel?"
0x21, 0x1F, 0x03, 0x02, 0x19, 0x1F, 0x03, 0x02, 0x1B, 0x35, 0x09, 0x03, 0x02, 0x0D, 0x1F, 0x03, 0x02, 0x09, 0x2D, 0x0F, 0x29, 0x03, 0x02, 0x36, 0x0C, 0x0C, 0x37, 0x37, 0x03, 0x02, 0x21, 0x0F, 0x37, 0x2A, 0x13, 0x03, 0x02, 0x0A, 0x1F, 0x07, 0x2D, 0x03, 0x02, 0x04, 0x04, 0x03,
#"Hello, Hello, Hello, Hello, Hello, Hello, Hello"
0x1B, 0x07, 0x2D, 0x35, 0x03, 0x02, 0x04, 0x1B, 0x07, 0x2D, 0x35, 0x03, 0x02, 0x04, 0x1B, 0x07, 0x2D, 0x35, 0x03, 0x02, 0x04, 0x1B, 0x07, 0x2D, 0x35, 0x03, 0x02, 0x04, 0x1B, 0x07, 0x2D, 0x35, 0x03, 0x02, 0x04, 0x1B, 0x07, 0x2D, 0x35, 0x03, 0x02, 0x04, 0x1B, 0x07, 0x2D, 0x35, 0x03, 0x02,
#"I want you"
0x17, 0x06, 0x03, 0x02, 0x2E, 0x18, 0x18, 0x0B, 0x0D, 0x03, 0x02, 0x19, 0x1F, 0x03, 0x02,
#"Hello"
0x1B, 0x07, 0x2D, 0x35, 0x03, 0x02,
#"I need my baby"
0x17, 0x06, 0x03, 0x02, 0x0B, 0x13, 0x15, 0x03, 0x02, 0x10, 0x06, 0x03, 0x02, 0x3F, 0x14, 0x36, 0x3F, 0x13, 0x03, 0x02,
#"Hello, Hello, Hello, Hello"
0x1B, 0x07, 0x2D, 0x35, 0x03, 0x02, 0x04, 0x1B, 0x07, 0x2D, 0x35, 0x03, 0x02, 0x04, 0x1B, 0x07, 0x2D, 0x35, 0x03, 0x02, 0x04, 0x1B, 0x07, 0x2D, 0x35, 0x03, 0x02,
]
#whizanddump ( 'testcase_001.wav', testcase_001 )
#=========================================================================
#Text2Speech rules
#This implementation is derived from the following research:
'''
AUTOMATIC TRANSLATION OF ENGLISH TEXT TO PHONETICS
BY MEANS OF LETTER-TO-SOUND RULES
NRL Report 7948
January 21st, 1976
Naval Research Laboratory, Washington, D.C.
Published by the National Technical Information Service as
document "AD/A021 929".
'''
#additionally, this implementation is derived from a work by
#<NAME> which the author placed into the public domain.
#additionally, this implementation uses additional rules
#presumably developed by <NAME> for his t2a program.
#additionally, I (ziggurat29) added a couple mods of my own here and there
#'rules' are a tuple of ( "left context", "bracket context", "right context", "phoneme list" )
#the way rules work are that the prefix, bracket, suffix must match literally. If they
#do, then the phoneme list is emitted.
#I called the middle part that is being matched and replaced, the 'bracket' context,
#because in the original text the rules are written as:
# a[b]c=d
#the NRL Report 7948 describes a system containing a small-ish set of rules
#that match text patterns, replacing them with phoneme sequences. As
#described, the rules work by attempting to match a text sequence (to be
#replaced) with the match being subject to the 'context' of the surrounding
#characters (which contribute to the match, but are not themselves
#replaced upon match).
#the left and right context matches have some enhancements: literal match for
#alphabetic characters, and the apostrophe, and space, and some meta
#character classes represented by these symbols:
# # one or more vowels
# : zero or more consonants
# ^ one consonant
# . one voiced consonant
# % 'e'-related things at the end of the word '-e', '-ed', '-er', '-es', '-ely', '-ing'
# + 'front' vowels 'e', 'i', 'y'
#note: I originally intended to use regexes instead of this bespoke
#implementation, but there were too many rules to hold all the machines,
#and anyway that would be less easily to port to MCUs.
#To expedite the matching process, the rules are grouped according to the first
#character in the left context. This tweak avoids testing most of the rules
#that have no chance of matching.
#A group of rules is processed linearly, so more specific rules should precede
#more general ones; the last rule should be a catchall for the group.
#The empty string represents 'anything', and the single space string represents
#beginning or end of line' (this works because text is processed word-by-word,
#and is given a leading and trailing space).
#(syntatic sugar for readability)
Silent = []
Anything = ""
Nothing = " "
#symbolic 'constants' for readability
PA1 = 0x00 #PAUSE 1OMS
PA2 = 0x01 #PAUSE 30MS
PA3 = 0x02 #PAUSE 50MS
PA4 = 0x03 #PAUSE 1OOMS
PA5 = 0x04 #PAUSE 200MS
OY = 0x05 #bOY 420MS
AY = 0x06 #skY 260MS
EH = 0x07 #End 70MS
KK3 = 0x08 #Comb 120MS
PP = 0x09 #Pow 21OMS
JH = 0x0a #doDGe 140MS
NN1 = 0x0b #thiN 140MS
IH = 0x0c #sIt 70MS
TT2 = 0x0d #To 140MS
RR1 = 0x0e #Rural 170MS
AX = 0x0f #sUcceed 70MS
AH = 0x0f #(pseudo-phoneme) XXX have to fixup rules; scrutinize this
MM = 0x10 #Milk 180MS
TT1 = 0x11 #parT 1OOMS
DH1 = 0x12 #THey 290MS
IY = 0x13 #sEE 250MS
EY = 0x14 #bEIge 280MS
DD1 = 0x15 #coulD 70MS
UW1 = 0x16 #tO 1OOMS
AO = 0x17 #AUght 1OOMS
AA = 0x18 #hOt 1OOMS
YY2 = 0x19 #Yes 180MS
AE = 0x1a #hAt 120MS
HH1 = 0x1b #He 130MS
BB1 = 0x1c #Business 80MS
TH = 0x1d #THin 180MS
UH = 0x1e #bOOk 100MS
UW2 = 0x1f #fOOd 260MS
AW = 0x20 #OUt 370MS
DD2 = 0x21 #Do 160MS
GG3 = 0x22 #wiG 140MS
VV = 0x23 #Vest 19OMS
GG1 = 0x24 #Got 80MS
SH = 0x25 #SHip 160MS
ZH = 0x26 #aZure 190MS
RR2 = 0x27 #bRain 12OMS
FF = 0x28 #Food 150MS
KK2 = 0x29 #sKy 190MS
KK1 = 0x2a #Can't 160MS
ZZ = 0x2b #Zoo 21OMS
NG = 0x2c #aNchor 220MS
LL = 0x2d #Lake 110MS
WW = 0x2e #Wool 180MS
XR = 0x2f #repAIR 360MS
WH = 0x30 #WHig 200MS
YY1 = 0x31 #Yes 130MS
CH = 0x32 #CHurch 190MS
ER1 = 0x33 #fIR 160MS
ER2 = 0x34 #fIR 300MS
OW = 0x35 #bEAU 240MS
DH2 = 0x36 #THey 240MS
SS = 0x37 #veSt 90MS
NN2 = 0x38 #No 190MS
HH2 = 0x39 #Hoe 180MS
OR = 0x3a #stORe 330MS
AR = 0x3b #alARm 290MS
YR = 0x3c #clEAR 350MS
GG2 = 0x3d #Guest 40MS
EL = 0x3e #saddLe 190MS
BB2 = 0x3f #Business 50MS
#0 - punctuation
r_punc = [
[ Anything, " ", Anything, [ PA4, PA3, ] ],
[ Anything, "-", Anything, [ PA4, ] ],
[ ".", "'s", Anything, [ ZZ, ] ],
[ "#:.e", "'s", Anything, [ ZZ, ] ],
[ "#", "'s", Anything, [ ZZ, ] ],
[ Anything, "'", Anything, [ PA1, ] ],
[ Anything, ";", Anything, [ PA5, ] ],
[ Anything, ":", Anything, [ PA5, ] ],
[ Anything, ",", Anything, [ PA5, ] ],
[ Anything, ".", "#", Silent ],
[ Anything, ".", "^", Silent ],
[ Anything, ".", Anything, [ PA5, PA5, PA4, ] ],
[ Anything, "?", Anything, [ PA5, PA5, PA4, ] ],
[ Anything, "!", Anything, [ PA5, PA5, PA4, ] ],
]
#1 - a
r_a = [
[ Nothing, "a", Nothing, [ EH, EY, ] ],
[ Anything, "ahead", Anything, [ AX, HH1, EH, EH, DD1, ] ],
[ Anything, "apropos", Anything, [ AE, PP, ER1, OW, PP, OW, ] ],
[ Anything, "ass", "h", [ AE, AE, SS, SS, ] ],
[ Anything, "allege", Anything, [ AX, LL, EH, DD2, JH, ] ],
[ Anything, "again", Anything, [ AX, GG3, EH, EH, NN1, ] ],
[ Nothing, "able", Anything, [ EY, HH1, BB2, AX, LL, ] ],
[ Nothing, "above", Nothing, [ AX, BB2, AX, AX, VV, HH1, ] ],
[ Nothing, "acro", ".", [ AE, HH1, KK1, ER1, OW, ] ],
[ Nothing, "are", Nothing, [ AA, ER2, ] ],
[ Nothing, "ally", Nothing, [ AE, AE, LL, AY, ] ],
[ Anything, "atomic", Anything, [ AX, TT2, AA, MM, PA1, IH, KK1, ] ],
[ Anything, "arch", "#v", [ AX, AX, ER1, PA1, KK1, IH, ] ],
[ Anything, "arch", "#.", [ AX, AX, ER1, CH, IH, ] ],
[ Anything, "arch", "#^", [ AX, AX, ER1, KK1, PA1, IH, ] ],
[ Anything, "argue", Anything, [ AA, ER2, GG1, YY2, UW2, ] ],
[ Nothing, "abb", Anything, [ AX, AX, BB2, ] ],
[ Nothing, "ab", Anything, [ AE, AE, BB1, PA2, ] ],
[ Nothing, "an", "#", [ AE, NN1, ] ],
[ Nothing, "allo", "t", [ AE, LL, AA, ] ],
[ Nothing, "allo", "w", [ AE, LL, AW, ] ],
[ Nothing, "allo", Anything, [ AE, LL, OW, ] ],
[ Nothing, "ar", "o", [ AX, ER2, ] ],
[ "#:", "ally", Anything, [ PA1, AX, LL, IY, ] ],
[ "^", "able", Anything, [ PA1, EY, HH1, BB2, AX, LL, ] ],
[ Anything, "able", Anything, [ PA1, AX, HH1, BB2, AX, LL, ] ],
[ "^", "ance", Anything, [ PA1, AE, NN1, SS, ] ],
[ Anything, "air", Anything, [ EY, XR, ] ],
[ Anything, "aic", Nothing, [ EY, IH, KK1, ] ],
[ "#:", "als", Nothing, [ AX, LL, ZZ, ] ],
[ Anything, "alk", Anything, [ AO, AO, KK1, ] ],
[ Anything, "arr", Anything, [ AA, ER1, ] ],
[ Anything, "ang", "+", [ EY, NN1, JH, ] ],
[ " :", "any", Anything, [ EH, NN1, IY, ] ],
[ Anything, "ary", Nothing, [ PA1, AX, ER2, IY, ] ],
[ "^", "as", "#", [ EY, SS, ] ],
[ "#:", "al", Nothing, [ AX, LL, ] ],
[ Anything, "al", "^", [ AO, LL, ] ],
[ Nothing, "al", "#", [ EH, EY, LL, ] ],
[ "#:", "ag", "e", [ IH, JH, ] ],
[ Anything, "ai", Anything, [ EH, EY, ] ],
[ Anything, "ay", Anything, [ EH, EY, ] ],
[ Anything, "au", Anything, [ AO, AO, ] ],
[ Anything, "aw", Nothing, [ AO, AO, ] ],
[ Anything, "aw", "^", [ AO, AO, ] ],
[ ":", "ae", Anything, [ EH, ] ],
[ Anything, "a", "tion", [ EY, ] ],
[ "c", "a", "bl", [ EH, EY, ] ],
[ "c", "a", "b#", [ AE, AE, ] ],
[ "c", "a", "pab", [ EH, EY, ] ],
[ "c", "a", "p#", [ AE, AE, ] | |
None:
"""
This method is used to retrieve a list of existing properties that match the given property ID in the form "<device access ID>.<device ID>.<property ID>". The wildcard
character "*" is supported for <device access ID> and <device ID> fields.
For example "*.inv.3136" represents all properties with ID 3136 on the device with ID "inv" connected through any device access, "demo.*.3136" represents all properties
with ID 3136 on any device that disposes that property connected through the device access "demo" and finally "*.*.3136" represents all properties with ID 3136 on any
device that disposes that property connected through any device access.
The status of the read operation and the actual value of the property are reported using the on_properties_found() callback.
:param property_id: The search wildcard ID.
:raises SIProtocolError: If the client is not connected or not yet authorized.
"""
# Ensure that the client is in the CONNECTED state.
self.__ensure_in_state(SIConnectionState.CONNECTED)
# Encode and send FIND PROPERTIES message to gateway.
self.__ws.send(super(SIAsyncGatewayClient, self).encode_find_properties_frame(property_id))
def read_property(self, property_id: str) -> None:
"""
This method is used to retrieve the actual value of a given property from the connected gateway. The property is identified by the property_id parameter.
The status of the read operation and the actual value of the property are reported using the on_property_read() callback.
:param property_id: The ID of the property to read in the form '{device access ID}.{device ID}.{property ID}'.
:raises SIProtocolError: If the client is not connected or not yet authorized.
"""
# Ensure that the client is in the CONNECTED state.
self.__ensure_in_state(SIConnectionState.CONNECTED)
# Encode and send READ PROPERTY message to gateway.
self.__ws.send(super(SIAsyncGatewayClient, self).encode_read_property_frame(property_id))
def read_properties(self, property_ids: List[str]) -> None:
"""
This method is used to retrieve the actual value of multiple property at the same time from the connected gateway. The properties are identified by the property_ids
parameter.
The status of the multiple read operations and the actual value of the properties are reported using the on_properties_read() callback.
:param property_ids: The IDs of the properties to read in the form '{device access ID}.{device ID}.{property ID}'.
:raises SIProtocolError: If the client is not connected or not yet authorized.
"""
# Ensure that the client is in the CONNECTED state.
self.__ensure_in_state(SIConnectionState.CONNECTED)
# Encode and send READ PROPERTIES message to gateway.
self.__ws.send(super(SIAsyncGatewayClient, self).encode_read_properties_frame(property_ids))
def write_property(self, property_id: str, value: any = None, flags: SIWriteFlags = None) -> None:
"""
The write_property method is used to change the actual value of a given property. The property is identified by the property_id parameter and the new value is passed by the
optional value parameter.
This value parameter is optional as it is possible to write to properties with the data type "Signal" where there is no actual value written, the write operation rather
triggers an action on the device.
The status of the write operation is reported using the on_property_written() callback.
:param property_id: The ID of the property to write in the form '{device access ID}.{<device ID}.{<property ID}'.
:param value: Optional value to write.
:param flags: Write flags, See SIWriteFlags for details, if not provided the flags are not send by the client and the gateway uses the default flags
(SIWriteFlags.PERMANENT).
:raises SIProtocolError: If the client is not connected or not yet authorized.
"""
# Ensure that the client is in the CONNECTED state.
self.__ensure_in_state(SIConnectionState.CONNECTED)
# Encode and send WRITE PROPERTY message to gateway.
self.__ws.send(super(SIAsyncGatewayClient, self).encode_write_property_frame(property_id, value, flags))
def subscribe_to_property(self, property_id: str) -> None:
"""
This method can be used to subscribe to a property on the connected gateway. The property is identified by the property_id parameter.
The status of the subscribe request is reported using the on_property_subscribed() callback.
:param property_id: The ID of the property to subscribe to in the form '{device access ID}.{device ID}.{property ID}'.
:raises SIProtocolError: If the client is not connected or not yet authorized.
"""
# Ensure that the client is in the CONNECTED state.
self.__ensure_in_state(SIConnectionState.CONNECTED)
# Encode and send SUBSCRIBE PROPERTY message to gateway.
self.__ws.send(super(SIAsyncGatewayClient, self).encode_subscribe_property_frame(property_id))
def subscribe_to_properties(self, property_ids: List[str]) -> None:
"""
This method can be used to subscribe to multiple properties on the connected gateway. The properties are identified by the property_ids parameter.
The status of the subscribe request is reported using the on_properties_subscribed() callback.
:param property_ids: The list of IDs of the properties to subscribe to in the form '{device access ID}.{device ID}.{property ID}'.
:raises SIProtocolError: If the client is not connected or not yet authorized.
"""
# Ensure that the client is in the CONNECTED state.
self.__ensure_in_state(SIConnectionState.CONNECTED)
# Encode and send SUBSCRIBE PROPERTIES message to gateway.
self.__ws.send(super(SIAsyncGatewayClient, self).encode_subscribe_properties_frame(property_ids))
def unsubscribe_from_property(self, property_id: str) -> None:
"""
This method can be used to unsubscribe from a property on the connected gateway. The property is identified by the property_id parameter.
The status of the unsubscribe request is reported using the on_property_unsubscribed() callback.
:param property_id: The ID of the property to unsubscribe from in the form '{device access ID}.{device ID}.{property ID}'.
:raises SIProtocolError: If the client is not connected or not yet authorized.
"""
# Ensure that the client is in the CONNECTED state.
self.__ensure_in_state(SIConnectionState.CONNECTED)
# Encode and send UNSUBSCRIBE PROPERTY message to gateway.
self.__ws.send(super(SIAsyncGatewayClient, self).encode_unsubscribe_property_frame(property_id))
def unsubscribe_from_properties(self, property_ids: List[str]) -> None:
"""
This method can be used to unsubscribe from multiple properties on the connected gateway. The properties are identified by the property_ids parameter.
The status of the unsubscribe request is reported using the on_properties_unsubscribed() callback.
:param property_ids: The list of IDs of the properties to unsubscribe from in the form '{device access ID}.{device ID}.{property ID}'.
:raises SIProtocolError: If the client is not connected or not yet authorized.
"""
# Ensure that the client is in the CONNECTED state.
self.__ensure_in_state(SIConnectionState.CONNECTED)
# Encode and send UNSUBSCRIBE PROPERTY message to gateway.
self.__ws.send(super(SIAsyncGatewayClient, self).encode_unsubscribe_properties_frame(property_ids))
def read_datalog_properties(self, from_: datetime.datetime = None, to: datetime.datetime = None) -> None:
"""
This method is used to retrieve the list of IDs of all properties for whom data is logged on the gateway. If a time window is given using from and to, only data in this
time windows is considered.
The status of the operation is the list of properties for whom logged data is available are reported using the on_datalog_properties_read() callback.
:param from_: Optional date and time of the start of the time window to be considered.
:param to: Optional date and time of the end of the time window to be considered.
:raises SIProtocolError: On a connection, protocol of framing error.
"""
# Ensure that the client is in the CONNECTED state.
self.__ensure_in_state(SIConnectionState.CONNECTED)
# Encode and send READ DATALOG message to gateway.
self.__ws.send(super(SIAsyncGatewayClient, self).encode_read_datalog_frame(None, from_, to, None))
def read_datalog(self, property_id: str, from_: datetime.datetime = None, to: datetime.datetime = None, limit: int = None) -> None:
"""
This method is used to retrieve all or a subset of logged data of a given property from the gateway.
The status of this operation and the respective values are reported using the on_datalog_read_csv() callback.
:param property_id: Global ID of the property for which the logged data should be retrieved. It has to be in the form '{device access ID}.{device ID}.{property ID}'.
:param from_: Optional date and time from which the data has to be retrieved, defaults to the oldest value logged.
:param to: Optional date and time to which the data has to be retrieved, defaults to the current time on the gateway.
:param limit: Using this optional parameter you can limit the number of results retrieved in total.
:raises SIProtocolError: If the client is not connected or not yet authorized.
"""
# Ensure that the client is in the CONNECTED state.
self.__ensure_in_state(SIConnectionState.CONNECTED)
# Encode and send READ DATALOG message to gateway.
self.__ws.send(super(SIAsyncGatewayClient, self).encode_read_datalog_frame(property_id, from_, to, limit))
def read_messages(self, from_: datetime.datetime = None, to: datetime.datetime = None, limit: int = None) -> None:
"""
The read_messages method can be used to retrieve all or a | |
assert ((np.abs(tmp)) < 1e-5).all()
# vH ~ uH
cur_vH = vH_0
next_vH = np.reshape(vHs_1_T_opt[0, :].T, (self.n_vH, 1))
next_uH = np.reshape(uHs_1_T_opt[0, :].T, (self.n_uH, 1))
assert next_vH.shape == cur_vH.shape == next_uH.shape
tmp = next_vH - cur_vH - self.dt * next_uH / self.mass
assert ((np.abs(tmp)) < 1e-5).all()
for i in range(horizon - 1):
cur_vH = vHs_1_T_opt[i, :].T
next_vH = vHs_1_T_opt[i+1, :].T
next_uH = uHs_1_T_opt[i+1, :].T
assert next_vH.shape == cur_vH.shape == next_uH.shape
tmp = next_vH - cur_vH - self.dt * next_uH / self.mass
assert ((np.abs(tmp)) < 1e-5).all()
# --------------------
if plot:
# (horizon + 1) x npH
pHs_0_T_int = np.zeros((dts.shape[0], self.n_pH))
for i in range(self.n_pH):
tmp = interpolate.splev(x=dts, tck=pw_spliness[i], ext=2)
assert pHs_0_T_int[:, i].shape == tmp.shape
pHs_0_T_int[:, i] = tmp
ref = pHs_0_T_ref
intp = pHs_0_T_int
opt = np.vstack((pH_0.T, pHs_1_T_opt))
assert self.n_pH == 2
fig, ax = plt.subplots()
ax.plot(opt[:, 0].squeeze(), opt[:, 1].squeeze(), '.', label='opt')
ax.plot(ref[:, 0].squeeze(), ref[:, 1].squeeze(), 'o', label='ref')
ax.plot(pH_0.squeeze()[0], pH_0.squeeze()[1], 'x', label='pH_0')
if pH_mode in ["pH_avoid_pR", "pH_move_to_pR"]:
ax.plot(pR_0.squeeze()[0], pR_0.squeeze()[1], 'x', label='pR_0')
ax.legend(loc='upper right', ncol=2)
plt.show()
plt.cla()
plt.clf()
plt.close()
fig, ax = plt.subplots()
ax.plot(dts, opt, 'o', label='opt')
ax.plot(dts, intp, label="intp_ref")
ax.legend(loc='upper right', ncol=2)
plt.show()
plt.cla()
plt.clf()
plt.close()
for i in range(self.n_pH):
pHs_0_T_opt = np.vstack(
(np.reshape(pH_0, (self.n_pH)), pHs_1_T_opt))
vHs_0_T_opt = np.vstack(
(np.reshape(vH_0, (self.n_vH)), vHs_1_T_opt))
uHs_0_T_opt = np.vstack((np.zeros(self.n_vH), uHs_1_T_opt))
# plt.figure()
fig, axs = plt.subplots(3)
fig.tight_layout()
axs[0].plot(dts, pHs_0_T_opt[:, i], 'ro')
axs[0].plot(dts, pHs_0_T_opt[:, i], 'g')
axs[0].set_title('pHs_0_T_opt')
axs[1].plot(dts, vHs_0_T_opt[:, i], 'ro')
axs[1].plot(dts, vHs_0_T_opt[:, i], 'g')
axs[1].set_title('vHs_0_T_opt')
axs[2].plot(dts, uHs_0_T_opt[:, i], 'ro')
axs[2].plot(dts, uHs_0_T_opt[:, i], 'g')
axs[2].set_title('uHs_0_T_opt')
plt.show()
plt.cla()
plt.clf()
plt.close()
return pHs_1_T_opt, vHs_1_T_opt, uHs_1_T_opt
def generate_boundary_csts_bounds(self, pHs_1_T, vHs_1_T,
uHs_1_T, horizon,
pw_spliness, terminal_goal_cst):
"""
Formulate symbolic constraint for the boundary conditions.
Parameters
----------
pHs_1_T: horizon x n_pH, symbolic human positions.
vHs_1_T: horizon x n_vH, symbolic human velocities.
uHs_1_T: horizon x n_uH, symbolic controls.
horizon: int, horizon of planning.
pw_spliness: the reference trajectory, used to extract the goal.
terminal_goal_cst: whether to set goal as a terminal constraint.
Returns
----------
g: constraint variables.
lbg: constraint lower bounds.
ubg: constraint upper bounds.
g_name: constraint names.
"""
self.check_shapes(pHs_1_T=pHs_1_T, vHs_1_T=vHs_1_T,
uHs_1_T=uHs_1_T, horizon=horizon)
g = []
lbg = []
ubg = []
g_name = []
# ui bound
if use_human_ui_bound:
uH_min = (self.uH_min + self.feas_tol).tolist()
uH_max = (self.uH_max - self.feas_tol).tolist()
for i in range(horizon - 1):
# nuH x 1
ui = uHs_1_T[i, :].T
g = vertcat(g, ui)
lbg += uH_min
ubg += uH_max
for j in range(self.n_uH):
g_name += ["u_bd_i={}_dim={}".format(i, j)]
# print("cur={}".format(i))
# uH terminal = 0
u_T = uHs_1_T[horizon-1, :].T
g = vertcat(g, u_T)
# We need vR terminal = 0, which will be constrained later.
# So we don't need u terminal to 0.
lbg += uH_min
ubg += uH_max
# lbg += [-1e-9] * self.n_uH
# ubg += [1e-9] * self.n_uH
for j in range(self.n_uH):
g_name += ["u_bd_i={}_dim={}".format(horizon-1, j)]
# print("cur={}".format(horizon-1))
# pH bound
pH_min = (self.pH_min + self.feas_tol).tolist()
pH_max = (self.pH_max - self.feas_tol).tolist()
for i in range(horizon - 1):
# n_pH x 1
pH = pHs_1_T[i, :].T
g = vertcat(g, pH)
lbg += pH_min
ubg += pH_max
for j in range(len(pH_min)):
g_name += ["pH_bd_i={}_dim={}".format(i, j)]
# print("cur={}".format(i))
# pH terminal = goal
pH_T = pHs_1_T[horizon - 1, :].T
if terminal_goal_cst:
goal = np.zeros((self.n_pH, 1))
for i in range(self.n_pH):
tmp = interpolate.splev(x=[horizon * self.dt],
tck=pw_spliness[i], ext=2)
assert tmp.shape == goal[i, :].shape
goal[i, :] = tmp
g = vertcat(g, goal - pH_T)
lbg += [-1e-9] * self.n_pH
ubg += [1e-9] * self.n_pH
for j in range(self.n_pH):
g_name += ["pH_bd_goal_i={}_dim={}".format(horizon, j)]
else:
g = vertcat(g, pH_T)
lbg += pH_min
ubg += pH_max
for j in range(len(pH_min)):
g_name += ["pH_bd_i={}_dim={}".format(i, j)]
# print("cur={}".format(horizon - 1))
# vH bound
vH_min = (self.vH_min + self.feas_tol).tolist()
vH_max = (self.vH_max - self.feas_tol).tolist()
for i in range(horizon - 1):
vH = vHs_1_T[i, :].T
g = vertcat(g, vH)
lbg += vH_min
ubg += vH_max
for j in range(len(vH_min)):
g_name += ["vH_bd_i={}_dim={}".format(i, j)]
# print("cur={}".format(i))
# vH terminal = 0
vH_T = vHs_1_T[horizon - 1, :].T
g = vertcat(g, vH_T)
lbg += [-1e-9] * self.n_vH
ubg += [1e-9] * self.n_vH
for j in range(self.n_vH):
g_name += ["vH_bd_i={}_dim={}".format(horizon-1, j)]
# print("cur={}".format(self.h_safe - 1))
assert g.shape[0] == len(lbg) == len(ubg) == len(g_name)
return g, lbg, ubg, g_name
def generate_dyn_csts(self, pHs_1_T, vHs_1_T, uHs_1_T,
pH_0, vH_0, horizon):
"""
Formulate symbolic constraint for the dynamics.
Parameters
----------
pHs_1_T: horizon x n_pH, symbolic human positions.
vHs_1_T: horizon x n_vH, symbolic human velocities.
uHs_1_T: horizon x n_uH, symbolic controls.
pH_0: n_pHx1, the initial human position.
vH_0: n_pHx1, the initial human velocity.
horizon: int, horizon of planning.
Returns
----------
g: constraint variables.
lbg: constraint lower bounds.
ubg: constraint upper bounds.
g_name: constraint names.
"""
self.check_shapes(pHs_1_T=pHs_1_T, vHs_1_T=vHs_1_T, uHs_1_T=uHs_1_T,
pH_0=pH_0, vH_0=vH_0, horizon=horizon)
g = []
lbg = []
ubg = []
g_name = []
# pH ~ vH
cur_pH = pH_0
next_pH = pHs_1_T[0, :].T
next_vH = vHs_1_T[0, :].T
tmp = next_pH - cur_pH - self.dt * next_vH
assert next_pH.shape == cur_pH.shape == next_vH.shape\
== tmp.shape == vH_0.shape
g = vertcat(g, tmp)
lbg += [-1e-9] * self.n_pH
ubg += [1e-9] * self.n_pH
for j in range(self.n_pH):
g_name += ["pH_dyn_t-1_vs_t0_dim={}".format(j)]
# print("cur={}, next={}".format(-1, 0))
for i in range(horizon - 1):
cur_pH = pHs_1_T[i, :].T
next_pH = pHs_1_T[i+1, :].T
next_vH = vHs_1_T[i+1, :].T
tmp = next_pH - cur_pH - self.dt * next_vH
assert next_pH.shape == cur_pH.shape == next_vH.shape == tmp.shape
g = vertcat(g, tmp)
lbg += [-1e-9] * self.n_pH
ubg += [1e-9] * self.n_pH
for j in range(self.n_pH):
g_name += ["pH_dyn_t{}_vs_t{}_dim={}".format(i, i+1, j)]
# print("cur={}, next={}".format(i, i+1))
# vH ~ uH
cur_vH = vH_0
next_vH = vHs_1_T[0, :].T
next_uH = uHs_1_T[0, :].T
tmp = next_vH - cur_vH - self.dt * next_uH / self.mass
assert next_uH.shape == next_vH.shape == cur_vH.shape == tmp.shape
g = vertcat(g, tmp)
lbg += [-1e-9] * self.n_vH
ubg += [1e-9] * self.n_vH
for j in range(self.n_vH):
g_name += ["vH_dyn_t-1_vs_t0_dim={}".format(j)]
# print("cur={}, next={}".format(-1, 0))
for i in range(horizon - 1):
cur_vH = vHs_1_T[i, :].T
next_vH = vHs_1_T[i+1, :].T
next_uH = uHs_1_T[i+1, :].T
tmp = next_vH - cur_vH - self.dt * next_uH / self.mass
assert next_uH.shape == next_vH.shape == cur_vH.shape == tmp.shape
g = vertcat(g, tmp)
lbg += [-1e-9] * self.n_vH
ubg += [1e-9] * self.n_vH
for j in range(self.n_vH):
g_name += ["vH_dyn_t{}_vs_t{}_dim={}".format(i, i+1, j)]
# print("cur={}, next={}".format(i, i+1))
assert g.shape[0] == len(lbg) == len(ubg) == len(g_name)
return g, lbg, ubg, g_name
def generate_coll_avoid_cur_pR_csts(self, pHs_1_T, cur_pR, horizon):
"""
Formulate symbolic constraint for the collision avoidance constraints.
Parameters
----------
pHs_1_T: horizon x n_pH, symbolic human positions.
cur_pR: n_pHx1, current robot position,
used to produce "human avoiding robot" behavior.
horizon: int, horizon of planning.
Returns
----------
g: constraint variables.
lbg: constraint lower bounds.
ubg: constraint upper bounds.
g_name: constraint names.
"""
self.check_shapes(pHs_1_T=pHs_1_T, pH_0=cur_pR, horizon=horizon)
g = []
lbg = []
ubg = []
g_name = []
for t in range(horizon):
# 2x1
pH = pHs_1_T[t, :].T
assert pH.shape == cur_pR.shape
assert pH.shape[1] == 1
tmp = pH - cur_pR
d_sqr = mtimes(tmp.T, tmp)
g = vertcat(g, d_sqr)
lbg += [(self.pH_view_pH_pR_min_sep_dist)**2+self.feas_tol]
ubg += [cas.inf]
g_name += ["pH_pR_d_i={}".format(t)]
assert g.shape[0] == len(lbg) == len(ubg) == len(g_name)
return g, lbg, ubg, g_name
def generate_cost_function(self, pHs_1_T, uHs_1_T, horizon, pw_spliness,
track_traj=True, pTarget=None, pAvoid=None):
"""
Formulate symbolic cost function.
1. Stay close to the reference trajectory = pw_spliness.
2. Control cost.
3. Stay close to pTarget.
4. Stay far from pAvoid.
Parameters
----------
pHs_1_T: horizon x n_pH, symbolic human positions.
uHs_1_T: horizon x n_uH, symbolic controls.
horizon: int, horizon of planning.
pw_spliness: the reference trajectory.
track_traj: bool, whether to track the reference trajectory or not.
pTarget: n_pHx1, stay close to pTarget across the entire horizon
pAvoid: n_pHx1, stay far from pAvoid across the entire horizon
Returns
----------
cost: symbolic cost variable.
"""
self.check_shapes(pHs_1_T=pHs_1_T, uHs_1_T=uHs_1_T, horizon=horizon)
cost = 0
domain_max_t = pw_spliness[0][0][-1]
assert domain_max_t == pw_spliness[1][0][-1]
# Tracking cost
if track_traj:
ts = []
# Note: horizon + 1 = the length of traj including x0.
for i in range(horizon):
# | |
# load extern modules
import gym
import csv
import time
import numpy as np
from stable_baselines.bench import Monitor
from supervisors.utils import distance_from_obstacles
from env.utils import obs_lidar_pseudo
import threading
from supervisors.cbf import initialize_gp_dynamics, predict_successor_state_gp, initialize_svm_prediction
from supervisors.cbf import initialize_svm_prediction_gp
from operator import itemgetter
from skopt.space import Space
from skopt.sampler import Grid
# from qpsolvers import solve_qp
class Supervisor(Monitor):
"""
A monitor wrapper for Gym environments to save collisions events
Parameters:
env (gym.Env): The environment
filename (Optional[str]): the location to save a log file, can be None for no log
"""
def __init__(self,
env: gym.Env,
filename: str,
safety_distance: float or None,
visibility: float,
safe_info: bool,
safe_states: bool,
supervisor: str,
coordinates_static_obstacles: np.array,
lidar_num_bins: int,
which_static: int,
record_svm_gp: bool,
cbf_quadratic: bool,
cbf_learn_online: bool,
rewards: np.array or None,
num_prior_data_cbf: str or None,
search_space: str or None,
scale_reward: bool):
super(Supervisor, self).__init__(env=env, filename=filename)
self.safety_distance = safety_distance
self.visibility = visibility
self.supervisor = supervisor
self.lidar_num_bins = lidar_num_bins
self.Supervised = 0
self.Intervention = 0
self.SafelyDone = 0
self.scale_reward = scale_reward
self.record_svm_gp = record_svm_gp
self.Crashed = 0
self.last_teacher_crash = 0
self.timeOut = 0
self.which_static = which_static
self.safe_states = safe_states
self.total_distance = 0
if supervisor == 'cbf-gp-logical' or supervisor == 'cbf-gp-svm':
if num_prior_data_cbf is None:
num_prior_data_cbf = '2k'
self.gp = initialize_gp_dynamics('2k')
if supervisor == 'cbf-gp-svm':
if num_prior_data_cbf is None:
num_prior_data_cbf = 100000
self.svm = initialize_svm_prediction_gp(num_prior_data=num_prior_data_cbf)
self.unsafe_threshold = 0.5
search_space = 'grid'
if supervisor == 'cbf-svm':
if num_prior_data_cbf is None:
num_prior_data_cbf = 2000
self.svm = initialize_svm_prediction(num_prior_data=num_prior_data_cbf)
self.unsafe_threshold = 0.6
if supervisor == 'cbf-gp-logical':
self.unsafe_threshold = 0.85
search_space = 'random'
self.cbf_quadratic = cbf_quadratic
if search_space == 'grid':
space = Space([(-1., 1.), (-1., 1.)])
grid = Grid(border="include", use_full_layout=False)
action_manipulated = grid.generate(space.dimensions, 160)
action_manipulated = np.array(action_manipulated)
action_manipulated2 = \
np.append(action_manipulated[(action_manipulated[:, 0] < -0.3) * (action_manipulated[:, 1] < -0.3), :],
action_manipulated[(action_manipulated[:, 0] > 0.3) * (action_manipulated[:, 1] > 0.3), :],
axis=0)
action_manipulated2 = \
np.append(action_manipulated2,
action_manipulated[(action_manipulated[:, 0] > 0.3) * (action_manipulated[:, 1] < -0.3), :],
axis=0)
action_manipulated2 = \
np.append(action_manipulated2,
action_manipulated[(action_manipulated[:, 0] < -0.3) * (action_manipulated[:, 1] > 0.3), :],
axis=0)
self.action_manipulated = action_manipulated2
if search_space == 'random':
self.action_manipulated = np.array([[-0.1, 0],
[0.1, 0],
[0, 0.1],
[0, -0.1],
[-0.25, 0],
[0.25, 0],
[0, 0.25],
[0, -0.25],
[-0.1, 0.1],
[0.1, 0.1],
[-0.1, -0.1],
[0.1, -0.1],
[-0.25, 0.25],
[0.25, 0.25],
[-0.25, -0.25],
[0.25, -0.25], ###############
[0.1, 0.05],
[0.05, 0.1],
[0.05, -0.1],
[-0.25, 0.1],
[0.25, 0.8],
[0.6, 0.25],
[0.3, -0.25],
[-0.1, 0.7],
[0.9, 0.1],
[-0.1, -1],
[1, -0.1],
[-0.2, 0.75],
[0.5, 0.5],
[-0.5, -0.5],
[0.75, 0],
[0.15, 0.05],
[0.6, 0.1],
[0.4, -0.1],
[-0.25, 0.15],
[0.25, 0.9],
[-0.35, 0.25],
[0.5, -0.25],
[-0.19, 0.19],
[1, 1],
[-1, -1],
[0, 1],
[-1, 0],
[0.2, 0.75],
[-0.8, 0],
[0, -0.58]])
self.cbf_learn_online = cbf_learn_online
self.TotalCollisions = []
self.filename = filename
self.observation_storage = []
self.safe_info = safe_info
self.csv_writer_lock = threading.Lock()
self.coordinates_static_obstacles = coordinates_static_obstacles
self.rewards = rewards
# reward shaping
if self.rewards is not None:
self.reward_reached_target = self.rewards[0]
self.reward_distance = self.rewards[1]
self.reward_crashed = self.rewards[2]
if self.supervisor == "logical":
self.reward_logical = self.rewards[3]
if self.supervisor == "cbf-gp-logical" or self.supervisor == "cbf-svm" or self.supervisor == "cbf-gp-svm":
self.reward_cbf = self.rewards[3]
# default reward settings
if self.rewards is None:
self.reward_reached_target = 150
self.reward_distance = 1.5
self.reward_crashed = 150
self.reward_cbf = 0.5
self.reward_logical = 100
# add extra static obstacles as boundary of the garden
self.extra_obstacles = np.array([[-2.5, -.15],
[-2.5, -.35],
[-2.5, -.55],
[-2.5, -.75],
[-2.5, -.95],
[-2.5, -1.15],
[-2.5, -1.35],
[-2.5, -1.55],
[-2.5, -1.75],
[-2.5, -1.95],
[-2.5, -2.15],
[-2.5, -2.35],
[-2.5, -2.55],
[-2.5, -2.75],
[-2.5, -2.95],
[-2.5, -3.15],
[-2.5, -3.35],
[2.55, -.25],
[2.55, -.35],
[2.55, -.55],
[2.55, -.75],
[2.55, -.95],
[2.55, -1.15],
[2.55, -1.35],
[2.55, -1.55],
[2.55, -1.75],
[2.55, -1.95],
[2.55, -2.15],
[2.55, -2.35],
[2.55, -2.55],
[2.55, -2.75],
[2.55, -2.95],
[2.55, -3.15],
[2.55, -3.35],
[-2.50, -0.15],
[-2.30, -0.15],
[-2.10, -0.15],
[-1.90, -0.15],
[-1.70, -0.15],
[-1.50, -0.15],
[-1.30, -0.15],
[-1.10, -0.15],
[-.90, -0.15],
[-.70, -0.15],
[-.5, -0.15],
[-.3, -0.15],
[-.1, -0.15],
[0.7, -0.15],
[0.9, -0.15],
[1.1, -0.15],
[1.3, -0.15],
[1.5, -0.15],
[1.7, -0.15],
[1.9, -0.15],
[2.1, -0.15],
[2.3, -0.15],
[2.5, -0.15],
[-2.40, -3.4],
[-2.20, -3.4],
[-2.00, -3.4],
[-1.90, -3.4],
[-1.70, -3.4],
[-1.50, -3.4],
[-1.30, -3.4],
[-1.10, -3.4],
[-.90, -3.4],
[-.70, -3.4],
[-.50, -3.4],
[-.3, -3.4],
[-.1, -3.4],
[0.1, -3.4],
[0.3, -3.4],
[0.5, -3.4],
[0.7, -3.4],
[0.9, -3.4],
[1.1, -3.4],
[1.3, -3.4],
[1.5, -3.4],
[1.7, -3.4],
[1.9, -3.4],
[2.1, -3.4],
[2.3, -3.4],
[2.5, -3.4],
])
# add extra obstacles as tress in the middle of the garden
self.extra_obstacles = np.concatenate((self.extra_obstacles, self.coordinates_static_obstacles))
def step(self, action):
"""
Get information for the next RL step
Parameters:
action (float, float): Action vector (speed)
Returns:
[float]: Observation vector
float: reward value
observation, reward, done, info
"""
reward = 0
# check if env needs reset
if self.needs_reset:
raise RuntimeError("Tried to step environment that needs reset")
# pass proposed action to the CBF (if CBF is active) and return the manipulated or the proposed action
if self.supervisor == 'cbf-gp-logical' or self.supervisor == 'cbf-svm' or self.supervisor == 'cbf-gp-svm':
index = int(len(self.observation_storage) - 1)
old_observation = self.observation_storage[index]
if self.cbf_learn_online is True:
if len(self.observation_storage) > 2:
state_x = self.observation_storage[index - 1]
state_x = state_x[0:self.lidar_num_bins]
state_x = np.asarray(state_x)
action_x = self.observation_storage[index]
action_x = action_x[28:30]
action_x = np.asarray(action_x)
state_action_x = np.append(state_x, action_x)
state_action_x = state_action_x.reshape(1, -1)
state_y = self.observation_storage[index]
state_y = state_y[26]
if state_y > 0:
state_y = int(1)
else:
state_y = int(-1)
state_y = np.asarray(state_y)
state_y = state_y.reshape(1, -1)
self.svm.fit(state_action_x, state_y)
change_proposed_action = False
if self.supervisor == 'cbf-gp-svm' or self.supervisor == 'cbf-gp-logical':
successor_state_worst = predict_successor_state_gp(self.gp,
observation=old_observation[0:self.lidar_num_bins],
action=action)
if self.supervisor == 'cbf-gp-svm':
successor_state_worst = np.sort(successor_state_worst)
successor_state_worst = successor_state_worst.reshape(1, -1)
probability = self.svm.predict_proba(successor_state_worst)
unsafe_probability = probability[0, 1]
# print(unsafe_probability)
if unsafe_probability > self.unsafe_threshold:
change_proposed_action = True
if self.supervisor == 'cbf-gp-logical':
change_proposed_action = max(successor_state_worst[0]) > self.unsafe_threshold
if self.supervisor == 'cbf-svm':
# hier nur svm predicten
state_action = np.concatenate((old_observation[0:self.lidar_num_bins], action), axis=0)
state_action = state_action.reshape(1, -1)
probability = self.svm.predict_proba(state_action)
unsafe = probability[0, 1]
if unsafe > self.unsafe_threshold:
change_proposed_action = True
if change_proposed_action:
if self.supervisor == 'cbf-gp-logical' or self.supervisor == 'cbf-gp-svm':
successor_state_worst_manipulated = []
manipulated = predict_successor_state_gp(self.gp,
observation=old_observation[0:self.lidar_num_bins],
action=self.action_manipulated)
if self.supervisor == 'cbf-gp-logical':
successor_state_worst_manipulated = np.amax(manipulated, axis=1)
if self.supervisor == 'cbf-gp-svm':
manipulated = np.sort(manipulated, axis=1)
probability = self.svm.predict_proba(manipulated)
successor_state_worst_manipulated = probability[:, 1]
if not self.cbf_quadratic:
index = np.argmin(successor_state_worst_manipulated)
distance_org = np.sqrt((self.action_manipulated[index, 0] - action[0]) ** 2 +
(self.action_manipulated[index, 1] - action[1]) ** 2)
self.total_distance += distance_org
action = self.action_manipulated[index]
if self.scale_reward:
reward -= self.reward_cbf * (distance_org / 2.8)
self.total_distance += distance_org
if self.cbf_quadratic:
if int(sum(successor_state_worst_manipulated < self.unsafe_threshold)) > 0.1:
safety_actions = self.action_manipulated[successor_state_worst_manipulated < self.unsafe_threshold]
else:
safety_actions = self.action_manipulated
distance_org = np.sqrt((safety_actions[:, 0] - action[0]) ** 2 +
(safety_actions[:, 1] - action[1]) ** 2)
index = min(enumerate(distance_org), key=itemgetter(1))[0]
action = safety_actions[index]
if self.scale_reward:
reward -= self.reward_cbf * (distance_org[index] / 2.8)
self.total_distance += distance_org[index]
#if self.supervisor == 'cbf-svm':
# successor_state_unsafe_prob_manipulated = []
# for j in range(0, len(self.action_manipulated)):
# state_action = np.concatenate((old_observation[0:self.lidar_num_bins],
# self.action_manipulated[j]), axis=0)
# state_action = state_action.reshape(1, -1)
# probability = self.svm.predict_proba(state_action)
# unsafe = probability[0, 1]
# successor_state_unsafe_prob_manipulated.append(unsafe)
# index = np.argmin(successor_state_unsafe_prob_manipulated)
# action = self.action_manipulated[index]
self.last_teacher_crash = 1
self.Intervention += 1
self.Supervised = 1
if not self.scale_reward:
reward -= self.reward_cbf
# step env
observation, reward_unity, done, info = self.env.step(action)
# manipulate reward with distance to target. maximum distance is ~5.
reward -= (observation[0] / 5) * self.reward_distance
# save org ibm obs
org_observation = observation
# check if safely done
if done:
self.SafelyDone += 1
reward += self.reward_reached_target
# compute distances to obstacles
distance = distance_from_obstacles(self, observation)
# check if drone crashed
if not done:
if np.min(distance) <= .2:
self.Crashed += 1
reward -= self.reward_crashed
done = True
# check if logical supervisor is active
if not done:
if self.supervisor == 'logical':
if not self.record_svm_gp:
if np.min(distance) <= (self.safety_distance + np.random.rand(1) / 25):
self.Supervised += 1
self.Intervention += 1
done = True
reward -= self.reward_logical
# the following is used when recording data
if self.record_svm_gp:
if np.min(distance) <= 0.29 + np.random.rand(1) / 25:
self.Supervised += 1
self.Intervention += 1
done = True
reward -= self.reward_logical
else:
if np.min(distance) <= 0.35 + np.random.rand(1) / 25:
self.Supervised += 1
# append reward
self.rewards.append(reward)
# and | |
not None:
self.Certificate_Signature.export(outfile, level, 'X509CertificateObj:', name_='Certificate_Signature')
def hasContent_(self):
if (
self.Certificate is not None or
self.Certificate_Signature is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='X509CertificateObjectType'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
if self.Certificate is not None:
showIndent(outfile, level)
outfile.write('Certificate=model_.X509CertificateType(\n')
self.Certificate.exportLiteral(outfile, level, name_='Certificate')
showIndent(outfile, level)
outfile.write('),\n')
if self.Certificate_Signature is not None:
showIndent(outfile, level)
outfile.write('Certificate_Signature=model_.X509CertificateSignatureType(\n')
self.Certificate_Signature.exportLiteral(outfile, level, name_='Certificate_Signature')
showIndent(outfile, level)
outfile.write('),\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
pass
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Certificate':
obj_ = X509CertificateType.factory()
obj_.build(child_)
self.set_Certificate(obj_)
elif nodeName_ == 'Certificate_Signature':
obj_ = X509CertificateSignatureType.factory()
obj_.build(child_)
self.set_Certificate_Signature(obj_)
super(X509CertificateObjectType, self).buildChildren(child_, node, nodeName_, True)
# end class X509CertificateObjectType
class X509CertificateType(GeneratedsSuper):
"""The X509CertificateType type represents the contents of an X.509
certificate, including items such as issuer, subject, and
others."""
subclass = None
superclass = None
def __init__(self, Issuer=None, Serial_Number=None, Signature_Algorithm=None, Subject=None, Subject_Public_Key=None, Validity=None, Version=None):
self.Issuer = Issuer
self.Serial_Number = Serial_Number
self.Signature_Algorithm = Signature_Algorithm
self.Subject = Subject
self.Subject_Public_Key = Subject_Public_Key
self.Validity = Validity
self.Version = Version
def factory(*args_, **kwargs_):
if X509CertificateType.subclass:
return X509CertificateType.subclass(*args_, **kwargs_)
else:
return X509CertificateType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Issuer(self): return self.Issuer
def set_Issuer(self, Issuer): self.Issuer = Issuer
def get_Serial_Number(self): return self.Serial_Number
def set_Serial_Number(self, Serial_Number): self.Serial_Number = Serial_Number
def get_Signature_Algorithm(self): return self.Signature_Algorithm
def set_Signature_Algorithm(self, Signature_Algorithm): self.Signature_Algorithm = Signature_Algorithm
def get_Subject(self): return self.Subject
def set_Subject(self, Subject): self.Subject = Subject
def get_Subject_Public_Key(self): return self.Subject_Public_Key
def set_Subject_Public_Key(self, Subject_Public_Key): self.Subject_Public_Key = Subject_Public_Key
def get_Validity(self): return self.Validity
def set_Validity(self, Validity): self.Validity = Validity
def get_Version(self): return self.Version
def set_Version(self, Version): self.Version = Version
def export(self, outfile, level, namespace_='X509CertificateObj:', name_='X509CertificateType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='X509CertificateType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='X509CertificateObj:', name_='X509CertificateType'):
super(X509CertificateType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='X509CertificateType')
def exportChildren(self, outfile, level, namespace_='X509CertificateObj:', name_='X509CertificateType', fromsubclass_=False):
if self.Issuer is not None:
self.Issuer.export(outfile, level, 'X509CertificateObj:', name_='Issuer')
if self.Serial_Number is not None:
self.Serial_Number.export(outfile, level, 'X509CertificateObj:', name_='Serial_Number')
if self.Signature_Algorithm is not None:
self.Signature_Algorithm.export(outfile, level, 'X509CertificateObj:', name_='Signature_Algorithm')
if self.Subject is not None:
self.Subject.export(outfile, level, 'X509CertificateObj:', name_='Subject')
if self.Subject_Public_Key is not None:
self.Subject_Public_Key.export(outfile, level, 'X509CertificateObj:', name_='Subject_Public_Key')
if self.Validity is not None:
self.Validity.export(outfile, level, 'X509CertificateObj:', name_='Validity')
if self.Version is not None:
self.Version.export(outfile, level, 'X509CertificateObj:', name_='Version')
def hasContent_(self):
if (
self.Issuer is not None or
self.Serial_Number is not None or
self.Signature_Algorithm is not None or
self.Subject is not None or
self.Subject_Public_Key is not None or
self.Validity is not None or
self.Version is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='X509CertificateType'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
if self.Issuer is not None:
showIndent(outfile, level)
outfile.write('Issuer=%s,\n' % quote_python(self.Issuer).encode(ExternalEncoding))
if self.Serial_Number is not None:
showIndent(outfile, level)
outfile.write('Serial_Number=%s,\n' % quote_python(self.Serial_Number).encode(ExternalEncoding))
if self.Signature_Algorithm is not None:
showIndent(outfile, level)
outfile.write('Signature_Algorithm=%s,\n' % quote_python(self.Signature_Algorithm).encode(ExternalEncoding))
if self.Subject is not None:
showIndent(outfile, level)
outfile.write('Subject=%s,\n' % quote_python(self.Subject).encode(ExternalEncoding))
if self.Subject_Public_Key is not None:
showIndent(outfile, level)
outfile.write('Subject_Public_Key=model_.SubjectPublicKeyType(\n')
self.Subject_Public_Key.exportLiteral(outfile, level, name_='Subject_Public_Key')
showIndent(outfile, level)
outfile.write('),\n')
if self.Validity is not None:
showIndent(outfile, level)
outfile.write('Validity=model_.ValidityType(\n')
self.Validity.exportLiteral(outfile, level, name_='Validity')
showIndent(outfile, level)
outfile.write('),\n')
if self.Version is not None:
showIndent(outfile, level)
outfile.write('Version=%s,\n' % quote_python(self.Version).encode(ExternalEncoding))
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
pass
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Issuer':
Issuer_ = child_.text
Issuer_ = self.gds_validate_string(Issuer_, node, 'Issuer')
self.Issuer = Issuer_
elif nodeName_ == 'Serial_Number':
Serial_Number_ = child_.text
Serial_Number_ = self.gds_validate_string(Serial_Number_, node, 'Serial_Number')
self.Serial_Number = Serial_Number_
elif nodeName_ == 'Signature_Algorithm':
Signature_Algorithm_ = child_.text
Signature_Algorithm_ = self.gds_validate_string(Signature_Algorithm_, node, 'Signature_Algorithm')
self.Signature_Algorithm = Signature_Algorithm_
elif nodeName_ == 'Subject':
Subject_ = child_.text
Subject_ = self.gds_validate_string(Subject_, node, 'Subject')
self.Subject = Subject_
elif nodeName_ == 'Subject_Public_Key':
obj_ = SubjectPublicKeyType.factory()
obj_.build(child_)
self.set_Subject_Public_Key(obj_)
elif nodeName_ == 'Validity':
obj_ = ValidityType.factory()
obj_.build(child_)
self.set_Validity(obj_)
elif nodeName_ == 'Version':
Version_ = child_.text
Version_ = self.gds_validate_string(Version_, node, 'Version')
self.Version = Version_
# end class X509CertificateType
class X509CertificateSignatureType(GeneratedsSuper):
"""The X509CertificateSignatureType contains the signature and
signature algorithm of this X.509 certificate."""
subclass = None
superclass = None
def __init__(self, Signature=None, Signature_Algorithm=None):
self.Signature = Signature
self.Signature_Algorithm = Signature_Algorithm
def factory(*args_, **kwargs_):
if X509CertificateSignatureType.subclass:
return X509CertificateSignatureType.subclass(*args_, **kwargs_)
else:
return X509CertificateSignatureType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Signature(self): return self.Signature
def set_Signature(self, Signature): self.Signature = Signature
def get_Signature_Algorithm(self): return self.Signature_Algorithm
def set_Signature_Algorithm(self, Signature_Algorithm): self.Signature_Algorithm = Signature_Algorithm
def export(self, outfile, level, namespace_='X509CertificateObj:', name_='X509CertificateSignatureType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='X509CertificateSignatureType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='X509CertificateObj:', name_='X509CertificateSignatureType'):
pass
def exportChildren(self, outfile, level, namespace_='X509CertificateObj:', name_='X509CertificateSignatureType', fromsubclass_=False):
if self.Signature is not None:
self.Signature.export(outfile, level, 'X509CertificateObj:', name_='Signature')
if self.Signature_Algorithm is not None:
self.Signature_Algorithm.export(outfile, level, 'X509CertificateObj:', name_='Signature_Algorithm')
def hasContent_(self):
if (
self.Signature is not None or
self.Signature_Algorithm is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='X509CertificateSignatureType'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
if self.Signature is not None:
showIndent(outfile, level)
outfile.write('Signature=%s,\n' % quote_python(self.Signature).encode(ExternalEncoding))
if self.Signature_Algorithm is not None:
showIndent(outfile, level)
outfile.write('Signature_Algorithm=%s,\n' % quote_python(self.Signature_Algorithm).encode(ExternalEncoding))
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
pass
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Signature':
Signature_ = child_.text
Signature_ = self.gds_validate_string(Signature_, node, 'Signature')
self.Signature = Signature_
elif nodeName_ == 'Signature_Algorithm':
Signature_Algorithm_ = child_.text
Signature_Algorithm_ = self.gds_validate_string(Signature_Algorithm_, node, 'Signature_Algorithm')
self.Signature_Algorithm = Signature_Algorithm_
# end class X509CertificateSignatureType
class SubjectPublicKeyType(GeneratedsSuper):
"""The SubjectPublicKeyType is used to carry the public key and
identify the algorithm with which the key is used."""
subclass = None
superclass = None
def __init__(self, Public_Key_Algorithm=None, RSA_Public_Key=None):
self.Public_Key_Algorithm = Public_Key_Algorithm
self.RSA_Public_Key = RSA_Public_Key
def factory(*args_, **kwargs_):
if SubjectPublicKeyType.subclass:
return SubjectPublicKeyType.subclass(*args_, **kwargs_)
else:
return SubjectPublicKeyType(*args_, **kwargs_)
factory = staticmethod(factory)
def get_Public_Key_Algorithm(self): return self.Public_Key_Algorithm
def set_Public_Key_Algorithm(self, Public_Key_Algorithm): self.Public_Key_Algorithm = Public_Key_Algorithm
def get_RSA_Public_Key(self): return self.RSA_Public_Key
def set_RSA_Public_Key(self, RSA_Public_Key): self.RSA_Public_Key = RSA_Public_Key
def export(self, outfile, level, namespace_='X509CertificateObj:', name_='SubjectPublicKeyType', namespacedef_=''):
showIndent(outfile, level)
outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
self.exportAttributes(outfile, level, already_processed, namespace_, name_='SubjectPublicKeyType')
if self.hasContent_():
outfile.write('>\n')
self.exportChildren(outfile, level + 1, namespace_, name_)
showIndent(outfile, level)
outfile.write('</%s%s>\n' % (namespace_, name_))
else:
outfile.write('/>\n')
def exportAttributes(self, outfile, level, already_processed, namespace_='X509CertificateObj:', name_='SubjectPublicKeyType'):
super(SubjectPublicKeyType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='SubjectPublicKeyType')
def exportChildren(self, outfile, level, namespace_='X509CertificateObj:', name_='SubjectPublicKeyType', fromsubclass_=False):
if self.Public_Key_Algorithm is not None:
self.Public_Key_Algorithm.export(outfile, level, 'X509CertificateObj:', name_='Public_Key_Algorithm')
if self.RSA_Public_Key is not None:
self.RSA_Public_Key.export(outfile, level, 'X509CertificateObj:', name_='RSA_Public_Key')
def hasContent_(self):
if (
self.Public_Key_Algorithm is not None or
self.RSA_Public_Key is not None
):
return True
else:
return False
def exportLiteral(self, outfile, level, name_='SubjectPublicKeyType'):
level += 1
self.exportLiteralAttributes(outfile, level, [], name_)
if self.hasContent_():
self.exportLiteralChildren(outfile, level, name_)
def exportLiteralAttributes(self, outfile, level, already_processed, name_):
pass
def exportLiteralChildren(self, outfile, level, name_):
if self.Public_Key_Algorithm is not None:
showIndent(outfile, level)
outfile.write('Public_Key_Algorithm=%s,\n' % quote_python(self.Public_Key_Algorithm).encode(ExternalEncoding))
if self.RSA_Public_Key is not None:
showIndent(outfile, level)
outfile.write('RSA_Public_Key=model_.RSA_Public_Key(\n')
self.RSA_Public_Key.exportLiteral(outfile, level)
showIndent(outfile, level)
outfile.write('),\n')
def build(self, node):
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
def buildAttributes(self, node, attrs, already_processed):
pass
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Public_Key_Algorithm':
Public_Key_Algorithm_ = child_.text
Public_Key_Algorithm_ = self.gds_validate_string(Public_Key_Algorithm_, node, 'Public_Key_Algorithm')
self.Public_Key_Algorithm = Public_Key_Algorithm_
elif nodeName_ == 'RSA_Public_Key':
obj_ = RSA_Public_Key.factory()
obj_.build(child_)
self.set_RSA_Public_Key(obj_)
# end class SubjectPublicKeyType
class RSA_Public_Key(GeneratedsSuper):
"""RSA Public Key is the public key contained in this X.509
certificate."""
subclass = None
superclass = None
def __init__(self, Modulus=None, Exponent=None):
self.Modulus = Modulus
self.Exponent = Exponent
def factory(*args_, **kwargs_):
if RSA_Public_Key.subclass:
return RSA_Public_Key.subclass(*args_, **kwargs_)
else:
return RSA_Public_Key(*args_, **kwargs_)
factory = staticmethod(factory)
| |
<reponame>lanl/minRL<gh_stars>0
# This material was prepared as an account of work sponsored by an agency of the
# United States Government. Neither the United States Government nor the United
# States Department of Energy, nor Battelle, nor any of their employees, nor any
# jurisdiction or organization that has cooperated in the development of these
# materials, makes any warranty, express or implied, or assumes any legal
# liability or responsibility for the accuracy, completeness, or usefulness or
# any information, apparatus, product, software, or process disclosed, or
# represents that its use would not infringe privately owned rights. Reference
# herein to any specific commercial product, process, or service by trade name,
# trademark, manufacturer, or otherwise does not necessarily constitute or imply
# its endorsement, recommendation, or favoring by the United States Government
# or any agency thereof, or Battelle Memorial Institute. The views and opinions
# of authors expressed herein do not necessarily state or reflect those of the
# United States Government or any agency thereof.
# PACIFIC NORTHWEST NATIONAL LABORATORY
# operated by
# BATTELLE
# for the
# UNITED STATES DEPARTMENT OF ENERGY
# under Contract DE-AC05-76RL01830
import time
import os
import math
import json
import csv
import random
import tensorflow as tf
import sys
import gym
import pickle
import exarl as erl
from exarl.base.comm_base import ExaComm
from tensorflow import keras
from collections import deque
from datetime import datetime
import numpy as np
from exarl.agents.agent_vault._prioritized_replay import PrioritizedReplayBuffer
import exarl.utils.candleDriver as cd
from exarl.utils import log
from exarl.utils.introspect import introspectTrace
from tensorflow.compat.v1.keras.backend import set_session
if ExaComm.num_learners > 1:
import horovod.tensorflow as hvd
multiLearner = True
else:
multiLearner = False
logger = log.setup_logger(__name__, cd.run_params['log_level'])
class LossHistory(keras.callbacks.Callback):
def on_train_begin(self, logs={}):
self.loss = []
def on_batch_end(self, batch, logs={}):
self.loss.append(logs.get('loss'))
# The Multi-Learner Discrete Double Deep Q-Network
class DQN(erl.ExaAgent):
def __init__(self, env, is_learner):
# Initial values
self.is_learner = is_learner
self.model = None
self.target_model = None
self.target_weights = None
self.device = None
self.mirrored_strategy = None
self.env = env
self.agent_comm = ExaComm.agent_comm
# MPI
self.rank = self.agent_comm.rank
self.size = self.agent_comm.size
# Timers
self.training_time = 0
self.ntraining_time = 0
self.dataprep_time = 0
self.ndataprep_time = 0
self.enable_xla = True if cd.run_params['xla'] == "True" else False
if self.enable_xla:
# Optimization using XLA (1.1x speedup)
tf.config.optimizer.set_jit(True)
# Optimization using mixed precision (1.5x speedup)
# Layers use float16 computations and float32 variables
from tensorflow.keras.mixed_precision import experimental as mixed_precision
policy = mixed_precision.Policy('mixed_float16')
mixed_precision.set_policy(policy)
# dqn intrinsic variables
self.results_dir = cd.run_params['output_dir']
self.gamma = cd.run_params['gamma']
self.epsilon = cd.run_params['epsilon']
self.epsilon_min = cd.run_params['epsilon_min']
self.epsilon_decay = cd.run_params['epsilon_decay']
self.learning_rate = cd.run_params['learning_rate']
self.batch_size = cd.run_params['batch_size']
self.tau = cd.run_params['tau']
self.model_type = cd.run_params['model_type']
if self.model_type == 'MLP':
# for mlp
self.dense = cd.run_params['dense']
if self.model_type == 'LSTM':
# for lstm
self.lstm_layers = cd.run_params['lstm_layers']
self.gauss_noise = cd.run_params['gauss_noise']
self.regularizer = cd.run_params['regularizer']
self.clipnorm = cd.run_params['clipnorm']
self.clipvalue = cd.run_params['clipvalue']
# for both
self.activation = cd.run_params['activation']
self.out_activation = cd.run_params['out_activation']
self.optimizer = cd.run_params['optimizer']
self.loss = cd.run_params['loss']
self.n_actions = cd.run_params['nactions']
self.priority_scale = cd.run_params['priority_scale']
# Check if the action space is discrete
self.is_discrete = (type(env.action_space) == gym.spaces.discrete.Discrete)
# If continuous, discretize the action space
# TODO: Incorpoorate Ai's class
if not self.is_discrete:
env.action_space.n = self.n_actions
self.actions = np.linspace(env.action_space.low, env.action_space.high, self.n_actions)
# Data types of action and observation space
self.dtype_action = np.array(self.env.action_space.sample()).dtype
self.dtype_observation = self.env.observation_space.sample().dtype
# Setup GPU cfg
if ExaComm.is_learner():
logger.info("Setting GPU rank", self.rank)
config = tf.compat.v1.ConfigProto(device_count={'GPU': 1, 'CPU': 1})
else:
logger.info("Setting no GPU rank", self.rank)
config = tf.compat.v1.ConfigProto(device_count={'GPU': 0, 'CPU': 1})
# Get which device to run on
self.device = self._get_device()
config.gpu_options.allow_growth = True
sess = tf.compat.v1.Session(config=config)
tf.compat.v1.keras.backend.set_session(sess)
# Build network model
if self.is_learner:
with tf.device(self.device):
self.model = self._build_model()
self.model.compile(loss=self.loss, optimizer=self.optimizer)
self.model.summary()
# self.mirrored_strategy = tf.distribute.MirroredStrategy()
# logger.info("Using learner strategy: {}".format(self.mirrored_strategy))
# with self.mirrored_strategy.scope():
# self.model = self._build_model()
# self.model._name = "learner"
# self.model.compile(loss=self.loss, optimizer=self.optimizer)
# logger.info("Active model: \n".format(self.model.summary()))
else:
self.model = None
with tf.device('/CPU:0'):
self.target_model = self._build_model()
self.target_model._name = "target_model"
self.target_model.compile(loss=self.loss, optimizer=self.optimizer)
# self.target_model.summary()
self.target_weights = self.target_model.get_weights()
if multiLearner and ExaComm.is_learner():
hvd.init(comm=ExaComm.learner_comm.raw())
self.first_batch = 1
# TODO: Update candle driver to include different losses and optimizers
# Default reduction is tf.keras.losses.Reduction.AUTO which errors out with distributed training
# self.loss_fn = tf.keras.losses.MeanSquaredError(reduction=tf.keras.losses.Reduction.NONE)
self.loss_fn = cd.candle.build_loss(self.loss, cd.kerasDefaults, reduction='none')
# self.opt = tf.keras.optimizers.Adam(self.learning_rate * hvd.size())
self.opt = cd.candle.build_optimizer(self.optimizer, self.learning_rate * hvd.size(), cd.kerasDefaults)
self.maxlen = cd.run_params['mem_length']
self.replay_buffer = PrioritizedReplayBuffer(maxlen=self.maxlen)
def _get_device(self):
cpus = tf.config.experimental.list_physical_devices('CPU')
gpus = tf.config.experimental.list_physical_devices('GPU')
ngpus = len(gpus)
logger.info('Number of available GPUs: {}'.format(ngpus))
if ngpus > 0:
gpu_id = self.rank % ngpus
return '/GPU:{}'.format(gpu_id)
else:
return '/CPU:0'
def _build_model(self):
if self.model_type == 'MLP':
from exarl.agents.agent_vault._build_mlp import build_model
return build_model(self)
elif self.model_type == 'LSTM':
from exarl.agents.agent_vault._build_lstm import build_model
return build_model(self)
else:
sys.exit("Oops! That was not a valid model type. Try again...")
# TODO: Check if this is used in any workflow, if not delete
def set_learner(self):
logger.debug(
"Agent[{}] - Creating active model for the learner".format(self.rank)
)
def remember(self, state, action, reward, next_state, done):
lost_data = self.replay_buffer.add((state, action, reward, next_state, done))
if lost_data and self.priority_scale:
# logger.warning("Priority replay buffer size too small. Data loss negates replay effect!")
print("Priority replay buffer size too small. Data loss negates replay effect!", flush=True)
def get_action(self, state):
random.seed(datetime.now())
random_data = os.urandom(4)
np.random.seed(int.from_bytes(random_data, byteorder="big"))
rdm = np.random.rand()
if rdm <= self.epsilon:
self.epsilon_adj()
action = random.randrange(self.env.action_space.n)
return action, 0
else:
np_state = np.array(state).reshape(1, 1, len(state))
with tf.device(self.device):
act_values = self.target_model.predict(np_state)
action = np.argmax(act_values[0])
return action, 1
@introspectTrace()
def action(self, state):
action, policy = self.get_action(state)
if not self.is_discrete:
action = [self.actions[action]]
return action, policy
@introspectTrace()
def calc_target_f(self, exp):
state, action, reward, next_state, done = exp
np_state = np.array(state, dtype=self.dtype_observation).reshape(1, 1, len(state))
np_next_state = np.array(next_state, dtype=self.dtype_observation).reshape(1, 1, len(next_state))
expectedQ = 0
if not done:
with tf.device(self.device):
expectedQ = self.gamma * np.amax(self.target_model.predict(np_next_state)[0])
target = reward + expectedQ
with tf.device(self.device):
target_f = self.target_model.predict(np_state)
# For handling continuous to discrete actions
action_idx = action if self.is_discrete else np.where(self.actions == action)[1]
target_f[0][action_idx] = target
return target_f[0]
def has_data(self):
return (self.replay_buffer.get_buffer_length() >= self.batch_size)
@introspectTrace()
def generate_data(self):
# Has data checks if the buffer is greater than batch size for training
if not self.has_data():
# Worker method to create samples for training
batch_states = np.zeros((self.batch_size, 1, self.env.observation_space.shape[0]), dtype=self.dtype_observation)
batch_target = np.zeros((self.batch_size, self.env.action_space.n), dtype=self.dtype_action)
indices = -1 * np.ones(self.batch_size)
importance = np.ones(self.batch_size)
else:
minibatch, importance, indices = self.replay_buffer.sample(self.batch_size, priority_scale=self.priority_scale)
batch_target = list(map(self.calc_target_f, minibatch))
batch_states = [np.array(exp[0], dtype=self.dtype_observation).reshape(1, 1, len(exp[0]))[0] for exp in minibatch]
batch_states = np.reshape(batch_states, [len(minibatch), 1, len(minibatch[0][0])])
batch_target = np.reshape(batch_target, [len(minibatch), self.env.action_space.n])
if self.priority_scale > 0:
yield batch_states, batch_target, indices, importance
else:
yield batch_states, batch_target
@introspectTrace()
def train(self, batch):
ret = None
if self.is_learner:
start_time = time.time()
with tf.device(self.device):
if self.priority_scale > 0:
if multiLearner:
loss = self.training_step(batch)
else:
loss = LossHistory()
sample_weight = batch[3] ** (1 - self.epsilon)
self.model.fit(batch[0], batch[1], epochs=1, batch_size=1, verbose=0, callbacks=loss, sample_weight=sample_weight)
loss = loss.loss
ret = batch[2], loss
else:
if multiLearner:
loss = self.training_step(batch)
else:
self.model.fit(batch[0], batch[1], epochs=1, verbose=0)
end_time = time.time()
self.training_time += (end_time - start_time)
self.ntraining_time += 1
logger.info('Agent[{}]- Training: {} '.format(self.rank, (end_time - start_time)))
start_time_episode = time.time()
logger.info('Agent[%s] - Target update time: %s ' % (str(self.rank), str(time.time() - start_time_episode)))
else:
logger.warning('Training will not be done because this instance is not set to learn.')
return ret
@tf.function
def training_step(self, batch):
with tf.GradientTape() as tape:
probs = self.model(batch[0], training=True)
if len(batch) > 2:
sample_weight = batch[3] * (1 - self.epsilon)
else:
sample_weight = np.ones(len(batch[0]))
loss_value = self.loss_fn(batch[1], probs, sample_weight=sample_weight)
# Horovod distributed gradient tape
tape = hvd.DistributedGradientTape(tape)
grads = tape.gradient(loss_value, self.model.trainable_variables)
self.opt.apply_gradients(zip(grads, self.model.trainable_variables))
if self.first_batch:
hvd.broadcast_variables(self.model.variables, root_rank=0)
hvd.broadcast_variables(self.opt.variables(), root_rank=0)
self.first_batch = 0
return loss_value
def set_priorities(self, indicies, loss):
self.replay_buffer.set_priorities(indicies, loss)
def get_weights(self):
logger.debug("Agent[%s] - get target weight." % str(self.rank))
return self.target_model.get_weights()
def set_weights(self, weights):
logger.info("Agent[%s] - set target weight." % str(self.rank))
logger.debug("Agent[%s] - set target weight: %s" % (str(self.rank), weights))
with tf.device(self.device):
self.target_model.set_weights(weights)
@introspectTrace()
def target_train(self):
if self.is_learner:
logger.info("Agent[%s] - update target weights." % str(self.rank))
with tf.device(self.device):
model_weights = self.model.get_weights()
target_weights = self.target_model.get_weights()
for i in range(len(target_weights)):
target_weights[i] = (
self.tau * model_weights[i] + (1 - self.tau) * target_weights[i]
)
self.set_weights(target_weights)
else:
logger.warning(
"Weights will not be updated because this instance is not set to learn."
)
def epsilon_adj(self):
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
def load(self, filename):
layers = self.target_model.layers
with open(filename, 'rb') as f:
pickle_list = pickle.load(f)
for | |
'''GDELTeda.py
Project: WGU Data Management/Analytics Undergraduate Capstone
<NAME>
August 2021
Class for collecting Pymongo and Pandas operations to automate EDA on
subsets of GDELT records (Events/Mentions, GKG, or joins).
Basic use should be by import and implementation within an IDE, or by editing
section # C00 and running this script directly.
Primary member functions include descriptive docstrings for their intent and
use.
WARNING: project file operations are based on relative pathing from the
'scripts' directory this Python script is located in, given the creation of
directories 'GDELTdata' and 'EDAlogs' parallel to 'scripts' upon first
GDELTbase and GDELTeda class initializations. If those directories are not
already present, a fallback method for string-literal directory reorientation
may be found in '__init__()' at this tag: # A02b - Project directory path.
Specification for any given user's main project directory should be made for
that os.chdir() call.
See also GDELTbase.py, tag # A01a - backup path specification, as any given
user's project directory must be specified there, also.
Contents:
A00 - GDELTeda
A01 - shared class data
A02 - __init__ with instanced data
A02a - Project directory maintenance
A02b - Project directory path specification
Note: Specification at A02b should be changed to suit a user's desired
directory structure, given their local filesystem.
B00 - class methods
B01 - batchEDA()
B02 - eventsBatchEDA()
B03 - mentionsBatchEDA()
B04 - gkgBatchEDA()
Note: see GDELTedaGKGhelpers.py for helper function code & docs
B05 - realtimeEDA()
B06 - loopEDA()
C00 - main w/ testing
C01 - previously-run GDELT realtime EDA testing
'''
import json
import multiprocessing
import numpy as np
import os
import pandas as pd
import pymongo
import shutil
import wget
from datetime import datetime, timedelta, timezone
from GDELTbase import GDELTbase
from GDELTedaGKGhelpers import GDELTedaGKGhelpers
from pandas_profiling import ProfileReport
from pprint import pprint as pp
from time import time, sleep
from urllib.error import HTTPError
from zipfile import ZipFile as zf
# A00
class GDELTeda:
'''Collects Pymongo and Pandas operations for querying GDELT records
subsets and performing semi-automated EDA.
Shared class data:
-----------------
logPath - dict
Various os.path objects for EDA log storage.
configFilePaths - dict
Various os.path objects for pandas_profiling.ProfileReport
configuration files, copied to EDA log storage directories upon
__init__, for use in report generation.
Instanced class data:
--------------------
gBase - GDELTbase instance
Used for class member functions, essential for realtimeEDA().
Class methods:
-------------
batchEDA()
eventsBatchEDA()
mentionsBatchEDA()
gkgBatchEDA()
realtimeEDA()
loopEDA()
Helper functions from GDELTedaGKGhelpers.py used in gkgBatchEDA():
pullMainGKGcolumns()
applyDtypes()
convertDatetimes()
convertGKGV15Tone()
mainReport()
locationsReport()
countsReport()
themesReport()
personsReport()
organizationsReport()
'''
# A01 - shared class data
# These paths are set relative to the location of this script, one directory
# up and in 'EDAlogs' parallel to the script directory, which can be named
# arbitrarily.
logPath = {}
logPath['base'] = os.path.join(os.path.abspath(__file__),
os.path.realpath('..'),
'EDAlogs')
logPath['events'] = {}
logPath['events'] = {
'table' : os.path.join(logPath['base'], 'events'),
'batch' : os.path.join(logPath['base'], 'events', 'batch'),
'realtime' : os.path.join(logPath['base'], 'events', 'realtime'),
}
logPath['mentions'] = {
'table' : os.path.join(logPath['base'], 'mentions'),
'batch' : os.path.join(logPath['base'], 'mentions', 'batch'),
'realtime' : os.path.join(logPath['base'], 'mentions', 'realtime'),
}
logPath['gkg'] = {
'table' : os.path.join(logPath['base'], 'gkg'),
'batch' : os.path.join(logPath['base'], 'gkg', 'batch'),
'realtime' : os.path.join(logPath['base'], 'gkg', 'realtime'),
}
# Turns out, the following isn't the greatest way of keeping track
# of each configuration file. It's easiest to just leave them in the
# exact directories where ProfileReport.to_html() is aimed (via
# os.chdir()), since it's pesky maneuvering outside parameters into
# multiprocessing Pool.map() calls.
# Still, these can and are used in realtimeEDA(), since the size of
# just the most recent datafiles should permit handling them without
# regard for Pandas DataFrame RAM impact (it's greedy, easiest method
# for mitigation is multiprocessing threads, that shouldn't be
# necessary for realtimeEDA()).
# Regardless, all these entries are for copying ProfileReport config
# files to their appropriate directories for use, given base-copies
# present in the 'scripts' directory. Those base copies may be edited
# in 'scripts', since each file will be copied from there.
configFilePaths = {}
configFilePaths['events'] = {
'batch' : os.path.join(logPath['base'],
os.path.realpath('..'),
'scripts',
"GDELTeventsEDAconfig_batch.yaml"),
'realtime' : os.path.join(logPath['base'],
os.path.realpath('..'),
'scripts',
"GDELTeventsEDAconfig_realtime.yaml"),
}
configFilePaths['mentions'] = {
'batch' : os.path.join(logPath['base'],
os.path.realpath('..'),
'scripts',
"GDELTmentionsEDAconfig_batch.yaml"),
'realtime' : os.path.join(logPath['base'],
os.path.realpath('..'),
'scripts',
"GDELTmentionsEDAconfig_realtime.yaml"),
}
configFilePaths['gkg'] = {}
configFilePaths['gkg']['batch'] = {
'main' : os.path.join(logPath['base'],
os.path.realpath('..'),
'scripts',
"GDELTgkgMainEDAconfig_batch.yaml"),
'locations' : os.path.join(logPath['base'],
os.path.realpath('..'),
'scripts',
"GDELTgkgLocationsEDAconfig_batch.yaml"),
'counts' : os.path.join(logPath['base'],
os.path.realpath('..'),
'scripts',
"GDELTgkgCountsEDAconfig_batch.yaml"),
'themes' : os.path.join(logPath['base'],
os.path.realpath('..'),
'scripts',
"GDELTgkgThemesEDAconfig_batch.yaml"),
'persons' : os.path.join(logPath['base'],
os.path.realpath('..'),
'scripts',
"GDELTgkgPersonsEDAconfig_batch.yaml"),
'organizations' : os.path.join(logPath['base'],
os.path.realpath('..'),
'scripts',
"GDELTgkgOrganizationsEDAconfig_batch.yaml"),
}
configFilePaths['gkg']['realtime'] = {
'main' : os.path.join(logPath['base'],
os.path.realpath('..'),
'scripts',
"GDELTgkgMainEDAconfig_realtime.yaml"),
'locations' : os.path.join(logPath['base'],
os.path.realpath('..'),
'scripts',
"GDELTgkgLocationsEDAconfig_realtime.yaml"),
'counts' : os.path.join(logPath['base'],
os.path.realpath('..'),
'scripts',
"GDELTgkgCountsEDAconfig_realtime.yaml"),
'themes' : os.path.join(logPath['base'],
os.path.realpath('..'),
'scripts',
"GDELTgkgThemesEDAconfig_realtime.yaml"),
'persons' : os.path.join(logPath['base'],
os.path.realpath('..'),
'scripts',
"GDELTgkgPersonsEDAconfig_realtime.yaml"),
'organizations' : os.path.join(logPath['base'],
os.path.realpath('..'),
'scripts',
"GDELTgkgOrganizationsEDAconfig_realtime.yaml"),
}
# A02
def __init__(self, tableList = ['events', 'mentions', 'gkg']):
'''GDELTeda class initialization, takes a list of GDELT tables to
perform EDA on. Instantiates a GDELTbase() instance for use by class
methods and checks for presence of EDAlogs directories, creating them if
they aren't present, and copying all ProfileReport-required config files
to their applicable directories.
Parameters:
----------
tableList - list of strings, default ['events','mentions','gkg']
Controls detection and creation of .../EDALogs/... subdirectories for
collection of Pandas Profiling ProfileReport HTML EDA document output.
Also controls permission for class member functions to perform
operations on tables specified by those functions' tableList parameters
as a failsafe against a lack of project directories required for those
operations, specifically output of HTML EDA documents.
output:
------
Produces exhaustive EDA for GDELT record subsets for specified tables
through Pandas Profiling ProfileReport-output HTML documents.
All procedurally automated steps towards report generation are shown
in console output during script execution.
'''
# instancing tables for operations to be passed to member functions
self.tableList = tableList
print("Instantiating GDELTeda...\n")
self.gBase = GDELTbase()
if 'events' not in tableList and \
'mentions' not in tableList and \
'gkg' not in tableList:
print("Error! 'tableList' values do not include a valid GDELT table.",
"\nPlease use one or more of 'events', 'mentions', and/or 'gkg'.")
# instancing trackers for realtimeEDA() and loopEDA()
self.realtimeStarted = False
self.realtimeLooping = False
self.realtimeWindow = 0
self.lastRealDatetime = ''
self.nextRealDatetime = ''
# A02a - Project EDA log directories confirmation and/or creation, and
# Pandas Profiling ProfileReport configuration file copying from 'scripts'
# directory.
print(" Checking log directory...")
if not os.path.isdir(self.logPath['base']):
print(" Doesn't exist! Making...")
# A02b - Project directory path
# For obvious reasons, any user of this script should change this
# string to suit their needs. The directory described with this string
# should be one directory above the location of the 'scripts' directory
# this file should be in. If this file is not in 'scripts', unpredictable
# behavior may occur, and no guarantees of functionality are intended for
# such a state.
os.chdir('C:\\Users\\urf\\Projects\\WGU capstone')
os.mkdir(self.logPath['base'])
for table in tableList:
# switch to EDAlogs directory
os.chdir(self.logPath['base'])
# Branch: table subdirectories not found, create all
if not os.path.isdir(self.logPath[table]['table']):
print("Did not find .../EDAlogs/", table, "...")
print(" Creating .../EDAlogs/", table, "...")
os.mkdir(self.logPath[table]['table'])
os.chdir(self.logPath[table]['table'])
print(" Creating .../EDAlogs/", table, "/batch")
os.mkdir(self.logPath[table]['batch'])
print(" Creating .../EDAlogs/", table, "/realtime")
os.mkdir(self.logPath[table]['realtime'])
os.chdir(self.logPath[table]['realtime'])
# Branch: table subdirectories found, create batch/realtime directories
# if not present.
else:
print(" Found .../EDAlogs/", table,"...")
os.chdir(self.logPath[table]['table'])
if not os.path.isdir(self.logPath[table]['batch']):
print(" Did not find .../EDAlogs/", table, "/batch , creating...")
os.mkdir(self.logPath[table]['batch'])
if not os.path.isdir(self.logPath[table]['realtime']):
print(" Did not find .../EDAlogs/", table, "/realtime , creating...")
os.mkdir(self.logPath[table]['realtime'])
os.chdir(self.logPath[table]['realtime'])
# Copying pandas_profiling.ProfileReport configuration files
print(" Copying configuration files...\n")
if table == 'gkg':
# There's a lot of these, but full normalization of GKG is
# prohibitively RAM-expensive, so reports need to be generated for
# both the main columns and the main columns normalized for each
# variable-length subfield.
shutil.copy(self.configFilePaths[table]['realtime']['main'],
self.logPath[table]['realtime'])
shutil.copy(self.configFilePaths[table]['realtime']['locations'],
self.logPath[table]['realtime'])
shutil.copy(self.configFilePaths[table]['realtime']['counts'],
self.logPath[table]['realtime'])
shutil.copy(self.configFilePaths[table]['realtime']['themes'],
self.logPath[table]['realtime'])
shutil.copy(self.configFilePaths[table]['realtime']['persons'],
self.logPath[table]['realtime'])
shutil.copy(self.configFilePaths[table]['realtime']['organizations'],
self.logPath[table]['realtime'])
os.chdir(self.logPath[table]['batch'])
shutil.copy(self.configFilePaths[table]['batch']['main'],
self.logPath[table]['batch'])
shutil.copy(self.configFilePaths[table]['batch']['locations'],
self.logPath[table]['batch'])
shutil.copy(self.configFilePaths[table]['batch']['counts'],
self.logPath[table]['batch'])
shutil.copy(self.configFilePaths[table]['batch']['themes'],
self.logPath[table]['batch'])
shutil.copy(self.configFilePaths[table]['batch']['persons'],
self.logPath[table]['batch'])
shutil.copy(self.configFilePaths[table]['batch']['organizations'],
self.logPath[table]['batch'])
else:
shutil.copy(self.configFilePaths[table]['realtime'],
self.logPath[table]['realtime'])
os.chdir(self.logPath[table]['batch'])
shutil.copy(self.configFilePaths[table]['batch'],
self.logPath[table]['batch'])
# B00 - class methods
# B01
def batchEDA(self, tableList = ['events','mentions','gkg']):
'''Reshapes and re-types GDELT records for generating Pandas
Profiling ProfileReport()-automated, simple EDA reports from Pandas
DataFrames, from MongoDB-query-cursors.
WARNING: extremely RAM, disk I/O, and processing intensive. Be aware of
what resources are available for these operations at runtime.
Relies on Python multiprocessing.Pool.map() calls against class member
functions eventsBatchEDA() and mentionsBatchEDA(), and a regular call on
gkgBatchEDA(), which uses multiprocessing.Pool.map() | |
#!/usr/bin/env python
# Copyright (c) 2013 VMware, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
import logging
import mock
import mox
import neutronclient.v2_0.client
import unittest
from congress.datasources.neutron_driver import NeutronDriver
import congress.dse.d6cage
import congress.policy.compile as compile
import congress.tests.helper as helper
class TestNeutronDriver(unittest.TestCase):
def setUp(self):
self.neutron_client = mock.MagicMock()
self.network = network_response
self.ports = port_response
self.neutron_client.list_networks.return_value = self.network
self.neutron_client.list_ports.return_value = self.ports
self.driver = NeutronDriver(poll_time=0)
def test_list_networks(self):
"""Test conversion of complex network objects to tables."""
network_list = self.neutron_client.list_networks()
network_tuple_list = \
self.driver._get_tuple_list(network_list,
self.driver.NEUTRON_NETWORKS)
network_tuple = network_tuple_list[0]
network_subnet_tuples = self.driver.network_subnet
self.assertIsNotNone(network_tuple_list)
self.assertEquals(1, len(network_tuple_list))
self.assertEquals(1, len(network_subnet_tuples))
key_to_index = self.driver.network_key_position_map()
logging.info("key_to_index: " + str(key_to_index))
logging.info("network: " + str(network_tuple))
subnet_tuple_guid = network_tuple[key_to_index['subnets']]
guid_key = network_subnet_tuples[0][0]
guid_value = network_subnet_tuples[0][1]
name = network_tuple[key_to_index['name']]
status = network_tuple[key_to_index['status']]
provider_physical_network = \
network_tuple[key_to_index['provider:physical_network']]
admin_state_up = network_tuple[key_to_index['admin_state_up']]
tenant_id = network_tuple[key_to_index['tenant_id']]
provider_network_type = \
network_tuple[key_to_index['provider:network_type']]
router_external = network_tuple[key_to_index['router:external']]
shared = network_tuple[key_to_index['shared']]
id = network_tuple[key_to_index['id']]
provider_segmentation_id = \
network_tuple[key_to_index['provider:segmentation_id']]
self.assertEquals('ACTIVE', status)
self.assertIsNotNone(subnet_tuple_guid)
self.assertEqual(guid_key, subnet_tuple_guid)
self.assertEqual('4cef03d0-1d02-40bb-8c99-2f442aac6ab0',
guid_value)
self.assertEquals('test-network',
name)
self.assertEquals('None', provider_physical_network)
self.assertEquals('True', admin_state_up)
self.assertEquals('570fe78a1dc54cffa053bd802984ede2',
tenant_id)
self.assertEquals('gre', provider_network_type)
self.assertEquals('False', router_external)
self.assertEquals('False', shared)
self.assertEquals('240ff9df-df35-43ae-9df5-27fae87f2492',
id)
self.assertEquals(4, provider_segmentation_id)
def test_list_ports(self):
"""Test conversion of complex port objects to tuples."""
port_list = self.neutron_client.list_ports()
port_tuple_list = \
self.driver._get_tuple_list(port_list,
self.driver.NEUTRON_PORTS)
self.port_address_pairs = self.driver.port_address_pairs
self.port_security_groups = self.driver.port_security_groups
self.port_binding_capabilities = self.driver.port_binding_capabilities
self.port_extra_dhcp_opts = self.driver.port_extra_dhcp_opts
self.port_fixed_ips = self.driver.port_fixed_ips
self.assertIsNotNone(port_tuple_list)
self.assertEquals(1, len(port_tuple_list))
# Input
# [{"status": "ACTIVE",'+
# '"binding:host_id": "havana", "name": "",' +
# '"allowed_address_pairs": [],'+
# '"admin_state_up": True, ' +
# '"network_id": "240ff9df-df35-43ae-9df5-27fae87f2492",'+
# '"tenant_id": "570fe78a1dc54cffa053bd802984ede2",
# "extra_dhcp_opts": [],'+
# '"binding:vif_type": "ovs",' +
# '"device_owner": "network:router_interface",'+
# '"binding:capabilities": {"port_filter": True},' +
# '"mac_address": "fa:16:3e:ab:90:df",'+
# '"fixed_ips": [{"subnet_id":
# "4cef03d0-1d02-40bb-8c99-2f442aac6ab0",' +
# '"ip_address":"192.168.127.12"}],'+
# '"id": "0a2ce569-85a8-45ec-abb3-0d4b34ff69ba",
# "security_groups": [],'+
# '"device_id": "864e4acf-bf8e-4664-8cf7-ad5daa95681e"}]}')
# Output
# [('ACTIVE', 'havana', '', '90a579ea-ea45-11e3-a085-000c292422e8',
# 'True',
# '240ff9df-df35-43ae-9df5-27fae87f2492',
# '570fe78a1dc54cffa053bd802984ede2',
# '90a5b5a4-ea45-11e3-a085-000c292422e8', 'ovs',
# 'network:router_interface',
# '90a5f564-ea45-11e3-a085-000c292422e8', 'fa:16:3e:ab:90:df',
# '90a63222-ea45-11e3-a085-000c292422e8',
# '0a2ce569-85a8-45ec-abb3-0d4b34ff69ba',
# '90a6397a-ea45-11e3-a085-000c292422e8',
# '864e4acf-bf8e-4664-8cf7-ad5daa95681e')]
status = port_tuple_list[0][0]
binding_host_id = port_tuple_list[0][1]
name = port_tuple_list[0][2]
guid_allowed_address_pairs = port_tuple_list[0][3]
guid_allowed_address_pairs_expected = self.port_address_pairs[0]
admin_state_up = port_tuple_list[0][4]
network_id = port_tuple_list[0][5]
tenant_id = port_tuple_list[0][6]
guid_extra_dhcp_opts = port_tuple_list[0][7]
guid_extra_dhcp_opts_expected = self.port_extra_dhcp_opts[0][0]
extra_dhcp_opts_value_actual = self.port_extra_dhcp_opts[0][1]
binding_vif_type = port_tuple_list[0][8]
device_owner = port_tuple_list[0][9]
guid_binding_capabilities = port_tuple_list[0][10]
guid_binding_capabilities_expected = \
self.port_binding_capabilities[0][0]
binding_capabilities_key_actual = self.port_binding_capabilities[0][1]
binding_capabilities_value_actual = \
self.port_binding_capabilities[0][2]
mac_address = port_tuple_list[0][11]
guid_fixed_ips = port_tuple_list[0][12]
guid_fixed_ips_expected = self.port_fixed_ips[0][0]
fixed_ips_key_one = self.port_fixed_ips[0][1]
fixed_ips_value_one = self.port_fixed_ips[0][2]
fixed_ips_key_two = self.port_fixed_ips[1][1]
fixed_ips_value_two = self.port_fixed_ips[1][2]
id = port_tuple_list[0][13]
guid_security_groups = port_tuple_list[0][14]
guid_security_groups_expected = self.port_security_groups[0][0]
security_groups_value = self.port_security_groups[0][1]
device_id = port_tuple_list[0][15]
self.assertEqual('ACTIVE', status)
self.assertEqual('havana', binding_host_id)
self.assertEqual('', name)
self.assertEqual(guid_allowed_address_pairs_expected[0],
guid_allowed_address_pairs)
self.assertEqual(1, len(self.port_address_pairs))
self.assertEqual('', self.port_address_pairs[0][1])
self.assertEqual('True', admin_state_up)
self.assertEqual('240ff9df-df35-43ae-9df5-27fae87f2492', network_id)
self.assertEqual('570fe78a1dc54cffa053bd802984ede2', tenant_id)
self.assertEqual(guid_extra_dhcp_opts_expected, guid_extra_dhcp_opts)
self.assertEqual(1, len(self.port_extra_dhcp_opts))
self.assertEqual('', extra_dhcp_opts_value_actual)
self.assertEqual(guid_binding_capabilities_expected,
guid_binding_capabilities)
self.assertEqual(1, len(self.port_binding_capabilities))
self.assertEqual('port_filter', binding_capabilities_key_actual)
self.assertEqual('True', binding_capabilities_value_actual)
self.assertEqual('ovs', binding_vif_type)
self.assertEqual('network:router_interface', device_owner)
# '"fixed_ips": [{"subnet_id":
# "4cef03d0-1d02-40bb-8c99-2f442aac6ab0",' +
# '"ip_address":"192.168.127.12"}],'+
self.assertEqual(guid_fixed_ips_expected, guid_fixed_ips)
self.assertEqual(2, len(self.port_fixed_ips))
self.assertEqual('subnet_id', fixed_ips_key_one)
self.assertEqual('4cef03d0-1d02-40bb-8c99-2f442aac6ab0',
fixed_ips_value_one)
self.assertEqual('ip_address', fixed_ips_key_two)
self.assertEqual('192.168.127.12', fixed_ips_value_two)
self.assertEqual('fa:16:3e:ab:90:df', mac_address)
self.assertEqual('0a2ce569-85a8-45ec-abb3-0d4b34ff69ba', id)
self.assertEqual(guid_security_groups_expected,
guid_security_groups)
self.assertEqual(1, len(self.port_security_groups))
self.assertEqual('', security_groups_value)
self.assertEqual('864e4acf-bf8e-4664-8cf7-ad5daa95681e', device_id)
#### Tests for DataSourceDriver
# Note: these tests are really testing the functionality of the class
# DataSourceDriver, but it's useful to use an actual subclass so
# we can test the functionality end-to-end. We use Neutron for
# that subclass. Leaving it in this file so that it is clear
# that when the Neutron driver changes, these tests may need
# to change as well. Tried to minimize the number of changes
# necessary.
def setup_polling(self, debug_mode=False):
"""Setup polling tests."""
cage = congress.dse.d6cage.d6Cage()
# so that we exit once test finishes; all other threads are forced
# to be daemons
cage.daemon = True
cage.start()
# Create mock of Neutron client so we can control data
mock_factory = mox.Mox()
neutron_client = mock_factory.CreateMock(
neutronclient.v2_0.client.Client)
neutron_client.list_networks().InAnyOrder(1).AndReturn(network1)
neutron_client.list_ports().InAnyOrder(1).AndReturn(port_response)
neutron_client.list_networks().InAnyOrder(2).AndReturn(network2)
neutron_client.list_ports().InAnyOrder(2).AndReturn(port_response)
mock_factory.ReplayAll()
# Create modules (without auto-polling)
cage.loadModule("NeutronDriver",
helper.data_module_path("neutron_driver.py"))
cage.loadModule("PolicyDriver", helper.policy_module_path())
cage.createservice(name="policy", moduleName="PolicyDriver")
cage.createservice(name="neutron", moduleName="NeutronDriver",
args={'poll_time': 0,
'client': neutron_client})
policy = cage.service_object('policy')
# Make it so that we get detailed info from policy engine
if debug_mode:
policy.debug_mode()
# insert rule into policy to make testing easier.
# (Some of the IDs are auto-generated each time we convert)
policy.insert(create_network_group('p'))
# create some garbage data
network_key_to_index = NeutronDriver.network_key_position_map()
network_max_index = max(network_key_to_index.values())
args1 = ['1'] * (network_max_index + 1)
args2 = ['2'] * (network_max_index + 1)
args1 = ",".join(args1)
args2 = ",".join(args2)
fake_networks = [
'neutron:networks({})'.format(args1),
'neutron:networks({})'.format(args2)]
# answer to query above for network1
datalog1 = \
('p("240ff9df-df35-43ae-9df5-27fae87f2492") '
'p("340ff9df-df35-43ae-9df5-27fae87f2492") '
'p("440ff9df-df35-43ae-9df5-27fae87f2492")')
# answer to query above for network2
datalog2 = \
('p("240ff9df-df35-43ae-9df5-27fae87f2492") '
'p("640ff9df-df35-43ae-9df5-27fae87f2492") '
'p("540ff9df-df35-43ae-9df5-27fae87f2492")')
# return value
d = {}
d['cage'] = cage
d['datalog1'] = datalog1
d['datalog2'] = datalog2
d['fake_networks'] = fake_networks
return d
def test_subscribe_poll(self):
"""Test subscribing before polling. The common case."""
info = self.setup_polling()
cage = info['cage']
policy = cage.service_object('policy')
neutron = cage.service_object('neutron')
datalog1 = info['datalog1']
datalog2 = info['datalog2']
# subscribe
policy.subscribe('neutron', 'networks', callback=policy.receive_data)
helper.pause() # so that subscription messages are processed
# poll 1
neutron.poll()
helper.pause() # so that data updates are processed
e = helper.db_equal(policy.select('p(x)'), datalog1)
self.assertTrue(e, 'Neutron insertion 1')
# poll 2
neutron.poll()
helper.pause()
e = helper.db_equal(policy.select('p(x)'), datalog2)
self.assertTrue(e, 'Neutron insertion 2')
def test_policy_initialization(self):
"""Test subscribing before polling. The common case."""
info = self.setup_polling()
cage = info['cage']
policy = cage.service_object('policy')
neutron = cage.service_object('neutron')
datalog1 = info['datalog1']
fake_networks = info['fake_networks']
# add garbage to policy
for formula in fake_networks:
logging.debug("Inserting fake_network: " + str(formula))
policy.insert(formula)
# subscribe
policy.subscribe('neutron', 'networks', callback=policy.receive_data)
helper.pause() # so that subscription messages are processed
# poll 1
neutron.poll()
helper.pause() # so that data updates are processed
e = helper.db_equal(policy.select('p(x)'), datalog1)
self.assertTrue(e, 'Neutron insertion 1')
def test_poll_subscribe(self):
"""Test polling before subscribing."""
info = self.setup_polling()
cage = info['cage']
policy = cage.service_object('policy')
neutron = cage.service_object('neutron')
datalog1 = info['datalog1']
datalog2 = info['datalog2']
fake_networks = info['fake_networks']
# add garbage to policy
for formula in fake_networks:
logging.debug("Inserting fake_network: " + str(formula))
policy.insert(formula)
# poll 1 and then subscribe; should still see first result
neutron.poll()
helper.pause() # so that data is sent
policy.subscribe('neutron', 'networks', callback=policy.receive_data)
helper.pause() # so that data updates are processed
e = helper.db_equal(policy.select('p(x)'), datalog1)
self.assertTrue(e, 'Neutron insertion 1')
# poll 2
neutron.poll()
helper.pause()
e = helper.db_equal(policy.select('p(x)'), datalog2)
self.assertTrue(e, 'Neutron insertion 2')
def test_double_poll_subscribe(self):
"""Test double polling before subscribing."""
info = self.setup_polling()
cage = info['cage']
policy = cage.service_object('policy')
neutron = cage.service_object('neutron')
datalog2 = info['datalog2']
# poll twice and then subscribe: should see 2nd result
neutron.poll()
helper.pause()
neutron.poll()
helper.pause()
policy.subscribe('neutron', 'networks', callback=policy.receive_data)
helper.pause() # so that messages are processed
e = helper.db_equal(policy.select('p(x)'), datalog2)
self.assertTrue(e, 'Neutron insertion 2')
def test_policy_recovery(self):
"""Test policy crashing and recovering (sort of)."""
info = self.setup_polling()
cage = info['cage']
policy = cage.service_object('policy')
neutron = cage.service_object('neutron')
datalog1 = info['datalog1']
# get initial data
policy.subscribe('neutron', 'networks', callback=policy.receive_data)
helper.pause()
neutron.poll()
helper.pause()
e = helper.db_equal(policy.select('p(x)'), datalog1)
self.assertTrue(e, 'Neutron insertion 1')
# clear out policy's neutron:networks data (to simulate crashing)
policy.initialize(['neutron:networks'], [])
# subscribe again (without unsubscribing)
policy.subscribe('neutron', 'networks', callback=policy.receive_data)
helper.pause()
# should get same data
e = helper.db_equal(policy.select('p(x)'), datalog1)
self.assertTrue(e, 'Neutron insertion 1')
def create_network_group(tablename, full_neutron_tablename=None):
if full_neutron_tablename is None:
full_neutron_tablename = 'neutron:networks'
network_key_to_index = NeutronDriver.network_key_position_map()
network_id_index = network_key_to_index['id']
network_max_index = max(network_key_to_index.values())
network_args = ['x' + str(i) for i in xrange(0, network_max_index + 1)]
formula = compile.parse1(
'{}({}) :- {}({})'.format(
tablename,
'x' + str(network_id_index),
full_neutron_tablename,
",".join(network_args)))
return formula
# Only diffs between network1 and network2 are the IDs
network1 = {'networks': [
{'status': 'ACTIVE',
'subnets': '4cef03d0-1d02-40bb-8c99-2f442aac6ab0',
'name': 'test-network',
'provider:physical_network': None,
'admin_state_up': True,
'tenant_id': '570fe78a1dc54cffa053bd802984ede2',
'provider:network_type': 'gre',
'router:external': False,
'shared': False,
'id': '240ff9df-df35-43ae-9df5-27fae87f2492',
'provider:segmentation_id': 4},
{'status': 'ACTIVE',
'subnets': '4cef03d0-1d02-40bb-8c99-2f442aac6ab0',
'name': 'test-network',
'provider:physical_network': None,
'admin_state_up': True,
'tenant_id': '570fe78a1dc54cffa053bd802984ede2',
'provider:network_type': 'gre',
'router:external': False,
'shared': False,
'id': '340ff9df-df35-43ae-9df5-27fae87f2492',
'provider:segmentation_id': 4},
{'status': 'ACTIVE',
'subnets': '4cef03d0-1d02-40bb-8c99-2f442aac6ab0',
'name': 'test-network',
'provider:physical_network': None,
'admin_state_up': True,
'tenant_id': '570fe78a1dc54cffa053bd802984ede2',
'provider:network_type': 'gre',
'router:external': False,
'shared': False,
'id': '440ff9df-df35-43ae-9df5-27fae87f2492',
'provider:segmentation_id': 4}]}
network2 = {'networks': [
{'status': | |
from beem.utils import formatTimeString, resolve_authorperm, construct_authorperm, addTzInfo
from beem.nodelist import NodeList
from beem.comment import Comment
from beem import Steem
from beem.account import Account
from beem.instance import set_shared_steem_instance
from beem.blockchain import Blockchain
import time
import json
import os
import math
import dataset
import random
from datetime import date, datetime, timedelta
from dateutil.parser import parse
from beem.constants import STEEM_100_PERCENT
from steemrewarding.post_storage import PostsTrx
from steemrewarding.command_storage import CommandsTrx
from steemrewarding.vote_rule_storage import VoteRulesTrx
from steemrewarding.pending_vote_storage import PendingVotesTrx
from steemrewarding.config_storage import ConfigurationDB
from steemrewarding.vote_storage import VotesTrx
from steemrewarding.vote_log_storage import VoteLogTrx
from steemrewarding.failed_vote_log_storage import FailedVoteLogTrx
from steemrewarding.broadcast_vote_storage import BroadcastVoteTrx
from steemrewarding.utils import isfloat, upvote_comment, valid_age, upvote_comment_without_check
from steemrewarding.version import version as rewardingversion
from steemrewarding.account_storage import AccountsDB
from steemrewarding.version import version as rewarding_version
import dataset
if __name__ == "__main__":
config_file = 'config.json'
if not os.path.isfile(config_file):
raise Exception("config.json is missing!")
else:
with open(config_file) as json_data_file:
config_data = json.load(json_data_file)
# print(config_data)
databaseConnector = config_data["databaseConnector"]
wallet_password = config_data["wallet_password"]
posting_auth_acc = config_data["posting_auth_acc"]
voting_round_sec = config_data["voting_round_sec"]
start_prep_time = time.time()
db = dataset.connect(databaseConnector)
# Create keyStorage
print("Start upvote_post_comments_timebased.py")
nobroadcast = False
# nobroadcast = True
postTrx = PostsTrx(db)
votesTrx = VotesTrx(db)
voteRulesTrx = VoteRulesTrx(db)
confStorage = ConfigurationDB(db)
pendingVotesTrx = PendingVotesTrx(db)
voteLogTrx = VoteLogTrx(db)
failedVoteLogTrx = FailedVoteLogTrx(db)
accountsTrx = AccountsDB(db)
broadcastVoteTrx = BroadcastVoteTrx(db)
conf_setup = confStorage.get()
# last_post_block = conf_setup["last_post_block"]
nodes = NodeList()
# nodes.update_nodes(weights={"block": 1})
try:
nodes.update_nodes()
except:
print("could not update nodes")
node_list = nodes.get_nodes(exclude_limited=False)
stm = Steem(node=node_list, num_retries=5, call_num_retries=3, timeout=15, nobroadcast=nobroadcast)
stm.wallet.unlock(wallet_password)
last_voter = None
print("Start apply new timebased votes")
voter_counter = 0
delete_pending_votes = []
rc_sp_to_low_account_list = []
vote_counter = 0
vote_count = 0
for pending_vote in pendingVotesTrx.get_command_list_timed():
settings = None
voter_acc = None
author, permlink = resolve_authorperm(pending_vote["authorperm"])
if pending_vote["voter"] in rc_sp_to_low_account_list:
continue
age_min = (datetime.utcnow() - pending_vote["comment_timestamp"]).total_seconds() / 60
maximum_vote_delay_min = pending_vote["maximum_vote_delay_min"]
if age_min < pending_vote["vote_delay_min"] - voting_round_sec / 2.0 / 60 - 3:
# print("%s is not ready yet - %.2f min should be %.2f" % (pending_vote["authorperm"], age_min, pending_vote["vote_delay_min"]))
continue
if settings is None:
settings = accountsTrx.get(pending_vote["voter"])
if settings is None:
voter_acc = Account(pending_vote["voter"], steem_instance=stm)
print("update %s - did not exists" % pending_vote["voter"])
posting_auth = False
for a in voter_acc["posting"]["account_auths"]:
if a[0] == posting_auth_acc:
posting_auth = True
if pending_vote["voter"] == posting_auth_acc:
posting_auth = True
accountsTrx.upsert({"name": pending_vote["voter"], "vp_update":datetime.utcnow(), "vp": voter_acc.vp, "down_vp": voter_acc.get_downvoting_power(),
"sp": voter_acc.sp, "rc": voter_acc.get_rc_manabar()["current_mana"] / 1e9, "last_update": datetime.utcnow(),
"posting_auth_acc": posting_auth})
pause_votes_below_vp = 0
settings = accountsTrx.get(pending_vote["voter"])
elif settings["sp"] is None or settings["vp"] is None or settings["last_update"] is None or settings["rc"] is None or settings["posting_auth_acc"] is None:
print("update %s - None" % pending_vote["voter"])
voter_acc = Account(pending_vote["voter"], steem_instance=stm)
posting_auth = False
for a in voter_acc["posting"]["account_auths"]:
if a[0] == posting_auth_acc:
posting_auth = True
if pending_vote["voter"] == posting_auth_acc:
posting_auth = True
accountsTrx.upsert({"name": pending_vote["voter"], "vp_update":datetime.utcnow(), "vp": voter_acc.vp, "down_vp": voter_acc.get_downvoting_power(),
"sp": voter_acc.sp, "rc": voter_acc.get_rc_manabar()["current_mana"] / 1e9, "last_update": datetime.utcnow(),
"posting_auth_acc": posting_auth})
settings = accountsTrx.get(pending_vote["voter"])
elif (datetime.utcnow() - settings["last_update"]).total_seconds() / 60 > 1:
print("update %s - last update was before %f s" % (pending_vote["voter"], (datetime.utcnow() - settings["last_update"]).total_seconds()))
voter_acc = Account(pending_vote["voter"], steem_instance=stm)
posting_auth = False
for a in voter_acc["posting"]["account_auths"]:
if a[0] == posting_auth_acc:
posting_auth = True
if pending_vote["voter"] == posting_auth_acc:
posting_auth = True
accountsTrx.upsert({"name": pending_vote["voter"], "vp_update":datetime.utcnow(), "vp": voter_acc.vp, "down_vp": voter_acc.get_downvoting_power(),
"sp": voter_acc.sp, "rc": voter_acc.get_rc_manabar()["current_mana"] / 1e9, "last_update": datetime.utcnow(),
"posting_auth_acc": posting_auth})
settings = accountsTrx.get(pending_vote["voter"])
if pending_vote["vote_weight"] > 0:
pause_votes_below_vp = settings["pause_votes_below_vp"]
vp = settings["vp"]
else:
pause_votes_below_vp = settings["pause_down_votes_below_down_vp"]
vp = settings["down_vp"]
vp_update = settings["last_update"]
if vp_update is not None:
diff_in_seconds = ((datetime.utcnow()) - (vp_update)).total_seconds()
regenerated_vp = diff_in_seconds * 10000 / 432000 / 100
vp = vp + regenerated_vp
#down_vp = down_vp + regenerated_vp
if vp > 100:
vp = 100
#if down_vp > 100:
# down_vp = 100
if vp < pause_votes_below_vp:
failedVoteLogTrx.add({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "error": "Voting is paused (VP = %.2f %%, which below pause_votes_below_vp of %.2f %%)" % (vp, pause_votes_below_vp),
"timestamp": datetime.utcnow(), "vote_weight": pending_vote["vote_weight"], "vote_delay_min": pending_vote["vote_delay_min"],
"min_vp": pending_vote["min_vp"], "vp": settings["vp"], "down_vp": settings["down_vp"], "vote_when_vp_reached": pending_vote["vote_when_vp_reached"],
"main_post": pending_vote["main_post"]})
delete_pending_votes.append({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "vote_when_vp_reached": pending_vote["vote_when_vp_reached"]})
continue
# print("time vote %.2f s - %d votes" % (time.time() - start_prep_time, vote_count))
if (pending_vote["vote_weight"] is None or pending_vote["vote_weight"] == 0) and (pending_vote["vote_sbd"] is None or float(pending_vote["vote_sbd"]) <= 0):
# voter_acc = Account(pending_vote["voter"], steem_instance=stm)
failedVoteLogTrx.add({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "error": "vote_weight was set to zero. (%s %% and %s $)" % (pending_vote["vote_weight"], pending_vote["vote_sbd"]),
"timestamp": datetime.utcnow(), "vote_weight": pending_vote["vote_weight"], "vote_delay_min": pending_vote["vote_delay_min"],
"min_vp": pending_vote["min_vp"], "vp": settings["vp"], "down_vp": settings["down_vp"], "vote_when_vp_reached": pending_vote["vote_when_vp_reached"],
"main_post": pending_vote["main_post"]})
delete_pending_votes.append({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "vote_when_vp_reached": pending_vote["vote_when_vp_reached"]})
continue
if maximum_vote_delay_min < 0:
maximum_vote_delay_min = 9360
if age_min > maximum_vote_delay_min + voting_round_sec / 60:
# voter_acc = Account(pending_vote["voter"], steem_instance=stm)
failedVoteLogTrx.add({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "error": "post is older than %.2f min." % (maximum_vote_delay_min),
"timestamp": datetime.utcnow(), "vote_weight": pending_vote["vote_weight"], "vote_delay_min": pending_vote["vote_delay_min"],
"min_vp": pending_vote["min_vp"], "vp": settings["vp"], "down_vp": settings["down_vp"], "vote_when_vp_reached": pending_vote["vote_when_vp_reached"],
"main_post": pending_vote["main_post"]})
delete_pending_votes.append({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "vote_when_vp_reached": pending_vote["vote_when_vp_reached"]})
continue
voter_counter += 1
# voter_acc = Account(pending_vote["voter"], steem_instance=stm)
if settings["sp"] < 0.1:
failedVoteLogTrx.add({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "error": "Could not vot %s, as Steem Power is almost zero." % (pending_vote["authorperm"]),
"timestamp": datetime.utcnow(), "vote_weight": pending_vote["vote_weight"], "vote_delay_min": pending_vote["vote_delay_min"],
"min_vp": pending_vote["min_vp"], "vp": settings["vp"], "down_vp": settings["down_vp"], "vote_when_vp_reached": pending_vote["vote_when_vp_reached"],
"main_post": pending_vote["main_post"]})
delete_pending_votes.append({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "vote_when_vp_reached": pending_vote["vote_when_vp_reached"]})
print("Could not process %s - sp < 0.1" % pending_vote["authorperm"])
rc_sp_to_low_account_list.append(pending_vote["voter"])
continue
if settings["rc"] < 0.5:
failedVoteLogTrx.add({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "error": "Could not vot %s, as RC is almost zero." % (pending_vote["authorperm"]),
"timestamp": datetime.utcnow(), "vote_weight": pending_vote["vote_weight"], "vote_delay_min": pending_vote["vote_delay_min"],
"min_vp": pending_vote["min_vp"], "vp": settings["vp"], "down_vp": settings["down_vp"], "vote_when_vp_reached": pending_vote["vote_when_vp_reached"],
"main_post": pending_vote["main_post"]})
delete_pending_votes.append({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "vote_when_vp_reached": pending_vote["vote_when_vp_reached"]})
print("Could not process %s - rc to low" % pending_vote["authorperm"])
rc_sp_to_low_account_list.append(pending_vote["voter"])
continue
vote_weight = pending_vote["vote_weight"]
if vote_weight is None or vote_weight == 0:
voter_acc = Account(pending_vote["voter"], steem_instance=stm)
vote_weight = voter_acc.get_vote_pct_for_SBD(float(pending_vote["vote_sbd"])) / 100.
if vote_weight > 100:
vote_weight = 100
elif vote_weight < 0.01:
failedVoteLogTrx.add({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "error": "vote_weight was set to zero.",
"timestamp": datetime.utcnow(), "vote_weight": vote_weight, "vote_delay_min": pending_vote["vote_delay_min"],
"min_vp": pending_vote["min_vp"], "vp": voter_acc.vp, "vote_when_vp_reached": pending_vote["vote_when_vp_reached"],
"main_post": pending_vote["main_post"]})
delete_pending_votes.append({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "vote_when_vp_reached": pending_vote["vote_when_vp_reached"]})
continue
age_hour = ((datetime.utcnow()) - pending_vote["created"]).total_seconds() / 60 / 60
if age_hour > 156:
failedVoteLogTrx.add({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "error": "post is older than 6.5 days.",
"timestamp": datetime.utcnow(), "vote_weight": vote_weight, "vote_delay_min": pending_vote["vote_delay_min"],
"min_vp": pending_vote["min_vp"], "vp": settings["vp"], "down_vp": settings["down_vp"], "vote_when_vp_reached": pending_vote["vote_when_vp_reached"],
"main_post": pending_vote["main_post"]})
delete_pending_votes.append({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "vote_when_vp_reached": pending_vote["vote_when_vp_reached"]})
continue
if vp < pending_vote["min_vp"]:
failedVoteLogTrx.add({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "error": "Voting power is %.2f %%, which is to low. (min_vp is %.2f %%)" % (vp, pending_vote["min_vp"]),
"timestamp": datetime.utcnow(), "vote_weight": vote_weight, "vote_delay_min": pending_vote["vote_delay_min"],
"min_vp": pending_vote["min_vp"], "vp": settings["vp"], "down_vp": settings["down_vp"], "vote_when_vp_reached": pending_vote["vote_when_vp_reached"],
"main_post": pending_vote["main_post"]})
delete_pending_votes.append({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "vote_when_vp_reached": pending_vote["vote_when_vp_reached"]})
continue
if pending_vote["max_votes_per_day"] > -1:
if settings is None:
settings = accountsTrx.get(pending_vote["voter"])
if settings is not None:
sliding_time_window = settings["sliding_time_window"]
else:
sliding_time_window = True
votes_24h_before = voteLogTrx.get_votes_per_day(pending_vote["voter"], author, sliding_time_window)
if votes_24h_before >= pending_vote["max_votes_per_day"]:
failedVoteLogTrx.add({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "error": "The author was already upvoted %d in the last 24h (max_votes_per_day is %d)." % (votes_24h_before, pending_vote["max_votes_per_day"]),
"timestamp": datetime.utcnow(), "vote_weight": vote_weight, "vote_delay_min": pending_vote["vote_delay_min"],
"min_vp": pending_vote["min_vp"], "vp": settings["vp"], "down_vp": settings["down_vp"], "vote_when_vp_reached": pending_vote["vote_when_vp_reached"],
"main_post": pending_vote["main_post"]})
delete_pending_votes.append({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "vote_when_vp_reached": pending_vote["vote_when_vp_reached"]})
continue
if pending_vote["max_votes_per_week"] > -1:
if settings is None:
settings = accountsTrx.get(pending_vote["voter"])
if settings is not None:
sliding_time_window = settings["sliding_time_window"]
else:
sliding_time_window = True
votes_168h_before = voteLogTrx.get_votes_per_week(pending_vote["voter"], author, sliding_time_window)
if votes_168h_before >= pending_vote["max_votes_per_week"]:
failedVoteLogTrx.add({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "error": "The author was already upvoted %d in the last 7 days (max_votes_per_week is %d)." % (votes_168h_before, pending_vote["max_votes_per_week"]),
"timestamp": datetime.utcnow(), "vote_weight": vote_weight, "vote_delay_min": pending_vote["vote_delay_min"],
"min_vp": pending_vote["min_vp"], "vp": settings["vp"], "down_vp": settings["down_vp"],"vote_when_vp_reached": pending_vote["vote_when_vp_reached"],
"main_post": pending_vote["main_post"]})
delete_pending_votes.append({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "vote_when_vp_reached": pending_vote["vote_when_vp_reached"]})
continue
if pending_vote["vp_scaler"] > 0:
vote_weight *= 1 - ((100 - vp) / 100 * pending_vote["vp_scaler"])
if abs(vote_weight) < 0.02:
error_msg = "Vote weight is zero or below zero (%.2f %%)" % vote_weight
failedVoteLogTrx.add({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "error": error_msg,
"timestamp": datetime.utcnow(), "vote_weight": vote_weight, "vote_delay_min": pending_vote["vote_delay_min"],
"min_vp": pending_vote["min_vp"], "vp": settings["vp"], "down_vp": settings["down_vp"],"vote_when_vp_reached": pending_vote["vote_when_vp_reached"],
"main_post": pending_vote["main_post"]})
delete_pending_votes.append({"authorperm": pending_vote["authorperm"], "voter": pending_vote["voter"], "vote_when_vp_reached": pending_vote["vote_when_vp_reached"]})
continue
cnt = 0
c = None
while c is None and cnt < 5:
cnt += 1
| |
<reponame>mahmoud/hematite
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from hematite.constants import (REQUEST_HEADERS,
RESPONSE_HEADERS,
FOLDABLE_HEADERS,
HEADER_CASE_MAP)
from hematite.serdes import (quote_header_value,
unquote_header_value,
http_date_to_bytes,
http_date_from_bytes,
range_spec_to_bytes,
range_spec_from_bytes,
list_header_to_bytes,
list_header_from_bytes,
retry_after_to_bytes,
retry_after_from_bytes,
items_header_to_bytes,
items_header_from_bytes,
accept_header_to_bytes,
accept_header_from_bytes,
default_header_to_bytes,
default_header_from_bytes,
content_header_from_bytes,
content_range_spec_from_bytes,
content_range_spec_to_bytes)
from hematite.url import URL, parse_hostinfo, QueryParamDict
ALL_FIELDS = None
RESPONSE_FIELDS = None
REQUEST_FIELDS = None
HTTP_REQUEST_FIELDS = None
def _init_field_lists():
global ALL_FIELDS, RESPONSE_FIELDS, REQUEST_FIELDS, HTTP_REQUEST_FIELDS
global_vals = globals().values()
ALL_FIELDS = [f for f in global_vals if isinstance(f, HTTPHeaderField)]
RESPONSE_FIELDS = [f for f in ALL_FIELDS
if f.http_name in RESPONSE_HEADERS]
HTTP_REQUEST_FIELDS = [f for f in ALL_FIELDS
if f.http_name in REQUEST_HEADERS]
_url_request_field_types = [f for f in global_vals if isinstance(f, type)
and issubclass(f, BaseURLField)]
URL_REQUEST_FIELDS = [f() for f in _url_request_field_types]
REQUEST_FIELDS = HTTP_REQUEST_FIELDS + URL_REQUEST_FIELDS
class HeaderValueWrapper(object):
# TODO: how to indicate whether header value should be included
# - __nonzero__ can collide with int-typed headers where 0 is valid
# - a blank to_bytes() output might work, but is a bit confusing
pass
class ETag(HeaderValueWrapper):
def __init__(self, tag, is_weak=None):
self.tag = tag
self.is_weak = is_weak or False
def to_bytes(self):
if self.tag == '*':
return '*' # can't have a weak star
ret = quote_header_value(self.tag, allow_token=False)
if self.is_weak:
ret = 'W/' + ret
return ret
@classmethod
def from_bytes(cls, bytestr):
tag = bytestr.strip()
first_two = tag[:2]
if first_two == 'W/' or first_two == 'w/':
is_weak = True
tag = tag[2:]
else:
is_weak = False
tag = unquote_header_value(tag)
return cls(tag=tag, is_weak=is_weak)
def __repr__(self):
cn = self.__class__.__name__
return '%s(%r, is_weak=%r)' % (cn, self.tag, self.is_weak)
class ETagSet(HeaderValueWrapper):
"""
TODO: all the matching logic
"""
def __init__(self, etags=None):
etags = list(etags or [])
self.etags = etags
@classmethod
def from_bytes(cls, bytestr):
etags = []
raw_tags = bytestr.split(',')
for raw_tag in raw_tags:
etags.append(ETag.from_bytes(raw_tag))
# TODO except on ValueError, drop invalid etags
return cls(etags=etags)
def to_bytes(self):
return ', '.join([etag.to_bytes() for etag in self.etags])
def __len__(self):
return len(self.etags)
def __repr__(self):
cn = self.__class__.__name__
return '%s(%r)' % (cn, self.etags)
class Range(HeaderValueWrapper):
def __init__(self, ranges=None, unit=None):
self.ranges = ranges or []
self.unit = unit or 'bytes'
@classmethod
def from_bytes(cls, bytestr):
unit, ranges = range_spec_from_bytes(bytestr)
return cls(unit=unit, ranges=ranges)
def to_bytes(self):
return range_spec_to_bytes((self.unit, self.ranges))
def __repr__(self):
cn = self.__class__.__name__
return '%s(ranges=%r, unit=%r)' % (cn, self.ranges, self.unit)
class ContentRange(HeaderValueWrapper):
def __init__(self, begin=None, end=None, total=None, unit=None):
self.begin, self.end, self.total, self.unit = begin, end, total, unit
@classmethod
def from_bytes(cls, bytestr):
unit, begin, end, total = content_range_spec_from_bytes(bytestr)
return cls(begin=begin, end=end, total=total, unit=unit)
def to_bytes(self):
return content_range_spec_to_bytes((self.unit, self.begin,
self.end, self.total))
def __repr__(self):
cn = self.__class__.__name__
return ('%s(begin=%r, end=%r, total=%r, unit=%r)'
% (cn, self.begin, self.end, self.total, self.unit))
class Field(object):
attr_name = None
def __delete__(self, obj):
raise AttributeError("can't delete field '%s'" % self.attr_name)
def __repr__(self):
cn = self.__class__.__name__
return '%s("%s")' % (cn, self.attr_name)
class HTTPHeaderField(Field):
def __init__(self, name, **kw):
assert name
assert name == name.lower()
self.attr_name = name # used for error messages
http_name = kw.pop('http_name', None)
if http_name is None:
http_name = HEADER_CASE_MAP[name.lower().replace('_', '-')]
self.http_name = http_name
self.native_type = kw.pop('native_type', unicode)
default_from_bytes = (getattr(self.native_type, 'from_bytes', None)
or default_header_from_bytes)
default_to_bytes = (getattr(self.native_type, 'to_bytes', None)
or default_header_to_bytes)
self.from_bytes = kw.pop('from_bytes', default_from_bytes)
self.to_bytes = kw.pop('to_bytes', default_to_bytes)
from_list = getattr(self.native_type, 'from_list', None)
self.from_list = from_list if callable(from_list) else None
from_tuple = getattr(self.native_type, 'from_tuple', None)
self.from_tuple = from_tuple if callable(from_tuple) else None
if kw:
raise TypeError('unexpected keyword arguments: %r' % kw)
self.is_foldable = self.http_name in FOLDABLE_HEADERS
# TODO: documentation field
# TODO: validate
def __get__(self, obj, objtype=None):
if obj is None:
return self
try:
return obj.headers[self.http_name]
except KeyError:
raise AttributeError(self.attr_name)
def _default_set_value(self, obj, value):
# TODO: special handling for None? text/unicode type? (i.e, not bytes)
if isinstance(value, str):
if value:
value = self.from_bytes(value)
elif value is None:
pass
elif not isinstance(value, self.native_type):
vtn = value.__class__.__name__
ntn = self.native_type.__name__
# TODO: include trunc'd value in addition to input type name
raise TypeError('expected bytes or %s for %s, not %s'
% (ntn, self.attr_name, vtn))
# TODO: if obj.headers.get(self.http_name) != value:
obj.headers[self.http_name] = value
__set__ = _default_set_value
date = HTTPHeaderField('date',
from_bytes=http_date_from_bytes,
to_bytes=http_date_to_bytes,
native_type=datetime)
last_modified = HTTPHeaderField('last_modified',
from_bytes=http_date_from_bytes,
to_bytes=http_date_to_bytes,
native_type=datetime)
etag = HTTPHeaderField('etag', native_type=ETag)
def expires_from_bytes(bytestr):
"""
According to RFC2616 14.21, invalid Expires headers MUST treat
invalid timestamps as "already expired", thus the epoch datetime.
"""
try:
return http_date_from_bytes(bytestr)
except:
return datetime.utcfromtimestamp(0)
expires = HTTPHeaderField('expires',
from_bytes=expires_from_bytes,
to_bytes=http_date_to_bytes,
native_type=datetime)
class ContentType(HeaderValueWrapper):
def __init__(self, media_type, charset=None, params=None):
self.media_type = media_type
self.charset = charset
self.params = dict(params) if params else {}
@classmethod
def from_bytes(cls, bytestr):
# TODO: order
media_type, items = content_header_from_bytes(bytestr)
params = dict(items)
charset = params.pop('charset', None)
return cls(media_type=media_type, charset=charset, params=params)
def to_bytes(self):
# TODO: quote parameter values
parts = [self.media_type]
if self.charset:
parts.append('charset=' + self.charset)
if self.params:
parts.extend(['%s=%s' % (k, v) for k, v in self.params.items()])
return '; '.join(parts)
def __repr__(self):
cn = self.__class__.__name__
if self.params:
return ('%s(%r, charset=%r, params=%r)'
% (cn, self.media_type, self.charset, self.params))
return '%s(%r, charset=%r)' % (cn, self.media_type, self.charset)
content_type = HTTPHeaderField('content_type', native_type=ContentType)
class ContentDisposition(HeaderValueWrapper):
def __init__(self,
disp_type,
filename=None,
filename_ext=None,
params=None):
self.disp_type = disp_type
self.filename = filename
self.filename_ext = filename_ext
self.params = dict(params) if params else {}
@classmethod
def from_bytes(cls, bytestr):
# TODO: RFC5987 decoding and saving of ext charsets where applicable
disp_type, params = content_header_from_bytes(bytestr)
filename, filename_ext, ext_params = None, None, []
for item in params:
if item[0].lower() == 'filename':
filename = item[1]
elif item[0].lower() == 'filename*':
filename_ext = item[1]
else:
ext_params.append(item)
return cls(disp_type=disp_type,
filename=filename,
filename_ext=filename_ext,
params=ext_params)
def to_bytes(self):
# TODO: quote parameter values
parts = [self.disp_type]
if self.filename is not None:
parts.append('filename=' + self.filename)
if self.filename_ext is not None:
parts.append('filename*=' + self.filename_ext)
if self.params:
parts.extend(['%s=%s' % (k, v) for k, v in self.params.items()])
return '; '.join(parts)
def get_filename(self, coerce_ext=True):
"""TODO: convenience method that automatically bridges the
presence of filename/filename_ext"""
@property
def is_inline(self):
return self.disp_type.lower() == 'inline'
@property
def is_attachment(self):
return self.disp_type.lower() == 'attachment'
def __repr__(self):
cn = self.__class__.__name__
if self.params:
return ('%s(%r, filename=%r, filename_ext=%r, params=%r)'
% (cn, self.disp_type, self.filename,
self.filename_ext, self.params))
return ('%s(%r, filename=%r, filename_ext=%r)'
% (cn, self.disp_type, self.filename, self.filename_ext))
content_disposition = HTTPHeaderField('content_disposition',
native_type=ContentDisposition)
content_encoding = HTTPHeaderField('content_encoding',
from_bytes=list_header_from_bytes,
to_bytes=list_header_to_bytes,
native_type=list)
content_language = HTTPHeaderField('content_language',
from_bytes=list_header_from_bytes,
to_bytes=list_header_to_bytes,
native_type=list)
# TODO: too simplistic with this one?
content_length = HTTPHeaderField('content_length',
from_bytes=int,
to_bytes=bytes,
native_type=int)
content_md5 = HTTPHeaderField('content_md5')
content_location = HTTPHeaderField('content_location',
native_type=URL)
content_range = HTTPHeaderField('content_range',
native_type=ContentRange)
range_field = HTTPHeaderField('range',
native_type=Range)
if_match = HTTPHeaderField('if_match', native_type=ETagSet)
if_none_match = HTTPHeaderField('if_none_match', native_type=ETagSet)
if_modified_since = HTTPHeaderField('if_modified_since',
from_bytes=http_date_from_bytes,
to_bytes=http_date_to_bytes,
native_type=datetime)
if_unmodified_since = HTTPHeaderField('if_unmodified_since',
from_bytes=http_date_from_bytes,
to_bytes=http_date_to_bytes,
native_type=datetime)
www_authenticate = HTTPHeaderField('www_authenticate',
from_bytes=items_header_from_bytes,
to_bytes=items_header_to_bytes,
native_type=list)
cache_control = HTTPHeaderField('cache_control',
from_bytes=items_header_from_bytes,
to_bytes=items_header_to_bytes,
native_type=list)
accept = HTTPHeaderField('accept',
from_bytes=accept_header_from_bytes,
to_bytes=accept_header_to_bytes,
native_type=list)
accept_language = HTTPHeaderField('accept_language',
from_bytes=accept_header_from_bytes,
to_bytes=accept_header_to_bytes,
native_type=list)
accept_encoding = HTTPHeaderField('accept_encoding',
from_bytes=accept_header_from_bytes,
to_bytes=accept_header_to_bytes,
native_type=list)
accept_charset = HTTPHeaderField('accept_charset',
from_bytes=accept_header_from_bytes,
to_bytes=accept_header_to_bytes,
native_type=list)
# TODO: accept_ranges could be implemented as a simpler field/flag,
# because really it's either 'bytes', 'none', or unset.
accept_ranges = HTTPHeaderField('accept_ranges',
from_bytes=list_header_from_bytes,
to_bytes=list_header_to_bytes,
native_type=list)
# TODO: referer or referrer?
referer = HTTPHeaderField('referer',
native_type=URL)
class HostHeaderField(HTTPHeaderField):
def __init__(self):
super(HostHeaderField, self).__init__(name='host')
def __set__(self, obj, value):
super(HostHeaderField, self).__set__(obj, value)
cur_val = obj.headers.get('Host')
url = obj._url
if not cur_val:
family, host, port = None, '', ''
else:
family, host, port = parse_hostinfo(cur_val)
url.family, url.host, url.port = family, host, port
return
host = HostHeaderField()
transfer_encoding = HTTPHeaderField('transfer_encoding')
retry_after = HTTPHeaderField('retry_after',
from_bytes=retry_after_from_bytes,
to_bytes=retry_after_to_bytes,
native_type=(datetime, timedelta))
from_field = HTTPHeaderField('_from', http_name='From')
server_field = HTTPHeaderField('server')
user_agent = HTTPHeaderField('user_agent')
connection = HTTPHeaderField('connection')
trailer = HTTPHeaderField('trailer',
from_bytes=list_header_from_bytes,
to_bytes=list_header_to_bytes,
native_type=list)
vary = HTTPHeaderField('vary',
from_bytes=list_header_from_bytes,
to_bytes=list_header_to_bytes,
native_type=list)
allow = HTTPHeaderField('allow',
from_bytes=list_header_from_bytes,
to_bytes=list_header_to_bytes,
native_type=list)
location = HTTPHeaderField('location', native_type=URL)
"""
Several key Request attributes are URL-based. Similar to the
HTTPHeaderField, which is backed by a Headers dict, URL fields are
backed by a URL object on the Request instance.
desired url-related fields:
request.url - bytes or unicode? can be set with URL instance, too
request.host - host *header* (should be equal to url.host + url.port)
request.hostname/request.domain - host attr of URL
request.path - url path (unicode)
request.port - int
request.args/.params/.query_params/.GET - QueryParamDict
request.query_string - bytes or unicode?
request.scheme - http/https
Some of these will need to trigger updates to the Host header and
the Host header field will need to trigger updates to some of
these.
other potential fields (that will likely remain on the underlying URL
object only for the time being):
- username
- password
- fragment
note: wz request obj has 71 public attributes (not starting with '_')
"""
class BaseURLField(Field):
pass
class URLField(BaseURLField):
attr_name = 'url'
def __get__(self, obj, objtype=None):
if obj is None:
return self
return obj._url.to_text() # unicode for now
def __set__(self, obj, value):
if isinstance(value, URL):
url_obj = value
else:
url_obj = URL(value)
| |
<reponame>nils-werner/pytorch-lightning<filename>pytorch_lightning/utilities/distributed.py
# Copyright The PyTorch Lightning team.
#
# 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 logging
import os
from functools import wraps
from platform import python_version
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import torch
from torch.nn.parallel.distributed import DistributedDataParallel
import pytorch_lightning as pl
from pytorch_lightning.utilities.imports import _TORCH_GREATER_EQUAL_1_8, _TORCH_GREATER_EQUAL_1_9, _TPU_AVAILABLE
if _TPU_AVAILABLE:
import torch_xla.core.xla_model as xm
if torch.distributed.is_available():
from torch.distributed import group, ReduceOp
else:
class ReduceOp: # type: ignore # (see https://github.com/python/mypy/issues/1153)
SUM = None
class group: # type: ignore
WORLD = None
log = logging.getLogger(__name__)
def rank_zero_only(fn: Callable) -> Callable:
@wraps(fn)
def wrapped_fn(*args: Any, **kwargs: Any) -> Optional[Any]:
if rank_zero_only.rank == 0:
return fn(*args, **kwargs)
return None
return wrapped_fn
# TODO: this should be part of the cluster environment
def _get_rank() -> int:
rank_keys = ("RANK", "SLURM_PROCID", "LOCAL_RANK")
for key in rank_keys:
rank = os.environ.get(key)
if rank is not None:
return int(rank)
return 0
# add the attribute to the function but don't overwrite in case Trainer has already set it
rank_zero_only.rank = getattr(rank_zero_only, "rank", _get_rank())
def _info(*args: Any, stacklevel: int = 2, **kwargs: Any) -> None:
if python_version() >= "3.8.0":
kwargs["stacklevel"] = stacklevel
log.info(*args, **kwargs)
def _debug(*args: Any, stacklevel: int = 2, **kwargs: Any) -> None:
if python_version() >= "3.8.0":
kwargs["stacklevel"] = stacklevel
log.debug(*args, **kwargs)
@rank_zero_only
def rank_zero_debug(*args: Any, stacklevel: int = 4, **kwargs: Any) -> None:
_debug(*args, stacklevel=stacklevel, **kwargs)
@rank_zero_only
def rank_zero_info(*args: Any, stacklevel: int = 4, **kwargs: Any) -> None:
_info(*args, stacklevel=stacklevel, **kwargs)
def gather_all_tensors(result: torch.Tensor, group: Optional[Any] = None) -> List[torch.Tensor]:
"""Function to gather all tensors from several ddp processes onto a list that is broadcasted to all processes.
Args:
result: the value to sync
group: the process group to gather results from. Defaults to all processes (world)
Return:
gathered_result: list with size equal to the process group where
gathered_result[i] corresponds to result tensor from process i
"""
if group is None:
group = torch.distributed.group.WORLD
# convert tensors to contiguous format
result = result.contiguous()
world_size = torch.distributed.get_world_size(group)
gathered_result = [torch.zeros_like(result) for _ in range(world_size)]
# sync and broadcast all
torch.distributed.barrier(group=group)
torch.distributed.all_gather(gathered_result, result, group)
return gathered_result
def distributed_available() -> bool:
return torch.distributed.is_available() and torch.distributed.is_initialized() or tpu_distributed()
def sync_ddp_if_available(
result: torch.Tensor, group: Optional[Any] = None, reduce_op: Optional[Union[ReduceOp, str]] = None
) -> torch.Tensor:
"""
Function to reduce a tensor across worker processes during distributed training
Args:
result: the value to sync and reduce (typically tensor or number)
group: the process group to gather results from. Defaults to all processes (world)
reduce_op: the reduction operation. Defaults to sum.
Can also be a string of 'avg', 'mean' to calculate the mean during reduction.
Return:
reduced value
"""
if distributed_available():
return sync_ddp(result, group=group, reduce_op=reduce_op)
return result
def sync_ddp(
result: torch.Tensor, group: Optional[Any] = None, reduce_op: Optional[Union[ReduceOp, str]] = None
) -> torch.Tensor:
"""Function to reduce the tensors from several ddp processes to one main process.
Args:
result: the value to sync and reduce (typically tensor or number)
group: the process group to gather results from. Defaults to all processes (world)
reduce_op: the reduction operation. Defaults to sum.
Can also be a string of 'avg', 'mean' to calculate the mean during reduction.
Return:
reduced value
"""
divide_by_world_size = False
if group is None:
group = torch.distributed.group.WORLD
if isinstance(reduce_op, str):
if reduce_op.lower() in ("avg", "mean"):
op = ReduceOp.SUM
divide_by_world_size = True
else:
op = getattr(ReduceOp, reduce_op.upper())
else:
op = reduce_op
# sync all processes before reduction
torch.distributed.barrier(group=group)
torch.distributed.all_reduce(result, op=op, group=group, async_op=False)
if divide_by_world_size:
result = result / torch.distributed.get_world_size(group)
return result
class AllGatherGrad(torch.autograd.Function):
@staticmethod
def forward(
ctx: Any,
tensor: torch.Tensor,
group: Optional["torch.distributed.ProcessGroup"] = group.WORLD,
) -> torch.Tensor:
ctx.group = group
gathered_tensor = [torch.zeros_like(tensor) for _ in range(torch.distributed.get_world_size())]
torch.distributed.all_gather(gathered_tensor, tensor, group=group)
gathered_tensor = torch.stack(gathered_tensor, dim=0)
return gathered_tensor
@staticmethod
def backward(ctx: Any, *grad_output: torch.Tensor) -> Tuple[torch.Tensor, None]:
grad_output = torch.cat(grad_output)
torch.distributed.all_reduce(grad_output, op=torch.distributed.ReduceOp.SUM, async_op=False, group=ctx.group)
return grad_output[torch.distributed.get_rank()], None
def all_gather_ddp_if_available(
tensor: torch.Tensor, group: Optional["torch.distributed.ProcessGroup"] = None, sync_grads: bool = False
) -> torch.Tensor:
"""Function to gather a tensor from several distributed processes.
Args:
tensor: tensor of shape (batch, ...)
group: the process group to gather results from. Defaults to all processes (world)
sync_grads: flag that allows users to synchronize gradients for all_gather op
Return:
A tensor of shape (world_size, batch, ...)
"""
group = group if group is not None else torch.distributed.group.WORLD
if distributed_available():
if sync_grads:
return AllGatherGrad.apply(tensor, group)
with torch.no_grad():
return AllGatherGrad.apply(tensor, group)
return tensor
def register_ddp_comm_hook(
model: DistributedDataParallel,
ddp_comm_state: Optional[object] = None,
ddp_comm_hook: Optional[Callable] = None,
ddp_comm_wrapper: Optional[Callable] = None,
) -> None:
"""Function to register communication hook for DDP model https://pytorch.org/docs/master/ddp_comm_hooks.html.
Args:
model:
DDP model
ddp_comm_state:
state is passed to the hook and can be used to maintain
and update any state information that users would like to
maintain as part of the training process. Examples: error
feedback in gradient compression, peers to communicate with
next in GossipGrad etc.
ddp_comm_hook:
hook(state: object, bucket: dist._GradBucket) -> torch.futures.Future
This callable function is called once the bucket is ready. The
hook can perform whatever processing is needed and return
a Future indicating completion of any async work (ex: allreduce).
If the hook doesn't perform any communication, it can also
just return a completed Future. The Future should hold the
new value of grad bucket's tensors. Once a bucket is ready,
c10d reducer would call this hook and use the tensors returned
by the Future and copy grads to individual parameters.
ddp_comm_wrapper:
communication hook wraper to support a communication hook such
as FP16 compression as wrapper, which could be combined with
ddp_comm_hook
.. warning ::
DDP communication hook needs pytorch version at least 1.8.0
.. warning ::
DDP communication wrapper needs pytorch version at least 1.9.0
Post-localSGD hook needs pytorch version at least 1.9.0
Example:
from torch.distributed.algorithms.ddp_comm_hooks import (
default_hooks as default,
powerSGD_hook as powerSGD,
post_localSGD_hook as post_localSGD,
)
# fp16_compress_hook for compress gradients
register_ddp_comm_hook(
model=ddp_model,
ddp_comm_hook=default.fp16_compress_hook,
)
# powerSGD_hook
register_ddp_comm_hook(
model=ddp_model,
ddp_comm_state=powerSGD.PowerSGDState(
process_group=None,
matrix_approximation_rank=1,
start_powerSGD_iter=5000,
),
ddp_comm_hook=powerSGD.powerSGD_hook,
)
# post_localSGD_hook
subgroup, _ = torch.distributed.new_subgroups()
register_comm_hook(
model=ddp_model,
state=post_localSGD.PostLocalSGDState(
process_group=None,
subgroup=subgroup,
start_localSGD_iter=1_000,
),
ddp_comm_hook=post_localSGD.post_localSGD_hook,
)
# fp16_compress_wrapper combined with other communication hook
register_ddp_comm_hook(
model=ddp_model,
ddp_comm_state=powerSGD.PowerSGDState(
process_group=None,
matrix_approximation_rank=1,
start_powerSGD_iter=5000,
),
ddp_comm_hook=powerSGD.powerSGD_hook,
ddp_comm_wrapper=default.fp16_compress_wrapper,
)
"""
from pytorch_lightning.utilities import rank_zero_warn
if not _TORCH_GREATER_EQUAL_1_8:
rank_zero_warn("Not registering DDP comm hook. To use communication hooks, please use pytorch>=1.8.0.")
return
if ddp_comm_hook is None:
return
# inform mypy that ddp_comm_hook is callable
ddp_comm_hook: Callable = ddp_comm_hook
if ddp_comm_wrapper is not None:
if not _TORCH_GREATER_EQUAL_1_9:
rank_zero_warn("Not applying DDP comm wrapper. To use communication wrapper, please use pytorch>=1.9.0.")
else:
rank_zero_info(
f"DDP comm wrapper is provided, apply {ddp_comm_wrapper.__qualname__}({ddp_comm_hook.__qualname__})."
)
ddp_comm_hook = ddp_comm_wrapper(ddp_comm_hook)
rank_zero_debug(f"Registering DDP comm hook: {ddp_comm_hook.__qualname__}.")
model.register_comm_hook(state=ddp_comm_state, hook=ddp_comm_hook)
def tpu_distributed() -> bool:
return _TPU_AVAILABLE and xm.xrt_world_size() > 1
def init_dist_connection(
cluster_environment: "pl.plugins.environments.ClusterEnvironment",
torch_distributed_backend: str,
global_rank: Optional[int] = None,
world_size: Optional[int] = None,
**kwargs: Any,
) -> None:
"""Utility function to initialize distributed connection by setting env variables and initiliazing the
distributed process group.
Args:
cluster_environment: ``ClusterEnvironment`` instance
torch_distributed_backend: backend to use (includes `nccl` and `gloo`)
global_rank: rank of the current process
world_size: number of processes in the group
kwargs: kwargs for ``init_process_group``
"""
global_rank = global_rank if global_rank is not None else cluster_environment.global_rank()
world_size = world_size if world_size is not None else cluster_environment.world_size()
os.environ["MASTER_ADDR"] = cluster_environment.main_address
os.environ["MASTER_PORT"] = str(cluster_environment.main_port)
if not torch.distributed.is_available():
raise RuntimeError("torch.distributed is not available. Cannot initialize distributed process group")
if not torch.distributed.is_initialized():
log.info(f"initializing distributed: GLOBAL_RANK: {global_rank}, MEMBER: {global_rank + 1}/{world_size}")
torch.distributed.init_process_group(
torch_distributed_backend, rank=global_rank, world_size=world_size, **kwargs
)
# on rank=0 let everyone know training is starting
rank_zero_info(
f"{'-' * 100}\n"
f"distributed_backend={torch_distributed_backend}\n"
f"All distributed processes registered. Starting with {world_size} processes\n"
f"{'-' * 100}\n"
)
def _collect_states_on_rank_zero(state: Dict[str, Any], device: torch.device) -> Optional[Dict[int, Any]]:
"""This distributed utility collects dictionary state across all processes.
Args:
| |
), imath.V2i( 10 ) ) ) )
globals = GafferOSL.OSLShader()
globals.loadShader( "Utility/Globals" )
outP = GafferOSL.OSLShader()
outP.loadShader( "ImageProcessing/OutLayer" )
outP["parameters"]["layerColor"].setInput( globals["out"]["globalP"] )
outU = GafferOSL.OSLShader()
outU.loadShader( "ImageProcessing/OutChannel" )
outU["parameters"]["channelName"].setValue( "u" )
outU["parameters"]["channelValue"].setInput( globals["out"]["globalU"] )
outV = GafferOSL.OSLShader()
outV.loadShader( "ImageProcessing/OutChannel" )
outV["parameters"]["channelName"].setValue( "v" )
outV["parameters"]["channelValue"].setInput( globals["out"]["globalV"] )
imageShader = GafferOSL.OSLShader()
imageShader.loadShader( "ImageProcessing/OutImage" )
imageShader["parameters"]["in0"].setInput( outP["out"]["layer"] )
imageShader["parameters"]["in1"].setInput( outU["out"]["channel"] )
imageShader["parameters"]["in2"].setInput( outV["out"]["channel"] )
image = GafferOSL.OSLImage()
image["in"].setInput( constant["out"] )
image["shader"].setInput( imageShader["out"]["out"] )
displayWindow = image["out"]["format"].getValue().getDisplayWindow()
samplerR = GafferImage.Sampler( image["out"], "R", displayWindow )
samplerG = GafferImage.Sampler( image["out"], "G", displayWindow )
samplerB = GafferImage.Sampler( image["out"], "B", displayWindow )
samplerU = GafferImage.Sampler( image["out"], "u", displayWindow )
samplerV = GafferImage.Sampler( image["out"], "v", displayWindow )
size = imath.V2f( displayWindow.size() )
uvStep = imath.V2f( 1.0 ) / size
uvMin = 0.5 * uvStep
for y in range( displayWindow.min().y, displayWindow.max().y ) :
for x in range( displayWindow.min().x, displayWindow.max().x ) :
self.assertEqual( samplerR.sample( x, y ), x + 0.5, "Pixel {},{}".format( x, y ) )
self.assertEqual( samplerG.sample( x, y ), y + 0.5, "Pixel {},{}".format( x, y ) )
self.assertEqual( samplerB.sample( x, y ), 0, "Pixel {},{}".format( x, y ) )
uv = uvMin + uvStep * imath.V2f( imath.V2i( x, y ) - displayWindow.min() )
self.assertAlmostEqual( samplerU.sample( x, y ), uv.x, delta = 0.0000001, msg = "Pixel {},{}".format( x, y ) )
self.assertAlmostEqual( samplerV.sample( x, y ), uv.y, delta = 0.0000001, msg = "Pixel {},{}".format( x, y ) )
def testTextureOrientation( self ) :
constant = GafferImage.Constant()
constant["format"].setValue( GafferImage.Format( 32, 32 ) )
textureFileName = os.path.dirname( __file__ ) + "/images/vRamp.tx"
outLayer = GafferOSL.OSLCode()
outLayer["out"]["layer"] = GafferOSL.ClosurePlug(
direction = Gaffer.Plug.Direction.Out,
flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic
)
outLayer["code"].setValue( 'layer = outLayer( "", texture( "{}", u, v ) )'.format( textureFileName ) )
outImage = GafferOSL.OSLShader()
outImage.loadShader( "ImageProcessing/OutImage" )
outImage["parameters"]["in0"].setInput( outLayer["out"]["layer"] )
oslImage = GafferOSL.OSLImage()
oslImage["in"].setInput( constant["out"] )
oslImage["shader"].setInput( outImage["out"]["out"] )
sampler = GafferImage.Sampler( oslImage["out"], "R", oslImage["out"]["dataWindow"].getValue() )
for y in range( 0, 31 ) :
self.assertAlmostEqual( sampler.sample( 5, y ), (y + 0.5) / 32.0, delta = 0.02 )
def testPullsMinimalSetOfInputChannels( self ) :
constant = GafferImage.Constant()
constant["color"].setValue( imath.Color4f( 0.1101, 0.1224, 0.1353, 0.135 ) )
constant["format"].setValue(
GafferImage.Format( GafferImage.ImagePlug.tileSize(), GafferImage.ImagePlug.tileSize() )
)
outLayer = GafferOSL.OSLShader()
outLayer.loadShader( "ImageProcessing/OutLayer" )
outImage = GafferOSL.OSLShader()
outImage.loadShader( "ImageProcessing/OutImage" )
outImage["parameters"][0].setInput( outLayer["out"]["layer"] )
oslImage = GafferOSL.OSLImage()
oslImage["in"].setInput( constant["out"] )
oslImage["shader"].setInput( outImage["out"]["out"] )
with Gaffer.PerformanceMonitor() as pm :
GafferImage.ImageAlgo.image( oslImage["out"] )
# Because the shader doesn't use any input channels,
# the OSLImage node shouldn't have needed to pull on
# any of the RGB channels. Because the shader doesn't
# write to alpha, it does need to pull on alpha to pass
# it through. Hence we expect a single computation for
# the Constant's channelData.
s = pm.plugStatistics( constant["out"]["channelData"] )
self.assertEqual( s.computeCount, 1 )
def testShaderNetworkGeneratedInGlobalContext( self ) :
constant = GafferImage.Constant()
outLayer = GafferOSL.OSLCode()
outLayer["out"]["layer"] = GafferOSL.ClosurePlug(
direction = Gaffer.Plug.Direction.Out,
flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic
)
outLayer["code"].setValue( 'layer = outLayer( "", color( 0, 1, 0) )' )
outImage = GafferOSL.OSLShader()
outImage.loadShader( "ImageProcessing/OutImage" )
outImage["parameters"]["in0"].setInput( outLayer["out"]["layer"] )
oslImage = GafferOSL.OSLImage()
oslImage["in"].setInput( constant["out"] )
oslImage["shader"].setInput( outImage["out"]["out"] )
with Gaffer.ContextMonitor( oslImage["__oslCode"] ) as cm :
GafferImageTest.processTiles( oslImage["out"] )
cs = cm.combinedStatistics()
self.assertEqual( cs.numUniqueContexts(), 1 )
self.assertNotIn( "image:tileOrigin", cs.variableNames() )
self.assertNotIn( "image:channelName", cs.variableNames() )
def testAllTypes( self ) :
i = GafferOSL.OSLImage()
i["defaultFormat"].setValue( GafferImage.Format( imath.Box2i( imath.V2i(0), imath.V2i( 5 ) ) ) )
i["channels"].addChild( Gaffer.NameValuePlug( "", imath.Color3f(1,3,5) ) )
i["channels"].addChild( Gaffer.NameValuePlug( "testFloat", 42.42 ) )
i["channels"].addChild( Gaffer.NameValuePlug( "testColor", imath.Color3f(12,13,14) ) )
image = GafferImage.ImageAlgo.image( i['out'] )
self.assertEqual( image["R"], IECore.FloatVectorData( [1]*25 ) )
self.assertEqual( image["G"], IECore.FloatVectorData( [3]*25 ) )
self.assertEqual( image["B"], IECore.FloatVectorData( [5]*25 ) )
self.assertEqual( image["testFloat"], IECore.FloatVectorData( [42.42]*25 ) )
self.assertEqual( image["testColor.R"], IECore.FloatVectorData( [12]*25 ) )
self.assertEqual( image["testColor.G"], IECore.FloatVectorData( [13]*25 ) )
self.assertEqual( image["testColor.B"], IECore.FloatVectorData( [14]*25 ) )
def testClosure( self ) :
i = GafferOSL.OSLImage()
i["defaultFormat"].setValue( GafferImage.Format( imath.Box2i( imath.V2i(0), imath.V2i( 5 ) ) ) )
i["channels"].addChild( Gaffer.NameValuePlug( "testClosure", GafferOSL.ClosurePlug() ) )
code = GafferOSL.OSLCode( "OSLCode" )
code["out"].addChild( GafferOSL.ClosurePlug( "output1", direction = Gaffer.Plug.Direction.Out ) )
code["code"].setValue( 'output1 = outLayer( "blah", color( 0.1, 0.2, 0.3 ) ) + outChannel( "foo", 0.5 );' )
i["channels"][0]["value"].setInput( code["out"]["output1"] )
image = GafferImage.ImageAlgo.image( i['out'] )
self.assertEqual( image["blah.R"], IECore.FloatVectorData( [0.1]*25 ) )
self.assertEqual( image["blah.G"], IECore.FloatVectorData( [0.2]*25 ) )
self.assertEqual( image["blah.B"], IECore.FloatVectorData( [0.3]*25 ) )
self.assertEqual( image["foo"], IECore.FloatVectorData( [0.5]*25 ) )
def testUndo( self ) :
s = Gaffer.ScriptNode()
i = GafferOSL.OSLImage()
s.addChild( i )
self.assertFalse( s.undoAvailable() )
self.assertEqual( len( i["__oslCode"]["parameters"].children() ), 0 )
with Gaffer.UndoScope( s ) :
i["channels"].addChild( Gaffer.NameValuePlug( "testColor", imath.Color3f( 42 ) ) )
i["channels"].addChild( Gaffer.NameValuePlug( "testFloat", 42.42 ) )
self.assertTrue( s.undoAvailable() )
self.assertEqual( len( i["__oslCode"]["parameters"].children() ), 4 )
with Gaffer.UndoScope( s ) :
del i["channels"][0]
del i["channels"][0]
self.assertEqual( len( i["__oslCode"]["parameters"].children() ), 0 )
# Test that the internal connections are recreated correctly when undoing adding and removing channels
s.undo()
self.assertEqual( len( i["__oslCode"]["parameters"].children() ), 4 )
s.undo()
self.assertEqual( len( i["__oslCode"]["parameters"].children() ), 0 )
def testDefaultFormat( self ):
constant = GafferImage.Constant()
oslImage = GafferOSL.OSLImage()
oslImage["channels"].addChild( Gaffer.NameValuePlug( "", imath.Color3f( 0.5, 0.6, 0.7 ) ) )
self.assertEqual( oslImage["out"]["dataWindow"].getValue(), imath.Box2i( imath.V2i( 0 ), imath.V2i( 1920, 1080 ) ) )
self.assertEqual( oslImage["out"]["format"].getValue().getDisplayWindow(), imath.Box2i( imath.V2i( 0 ), imath.V2i( 1920, 1080 ) ) )
oslImage["defaultFormat"].setValue( GafferImage.Format( imath.Box2i( imath.V2i(0), imath.V2i( 5 ) ) ) )
self.assertEqual( oslImage["out"]["dataWindow"].getValue(), imath.Box2i( imath.V2i( 0 ), imath.V2i( 5, 5 ) ) )
self.assertEqual( oslImage["out"]["format"].getValue().getDisplayWindow(), imath.Box2i( imath.V2i( 0 ), imath.V2i( 5, 5 ) ) )
self.assertEqual( GafferImage.ImageAlgo.image( oslImage["out"] )["G"], IECore.FloatVectorData( [0.6] * 25 ) )
oslImage["in"].setInput( constant["out"] )
self.assertEqual( oslImage["out"]["dataWindow"].getValue(), imath.Box2i( imath.V2i( 0 ), imath.V2i( 1920, 1080 ) ) )
self.assertEqual( oslImage["out"]["format"].getValue().getDisplayWindow(), imath.Box2i( imath.V2i( 0 ), imath.V2i( 1920, 1080 ) ) )
constant["format"].setValue( GafferImage.Format( imath.Box2i( imath.V2i(0), imath.V2i( 4 ) ) ) )
self.assertEqual( oslImage["out"]["dataWindow"].getValue(), imath.Box2i( imath.V2i( 0 ), imath.V2i( 4, 4 ) ) )
self.assertEqual( oslImage["out"]["format"].getValue().getDisplayWindow(), imath.Box2i( imath.V2i( 0 ), imath.V2i( 4, 4 ) ) )
self.assertEqual( GafferImage.ImageAlgo.image( oslImage["out"] )["G"], IECore.FloatVectorData( [0.6] * 16 ) )
# Extreme example of doing something very expensive in OSLImage
def mandelbrotNode( self ):
mandelbrotCode = GafferOSL.OSLCode()
mandelbrotCode["parameters"].addChild( Gaffer.IntPlug( "iterations", defaultValue = 0, flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic, ) )
mandelbrotCode["out"].addChild( Gaffer.FloatPlug( "outFloat", direction = Gaffer.Plug.Direction.Out ) )
mandelbrotCode["code"].setValue( inspect.cleandoc(
"""
// Basic mandelbrot adapted from surface shader here:
// https://github.com/AcademySoftwareFoundation/OpenShadingLanguage/blob/master/src/shaders/mandelbrot.osl
point center = point (0,0,0);
float scale = 2;
point cent = center;
point c = scale * point(2*(u-0.5), 2*((1-v)-0.5), 0) + cent;
point z = c;
int i;
for (i = 1; i < iterations && dot(z,z) < 4.0; ++i) {
float x = z[0], y = z[1];
z = point (x*x - y*y, 2*x*y, 0) + c;
}
if (i < iterations) {
float f = pow(float(i)/iterations, 1/log10(float(iterations)));
outFloat = f;
} else {
outFloat = 0;
}
"""
) )
return mandelbrotCode
def testBadCachePolicyHang( self ):
# Using the legacy cache policy for OSLImage.shadingPlug creates a hang due to tbb task stealing,
# though it's a bit hard to actually demonstrate
constant = GafferImage.Constant()
constant["format"].setValue( GafferImage.Format( 128, 128, 1.000 ) )
# Need a slow to compute OSL code in order to trigger hang
mandelbrotCode = self.mandelbrotNode()
# In order to trigger the hang, we need to mix threads which are stuck waiting for an expression which
# uses the Standard policy with threads that are actually finishing, so that tbb tries to start up new
# threads while we're waiting for the expression result. To do this, we use the "var" context variable
# to create two versions of this OSLCode
mandelbrotCode["varExpression"] = Gaffer.Expression()
mandelbrotCode["varExpression"].setExpression( 'parent.parameters.iterations = 100000 + context( "var", 0 );', "OSL" )
oslImage = GafferOSL.OSLImage()
oslImage["channels"].addChild( Gaffer.NameValuePlug( "", Gaffer.Color3fPlug( "value", defaultValue = imath.Color3f( 1, 1, 1 ), flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic, ), True, "channel", Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic ) )
oslImage["in"].setInput( constant["out"] )
oslImage["channels"]["channel"]["value"][0].setInput( mandelbrotCode["out"]["outFloat"] )
oslImage["channels"]["channel"]["value"][1].setInput( mandelbrotCode["out"]["outFloat"] )
oslImage["channels"]["channel"]["value"][2].setInput( mandelbrotCode["out"]["outFloat"] )
# This imageStats is use to create non-blocking slow calculations
imageStats = GafferImage.ImageStats()
imageStats["in"].setInput( oslImage["out"] )
imageStats["area"].setValue( imath.Box2i( imath.V2i( 0, 0 ), imath.V2i( 64, 64 ) ) )
# This box does the non-blocking slow calculation, followed by a blocking slow calculation.
# This ensures that tasks which do just the non-block calculation will start finishing while
# the blocking slow calculation is still running, allowing tbb to try running more threads
# on the blocking calcluation, realizing they can't run, and stealing tasks onto those threads
# which can hit the Standard policy lock on the expression upstream and deadlock, unless the
# OSLImage isolates its threads correctly
expressionBox = Gaffer.Box()
expressionBox.addChild( Gaffer.FloatVectorDataPlug( "inChannelData", defaultValue = IECore.FloatVectorData( [ ] ) ) )
expressionBox.addChild( Gaffer.FloatPlug( "inStat" ) )
expressionBox.addChild( Gaffer.FloatPlug( "out", direction = Gaffer.Plug.Direction.Out ) )
expressionBox["inChannelData"].setInput( oslImage["out"]["channelData"] )
expressionBox["inStat"].setInput( imageStats["average"]["r"] )
expressionBox["contextVariables"] = Gaffer.ContextVariables()
expressionBox["contextVariables"].setup( Gaffer.FloatVectorDataPlug( "in", defaultValue = IECore.FloatVectorData( [ ] ) ) )
expressionBox["contextVariables"]["variables"].addChild( Gaffer.NameValuePlug( "image:tileOrigin", Gaffer.V2iPlug( "value" ), True, "member1" ) )
expressionBox["contextVariables"]["variables"].addChild( Gaffer.NameValuePlug( "image:channelName", Gaffer.StringPlug( "value", defaultValue = 'R' ), True, "member2" ) )
expressionBox["contextVariables"]["variables"].addChild( Gaffer.NameValuePlug( "var", Gaffer.IntPlug( "value", defaultValue = 1 ), True, "member3" ) )
expressionBox["contextVariables"]["in"].setInput( expressionBox["inChannelData"] )
expressionBox["expression"] = Gaffer.Expression()
expressionBox["expression"].setExpression( inspect.cleandoc(
"""
d = parent["contextVariables"]["out"]
parent["out"] = d[0] + parent["inStat"]
"""
) )
# Create a switch to mix which tasks perform the non-blocking or blocking calculation - we need a mixture
# to trigger the hang
switch = Gaffer.Switch()
switch.setup( Gaffer.IntPlug( "in", defaultValue = 0, ) )
switch["in"][0].setInput( expressionBox["out"] )
switch["in"][1].setInput( imageStats["average"]["r"] )
switch["switchExpression"] = Gaffer.Expression()
switch["switchExpression"].setExpression( 'parent.index = ( stoi( context( "testContext", "0" ) ) % 10 ) > 5;', "OSL" )
# In | |
large will usually lead to"
" bad results. You could try setting max_size parameters "
"on your collections and turning "
"max_leaves down on recursive() calls."
)
% (state.overrun_examples, state.valid_examples),
HealthCheck.data_too_large,
)
if state.invalid_examples == max_invalid_draws:
fail_health_check(
self.settings,
(
"It looks like your strategy is filtering out a lot "
"of data. Health check found %d filtered examples but "
"only %d good ones. This will make your tests much "
"slower, and also will probably distort the data "
"generation quite a lot. You should adapt your "
"strategy to filter less. This can also be caused by "
"a low max_leaves parameter in recursive() calls"
)
% (state.invalid_examples, state.valid_examples),
HealthCheck.filter_too_much,
)
draw_time = sum(state.draw_times)
if draw_time > 1.0:
fail_health_check(
self.settings,
(
"Data generation is extremely slow: Only produced "
"%d valid examples in %.2f seconds (%d invalid ones "
"and %d exceeded maximum size). Try decreasing "
"size of the data you're generating (with e.g."
"max_size or max_leaves parameters)."
)
% (
state.valid_examples,
draw_time,
state.invalid_examples,
state.overrun_examples,
),
HealthCheck.too_slow,
)
def save_buffer(self, buffer, sub_key=None):
if self.settings.database is not None:
key = self.sub_key(sub_key)
if key is None:
return
self.settings.database.save(key, bytes(buffer))
def downgrade_buffer(self, buffer):
if self.settings.database is not None and self.database_key is not None:
self.settings.database.move(self.database_key, self.secondary_key, buffer)
def sub_key(self, sub_key):
if self.database_key is None:
return None
if sub_key is None:
return self.database_key
return b".".join((self.database_key, sub_key))
@property
def secondary_key(self):
return self.sub_key(b"secondary")
@property
def pareto_key(self):
return self.sub_key(b"pareto")
def debug(self, message):
if self.settings.verbosity >= Verbosity.debug:
base_report(message)
@property
def report_debug_info(self):
return self.settings.verbosity >= Verbosity.debug
def debug_data(self, data):
if not self.report_debug_info:
return
stack = [[]]
def go(ex):
if ex.length == 0:
return
if len(ex.children) == 0:
stack[-1].append(int_from_bytes(data.buffer[ex.start : ex.end]))
else:
node = []
stack.append(node)
for v in ex.children:
go(v)
stack.pop()
if len(node) == 1:
stack[-1].extend(node)
else:
stack[-1].append(node)
go(data.examples[0])
assert len(stack) == 1
status = repr(data.status)
if data.status == Status.INTERESTING:
status = f"{status} ({data.interesting_origin!r})"
self.debug(f"{data.index} bytes {stack[0]!r} -> {status}, {data.output}")
def run(self):
with local_settings(self.settings):
try:
self._run()
except RunIsComplete:
pass
for v in self.interesting_examples.values():
self.debug_data(v)
self.debug(
"Run complete after %d examples (%d valid) and %d shrinks"
% (self.call_count, self.valid_examples, self.shrinks)
)
@property
def database(self):
if self.database_key is None:
return None
return self.settings.database
def has_existing_examples(self):
return self.database is not None and Phase.reuse in self.settings.phases
def reuse_existing_examples(self):
"""If appropriate (we have a database and have been told to use it),
try to reload existing examples from the database.
If there are a lot we don't try all of them. We always try the
smallest example in the database (which is guaranteed to be the
last failure) and the largest (which is usually the seed example
which the last failure came from but we don't enforce that). We
then take a random sampling of the remainder and try those. Any
examples that are no longer interesting are cleared out.
"""
if self.has_existing_examples():
self.debug("Reusing examples from database")
# We have to do some careful juggling here. We have two database
# corpora: The primary and secondary. The primary corpus is a
# small set of minimized examples each of which has at one point
# demonstrated a distinct bug. We want to retry all of these.
# We also have a secondary corpus of examples that have at some
# point demonstrated interestingness (currently only ones that
# were previously non-minimal examples of a bug, but this will
# likely expand in future). These are a good source of potentially
# interesting examples, but there are a lot of them, so we down
# sample the secondary corpus to a more manageable size.
corpus = sorted(
self.settings.database.fetch(self.database_key), key=sort_key
)
factor = 0.1 if (Phase.generate in self.settings.phases) else 1
desired_size = max(2, ceil(factor * self.settings.max_examples))
if len(corpus) < desired_size:
extra_corpus = list(self.settings.database.fetch(self.secondary_key))
shortfall = desired_size - len(corpus)
if len(extra_corpus) <= shortfall:
extra = extra_corpus
else:
extra = self.random.sample(extra_corpus, shortfall)
extra.sort(key=sort_key)
corpus.extend(extra)
for existing in corpus:
data = self.cached_test_function(existing)
if data.status != Status.INTERESTING:
self.settings.database.delete(self.database_key, existing)
self.settings.database.delete(self.secondary_key, existing)
# If we've not found any interesting examples so far we try some of
# the pareto front from the last run.
if len(corpus) < desired_size and not self.interesting_examples:
desired_extra = desired_size - len(corpus)
pareto_corpus = list(self.settings.database.fetch(self.pareto_key))
if len(pareto_corpus) > desired_extra:
pareto_corpus = self.random.sample(pareto_corpus, desired_extra)
pareto_corpus.sort(key=sort_key)
for existing in pareto_corpus:
data = self.cached_test_function(existing)
if data not in self.pareto_front:
self.settings.database.delete(self.pareto_key, existing)
if data.status == Status.INTERESTING:
break
def exit_with(self, reason):
if self.ignore_limits:
return
self.statistics["stopped-because"] = reason.describe(self.settings)
if self.best_observed_targets:
self.statistics["targets"] = dict(self.best_observed_targets)
self.debug(f"exit_with({reason.name})")
self.exit_reason = reason
raise RunIsComplete()
def should_generate_more(self):
# End the generation phase where we would have ended it if no bugs had
# been found. This reproduces the exit logic in `self.test_function`,
# but with the important distinction that this clause will move on to
# the shrinking phase having found one or more bugs, while the other
# will exit having found zero bugs.
if self.valid_examples >= self.settings.max_examples or self.call_count >= max(
self.settings.max_examples * 10, 1000
): # pragma: no cover
return False
# If we haven't found a bug, keep looking - if we hit any limits on
# the number of tests to run that will raise an exception and stop
# the run.
if not self.interesting_examples:
return True
# If we've found a bug and won't report more than one, stop looking.
elif not self.settings.report_multiple_bugs:
return False
assert self.first_bug_found_at <= self.last_bug_found_at <= self.call_count
# Otherwise, keep searching for between ten and 'a heuristic' calls.
# We cap 'calls after first bug' so errors are reported reasonably
# soon even for tests that are allowed to run for a very long time,
# or sooner if the latest half of our test effort has been fruitless.
return self.call_count < MIN_TEST_CALLS or self.call_count < min(
self.first_bug_found_at + 1000, self.last_bug_found_at * 2
)
def generate_new_examples(self):
if Phase.generate not in self.settings.phases:
return
if self.interesting_examples:
# The example database has failing examples from a previous run,
# so we'd rather report that they're still failing ASAP than take
# the time to look for additional failures.
return
self.debug("Generating new examples")
assert self.should_generate_more()
zero_data = self.cached_test_function(bytes(BUFFER_SIZE))
if zero_data.status > Status.OVERRUN:
self.__data_cache.pin(zero_data.buffer)
if zero_data.status == Status.OVERRUN or (
zero_data.status == Status.VALID and len(zero_data.buffer) * 2 > BUFFER_SIZE
):
fail_health_check(
self.settings,
"The smallest natural example for your test is extremely "
"large. This makes it difficult for Hypothesis to generate "
"good examples, especially when trying to reduce failing ones "
"at the end. Consider reducing the size of your data if it is "
"of a fixed size. You could also fix this by improving how "
"your data shrinks (see https://hypothesis.readthedocs.io/en/"
"latest/data.html#shrinking for details), or by introducing "
"default values inside your strategy. e.g. could you replace "
"some arguments with their defaults by using "
"one_of(none(), some_complex_strategy)?",
HealthCheck.large_base_example,
)
self.health_check_state = HealthCheckState()
# We attempt to use the size of the minimal generated test case starting
# from a given novel prefix as a guideline to generate smaller test
# cases for an initial period, by restriscting ourselves to test cases
# that are not much larger than it.
#
# Calculating the actual minimal generated test case is hard, so we
# take a best guess that zero extending a prefix produces the minimal
# test case starting with that prefix (this is true for our built in
# strategies). This is only a reasonable thing to do if the resulting
# test case is valid. If we regularly run into situations where it is
# not valid then this strategy is a waste of time, so we want to
# abandon it early. In order to do this we track how many times in a
# row it has failed to work, and abort small test case generation when
# it has failed too many times in a row.
consecutive_zero_extend_is_invalid = 0
# We control growth | |
# -*- coding: utf-8 -*-
import asyncio
import re
from typing import Coroutine, Generator, Union
from unittest.mock import patch
from aiohttp import hdrs
from aiohttp import http
from aiohttp.client import ClientSession
from aiohttp.client_reqrep import ClientResponse
from asynctest import fail_on, skipIf
from asynctest.case import TestCase
from ddt import ddt, data
from asyncio import CancelledError, TimeoutError
try:
from aiohttp.errors import (
ClientConnectionError,
ClientResponseError,
HttpProcessingError,
)
except ImportError:
from aiohttp.client_exceptions import (
ClientConnectionError,
ClientResponseError,
)
from aiohttp.http_exceptions import HttpProcessingError
from aioresponses.compat import AIOHTTP_VERSION, URL
from aioresponses import CallbackResult, aioresponses
@ddt
class AIOResponsesTestCase(TestCase):
use_default_loop = False
@asyncio.coroutine
def setUp(self):
self.url = 'http://example.com/api?foo=bar#fragment'
self.session = ClientSession()
super().setUp()
@asyncio.coroutine
def tearDown(self):
close_result = self.session.close()
if close_result is not None:
yield from close_result
super().tearDown()
def run_async(self, coroutine: Union[Coroutine, Generator]):
return self.loop.run_until_complete(coroutine)
@asyncio.coroutine
def request(self, url: str):
return (yield from self.session.get(url))
@data(
hdrs.METH_HEAD,
hdrs.METH_GET,
hdrs.METH_POST,
hdrs.METH_PUT,
hdrs.METH_PATCH,
hdrs.METH_DELETE,
hdrs.METH_OPTIONS,
)
@patch('aioresponses.aioresponses.add')
@fail_on(unused_loop=False)
def test_shortcut_method(self, http_method, mocked):
with aioresponses() as m:
getattr(m, http_method.lower())(self.url)
mocked.assert_called_once_with(self.url, method=http_method)
@aioresponses()
def test_returned_instance(self, m):
m.get(self.url)
response = self.run_async(self.session.get(self.url))
self.assertIsInstance(response, ClientResponse)
@aioresponses()
@asyncio.coroutine
def test_returned_instance_and_status_code(self, m):
m.get(self.url, status=204)
response = yield from self.session.get(self.url)
self.assertIsInstance(response, ClientResponse)
self.assertEqual(response.status, 204)
@aioresponses()
@asyncio.coroutine
def test_returned_response_headers(self, m):
m.get(self.url,
content_type='text/html',
headers={'Connection': 'keep-alive'})
response = yield from self.session.get(self.url)
self.assertEqual(response.headers['Connection'], 'keep-alive')
self.assertEqual(response.headers[hdrs.CONTENT_TYPE], 'text/html')
@aioresponses()
@asyncio.coroutine
def test_returned_response_cookies(self, m):
m.get(self.url,
headers={'Set-Cookie': 'cookie=value'})
response = yield from self.session.get(self.url)
self.assertEqual(response.cookies['cookie'].value, 'value')
@aioresponses()
@asyncio.coroutine
def test_returned_response_raw_headers(self, m):
m.get(self.url,
content_type='text/html',
headers={'Connection': 'keep-alive'})
response = yield from self.session.get(self.url)
expected_raw_headers = (
(hdrs.CONTENT_TYPE.encode(), b'text/html'),
(b'Connection', b'keep-alive')
)
self.assertEqual(response.raw_headers, expected_raw_headers)
@aioresponses()
@asyncio.coroutine
def test_raise_for_status(self, m):
m.get(self.url, status=400)
with self.assertRaises(ClientResponseError) as cm:
response = yield from self.session.get(self.url)
response.raise_for_status()
self.assertEqual(cm.exception.message, http.RESPONSES[400][0])
@aioresponses()
@asyncio.coroutine
@skipIf(condition=AIOHTTP_VERSION < '3.4.0',
reason='aiohttp<3.4.0 does not support raise_for_status '
'arguments for requests')
def test_request_raise_for_status(self, m):
m.get(self.url, status=400)
with self.assertRaises(ClientResponseError) as cm:
yield from self.session.get(self.url, raise_for_status=True)
self.assertEqual(cm.exception.message, http.RESPONSES[400][0])
@aioresponses()
@asyncio.coroutine
def test_returned_instance_and_params_handling(self, m):
expected_url = 'http://example.com/api?foo=bar&x=42#fragment'
m.get(expected_url)
response = yield from self.session.get(self.url, params={'x': 42})
self.assertIsInstance(response, ClientResponse)
self.assertEqual(response.status, 200)
expected_url = 'http://example.com/api?x=42#fragment'
m.get(expected_url)
response = yield from self.session.get(
'http://example.com/api#fragment',
params={'x': 42}
)
self.assertIsInstance(response, ClientResponse)
self.assertEqual(response.status, 200)
@aioresponses()
def test_method_dont_match(self, m):
m.get(self.url)
with self.assertRaises(ClientConnectionError):
self.run_async(self.session.post(self.url))
@aioresponses()
@asyncio.coroutine
def test_streaming(self, m):
m.get(self.url, body='Test')
resp = yield from self.session.get(self.url)
content = yield from resp.content.read()
self.assertEqual(content, b'Test')
@aioresponses()
@asyncio.coroutine
def test_streaming_up_to(self, m):
m.get(self.url, body='Test')
resp = yield from self.session.get(self.url)
content = yield from resp.content.read(2)
self.assertEqual(content, b'Te')
content = yield from resp.content.read(2)
self.assertEqual(content, b'st')
@asyncio.coroutine
def test_mocking_as_context_manager(self):
with aioresponses() as aiomock:
aiomock.add(self.url, payload={'foo': 'bar'})
resp = yield from self.session.get(self.url)
self.assertEqual(resp.status, 200)
payload = yield from resp.json()
self.assertDictEqual(payload, {'foo': 'bar'})
def test_mocking_as_decorator(self):
@aioresponses()
def foo(loop, m):
m.add(self.url, payload={'foo': 'bar'})
resp = loop.run_until_complete(self.session.get(self.url))
self.assertEqual(resp.status, 200)
payload = loop.run_until_complete(resp.json())
self.assertDictEqual(payload, {'foo': 'bar'})
foo(self.loop)
@asyncio.coroutine
def test_passing_argument(self):
@aioresponses(param='mocked')
@asyncio.coroutine
def foo(mocked):
mocked.add(self.url, payload={'foo': 'bar'})
resp = yield from self.session.get(self.url)
self.assertEqual(resp.status, 200)
yield from foo()
@fail_on(unused_loop=False)
def test_mocking_as_decorator_wrong_mocked_arg_name(self):
@aioresponses(param='foo')
def foo(bar):
# no matter what is here it should raise an error
pass
with self.assertRaises(TypeError) as cm:
foo()
exc = cm.exception
self.assertIn("foo() got an unexpected keyword argument 'foo'",
str(exc))
@asyncio.coroutine
def test_unknown_request(self):
with aioresponses() as aiomock:
aiomock.add(self.url, payload={'foo': 'bar'})
with self.assertRaises(ClientConnectionError):
yield from self.session.get('http://example.com/foo')
@asyncio.coroutine
def test_raising_exception(self):
with aioresponses() as aiomock:
url = 'http://example.com/Exception'
aiomock.get(url, exception=Exception)
with self.assertRaises(Exception):
yield from self.session.get(url)
url = 'http://example.com/Exception_object'
aiomock.get(url, exception=Exception())
with self.assertRaises(Exception):
yield from self.session.get(url)
url = 'http://example.com/BaseException'
aiomock.get(url, exception=BaseException)
with self.assertRaises(BaseException):
yield from self.session.get(url)
url = 'http://example.com/BaseException_object'
aiomock.get(url, exception=BaseException())
with self.assertRaises(BaseException):
yield from self.session.get(url)
url = 'http://example.com/CancelError'
aiomock.get(url, exception=CancelledError)
with self.assertRaises(CancelledError):
yield from self.session.get(url)
url = 'http://example.com/TimeoutError'
aiomock.get(url, exception=TimeoutError)
with self.assertRaises(TimeoutError):
yield from self.session.get(url)
url = 'http://example.com/HttpProcessingError'
aiomock.get(url, exception=HttpProcessingError(message='foo'))
with self.assertRaises(HttpProcessingError):
yield from self.session.get(url)
@asyncio.coroutine
def test_multiple_requests(self):
"""Ensure that requests are saved the way they would have been sent."""
with aioresponses() as m:
m.get(self.url, status=200)
m.get(self.url, status=201)
m.get(self.url, status=202)
json_content_as_ref = [1]
resp = yield from self.session.get(
self.url, json=json_content_as_ref
)
self.assertEqual(resp.status, 200)
json_content_as_ref[:] = [2]
resp = yield from self.session.get(
self.url, json=json_content_as_ref
)
self.assertEqual(resp.status, 201)
json_content_as_ref[:] = [3]
resp = yield from self.session.get(
self.url, json=json_content_as_ref
)
self.assertEqual(resp.status, 202)
key = ('GET', URL(self.url))
self.assertIn(key, m.requests)
self.assertEqual(len(m.requests[key]), 3)
first_request = m.requests[key][0]
self.assertEqual(first_request.args, tuple())
self.assertEqual(first_request.kwargs,
{'allow_redirects': True, "json": [1]})
second_request = m.requests[key][1]
self.assertEqual(second_request.args, tuple())
self.assertEqual(second_request.kwargs,
{'allow_redirects': True, "json": [2]})
third_request = m.requests[key][2]
self.assertEqual(third_request.args, tuple())
self.assertEqual(third_request.kwargs,
{'allow_redirects': True, "json": [3]})
@asyncio.coroutine
def test_request_with_non_deepcopyable_parameter(self):
def non_deep_copyable():
"""A generator does not allow deepcopy."""
for line in ["header1,header2", "v1,v2", "v10,v20"]:
yield line
generator_value = non_deep_copyable()
with aioresponses() as m:
m.get(self.url, status=200)
resp = yield from self.session.get(self.url, data=generator_value)
self.assertEqual(resp.status, 200)
key = ('GET', URL(self.url))
self.assertIn(key, m.requests)
self.assertEqual(len(m.requests[key]), 1)
request = m.requests[key][0]
self.assertEqual(request.args, tuple())
self.assertEqual(request.kwargs,
{'allow_redirects': True, "data": generator_value})
@asyncio.coroutine
def test_request_retrieval_in_case_no_response(self):
with aioresponses() as m:
with self.assertRaises(ClientConnectionError):
yield from self.session.get(self.url)
key = ('GET', URL(self.url))
self.assertIn(key, m.requests)
self.assertEqual(len(m.requests[key]), 1)
self.assertEqual(m.requests[key][0].args, tuple())
self.assertEqual(m.requests[key][0].kwargs,
{'allow_redirects': True})
@asyncio.coroutine
def test_request_failure_in_case_session_is_closed(self):
@asyncio.coroutine
def do_request(session):
return (yield from session.get(self.url))
with aioresponses():
coro = do_request(self.session)
yield from self.session.close()
with self.assertRaises(RuntimeError) as exception_info:
yield from coro
assert str(exception_info.exception) == "Session is closed"
@asyncio.coroutine
def test_address_as_instance_of_url_combined_with_pass_through(self):
external_api = 'http://httpbin.org/status/201'
@asyncio.coroutine
def doit():
api_resp = yield from self.session.get(self.url)
# we have to hit actual url,
# otherwise we do not test pass through option properly
ext_rep = yield from self.session.get(URL(external_api))
return api_resp, ext_rep
with aioresponses(passthrough=[external_api]) as m:
m.get(self.url, status=200)
api, ext = yield from doit()
self.assertEqual(api.status, 200)
self.assertEqual(ext.status, 201)
@asyncio.coroutine
def test_pass_through_with_origin_params(self):
external_api = 'http://httpbin.org/get'
@asyncio.coroutine
def doit(params):
# we have to hit actual url,
# otherwise we do not test pass through option properly
ext_rep = (yield from self.session.get(URL(external_api), params=params))
return ext_rep
with aioresponses(passthrough=[external_api]) as m:
params = {'foo': 'bar'}
ext = yield from doit(params=params)
self.assertEqual(ext.status, 200)
self.assertEqual(str(ext.url), 'http://httpbin.org/get?foo=bar')
@aioresponses()
@asyncio.coroutine
def test_custom_response_class(self, m):
class CustomClientResponse(ClientResponse):
pass
m.get(self.url, body='Test', response_class=CustomClientResponse)
resp = yield from self.session.get(self.url)
self.assertTrue(isinstance(resp, CustomClientResponse))
@aioresponses()
def test_exceptions_in_the_middle_of_responses(self, mocked):
mocked.get(self.url, payload={}, status=204)
mocked.get(self.url, exception=ValueError('oops'), )
mocked.get(self.url, payload={}, status=204)
mocked.get(self.url, exception=ValueError('oops'), )
mocked.get(self.url, payload={}, status=200)
@asyncio.coroutine
def doit():
return (yield from self.session.get(self.url))
self.assertEqual(self.run_async(doit()).status, 204)
with self.assertRaises(ValueError):
self.run_async(doit())
self.assertEqual(self.run_async(doit()).status, 204)
with self.assertRaises(ValueError):
self.run_async(doit())
self.assertEqual(self.run_async(doit()).status, 200)
@aioresponses()
@asyncio.coroutine
def test_request_should_match_regexp(self, mocked):
mocked.get(
re.compile(r'^http://example\.com/api\?foo=.*$'),
payload={}, status=200
)
response = yield from self.request(self.url)
self.assertEqual(response.status, 200)
@aioresponses()
@asyncio.coroutine
def test_request_does_not_match_regexp(self, mocked):
mocked.get(
re.compile(r'^http://exampleexample\.com/api\?foo=.*$'),
payload={}, status=200
)
with self.assertRaises(ClientConnectionError):
yield from self.request(self.url)
@aioresponses()
def test_timeout(self, mocked):
mocked.get(self.url, timeout=True)
with self.assertRaises(asyncio.TimeoutError):
self.run_async(self.request(self.url))
@aioresponses()
def test_callback(self, m):
body = b'New body'
def callback(url, **kwargs):
self.assertEqual(str(url), self.url)
self.assertEqual(kwargs, {'allow_redirects': True})
return CallbackResult(body=body)
m.get(self.url, callback=callback)
response = self.run_async(self.request(self.url))
data = self.run_async(response.read())
assert data == body
@aioresponses()
def test_callback_coroutine(self, m):
body = b'New body'
event = asyncio.Event()
@asyncio.coroutine
def callback(url, **kwargs):
yield from event.wait()
self.assertEqual(str(url), self.url)
self.assertEqual(kwargs, {'allow_redirects': True})
return CallbackResult(body=body)
m.get(self.url, callback=callback)
future = asyncio.ensure_future(self.request(self.url))
self.run_async(asyncio.wait([future], timeout=0))
assert not future.done()
event.set()
self.run_async(asyncio.wait([future], timeout=0))
assert future.done()
response = future.result()
data = self.run_async(response.read())
assert data == body
@aioresponses()
@asyncio.coroutine
def test_exception_requests_are_tracked(self, mocked):
kwargs = {"json": [42], "allow_redirects": True}
mocked.get(self.url, exception=ValueError('oops'))
with self.assertRaises(ValueError):
yield from self.session.get(self.url, **kwargs)
key = ('GET', URL(self.url))
mocked_requests = mocked.requests[key]
self.assertEqual(len(mocked_requests), 1)
request = mocked_requests[0]
self.assertEqual(request.args, ())
self.assertEqual(request.kwargs, kwargs)
class AIOResponsesRaiseForStatusSessionTestCase(TestCase):
"""Test case for sessions with raise_for_status=True.
This flag, introduced in aiohttp v2.0.0, automatically calls
`raise_for_status()`.
It is overridden by the `raise_for_status` argument of the request since
aiohttp v3.4.a0.
"""
use_default_loop = False
@asyncio.coroutine
def setUp(self):
self.url = 'http://example.com/api?foo=bar#fragment'
self.session = ClientSession(raise_for_status=True)
super().setUp()
@asyncio.coroutine
def tearDown(self):
close_result = self.session.close()
if close_result is not None:
yield from close_result
super().tearDown()
@aioresponses()
@asyncio.coroutine
def test_raise_for_status(self, m):
m.get(self.url, status=400)
with self.assertRaises(ClientResponseError) as cm:
yield from self.session.get(self.url)
self.assertEqual(cm.exception.message, http.RESPONSES[400][0])
@aioresponses()
@asyncio.coroutine
@skipIf(condition=AIOHTTP_VERSION < '3.4.0',
reason='aiohttp<3.4.0 does not support raise_for_status '
'arguments for requests')
def test_do_not_raise_for_status(self, m):
m.get(self.url, status=400)
response = yield from self.session.get(self.url,
raise_for_status=False)
self.assertEqual(response.status, 400)
class AIOResponseRedirectTest(TestCase):
@asyncio.coroutine
def setUp(self):
self.url = "http://10.1.1.1:8080/redirect"
self.session = ClientSession()
super().setUp()
@asyncio.coroutine
def tearDown(self):
close_result = self.session.close()
if close_result is not None:
yield from close_result
super().tearDown()
@aioresponses()
@asyncio.coroutine
def test_redirect_followed(self, rsps):
rsps.get(
self.url,
status=307,
headers={"Location": "https://httpbin.org"},
)
rsps.get("https://httpbin.org")
response = yield from self.session.get(
self.url, allow_redirects=True
)
self.assertEqual(response.status, 200)
self.assertEqual(str(response.url), "https://httpbin.org")
self.assertEqual(len(response.history), 1)
self.assertEqual(str(response.history[0].url), self.url)
@aioresponses()
@asyncio.coroutine
def test_redirect_missing_mocked_match(self, rsps):
rsps.get(
self.url,
status=307,
headers={"Location": "https://httpbin.org"},
)
with self.assertRaises(ClientConnectionError) as cm:
yield from self.session.get(
self.url, allow_redirects=True
)
self.assertEqual(
str(cm.exception),
'Connection refused: GET http://10.1.1.1:8080/redirect'
)
@aioresponses()
@asyncio.coroutine
def test_redirect_missing_location_header(self, rsps):
rsps.get(self.url, status=307)
response = yield from self.session.get(self.url, allow_redirects=True)
self.assertEqual(str(response.url), self.url)
@aioresponses()
| |
# -*- coding: utf-8 -*-
from .compat import PY2, LOCALE, unicode, str_compat
from .handlers import commands as hc
@str_compat
class ProtocolError(IOError):
def __str__(self):
if self.errno is None and PY2:
message = self.message
else:
# метод __str__ вернет str, если strerror является str
# метод __str__ вернет unicode, если strerror является unicode
message = super(ProtocolError, self).__str__()
if PY2 and isinstance(message, str):
message = message.decode(LOCALE)
return message
class NoConnectionError(ProtocolError):
def __init__(self, *args):
if not args:
args = (u'Нет связи с ККМ', )
super(NoConnectionError, self).__init__(*args)
class UnexpectedResponseError(ProtocolError):
pass
class FDError(ProtocolError):
pass
@str_compat
class Error(ProtocolError):
codes = {
0x00: u'Ошибок нет',
0x01: u'Неисправен накопитель ФП 1, ФП 2 или часы',
0x02: u'Отсутствует ФП 1',
0x03: u'Отсутствует ФП 2',
0x04: u'Некорректные параметры в команде обращения к ФП',
0x05: u'Нет запрошенных данных',
0x06: u'ФП в режиме вывода данных',
0x07: u'Некорректные параметры в команде для данной реализации ФП',
0x08: u'Команда не поддерживается в данной реализации ФП',
0x09: u'Некорректная длина команды',
0x0A: u'Формат данных не BCD',
0x0B: u'Неисправна ячейка памяти ФП при записи итога',
0x0C: u'Переполнение необнуляемой суммы',
0x0D: u'Переполнение суммы итогов смен',
0x11: u'Не введена лицензия',
0x12: u'Заводской номер уже введен',
0x13: u'Текущая дата меньше даты последней записи в ФП',
0x14: u'Область сменных итогов ФП переполнена',
0x15: u'Смена уже открыта',
0x16: u'Смена не открыта',
0x17: u'Номер первой смены больше номера последней смены',
0x18: u'Дата первой смены больше даты последней смены',
0x19: u'Нет данных в ФП',
0x1A: u'Область перерегистраций в ФП переполнена',
0x1B: u'Заводской номер не введен',
0x1C: u'В заданном диапазоне есть поврежденная запись',
0x1D: u'Повреждена последняя запись сменных итогов',
0x1E: u'Запись фискализации (перерегистрации ККМ) в накопителе не найдена',
0x1F: u'Отсутствует память регистров',
0x20: u'Переполнение денежного регистра при добавлении',
0x21: u'Вычитаемая сумма больше содержимого денежного регистра',
0x22: u'Неверная дата',
0x23: u'Нет записи активизации',
0x24: u'Область активизаций переполнена',
0x25: u'Нет активизации с запрашиваемым номером',
0x26: u'В ФП присутствует 3 или более битые записи сменных итогов.',
0x27: u'Признак несовпадения КС, з/н, перерегистраций или активизаций',
0x28: u'Технологическая метка в накопителе присутствует',
0x29: u'Технологическая метка в накопителе отсутствует, возможно накопитель пуст',
0x2A: u'Фактическая емкость микросхемы накопителя не соответствует текущей версии ПО',
0x2B: u'Невозможно отменить предыдущую команду',
0x2C: u'Обнулённая касса (повторное гашение невозможно)',
0x2D: u'Сумма чека по секции меньше суммы сторно',
0x2E: u'В ККТ нет денег для выплаты',
0x2F: u'Не совпадает заводской номер ККМ в оперативной памяти ФП с номером в накопителе',
0x30: u'ККТ заблокирован, ждет ввода пароля налогового инспектора',
0x31: u'Сигнатура емкости накопителя не соответствует текущей версии ПО',
0x32: u'Требуется выполнение общего гашения',
0x33: u'Некорректные параметры в команде',
0x34: u'Нет данных',
0x35: u'Некорректный параметр при данных настройках',
0x36: u'Некорректные параметры в команде для данной реализации ККТ',
0x37: u'Команда не поддерживается в данной реализации ККТ',
0x38: u'Ошибка в ПЗУ',
0x39: u'Внутренняя ошибка ПО ККТ',
0x3A: u'Переполнение накопления по надбавкам в смене',
0x3B: u'Переполнение накопления в смене',
0x3C: u'ЭКЛЗ: неверный регистрационный номер',
0x3D: u'Смена не открыта – операция невозможна',
0x3E: u'Переполнение накопления по секциям в смене',
0x3F: u'Переполнение накопления по скидкам в смене',
0x40: u'Переполнение диапазона скидок',
0x41: u'Переполнение диапазона оплаты наличными',
0x42: u'Переполнение диапазона оплаты типом 2',
0x43: u'Переполнение диапазона оплаты типом 3',
0x44: u'Переполнение диапазона оплаты типом 4',
0x45: u'Сумма всех типов оплаты меньше итога чека',
0x46: u'Не хватает наличности в кассе',
0x47: u'Переполнение накопления по налогам в смене',
0x48: u'Переполнение итога чека',
0x49: u'Операция невозможна в открытом чеке данного типа',
0x4A: u'Открыт чек – операция невозможна',
0x4B: u'Буфер чека переполнен',
0x4C: u'Переполнение накопления по обороту налогов в смене',
0x4D: u'Вносимая безналичной оплатой сумма больше суммы чека',
0x4E: u'Смена превысила 24 часа',
0x4F: u'Неверный пароль',
0x50: u'Идет печать результатов выполнения предыдущей команды',
0x51: u'Переполнение накоплений наличными в смене',
0x52: u'Переполнение накоплений по типу оплаты 2 в смене',
0x53: u'Переполнение накоплений по типу оплаты 3 в смене',
0x54: u'Переполнение накоплений по типу оплаты 4 в смене',
0x55: u'Чек закрыт – операция невозможна',
0x56: u'Нет документа для повтора',
0x57: u'ЭКЛЗ: количество закрытых смен не совпадает с ФП',
0x58: u'Ожидание команды продолжения печати',
0x59: u'Документ открыт другим оператором',
0x5A: u'Скидка превышает накопления в чеке',
0x5B: u'Переполнение диапазона надбавок',
0x5C: u'Понижено напряжение 24В',
0x5D: u'Таблица не определена',
0x5E: u'Неверная операция',
0x5F: u'Отрицательный итог чека',
0x60: u'Переполнение при умножении',
0x61: u'Переполнение диапазона цены',
0x62: u'Переполнение диапазона количества',
0x63: u'Переполнение диапазона отдела',
0x64: u'ФП отсутствует',
0x65: u'Не хватает денег в секции',
0x66: u'Переполнение денег в секции',
0x67: u'Ошибка связи с ФП',
0x68: u'Не хватает денег по обороту налогов',
0x69: u'Переполнение денег по обороту налогов',
0x6A: u'Ошибка питания в момент ответа по I2C',
0x6B: u'Нет чековой ленты',
0x6C: u'Нет контрольной ленты',
0x6D: u'Не хватает денег по налогу',
0x6E: u'Переполнение денег по налогу',
0x6F: u'Переполнение по выплате в смене',
0x70: u'Переполнение ФП',
0x71: u'Ошибка отрезчика',
0x72: u'Команда не поддерживается в данном подрежиме',
0x73: u'Команда не поддерживается в данном режиме',
0x74: u'Ошибка ОЗУ',
0x75: u'Ошибка питания',
0x76: u'Ошибка принтера: нет импульсов с тахогенератора',
0x77: u'Ошибка принтера: нет сигнала с датчиков',
0x78: u'Замена ПО',
0x79: u'Замена ФП',
0x7A: u'Поле не редактируется',
0x7B: u'Ошибка оборудования',
0x7C: u'Не совпадает дата',
0x7D: u'Неверный формат даты',
0x7E: u'Неверное значение в поле длины',
0x7F: u'Переполнение диапазона итога чека',
0x80: u'Ошибка связи с ФП (превышен таймаут I2C с контроллером)',
0x81: u'Ошибка связи с ФП (контроллер отсутствует!? (получен NAK по I2C) '
u'или принят неполный кадр от контроллера UART)',
0x82: u'Ошибка связи с ФП (неверный формат данных в кадре I2C)',
0x83: u'Ошибка связи с ФП (неверная контрольная сумма передаваемого кадра по I2C)',
0x84: u'Переполнение наличности',
0x85: u'Переполнение по продажам в смене',
0x86: u'Переполнение по покупкам в смене',
0x87: u'Переполнение по возвратам продаж в смене',
0x88: u'Переполнение по возвратам покупок в смене',
0x89: u'Переполнение по внесению в смене',
0x8A: u'Переполнение по надбавкам в чеке',
0x8B: u'Переполнение по скидкам в чеке',
0x8C: u'Отрицательный итог надбавки в чеке',
0x8D: u'Отрицательный итог скидки в чеке',
0x8E: u'Нулевой итог чека',
0x8F: u'Касса не фискализирована',
0x90: u'Поле превышает размер, установленный в настройках',
0x91: u'Выход за границу поля печати при данных настройках шрифта',
0x92: u'Наложение полей',
0x93: u'Восстановление ОЗУ прошло успешно',
0x94: u'Исчерпан лимит операций в чеке',
0x95: u'Неизвестная ошибка ЭКЛЗ',
0x96: u'Выполните суточный отчет с гашением',
0x9B: u'Некорректное действие',
0x9C: u'Товар не найден по коду в базе товаров',
0x9D: u'Неверные данные в записе о товаре в базе товаров',
0x9E: u'Неверный размер файла базы или регистров товаров',
0xA0: u'Ошибка связи с ЭКЛЗ',
0xA1: u'ЭКЛЗ отсутствует',
0xA2: u'ЭКЛЗ: Некорректный формат или параметр команды',
0xA3: u'Некорректное состояние ЭКЛЗ',
0xA4: u'Авария ЭКЛЗ',
0xA5: u'Авария КС в составе ЭКЛЗ',
0xA6: u'Исчерпан временной ресурс ЭКЛЗ',
0xA7: u'ЭКЛЗ переполнена',
0xA8: u'ЭКЛЗ: Неверные дата и время',
0xA9: u'ЭКЛЗ: Нет запрошенных данных',
0xAA: u'Переполнение ЭКЛЗ (отрицательный итог документа)',
0xAF: u'Некорректные значения принятых данных от ЭКЛЗ',
0xB0: u'ЭКЛЗ: Переполнение в параметре количество',
0xB1: u'ЭКЛЗ: Переполнение в параметре сумма',
0xB2: u'ЭКЛЗ: Уже активизирована',
0xB4: u'Найденная запись фискализации (регистрации ККМ) повреждена',
0xB5: u'Запись заводского номера ККМ повреждена',
0xB6: u'Найденная запись активизации ЭКЛЗ повреждена',
0xB7: u'Записи сменных итогов в накопителе не найдены',
0xB8: u'Последняя запись сменных итогов не записана',
0xB9: u'Сигнатура версии структуры данных в накопителе не совпадает с текущей версией ПО',
0xBA: u'Структура накопителя повреждена',
0xBB: u'Текущая дата+время меньше даты+времени последней записи активизации ЭКЛЗ',
0xBC: u'Текущая дата+время меньше даты+времени последней записи фискализации (перерегистрации ККМ)',
0xBD: u'Текущая дата меньше даты последней записи сменного итога',
0xBE: u'Команда не поддерживается в текущем состоянии',
0xBF: u'Инициализация накопителя невозможна',
0xC0: u'Контроль даты и времени (подтвердите дату и время)',
0xC1: u'ЭКЛЗ: суточный отчёт с гашением прервать нельзя',
0xC2: u'Превышение напряжения в блоке питания',
0xC3: u'Несовпадение итогов чека и ЭКЛЗ',
0xC4: u'Несовпадение номеров смен',
0xC5: u'Буфер подкладного документа пуст',
0xC6: u'Подкладной документ отсутствует',
0xC7: u'Поле не редактируется в данном режиме',
0xC8: u'Отсутствуют импульсы от таходатчика',
0xC9: u'Перегрев печатающей головки',
0xCA: u'Температура вне условий эксплуатации',
0xCB: u'Неверный подытог чека',
0xCC: u'Смена в ЭКЛЗ уже закрыта',
0xCD: u'Обратитесь в ЦТО: тест целостности архива ЭКЛЗ не прошел, '
u'код ошибки ЭКЛЗ можно запросить командой 10H',
0xCE: u'Лимит минимального свободного объема ОЗУ или ПЗУ на ККМ исчерпан',
0xCF: u'Неверная дата (Часы сброшены? Установите дату!)',
0xD0: u'Отчет | |
is not None:
print(diccionario)
tabla_padre = tablaSimbolos.get(useActual).getTabla(tabla.padre)
if tabla_padre is not None:
print("Tiene Padre :)")
if rs == 0:
consola += "Se actualizó con éxito la tupla" + str(tupla) + "\n"
elif rs == 1:
listaSemanticos.append(Error.ErrorS("Error Semantico", "Fallo al insertar la tupla: " + str(tupla)))
elif rs == 2:
listaSemanticos.append(
Error.ErrorS("Error Semantico", "Fallo al insertar, la base de datos '%s' no existe " % useActual))
elif rs == 3:
listaSemanticos.append(
Error.ErrorS("Error Semantico", "Fallo al insertar, la tabla '%s' no existe" % tabla.nombre))
elif rs == 4:
listaSemanticos.append(
Error.ErrorS("Error Semantico", "Fallo al insertar, La llave primaria '%s' no existe" % str(pk)))
elif b["cod"] == 1:
listaSemanticos.append(Error.ErrorS(
"Error Semantico", "La columna " + b["col"] + "no existe en la tabla"))
elif b["cod"] == 2:
listaSemanticos.append(Error.ErrorS(
"Error Semantico", "La columna " + b["col"] + " no puede ser nula"))
# MÉTODO PARA RETORNAR LA TUPLA COMPLETA
def validarDefault(listaC, listaV, tabla, tablaSimbolos):
tupla = []
indice = 0
for i in tabla.columnas:
encontrado = False
print(tabla.columnas[i].index,indice)
if tabla.columnas[i].index == indice:
for j in range(len(listaC)):
if tabla.columnas[i].nombre == listaC[j].valor:
tupla.append(listaV[j].valor)
indice += 1
i = 0
encontrado = True
break
if not encontrado:
if tabla.columnas[i].default != None:
tupla.append(Interpreta_Expresion(tabla.columnas[i].default, tablaSimbolos, tabla).valor)
else:
tupla.append(None)
indice += 1
if (len(tabla.columnas) == len(tupla) ):
return tupla
# MÉTODO PARA RETORNAR LA TUPLA COMPLETA
def validarDefault2(listaC, listaV, tabla, tablaSimbolos):
tupla = []
indice = 0
encontrado = False
for i in tabla.columnas:
if tabla.columnas[i].index == indice:
for j in range(len(listaC)):
if tabla.columnas[i].nombre == listaC[j]:
tupla.append(Interpreta_Expresion(listaV[j], tablaSimbolos, tabla).valor)
indice += 1
i = 0
encontrado = True
break
if not encontrado:
if tabla.columnas[i].default != None:
tupla.append(Interpreta_Expresion(tabla.columnas[i].default, tablaSimbolos, tabla).valor)
else:
tupla.append(None)
if (len(tabla.columnas) == len(tupla)):
return tupla
# MÉTODO PARA VALIDAR LAS LLAVES FORÁNEAS
def validarFK(col, val, tabla, tablaSimbolos):
if col.foreign_key != None:
registro = jBase.extractTable(useActual, col.foreign_key["tabla"])
indice = tablaSimbolos.getColumna(
useActual, col.foreign_key["tabla"], col.foreign_key["columna"]).index
if registro != None and len(registro) > 0:
for i in range(len(registro)):
if val == registro[i][indice]:
return True
return False
else:
return False
return True
# MÉTODO PARA VALIDAR LOS CHECKS
def validaCheck(col, val, columnas, valores):
if col.check != None:
tipo = col.check["condicion"].opDer.tipo
if tipo == Expresion.ID:
for i in range(len(columnas)):
if columnas[i].valor == col.check["condicion"].opDer.valor:
nuevo = SOperacion(val, valores[i], col.check["condicion"].operador)
if Interpreta_Expresion(nuevo, None, None).valor:
return 0
else:
return 1
return 2
else:
nuevo = SOperacion(val, col.check["condicion"].opDer, col.check["condicion"].operador)
r = Interpreta_Expresion(nuevo, None, None)
if r.valor:
return 0
else:
return 1
return 0
# MÉTODO PARA VALIDAR LOS UNIQUE
def validarUnique(col, val, tabla):
global useActual
registros = jBase.extractTable(useActual, tabla.nombre)
indice = col.index
if (col.unique == True):
for i in range(len(registros)):
if registros[i][indice] == val:
return False
return True
# MÉTODO PARA VALIDAR LAS PRIMARY KEY
def validarPK(col, val, tabla):
global useActual
registros = jBase.extractTable(useActual, tabla.nombre)
indice = col.index
if (col.primary_key == True):
if registros != None:
for i in range(len(registros)):
if registros[i][indice] == val:
return False
return True
def validarTiposNumericos(dato, expresion):
if dato == "smallint":
if expresion.tipo == Expresion.ENTERO or expresion.tipo == Expresion.NEGATIVO:
if expresion.valor >= -32768 and expresion.valor <= 32767:
return True
elif dato == "integer":
if expresion.tipo == Expresion.ENTERO or expresion.tipo == Expresion.NEGATIVO:
if expresion.valor >= -2147483648 and expresion.valor <= 2147483647:
return True
elif dato == "bigint":
if expresion.tipo == Expresion.ENTERO or expresion.tipo == Expresion.NEGATIVO:
if expresion.valor >= -9223372036854775808 and expresion.valor <= 9223372036854775807:
return True
elif dato == "decimal":
if expresion.tipo == Expresion.DECIMAL or expresion.tipo == Expresion.NEGATIVO:
return True
elif dato == "numeric":
if expresion.tipo == Expresion.DECIMAL or expresion.tipo == Expresion.NEGATIVO:
return True
elif dato == "real":
if expresion.tipo == Expresion.DECIMAL or expresion.tipo == Expresion.NEGATIVO:
return True
elif dato == "double":
if expresion.tipo == Expresion.DECIMAL or expresion.tipo == Expresion.NEGATIVO:
return True
elif dato == "money":
if expresion.tipo == Expresion.DECIMAL or expresion.tipo == Expresion.ENTERO:
return True
if expresion.tipo==Expresion.NULL:
return True
return False
def validarTiposChar(dato, expresion):
if dato.dato.lower() == "varying" or dato.dato.lower() == "varchar":
if len(expresion.valor) <= dato.cantidad:
return True
elif dato.dato.lower() == "character" or dato.dato.lower() == "char":
if len(expresion.valor) <= dato.cantidad:
return True
elif dato.dato.lower() == "text":
return True
if expresion.tipo == Expresion.NULL:
return True
return False
def validarTiposFecha(dato, expresion):
if dato == "date":
if expresion.tipo == Expresion.FECHA:
return True
elif dato == "timestamp":
if expresion.tipo == Expresion.FECHA or expresion.tipo == Expresion.FECHA_HORA:
return True
elif dato == "time":
if expresion.tipo == Expresion.HORA:
return True
elif dato == "interval":
if expresion.tipo == Expresion.INTERVALO:
return True
if expresion.tipo == Expresion.NULL:
return True
return False
def Interpreta_Expresion(expresion, tablaSimbolos, tabla):
global consola
if isinstance(expresion, SOperacion):
# Logicas
if (expresion.operador == Logicas.AND):
opIzq = Interpreta_Expresion(expresion.opIzq, tablaSimbolos, tabla).valor
opDer = Interpreta_Expresion(expresion.opDer, tablaSimbolos, tabla).valor
result = (opIzq and opDer)
return SExpresion(result, Expresion.BOOLEAN)
if (expresion.operador == Logicas.OR):
opIzq = Interpreta_Expresion(expresion.opIzq, tablaSimbolos, tabla).valor
opDer = Interpreta_Expresion(expresion.opDer, tablaSimbolos, tabla).valor
result = (opIzq or opDer)
return SExpresion(result, Expresion.BOOLEAN)
# Relacionales
if (expresion.operador == Relacionales.IGUAL):
opIzq = Interpreta_Expresion(expresion.opIzq, tablaSimbolos, tabla).valor
opDer = Interpreta_Expresion(expresion.opDer, tablaSimbolos, tabla).valor
result = (opIzq == opDer)
return SExpresion(result, Expresion.BOOLEAN)
if (expresion.operador == Relacionales.DIFERENTE):
opIzq = Interpreta_Expresion(expresion.opIzq, tablaSimbolos, tabla).valor
opDer = Interpreta_Expresion(expresion.opDer, tablaSimbolos, tabla).valor
result = (opIzq != opDer)
return SExpresion(result, Expresion.BOOLEAN)
if (expresion.operador == Relacionales.MENORIGUAL_QUE):
opIzq = Interpreta_Expresion(expresion.opIzq, tablaSimbolos, tabla)
opDer = Interpreta_Expresion(expresion.opDer, tablaSimbolos, tabla)
result = opIzq.valor <= opDer.valor
return SExpresion(result, opIzq.tipo)
if (expresion.operador == Relacionales.MAYORIGUAL_QUE):
opIzq = Interpreta_Expresion(expresion.opIzq, tablaSimbolos, tabla)
opDer = Interpreta_Expresion(expresion.opDer, tablaSimbolos, tabla)
result = opIzq.valor >= opDer.valor
return SExpresion(result, opIzq.tipo)
if (expresion.operador == Relacionales.MENOR_QUE):
opIzq = Interpreta_Expresion(expresion.opIzq, tablaSimbolos, tabla)
opDer = Interpreta_Expresion(expresion.opDer, tablaSimbolos, tabla)
result = opIzq.valor < opDer.valor
return SExpresion(result, opIzq.tipo)
if (expresion.operador == Relacionales.MAYOR_QUE):
opIzq = Interpreta_Expresion(expresion.opIzq, tablaSimbolos, tabla)
opDer = Interpreta_Expresion(expresion.opDer, tablaSimbolos, tabla)
result = opIzq.valor > opDer.valor
return SExpresion(result, opIzq.tipo)
# Aritmetica
if (expresion.operador == Aritmetica.MAS):
opIzq = Interpreta_Expresion(expresion.opIzq, tablaSimbolos, tabla)
opDer = Interpreta_Expresion(expresion.opDer, tablaSimbolos, tabla)
if (opIzq.tipo == Expresion.ENTERO or opIzq.tipo == Expresion.DECIMAL) and (
opDer.tipo == Expresion.ENTERO or opDer.tipo == Expresion.DECIMAL):
result = opIzq.valor + opDer.valor
return SExpresion(result, opIzq.tipo)
if (expresion.operador == Aritmetica.MENOS):
opIzq = Interpreta_Expresion(expresion.opIzq, tablaSimbolos, tabla)
opDer = Interpreta_Expresion(expresion.opDer, tablaSimbolos, tabla)
if (opIzq.tipo == Expresion.ENTERO or opIzq.tipo == Expresion.DECIMAL) and (
opDer.tipo == Expresion.ENTERO or opDer.tipo == Expresion.DECIMAL):
result = opIzq.valor - opDer.valor
return SExpresion(result, opIzq.tipo)
if (expresion.operador == Aritmetica.POR):
opIzq = Interpreta_Expresion(expresion.opIzq, tablaSimbolos, tabla)
opDer = Interpreta_Expresion(expresion.opDer, tablaSimbolos, tabla)
if (opIzq.tipo == Expresion.ENTERO or opIzq.tipo == Expresion.DECIMAL) and (
opDer.tipo == Expresion.ENTERO or opDer.tipo == Expresion.DECIMAL):
result = opIzq.valor * opDer.valor
return SExpresion(result, opIzq.tipo)
if (expresion.operador == Aritmetica.DIVIDIDO):
opIzq = Interpreta_Expresion(expresion.opIzq, tablaSimbolos, tabla)
opDer = Interpreta_Expresion(expresion.opDer, tablaSimbolos, tabla)
if (opIzq.tipo == Expresion.ENTERO or opIzq.tipo == Expresion.DECIMAL) and (
opDer.tipo == Expresion.ENTERO or opDer.tipo == Expresion.DECIMAL):
result = opIzq.valor / opDer.valor
return SExpresion(result, opIzq.tipo)
if (expresion.operador == Aritmetica.MODULO):
opIzq = Interpreta_Expresion(expresion.opIzq, tablaSimbolos, tabla)
opDer = Interpreta_Expresion(expresion.opDer, tablaSimbolos, tabla)
if (opIzq.tipo == Expresion.ENTERO or opIzq.tipo == Expresion.DECIMAL) and (
opDer.tipo == Expresion.ENTERO or opDer.tipo == Expresion.DECIMAL):
result = opIzq.valor % opDer.valor
return SExpresion(result, opIzq.tipo)
if (expresion.operador == Aritmetica.POTENCIA):
opIzq = Interpreta_Expresion(expresion.opIzq, tablaSimbolos, tabla)
opDer = Interpreta_Expresion(expresion.opDer, tablaSimbolos, tabla)
if (opIzq.tipo == Expresion.ENTERO or opIzq.tipo == Expresion.DECIMAL) and (
opDer.tipo == Expresion.ENTERO or opDer.tipo == Expresion.DECIMAL):
result = opIzq.valor ** opDer.valor
return SExpresion(result, opIzq.tipo)
# f
elif isinstance(expresion, SFuncMath):
if expresion.funcion.lower() == "abs":
param = Interpreta_Expresion(expresion.param, tablaSimbolos, tabla)
val = abs(param.valor)
return SExpresion(val, param.tipo)
elif expresion.funcion.lower() == "cbrt":
param = Interpreta_Expresion(expresion.param, tablaSimbolos, tabla)
val = (param.valor) ** (1 / 3)
return SExpresion(val, param.tipo)
elif expresion.funcion.lower() == "ceil":
param = Interpreta_Expresion(expresion.param, tablaSimbolos, tabla)
val = math.ceil(param.valor)
return SExpresion(val, param.tipo)
elif expresion.funcion.lower() == "ceiling":
param = Interpreta_Expresion(expresion.param, tablaSimbolos, tabla)
val = math.ceil(param.valor)
return SExpresion(val, param.tipo)
elif expresion.funcion.lower() == "degrees":
param = Interpreta_Expresion(expresion.param, tablaSimbolos, tabla)
val = math.degrees(param.valor)
return SExpresion(val, param.tipo)
elif expresion.funcion.lower() == "exp":
param = Interpreta_Expresion(expresion.param, tablaSimbolos, tabla)
val = math.exp(param.valor)
return SExpresion(val, param.tipo)
elif expresion.funcion.lower() == "factorial":
param = Interpreta_Expresion(expresion.param, tablaSimbolos, tabla)
val = math.factorial(param.valor)
return SExpresion(val, param.tipo)
elif expresion.funcion.lower() == "floor":
param = Interpreta_Expresion(expresion.param, tablaSimbolos, tabla)
val = math.floor(param.valor)
return SExpresion(val, param.tipo)
elif expresion.funcion.lower() == "ln":
param = Interpreta_Expresion(expresion.param, tablaSimbolos, tabla)
val = math.log(param.valor)
return SExpresion(val, param.tipo)
elif expresion.funcion.lower() == "log":
param | |
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="emfh",
name="ESP minimum free heap since boot",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="emhb",
name="ESP maximum size of allocated heap block since boot",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="err",
name="Error",
state=transform_code,
attribute="err",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=None,
icon="mdi:alert-circle-outline",
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="err",
name="Error code",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=None,
icon="mdi:alert-circle-outline",
entity_registry_enabled_default=False,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="esr",
name="RTC reset reason",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="eto",
name="Total energy",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_ENERGY,
native_unit_of_measurement=ENERGY_WATT_HOUR, # @FIXME: 120 means 12 kWh probably
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="etop",
name="Total energy persisted",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_ENERGY,
native_unit_of_measurement=ENERGY_WATT_HOUR,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="ffb",
name="Lock feedback",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="ffba",
name="Lock feedback age",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=TIME_MILLISECONDS,
state_class=STATE_CLASS_MEASUREMENT,
icon="mdi:timer-outline",
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="fhz",
name="Grid frequency",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=FREQUENCY_HERTZ,
state_class=STATE_CLASS_MEASUREMENT,
icon="mdi:current-ac",
entity_registry_enabled_default=False,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="fsptws",
name="Force single phase toggle wished since",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=TIME_MILLISECONDS,
state_class=STATE_CLASS_MEASUREMENT,
icon="mdi:timer-outline",
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="host",
name="Hostname on STA interface",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="lbp",
name="Last button press",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="lccfc",
name="Last car state changed from charging",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=TIME_MILLISECONDS,
state_class=STATE_CLASS_MEASUREMENT,
icon="mdi:timer-outline",
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="lccfi",
name="Last car state changed from idle",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=TIME_MILLISECONDS,
state_class=STATE_CLASS_MEASUREMENT,
icon="mdi:timer-outline",
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="lcctc",
name="Last car state changed to charging",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=TIME_MILLISECONDS,
state_class=STATE_CLASS_MEASUREMENT,
icon="mdi:timer-outline",
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="lck",
name="Effective lock setting",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="led",
name="LED animation details",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="lfspt",
name="Last force single phase toggle",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=TIME_MILLISECONDS,
state_class=STATE_CLASS_MEASUREMENT,
icon="mdi:timer-outline",
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="lmsc",
name="Last mode change",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=TIME_MILLISECONDS,
state_class=STATE_CLASS_MEASUREMENT,
icon="mdi:timer-outline",
entity_registry_enabled_default=False,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="loa",
name="Load balancing available current",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_CURRENT,
native_unit_of_measurement=ELECTRIC_CURRENT_AMPERE,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="loc",
name="Local time",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Valueless with a high update interval of 1s",
),
GoEChargerSensorEntityDescription(
key="lom",
name="Load balancing members",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
icon="mdi:account-multiple",
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="los",
name="Load balancing status",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="lssfc",
name="WiFi station disconnected since",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="lsstc",
name="WiFi station connected since",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="mcpea",
name="Minimum charge pause ends at",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=TIME_MILLISECONDS,
state_class=STATE_CLASS_MEASUREMENT,
icon="mdi:timer-outline",
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="mmp",
name="Maximum measured charging power",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_POWER,
native_unit_of_measurement=POWER_WATT,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="modelStatus",
name="Status",
state=transform_code,
attribute="modelStatus",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=None,
icon="mdi:heart-pulse",
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="modelStatus",
name="Status code",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=None,
icon="mdi:heart-pulse",
entity_registry_enabled_default=False,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="msi",
name="Reason why we allow charging or not",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="nrg",
attribute="0",
name="Voltage L1",
state=extract_item_from_array_to_int,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_VOLTAGE,
native_unit_of_measurement=ELECTRIC_POTENTIAL_VOLT,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="nrg",
attribute="1",
name="Voltage L2",
state=extract_item_from_array_to_int,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_VOLTAGE,
native_unit_of_measurement=ELECTRIC_POTENTIAL_VOLT,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="nrg",
attribute="2",
name="Voltage L3",
state=extract_item_from_array_to_int,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_VOLTAGE,
native_unit_of_measurement=ELECTRIC_POTENTIAL_VOLT,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="nrg",
attribute="3",
name="Voltage N",
state=extract_item_from_array_to_int,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_VOLTAGE,
native_unit_of_measurement=ELECTRIC_POTENTIAL_VOLT,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="nrg",
attribute="4",
name="Current L1",
state=extract_item_from_array_to_int,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_CURRENT,
native_unit_of_measurement=ELECTRIC_CURRENT_AMPERE,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="nrg",
attribute="5",
name="Current L2",
state=extract_item_from_array_to_int,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_CURRENT,
native_unit_of_measurement=ELECTRIC_CURRENT_AMPERE,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="nrg",
attribute="6",
name="Current L3",
state=extract_item_from_array_to_int,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_CURRENT,
native_unit_of_measurement=ELECTRIC_CURRENT_AMPERE,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="nrg",
attribute="7",
name="Power L1",
state=extract_item_from_array_to_int,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_POWER,
native_unit_of_measurement=POWER_KILO_WATT,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="nrg",
attribute="8",
name="Power L2",
state=extract_item_from_array_to_int,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_POWER,
native_unit_of_measurement=POWER_KILO_WATT,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="nrg",
attribute="9",
name="Power L3",
state=extract_item_from_array_to_int,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_POWER,
native_unit_of_measurement=POWER_KILO_WATT,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="nrg",
attribute="10",
name="Power N",
state=extract_item_from_array_to_int,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_POWER,
native_unit_of_measurement=POWER_KILO_WATT,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="nrg",
attribute="11",
name="Current power",
state=extract_item_from_array_to_int,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_POWER,
native_unit_of_measurement=POWER_KILO_WATT,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="nrg",
attribute="12",
name="Power factor L1",
state=extract_item_from_array_to_int,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_POWER_FACTOR,
native_unit_of_measurement=PERCENTAGE,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="nrg",
attribute="13",
name="Power factor L2",
state=extract_item_from_array_to_int,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_POWER_FACTOR,
native_unit_of_measurement=PERCENTAGE,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="nrg",
attribute="14",
name="Power factor L3",
state=extract_item_from_array_to_int,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_POWER_FACTOR,
native_unit_of_measurement=PERCENTAGE,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="nrg",
attribute="15",
name="Power factor N",
state=extract_item_from_array_to_int,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_POWER_FACTOR,
native_unit_of_measurement=PERCENTAGE,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="oca",
name="OTA cloud app description",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="ocl",
name="OTA from cloud length",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="ocm",
name="OTA from cloud message",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="ocp",
name="OTA from cloud progress",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="ocs",
name="OTA from cloud status",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="ocu",
name="List of available firmware versions",
state=json_array_to_csv,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
icon="mdi:numeric",
entity_registry_enabled_default=False,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="onv",
name="Newest OTA version",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=None,
icon="mdi:numeric",
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="pwm",
name="Phase wish mode for debugging",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="qsc",
name="Queue size cloud",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="qsw",
name="Queue size web",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="rbc",
name="Reboot counter",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_TOTAL_INCREASING,
icon="mdi:counter",
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="rbt",
name="Uptime",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="TODO: Convert to a timestamp first",
),
GoEChargerSensorEntityDescription(
key="rcd",
name="Residual current detection",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="rfb",
name="Relay feedback",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="rr",
name="ESP reset reason",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="rssi",
name="WiFi signal strength",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_SIGNAL_STRENGTH,
native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="scaa",
name="WiFi scan age",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="scan",
name="WiFi scan result",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="scas",
name="WiFi scan status",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="tma",
name="Temperature sensor 1",
state=extract_item_from_array_to_float,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_TEMPERATURE,
native_unit_of_measurement=TEMP_CELSIUS,
state_class=STATE_CLASS_MEASUREMENT,
attribute="0",
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="tma",
name="Temperature sensor 2",
state=extract_item_from_array_to_float,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_TEMPERATURE,
native_unit_of_measurement=TEMP_CELSIUS,
state_class=STATE_CLASS_MEASUREMENT,
attribute="1",
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="tpa",
name="Total power average",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_POWER,
native_unit_of_measurement=POWER_WATT,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="trx",
name="Transaction",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
icon="mdi:message-text-lock-outline",
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="tsom",
name="Time server operating mode",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="utc",
name="UTC time",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Valueless with a high update interval of 1s",
),
GoEChargerSensorEntityDescription(
key="wcch",
name="Clients via http",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="wccw",
name="Clients via websocket",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT in firmware 053.1",
),
GoEChargerSensorEntityDescription(
key="wh",
name="Charged energy",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=DEVICE_CLASS_ENERGY,
native_unit_of_measurement=ENERGY_WATT_HOUR,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=True,
disabled=False,
),
GoEChargerSensorEntityDescription(
key="wsms",
name="WiFi state machine state",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=None,
native_unit_of_measurement=None,
state_class=STATE_CLASS_MEASUREMENT,
entity_registry_enabled_default=False,
disabled=True,
disabled_reason="Not exposed via MQTT | |
= [tag_id, ctx.guild.id]
else:
args = [tag_id, ctx.guild.id, ctx.author.id]
clause = f'{clause} AND owner_id=$3'
query = f'DELETE FROM tag_lookup WHERE {clause} RETURNING tag_id;'
deleted = await ctx.db.fetchrow(query, *args)
if deleted is None:
await ctx.send('Could not delete tag. Either it does not exist or you do not have permissions to do so.')
return
if bypass_owner_check:
clause = 'id=$1 AND location_id=$2'
args = [deleted[0], ctx.guild.id]
else:
clause = 'id=$1 AND location_id=$2 AND owner_id=$3'
args = [deleted[0], ctx.guild.id, ctx.author.id]
query = f'DELETE FROM tags WHERE {clause};'
status = await ctx.db.execute(query, *args)
# the status returns DELETE <count>, similar to UPDATE above
if status[-1] == '0':
# this is based on the previous delete above
await ctx.send('Tag alias successfully deleted.')
else:
await ctx.send('Tag and corresponding aliases successfully deleted.')
async def _send_alias_info(self, ctx, record):
embed = discord.Embed(colour=discord.Colour.blurple())
owner_id = record['lookup_owner_id']
embed.title = record['lookup_name']
embed.timestamp = record['lookup_created_at']
embed.set_footer(text='Alias created at')
user = self.bot.get_user(owner_id) or (await self.bot.fetch_user(owner_id))
embed.set_author(name=str(user), icon_url=user.avatar_url)
embed.add_field(name='Owner', value=f'<@{owner_id}>')
embed.add_field(name='Original', value=record['name'])
await ctx.send(embed=embed)
async def _send_tag_info(self, ctx, record):
embed = discord.Embed(colour=discord.Colour.blurple())
owner_id = record['owner_id']
embed.title = record['name']
embed.timestamp = record['created_at']
embed.set_footer(text='Tag created at')
user = self.bot.get_user(owner_id) or (await self.bot.fetch_user(owner_id))
embed.set_author(name=str(user), icon_url=user.avatar_url)
embed.add_field(name='Owner', value=f'<@{owner_id}>')
embed.add_field(name='Uses', value=record['uses'])
query = """SELECT (
SELECT COUNT(*)
FROM tags second
WHERE (second.uses, second.id) >= (first.uses, first.id)
AND second.location_id = first.location_id
) AS rank
FROM tags first
WHERE first.id=$1
"""
rank = await ctx.db.fetchrow(query, record['id'])
if rank is not None:
embed.add_field(name='Rank', value=rank['rank'])
await ctx.send(embed=embed)
@tag.command( aliases=['owner'])
@suggest_box()
async def info(self, ctx, *, name: TagName(lower=True)):
"""Retrieves info about a tag.
The info includes things like the owner and how many times it was used.
"""
query = """SELECT
tag_lookup.name <> tags.name AS "Alias",
tag_lookup.name AS lookup_name,
tag_lookup.created_at AS lookup_created_at,
tag_lookup.owner_id AS lookup_owner_id,
tags.*
FROM tag_lookup
INNER JOIN tags ON tag_lookup.tag_id = tags.id
WHERE LOWER(tag_lookup.name)=$1 AND tag_lookup.location_id=$2
"""
record = await ctx.db.fetchrow(query, name, ctx.guild.id)
if record is None:
return await ctx.send('Tag not found.')
if record['Alias']:
await self._send_alias_info(ctx, record)
else:
await self._send_tag_info(ctx, record)
@tag.command(pass_context=True)
@suggest_box()
async def raw(self, ctx, *, name: TagName(lower=True)):
"""Gets the raw content of the tag.
This is with markdown escaped. Useful for editing.
"""
try:
tag = await self.get_tag(ctx.guild.id, name, connection=ctx.db)
except RuntimeError as e:
return await ctx.send(e)
first_step = discord.utils.escape_markdown(tag['content'])
await ctx.safe_send(first_step.replace('<', '\\<'), escape_mentions=False)
@tag.command(name='list')
@suggest_box()
async def _list(self, ctx, *, member: TagMember = None):
"""Lists all the tags that belong to you or someone else."""
member = member or ctx.author
query = """SELECT name, id
FROM tag_lookup
WHERE location_id=$1 AND owner_id=$2
ORDER BY name
"""
rows = await ctx.db.fetch(query, ctx.guild.id, member.id)
await ctx.release()
if rows:
try:
p = TagPages(entries=rows)
p.embed.set_author(name=member.display_name, icon_url=member.avatar_url)
await p.start(ctx)
except menus.MenuError as e:
await ctx.send(e)
else:
await ctx.send(f'{member} has no tags.')
@commands.command()
@suggest_box()
async def tags(self, ctx, *, member: TagMember = None):
"""An alias for tag list command."""
await ctx.invoke(self._list, member=member)
@staticmethod
def _get_tag_all_arguments(args):
parser = Arguments(add_help=False, allow_abbrev=False)
parser.add_argument('--text', action='store_true')
if args is not None:
return parser.parse_args(shlex.split(args))
else:
return parser.parse_args([])
async def _tag_all_text_mode(self, ctx):
query = """SELECT tag_lookup.id,
tag_lookup.name,
tag_lookup.owner_id,
tags.uses,
$2 OR $3 = tag_lookup.owner_id AS "can_delete",
LOWER(tag_lookup.name) <> LOWER(tags.name) AS "is_alias"
FROM tag_lookup
INNER JOIN tags ON tags.id = tag_lookup.tag_id
WHERE tag_lookup.location_id=$1
ORDER BY tags.uses DESC;
"""
bypass_owner_check = ctx.author.id == self.bot.owner_id or ctx.author.guild_permissions.manage_messages
rows = await ctx.db.fetch(query, ctx.guild.id, bypass_owner_check, ctx.author.id)
if not rows:
return await ctx.send('This server has no server-specific tags.')
table = formats.TabularData()
table.set_columns(list(rows[0].keys()))
table.add_rows(list(r.values()) for r in rows)
fp = io.BytesIO(table.render().encode('utf-8'))
await ctx.send(file=discord.File(fp, 'tags.txt'))
@tag.command(name='all')
@suggest_box()
async def _all(self, ctx, *, args: str = None):
"""Lists all server-specific tags for this server.
You can pass specific flags to this command to control the output:
`--text`: Dumps into a text file
"""
try:
args = self._get_tag_all_arguments(args)
except RuntimeError as e:
return await ctx.send(e)
if args.text:
return await self._tag_all_text_mode(ctx)
query = """SELECT name, id
FROM tag_lookup
WHERE location_id=$1
ORDER BY name
"""
rows = await ctx.db.fetch(query, ctx.guild.id)
await ctx.release()
if rows:
# PSQL orders this oddly for some reason
try:
p = TagPages(entries=rows, per_page=20)
await p.start(ctx)
except menus.MenuError as e:
await ctx.send(e)
else:
await ctx.send('This server has no server-specific tags.')
@tag.command()
@suggest_box()
@checks.has_guild_permissions(manage_messages=True)
async def purge(self, ctx, member: TagMember):
"""Removes all server-specific tags by a user.
You must have server-wide Manage Messages permissions to use this.
"""
# Though inefficient, for UX purposes we should do two queries
query = "SELECT COUNT(*) FROM tags WHERE location_id=$1 AND owner_id=$2;"
count = await ctx.db.fetchrow(query, ctx.guild.id, member.id)
count = count[0] # COUNT(*) always returns 0 or higher
if count == 0:
return await ctx.send(f'{member} does not have any tags to purge.')
confirm = await ctx.prompt(f'This will delete {count} tags are you sure? **This action cannot be reversed**.')
if not confirm:
return await ctx.send('Cancelling tag purge request.')
query = "DELETE FROM tags WHERE location_id=$1 AND owner_id=$2;"
await ctx.db.execute(query, ctx.guild.id, member.id)
await ctx.send(f'Successfully removed all {count} tags that belong to {member}.')
@tag.command()
@suggest_box()
async def search(self, ctx, *, query: commands.clean_content):
"""Searches for a tag.
The query must be at least 3 characters.
"""
if len(query) < 3:
return await ctx.send('The query length must be at least three characters.')
sql = """SELECT name, id
FROM tag_lookup
WHERE location_id=$1 AND name % $2
ORDER BY similarity(name, $2) DESC
LIMIT 100;
"""
results = await ctx.db.fetch(sql, ctx.guild.id, query)
if results:
try:
p = TagPages(entries=results, per_page=20)
except menus.MenuError as e:
await ctx.send(e)
else:
await ctx.release()
await p.start(ctx)
else:
await ctx.send('No tags found.')
@tag.command()
@suggest_box()
async def claim(self, ctx, *, tag: TagName):
"""Claims an unclaimed tag.
An unclaimed tag is a tag that effectively
has no owner because they have left the server.
"""
# requires 2 queries for UX
query = "SELECT id, owner_id FROM tags WHERE location_id=$1 AND LOWER(name)=$2;"
row = await ctx.db.fetchrow(query, ctx.guild.id, tag.lower())
if row is None:
return await ctx.send(f'A tag with the name of "{tag}" does not exist.')
try:
member = ctx.guild.get_member(row[1]) or await ctx.guild.fetch_member(row[1])
except discord.NotFound:
member = None
if member is not None:
return await ctx.send('Tag owner is still in server.')
async with ctx.acquire():
async with ctx.db.transaction():
query = "UPDATE tags SET owner_id=$1 WHERE id=$2;"
await ctx.db.execute(query, ctx.author.id, row[0])
query = "UPDATE tag_lookup SET owner_id=$1 WHERE tag_id=$2;"
await ctx.db.execute(query, ctx.author.id, row[0])
await ctx.send('Successfully transferred tag ownership to you.')
@tag.command()
@suggest_box()
async def transfer(self, ctx, member: discord.Member, *, tag: TagName):
"""Transfers a tag to another member.
You must own the tag before doing this.
"""
if member.bot:
return await ctx.send('You cannot transfer a tag to a bot.')
query = "SELECT id FROM tags WHERE location_id=$1 AND LOWER(name)=$2 AND owner_id=$3;"
row = await ctx.db.fetchrow(query, ctx.guild.id, tag.lower(), ctx.author.id)
if row is None:
return await ctx.send(f'A tag with the name of "{tag}" does not exist or is not owned by you.')
async with ctx.acquire():
async with ctx.db.transaction():
query = "UPDATE tags SET owner_id=$1 WHERE id=$2;"
await ctx.db.execute(query, member.id, row[0])
query = "UPDATE tag_lookup SET owner_id=$1 WHERE tag_id=$2;"
await ctx.db.execute(query, member.id, row[0])
await ctx.send(f'Successfully transferred tag ownership to {member}.')
@tag.group()
@can_use_box()
async def box(self, ctx):
"""The tag box is where global tags are stored.
The tags in the box are not part of your server's tag list
unless you explicitly enable them. As a result, only those
with Manage Messages can check out the tag box, or anyone
if it's a private message.
To play around with the tag box, you should use the subcommands
provided.
"""
if ctx.invoked_subcommand is None or ctx.subcommand_passed == 'box':
await ctx.send_help('tag box')
@box.command(name='put')
async def box_put(self, ctx, name: TagName, *, content: commands.clean_content):
"""Puts a tag in the tag box.
These are global tags that anyone can opt-in to receiving
via the "tag box take" subcommand.
"""
query = "INSERT INTO tags (name, content, owner_id) VALUES ($1, $2, $3);"
try:
await ctx.db.execute(query, name, content, ctx.author.id)
except asyncpg.UniqueViolationError:
await ctx.send('A tag with this name exists in the box already.')
else:
await ctx.send('Successfully put tag in the box.')
@box.command(name='take')
@commands.guild_only()
async def box_take(self, ctx, *, name: TagName(lower=True)):
| |
fields to weight
src_cv: CloudVolume for forward field
dst_cv: CloudVolume for inverted field
bbox: boundingbox of region to process
mip: field MIP level
optimizer: bool to use the Optimizer instead of the net
"""
start = time()
chunks = self.break_into_chunks(bbox, cm.vec_chunk_sizes[mip],
cm.vec_voxel_offsets[mip], mip=mip)
print("Vector field inversion for slice {0} @ MIP{1} ({2} chunks)".
format(z, mip, len(chunks)), flush=True)
if self.distributed:
batch = []
for patch_bbox in chunks:
batch.append(tasks.InvertFieldTask(z, src_cv, dst_cv, patch_bbox,
mip, optimizer))
self.upload_tasks(batch)
else:
#for patch_bbox in chunks:
def chunkwise(patch_bbox):
self.invert_field(z, src_cv, dst_cv, patch_bbox, mip)
self.pool.map(chunkwise, chunks)
end = time()
print (": {} sec".format(end - start))
def res_and_compose(self, model_path, src_cv, tgt_cv, z, tgt_range, bbox,
mip, write_F_cv, pad, softmin_temp):
T = 2**mip
fields = []
for z_offset in tgt_range:
src_z = z
tgt_z = src_z - z_offset
print("calc res for src {} and tgt {}".format(src_z, tgt_z))
f = self.compute_field_chunk(model_path, src_cv, tgt_cv, src_z,
tgt_z, bbox, mip, pad)
#print("--------f shape is ---", f.shape)
fields.append(f)
#fields.append(f)
fields = [torch.from_numpy(i).to(device=self.device) for i in fields]
#print("device is ", fields[0].device)
field = vector_vote(fields, softmin_temp=softmin_temp)
field = field.data.cpu().numpy()
self.save_field(field, write_F_cv, z, bbox, mip, relative=False)
def downsample_range(self, cv, z_range, bbox, source_mip, target_mip):
"""Downsample a range of sections, downsampling a given MIP across all sections
before proceeding to the next higher MIP level.
Args:
cv: MiplessCloudVolume where images will be loaded and written
z_range: list of ints for section indices that will be downsampled
bbox: BoundingBox for region to be downsampled in each section
source_mip: int for MIP level of the data to be initially loaded
target_mip: int for MIP level after which downsampling will stop
"""
for mip in range(source_mip, target_mip):
print('downsample_range from {src} to {tgt}'.format(src=source_mip, tgt=target_mip))
for z in z_range:
self.downsample(cv, z, bbox, mip, mip+1, wait=False)
if self.distributed:
self.task_handler.wait_until_ready()
def generate_pairwise_and_compose(self, z_range, compose_start, bbox, mip, forward_match,
reverse_match, batch_size=1):
"""Create all pairwise matches for each SRC_Z in Z_RANGE to each TGT_Z in TGT_RADIUS
Args:
z_range: list of z indices to be matches
bbox: BoundingBox object for bounds of 2D region
forward_match: bool indicating whether to match from z to z-i
for i in range(tgt_radius)
reverse_match: bool indicating whether to match from z to z+i
for i in range(tgt_radius)
batch_size: (for distributed only) int describing how many sections to issue
multi-match tasks for, before waiting for all tasks to complete
"""
m = mip
batch_count = 0
start = 0
chunks = self.break_into_chunks(bbox, cm.vec_chunk_sizes[m],
cm.vec_voxel_offsets[m], mip=m)
if forward_match:
cm.add_composed_cv(compose_start, inverse=False,
as_int16=as_int16)
write_F_k = cm.get_composed_key(compose_start, inverse=False)
write_F_cv = cm.for_write(write_F_k)
if reverse_match:
cm.add_composed_cv(compose_start, inverse=True,
as_int16=as_int16)
write_invF_k = cm.get_composed_key(compose_start, inverse=True)
write_F_cv = cm.for_write(write_invF_k)
for z in z_range:
start = time()
batch_count += 1
i = 0
if self.distributed:
print("chunks size is", len(chunks))
batch = []
for patch_bbox in chunks:
batch.append(tasks.ResAndComposeTask(z, forward_match,
reverse_match,
patch_bbox, mip,
write_F_cv))
self.upload_tasks(batch)
else:
def chunkwise(patch_bbox):
self.res_and_compose(z, forward_match, reverse_match, patch_bbox,
mip, write_F_cv)
self.pool.map(chunkwise, chunks)
if batch_count == batch_size and self.distributed:
print('generate_pairwise waiting for {batch} sections'.format(batch=batch_size))
print('batch_count is {}'.format(batch_count), flush = True)
self.task_queue.block_until_empty()
end = time()
print (": {} sec".format(end - start))
batch_count = 0
# report on remaining sections after batch
if batch_count > 0 and self.distributed:
print('generate_pairwise waiting for {batch} sections'.format(batch=batch_size))
self.task_queue.block_until_empty()
end = time()
print (": {} sec".format(end - start))
def compute_field_and_vector_vote(self, cm, model_path, src_cv, tgt_cv, vvote_field,
tgt_range, z, bbox, mip, pad, softmin_temp):
"""Create all pairwise matches for each SRC_Z in Z_RANGE to each TGT_Z in
TGT_RADIUS and perform vetor voting
"""
m = mip
chunks = self.break_into_chunks(bbox, cm.vec_chunk_sizes[m],
cm.vec_voxel_offsets[m], mip=m,
max_mip=cm.num_scales)
batch = []
for patch_bbox in chunks:
batch.append(tasks.ResAndComposeTask(model_path, src_cv, tgt_cv, z,
tgt_range, patch_bbox, mip,
vvote_field, pad, softmin_temp))
return batch
def generate_pairwise(self, z_range, bbox, forward_match, reverse_match,
render_match=False, batch_size=1, wait=True):
"""Create all pairwise matches for each SRC_Z in Z_RANGE to each TGT_Z in TGT_RADIUS
Args:
z_range: list of z indices to be matches
bbox: BoundingBox object for bounds of 2D region
forward_match: bool indicating whether to match from z to z-i
for i in range(tgt_radius)
reverse_match: bool indicating whether to match from z to z+i
for i in range(tgt_radius)
render_match: bool indicating whether to separately render out
each aligned section before compiling vector fields with voting
(useful for debugging)
batch_size: (for distributed only) int describing how many sections to issue
multi-match tasks for, before waiting for all tasks to complete
wait: (for distributed only) bool to wait after batch_size for all tasks
to finish
"""
mip = self.process_low_mip
batch_count = 0
start = 0
for z in z_range:
start = time()
batch_count += 1
self.multi_match(z, forward_match=forward_match, reverse_match=reverse_match,
render=render_match)
if batch_count == batch_size and self.distributed and wait:
print('generate_pairwise waiting for {batch} section(s)'.format(batch=batch_size))
self.task_queue.block_until_empty()
end = time()
print (": {} sec".format(end - start))
batch_count = 0
# report on remaining sections after batch
if batch_count > 0 and self.distributed and wait:
print('generate_pairwise waiting for {batch} section(s)'.format(batch=batch_size))
self.task_queue.block_until_empty()
end = time()
print (": {} sec".format(end - start))
#if self.p_render:
# self.task_queue.block_until_empty()
def compose_pairwise(self, z_range, compose_start, bbox, mip,
forward_compose=True, inverse_compose=True,
negative_offsets=False, serial_operation=False):
"""Combine pairwise vector fields in TGT_RADIUS using vector voting, while composing
with earliest section at COMPOSE_START.
Args
z_range: list of ints (assumed to be monotonic & sequential)
compose_start: int of earliest section used in composition
bbox: BoundingBox defining chunk region
mip: int for MIP level of data
forward_compose: bool, indicating whether to compose with forward transforms
inverse_compose: bool, indicating whether to compose with inverse transforms
negative_offsets: bool indicating whether to use offsets less than 0 (z-i <-- z)
serial_operation: bool indicating to if a previously composed field is
not necessary
"""
T = 2**mip
print('softmin temp: {0}'.format(T))
if forward_compose:
cm.add_composed_cv(compose_start, inverse=False,
as_int16=as_int16)
if inverse_compose:
cm.add_composed_cv(compose_start, inverse=True,
as_int16=as_int16)
write_F_k = cm.get_composed_key(compose_start, inverse=False)
write_invF_k = cm.get_composed_key(compose_start, inverse=True)
read_F_k = write_F_k
read_invF_k = write_invF_k
if forward_compose:
read_F_cv = cm.for_read(read_F_k)
write_F_cv = cm.for_write(write_F_k)
self.vector_vote_chunkwise(z_range, read_F_cv, write_F_cv, bbox, mip,
inverse=False, T=T, negative_offsets=negative_offsets,
serial_operation=serial_operation)
if inverse_compose:
read_F_cv = cm.for_read(read_invF_k)
write_F_cv = cm.for_write(write_invF_k)
self.vector_vote_chunkwise(z_range, read_F_cv, write_F_cv, bbox, mip,
inverse=False, T=T, negative_offsets=negative_offsets,
serial_operation=serial_operation)
def get_neighborhood(self, z, F_cv, bbox, mip):
"""Compile all vector fields that warp neighborhood in TGT_RANGE to Z
Args
z: int for index of SRC section
F_cv: CloudVolume with fields
bbox: BoundingBox defining chunk region
mip: int for MIP level of data
"""
fields = []
z_range = [z+z_offset for z_offset in range(self.tgt_radius + 1)]
for k, tgt_z in enumerate(z_range):
F = self.get_field(F_cv, tgt_z, bbox, mip, relative=True, to_tensor=True,
as_int16=as_int16)
fields.append(F)
return torch.cat(fields, 0)
def shift_neighborhood(self, Fs, z, F_cv, bbox, mip, keep_first=False):
"""Shift field neighborhood by dropping earliest z & appending next z
Args
invFs: 4D torch tensor of inverse composed vector vote fields
z: int representing the z of the input invFs. invFs will be shifted to z+1.
F_cv: CloudVolume where next field will be loaded
bbox: BoundingBox representing xy extent of invFs
mip: int for data resolution of the field
"""
next_z = z + self.tgt_radius + 1
next_F = self.get_field(F_cv, next_z, bbox, mip, relative=True,
to_tensor=True, as_int16=as_int16)
if keep_first:
return torch.cat((Fs, next_F), 0)
else:
return torch.cat((Fs[1:, ...], next_F), 0)
def regularize_z(self, z_range, dir_z, bbox, mip, sigma=1.4):
"""For a given chunk, temporally regularize each Z in Z_RANGE
Make Z_RANGE as large as possible to avoid IO: self.shift_field
is called to add and remove the newest and oldest sections.
Args
z_range: list of ints (assumed to be a contiguous block)
overlap: int for number of sections that overlap with a chunk
bbox: BoundingBox defining chunk region
mip: int for MIP level of data
sigma: float standard deviation of the Gaussian kernel used for the
weighted average inverse
"""
block_size = len(z_range)
overlap = self.tgt_radius
curr_block = z_range[0]
next_block = curr_block + block_size
cm.add_composed_cv(curr_block, inverse=False,
as_int16=as_int16)
cm.add_composed_cv(curr_block, inverse=True,
as_int16=as_int16)
cm.add_composed_cv(next_block, inverse=False,
as_int16=as_int16)
F_cv = cm.get_composed_cv(curr_block, inverse=False, for_read=True)
invF_cv = cm.get_composed_cv(curr_block, inverse=True, for_read=True)
next_cv = cm.get_composed_cv(next_block, inverse=False, for_read=False)
z = z_range[0]
invFs = self.get_neighborhood(z, invF_cv, bbox, mip)
bump_dims = | |
import os
import re
import nipype
from nipype.interfaces.base import (TraitedSpec, File, traits, InputMultiPath,
BaseInterface, OutputMultiPath, BaseInterfaceInputSpec, isdefined)
from Extra.base import MINCCommand, MINCCommandInputSpec, Info
from nipype.interfaces.base import (TraitedSpec, File, traits, InputMultiPath,isdefined)
from scipy.integrate import simps
import pandas as pd
import numpy as np
import nipype.pipeline.engine as pe
import nipype.interfaces.io as nio
import nipype.interfaces.utility as util
import nipype.interfaces.utility as niu
import json
from Extra.concat import concat_df
from Quality_Control.qc import metric_columns
results_columns = metric_columns + ['frame']
"""
.. module:: Results_Report.results
:platform: Unix
:synopsis: Module to get results from output image
.. moduleauthor:: <NAME> <<EMAIL>>
"""
######################################
# Group level descriptive statistics #
######################################
def group_level_descriptive_statistics(opts, args):
vol_surf_list = ['']
if opts.use_surfaces :
vol_surf_list += ['surf']
for surf in vol_surf_list:
print(surf, "\n")
#Setup workflow
workflow = pe.Workflow(name=opts.preproc_dir)
workflow.base_dir = opts.targetDir
#Datasink
datasink=pe.Node(interface=nio.DataSink(), name="output")
datasink.inputs.base_directory= opts.targetDir+os.sep+os.sep+"stats"+os.sep+surf
datasink.inputs.substitutions = [('_cid_', ''), ('sid_', '')]
#Datagrabber
if not opts.test_group_qc : scan_stats_dict = dict(scan_stats='*'+os.sep+'results_'+surf+'*'+os.sep+'*_3d.csv')
else : scan_stats_dict = dict(scan_stats='*'+os.sep+'*'+os.sep+'results_'+surf+'*'+os.sep+'*_3d.csv')
datasource = pe.Node( interface=nio.DataGrabber( outfields=['scan_stats'], raise_on_empty=True, sort_filelist=False), name="datasource")
datasource.inputs.base_directory = opts.targetDir + os.sep +opts.preproc_dir
datasource.inputs.template = '*'
datasource.inputs.field_template = scan_stats_dict
#Concatenate descriptive statistics
concat_statisticsNode=pe.Node(interface=concat_df(), name="concat_statistics")
concat_statisticsNode.inputs.out_file="descriptive_statistics.csv"
workflow.connect(datasource, 'scan_stats', concat_statisticsNode, 'in_list')
workflow.connect(concat_statisticsNode, "out_file", datasink, 'results')
#Calculate descriptive statistics
descriptive_statisticsNode = pe.Node(interface=descriptive_statisticsCommand(), name="descriptive_statistics")
workflow.connect(concat_statisticsNode, 'out_file', descriptive_statisticsNode, 'in_file')
workflow.connect(descriptive_statisticsNode, "sub", datasink, 'sub')
workflow.connect(descriptive_statisticsNode, "ses", datasink, 'ses')
workflow.connect(descriptive_statisticsNode, "task", datasink, 'task')
workflow.connect(descriptive_statisticsNode, "sub_task", datasink, 'sub_task')
workflow.connect(descriptive_statisticsNode, "sub_ses", datasink, 'sub_ses')
workflow.run()
class resultsInput(TraitedSpec):
in_file = traits.File(desc="Input file ")
mask = traits.File(desc="ROI PET mask ")
surf_mesh = traits.File(desc="Surface mesh (.obj) ")
surf_mask = traits.File(desc="Surface mask (.txt) ")
header = traits.File(desc="PET Header")
out_file_3d = traits.File(desc="3d Output file ")
out_file_4d = traits.File(desc="4d Output file ")
dim = traits.Str("Number of dimensions")
sub = traits.Str("Subject ID")
task = traits.Str(default_value='NA',usedefault=True)
ses = traits.Str(desc="Ses",usedefault=True,default_value="NA")
run = traits.Str(desc="Run",usedefault=True,default_value="NA")
acq = traits.Str(desc="Acquisition",usedefault=True,default_value="NA")
rec = traits.Str(desc="Reconstruction",usedefault=True,default_value="NA")
node = traits.Str(mandatory=True, desc="Node name")
class resultsOutput(TraitedSpec):
out_file_3d = traits.File(desc="3D Output file ")
out_file_4d = traits.File(desc="4D Output file ")
class resultsCommand( BaseInterface):
input_spec = resultsInput
output_spec = resultsOutput
def _gen_output(self, in_file):
print "\n\n",in_file,"\n\n"
ii = os.path.splitext(os.path.basename(in_file))[0]
out_file_3d = os.getcwd() + os.sep + ii + "_3d.csv"
out_file_4d = os.getcwd() + os.sep + ii + "_4d.csv"
return [out_file_3d, out_file_4d]
def _run_interface(self, runtime):
print '\n\n', self.inputs.in_file, '\n\n'
if not isdefined(self.inputs.out_file_3d) or not isdefined(self.inputs.out_file_4d) :
[self.inputs.out_file_3d, self.inputs.out_file_4d ]=self._gen_output(self.inputs.in_file)
resultsReport = groupstatsCommand()
resultsReport.inputs.image = self.inputs.in_file
resultsReport.inputs.vol_roi = self.inputs.mask
if isdefined(self.inputs.surf_mesh) and isdefined(self.inputs.surf_mask) :
resultsReport.inputs.surf_roi = self.inputs.surf_mesh + ' ' + self.inputs.surf_mask
resultsReport.inputs.out_file = os.getcwd()+os.sep+'temp.csv'
print resultsReport.cmdline
acq_list = [ re.sub('acq-','',f) for f in self.inputs.in_file.split('_') if 'acq' in f ]
rec_list = [ re.sub('rec-','',f) for f in self.inputs.in_file.split('_') if 'rec' in f ]
resultsReport.run()
add_csvInfoNode = add_csvInfoCommand()
add_csvInfoNode.inputs.in_file = resultsReport.inputs.out_file
add_csvInfoNode.inputs.sub = self.inputs.sub
add_csvInfoNode.inputs.ses = self.inputs.ses
add_csvInfoNode.inputs.task =self.inputs.task
if isdefined(self.inputs.run):
add_csvInfoNode.inputs.run =self.inputs.run
if isdefined(self.inputs.rec):
add_csvInfoNode.inputs.rec =self.inputs.rec
elif len(rec_list) > 0 :
add_csvInfoNode.inputs.rec = rec_list[0]
if isdefined(self.inputs.acq):
add_csvInfoNode.inputs.acq =self.inputs.acq
elif len(acq_list) > 0 :
add_csvInfoNode.inputs.acq = acq_list[0]
add_csvInfoNode.inputs.node =self.inputs.node
if self.inputs.dim == '4': add_csvInfoNode.inputs.out_file = self.inputs.out_file_4d
else: add_csvInfoNode.inputs.out_file = self.inputs.out_file_3d
add_csvInfoNode.run()
if self.inputs.dim == '4':
integrate_resultsReport = integrate_TACCommand()
integrate_resultsReport.inputs.header = self.inputs.header
integrate_resultsReport.inputs.in_file = add_csvInfoNode.inputs.out_file
integrate_resultsReport.inputs.out_file = self.inputs.out_file_3d
integrate_resultsReport.run()
return runtime
def _list_outputs(self):
if not isdefined(self.inputs.out_file_3d) or not isdefined(self.inputs.out_file_4d) :
[ self.inputs.out_file_3d, self.inputs.out_file_4d ] = self._gen_output(self.inputs.in_file)
outputs = self.output_spec().get()
outputs["out_file_3d"] = self.inputs.out_file_3d
outputs["out_file_4d"] = self.inputs.out_file_4d
return outputs
class groupstatsInput(MINCCommandInputSpec):
image = traits.File(argstr="-i %s", mandatory=True, desc="Image")
vol_roi = traits.File(argstr="-v %s", desc="Volumetric image containing ROI")
surf_roi = traits.File(argstr="-s %s", desc="obj and txt files containing surface ROI")
out_file = traits.File(argstr="-o %s", desc="Output csv file")
label = traits.Str(desc="Label for output file")
class groupstatsOutput(TraitedSpec):
out_file = File(desc="Extract values from PET images based on ROI")
class groupstatsCommand(MINCCommand, Info):
_cmd = "mincgroupstats"
input_spec = groupstatsInput
output_spec = groupstatsOutput
_suffix='results'
def _parse_inputs(self, label=None, skip=None):
if skip is None:
skip = []
if not isdefined(self.inputs.out_file):
if label == None: label_str=''
else : label_str=label + '_'
self.inputs.out_file = os.getcwd() + os.sep + label_str + "results.csv" #fname_presuffix(self.inputs.image, suffix=self._suffix)
return super(groupstatsCommand, self)._parse_inputs(skip=skip)
def _list_outputs(self):
outputs = self.output_spec().get()
outputs["out_file"] = self.inputs.out_file
return outputs
def _gen_filename(self, name):
if name == "out_file":
return self._list_outputs()["out_file"]
return None
class add_csvInfoInput(MINCCommandInputSpec):
in_file = File(mandatory=True, desc="Input file")
ses = traits.Str(mandatory=True, desc="Session",usedefault=True,default_value="NA")
task = traits.Str(mandatory=True, desc="Task",usedefault=True,default_value="NA")
sub = traits.Str(mandatory=True, desc="Subject")
run = traits.Str(mandatory=False, desc="Run",usedefault=True,default_value="NA")
acq = traits.Str(mandatory=False, desc="Radiotracer",usedefault=True,default_value="NA")
rec = traits.Str(mandatory=False, desc="Reconstruction",usedefault=True,default_value="NA")
node = traits.Str(mandatory=True, desc="Node name")
out_file = File(desc="Output file")
class add_csvInfoOutput(TraitedSpec):
out_file = File(desc="Output file")
class add_csvInfoCommand(BaseInterface):
input_spec = add_csvInfoInput
output_spec = add_csvInfoOutput
def _run_interface(self, runtime):
#print(self.inputs); exit(1)
sub = self.inputs.sub
task= self.inputs.task
ses= self.inputs.ses
node = self.inputs.node
run = self.inputs.run
acq = self.inputs.acq
rec = self.inputs.rec
print "\nadd_csvInfo: ", self.inputs.in_file, "\n"
df = pd.read_csv( self.inputs.in_file, header=None )
df.columns= ['ndim', 'roi', 'frame', 'mean','sd','max','min','vol']
dfo =pd.DataFrame( columns=results_columns)
dfo["analysis"] = [node] * df.shape[0]
dfo["sub"] = [sub] * df.shape[0]
dfo["ses"] = [ses] * df.shape[0]
dfo["task"] = [task] * df.shape[0]
dfo["run"] = [run] * df.shape[0]
dfo["acq"] = [acq] * df.shape[0]
dfo["rec"] = [rec] * df.shape[0]
dfo["roi"] = df['roi']
dfo['metric'] = ['mean'] * df.shape[0]
dfo['value'] = df['mean']
if 'frame' in df.columns:
dfo['frame'] = df['frame']
else: dfo['frame'] = [0] * df.shape[0]
dfo = dfo[ results_columns ]
print(dfo["run"])
print(dfo)
if not isdefined(self.inputs.out_file):
self.inputs.out_file = self._gen_output(self.inputs.in_file)
dfo.to_csv(self.inputs.out_file, index=False)
return runtime
def _gen_output(self, basename):
sbasename = os.path.splitext(basename)
return sbasename[0]+'_withInfo'+sbasename[1]
def _list_outputs(self):
outputs = self.output_spec().get()
if not isdefined(self.inputs.out_file):
self.inputs.out_file = self._gen_output(self.inputs.in_file)
outputs["out_file"] = self.inputs.out_file
return outputs
class descriptive_statisticsInput(MINCCommandInputSpec):
in_file = traits.File(desc="Input file ")
ses = traits.File(desc="Output averaged by sesion")
task = traits.File(desc="Output averaged by task")
sub = traits.File(desc="Output averaged by subject")
sub_task = traits.File(desc="Output averaged by subject x task")
sub_ses = traits.File(desc="Output averaged by subject x ses")
class descriptive_statisticsOutput(TraitedSpec):
ses = traits.File(desc="Output averaged by sesion")
task = traits.File(desc="Output averaged by task")
sub = traits.File(desc="Output averaged by subject")
sub_task = traits.File(desc="Output averaged by subject x task")
sub_ses = traits.File(desc="Output averaged by subject x ses")
class descriptive_statisticsCommand( BaseInterface):
input_spec = descriptive_statisticsInput
output_spec = descriptive_statisticsOutput
def _parse_inputs(self, skip=None):
if skip is None:
skip = []
if not isdefined(self.inputs.in_file):
self.inputs.out_file = os.getcwd() + os.sep + "results.csv"
return super(descriptive_statisticsCommand, self)._parse_inputs(skip=skip)
def _run_interface(self, runtime):
df = pd.read_csv( self.inputs.in_file )
# df_pivot = lambda y : pd.DataFrame(df.pivot_table(rows=y,values=["value"], aggfunc=np.mean).reset_index(level=y))
df_pivot = lambda y : pd.DataFrame(df.pivot_table(index=y,values=["value"], aggfunc=np.mean).reset_index(level=y))
ses_df = df_pivot(["analysis", "metric", "roi", "ses"])
task_df =df_pivot(["analysis", "metric","roi", "task"])
sub_df = df_pivot(["analysis", "metric","roi", "sub"])
sub_ses_df = df_pivot(["analysis", "metric","roi", "sub","ses"])
sub_task_df = df_pivot(["analysis", "metric","roi", "sub","task"])
self.inputs.ses = self._gen_output(self.inputs.in_file, "ses")
self.inputs.task = self._gen_output(self.inputs.in_file, "task")
self.inputs.sub = self._gen_output(self.inputs.in_file, "sub")
self.inputs.sub_task = self._gen_output(self.inputs.in_file, "sub_task")
self.inputs.sub_ses= self._gen_output(self.inputs.in_file, "sub_ses")
ses_df.to_csv(self.inputs.ses, index=False)
task_df.to_csv(self.inputs.task, index=False)
sub_df.to_csv(self.inputs.sub, index=False)
sub_ses_df.to_csv(self.inputs.sub_task, index=False)
sub_task_df.to_csv(self.inputs.sub_ses, index=False)
return runtime
def _list_outputs(self):
outputs = self.output_spec().get()
outputs["ses"] = self.inputs.ses
outputs["task"] = self.inputs.task
outputs["sub"] = self.inputs.sub
outputs["sub_task"] = self.inputs.sub_task
outputs["sub_ses"] = self.inputs.sub_ses
return outputs
def _gen_output(self, in_file, label):
ii = os.path.splitext(os.path.basename(in_file))[0]
out_file = os.getcwd() + os.sep + ii + "_"+label+".csv"
return out_file
### TKA metrics
class integrate_TACInput(MINCCommandInputSpec):
in_file = traits.File(desc="Input file ")
header = traits.File(desc="PET Header file ")
out_file = traits.File(desc="Output file ")
class integrate_TACOutput(TraitedSpec):
out_file = traits.File(desc="Output file ")
class integrate_TACCommand( BaseInterface):
input_spec = integrate_TACInput
output_spec = integrate_TACOutput
def _gen_output(self, in_file):
ii = os.path.splitext(os.path.basename(in_file))[0]
out_file = os.getcwd() + os.sep + ii + "_int.csv"
return out_file
def _run_interface(self, runtime):
header = json.load(open( self.inputs.header ,"rb"))
df = pd.read_csv( self.inputs.in_file )
#if time frames is not a list of numbers, .e.g., "unknown",
#then set time frames to 1
time_frames = []
if time_frames == [] :
try :
header['Time']['FrameTimes']['Values']
time_frames = [ float(s) for s,e in header['Time']["FrameTimes"]["Values"] ]
#for i in range(1, len(time_frames)) :
# time_frames[i] = time_frames[i] + time_frames[i-1]
except ValueError :
time_frames = []
if time_frames == [] : time_frames = [1.]
out_df = pd.DataFrame( columns=metric_columns)
for name, temp_df in df.groupby(["analysis", "sub", "ses", "task","run", "acq", "rec", "roi"]):
print temp_df
print time_frames
if len(time_frames) > 1 :
mean_int = simps(temp_df["value"], time_frames)
print("Integral of mean:", mean_int)
else:
mean_int = temp_df.value.values[0] * time_frames[0]
print "\n",mean_int, "=", temp_df.value.values[0], "x", time_frames[0], "\n"
row = pd.DataFrame( [list(name) + ['integral', mean_int]], columns=metric_columns )
out_df = pd.concat( [out_df, row] )
out_df["frame"] = [0] * out_df.shape[0]
if not isdefined(self.inputs.in_file):
self.inputs.out_file = self._gen_output(self.inputs.in_file)
out_df.to_csv(self.inputs.out_file, index=False)
return runtime
def _parse_inputs(self):
if not isdefined(self.inputs.out_file):
self.inputs.out_file =self._gen_output(self.inputs.in_file)
return super(integrate_TACCommand, self)._parse_inputs(skip=skip)
def _list_outputs(self):
if not isdefined(self.inputs.out_file):
self.inputs.out_file | |
--help\n'.format(app_name)
def is_valid_medialive_channel_arn(mlive_channel_arn):
"""Determine if the ARN provided is a valid / complete MediaLive Channel ARN"""
if mlive_channel_arn.startswith("arn:aws:medialive:") and "channel" in mlive_channel_arn:
return True
else:
return False
def extract_medialive_region(ml_channel_arn):
""""Given a MediaLive Channel Arn determine the region the channel is in."""
region = None
# arn:aws:medialive:us-west-2:0123456789:channel:123456
if is_valid_medialive_channel_arn(ml_channel_arn):
arn_parts = ml_channel_arn.split(":")
if len(arn_parts) == 7:
region = arn_parts[3]
return region
def extract_medialive_channel_id(ml_channel_arn):
"""Given a MediaLive Channel ARN, return the MediaLive Channel ID"""
ml_channel_id = None
if is_valid_medialive_channel_arn(ml_channel_arn):
ml_channel_id = ml_channel_arn.strip().split(":")[-1]
return ml_channel_id
def load_eml_arn_list(ml_list_file):
"""Load the MediaLive Channel ARNs defined in "ml_list_file" and return as a list.
All MediaLive Channels must be in the same region to be eligble for inclusion into a CloudWatch Dashboard metric
widget. Therefore only Channel ARNs in the same region as the first Channel ARN in the list will be returned.
Additionally, any duplicate ARNs will be discarded as well."""
first_region = None
is_first_arn = True
result = []
try:
with open(ml_list_file, "rt") as in_file:
for line in in_file:
line = line.strip()
if is_valid_medialive_channel_arn(line):
current_region = extract_medialive_region(line)
if is_first_arn:
first_region = current_region
is_first_arn = False
if current_region == first_region:
if line not in result:
result.append(line)
else:
print "Skipping duplicate MediaLive ARN '{0}', since it already exists in the " \
"list".format(line)
else:
print "Ignoring MediaLive ARN '{0}', since it's not in the same region as the first " \
"ARN in the list.".format(line)
else:
if line is not "":
print "'{0}' is not a valid MediaLive Channel ARN".format(line)
return result
except Exception, e:
print "Error: Processing EML Channel ARN List file '{0}'\n{1}".format(ml_list_file, e.message)
# MediaLive related functions
def create_medialive_client_instance(ml_region):
"""Create a MediaLive Client Instance for the region specified in "ml_region". """
try:
medialive = boto3.client('medialive', region_name=ml_region)
return medialive
except Exception, e:
print "Error: Creating a MediaLive Client instance:\n '{0}'".format(e.message)
exit(-1)
def extract_medialive_channel_info(ml_client, ml_channel_id):
"""Perform a list-channels query against all MediaLive channel in the region specified by the
MediaLive Channel ID and retrieve the MediaLive Channel Name, and MediaPackage Channel ARNs
Returns: MediaLive_Channel_Name & a list of MediaPackage channels"""
mediapackage_channel_list = []
channel_name = None
try:
response = ml_client.describe_channel(
ChannelId=ml_channel_id
)
channel_name = str(response["Name"])
destinations = response["Destinations"]
for destination in destinations:
for output in destination["Settings"]:
url = str(output["Url"])
if "mediapackage" in url:
mediapackage_channel_list.append(url)
except Exception, e:
print "Error:", e.message
return channel_name, mediapackage_channel_list
def extract_medialive_outputgroup_names(ml_client, ml_channel_id):
"""given the MediaLive Channel ID "ml_channel_id" retrieve a list of all Output Group Names defined in the
channel configuration."""
mp_outputgroup_names = []
try:
channel_response = ml_client.describe_channel(ChannelId=ml_channel_id)
outputgroups = channel_response["EncoderSettings"]["OutputGroups"]
for outputgroup in outputgroups:
groupname = str(outputgroup["Name"])
mp_outputgroup_names.append(groupname)
return mp_outputgroup_names
except Exception, e:
print "Error: Unable to perform the describe-channel() query for the MediaLive Channel", ml_channel_id
print "Error message:", e
# MediaPackage related functions
def create_mediapackage_client_instance(mp_region):
"""Create a MediaPackage Client Instance for the region specified in "mp_region". """
try:
mediapackage = boto3.client('mediapackage', region_name=mp_region)
return mediapackage
except Exception, e:
print "Error: Creating a MediaPackage Client instance '{0}'".format(e.message)
def extract_mediapackage_channel_names(mp_client, mediapackage_url_list, ml_region):
"""Using the list-channels query, in the region "ml_region", find the MediaPackage Channel Id for the MediaPackage
Channels defined in "mediapackage_url_list"."""
mp_uids = []
mp_channel_names = []
for mediapackage_url in mediapackage_url_list:
if "mediapackage." + ml_region in mediapackage_url:
if "/v1/" in mediapackage_url:
url_parts = mediapackage_url.split("/")
if len(url_parts) == 7:
emp_ch_id = url_parts[5]
mp_uids.append(emp_ch_id)
elif "/v2/" in mediapackage_url:
url_parts = mediapackage_url.split("/")
if len(url_parts) == 8:
emp_ch_id = url_parts[5]
if emp_ch_id not in mp_uids:
mp_uids.append(emp_ch_id)
if len(mp_uids) > 0:
response = mp_client.list_channels()
for channel in response["Channels"]:
channel_arn = channel["Arn"]
channel_uid = channel_arn.split("/")[-1]
if channel_uid in mp_uids:
mp_channel_names.append(channel["Id"])
return mp_channel_names
def extract_mediapackage_endpoints(mp_client, mp_channel_id_list):
"""Using the list_origin_endpoints query, find all the MediaPackage endpoints for the MediaPackage
channels defined in "mediapackage_channel_id_list" """
emp_endpoint_list = {}
for channel in mp_channel_id_list:
emp_endpoint_list[str(channel)] = []
response = mp_client.list_origin_endpoints()
for endpoint in response['OriginEndpoints']:
if str(endpoint["ChannelId"]) in mp_channel_id_list:
emp_endpoint_list[str(endpoint["ChannelId"])].append(str(endpoint['Id']))
return emp_endpoint_list
# CloudWatch related functions
def create_cloudwatch_client_instance():
"""Create a CloudWatch Client Instance. """
try:
cloudwatch = boto3.client('cloudwatch')
return cloudwatch
except Exception, e:
print "Error: Creating a CloudWatch Client instance:\n '{0}'".format(e.message)
exit(-1)
def extract_cw_metrics_output_names(cw_client, ml_channel_id):
"""Retrieve a list of MediaLive OutputNames for all Outputs defined in the OutputVideoFrameRate CloudWatch Metric
of the MediaLive defined by the MediaLive Channel ID "ml_channel_id" """
output_name_list = []
try:
paginator = cw_client.get_paginator('list_metrics')
for response in paginator.paginate(Dimensions=[{'Name': 'ChannelId', 'Value': ml_channel_id},
{'Name': 'OutputName'},
{'Name': 'Pipeline'}],
MetricName='OutputVideoFrameRate',
Namespace='MediaLive'):
if len(response["Metrics"]) > 0:
for metric in response["Metrics"]:
entry = {}
dimensions = metric["Dimensions"]
for dimension in dimensions:
if dimension["Name"] == "OutputName":
entry["OutputName"] = dimension["Value"]
elif dimension["Name"] == "ChannelId":
entry["ChannelId"] = dimension["Value"]
elif dimension["Name"] == "Pipeline":
entry["Pipeline"] = dimension["Value"]
output_name_list.append(entry)
return output_name_list
except Exception, e:
print "Error while retrieving CloudWatch OutputName information", e.message
def create_cloudwatch_dashboard(cw_client, cw_dashboard_name, cw_dashboard_body):
"""Use put_dashboard to create a new CloudWatch Dashboard named "cw_dashboard_name" that consists of the definition
as defined in "cw_dashboard_body" """
try:
cw_dashboard_name = cw_dashboard_name.replace(" ", "-")
response = cw_client.put_dashboard(
DashboardName=cw_dashboard_name,
DashboardBody=cw_dashboard_body
)
result_code = response["ResponseMetadata"]["HTTPStatusCode"]
if result_code == 200:
print "Successfully created Dashboard '{0}'".format(cw_dashboard_name)
else:
print "HTTP Status Code:", result_code
except Exception, e:
print "Error while trying to create new CloudWatch Dashboard:\n", e.message
exit(-5)
# CloudWatch Dashboard metrics related
def update_ingress_bytes_metric(mp_channel_names):
"""Update the metrics of the "Ingress Bytes (sum)" dashboard widget """
results = []
for mp_name in mp_channel_names:
entry = ["AWS/MediaPackage", "IngressBytes", "Channel", mp_name]
results.append(entry)
return results
def update_ingress_resp_times_metric(mp_channel_names):
"""Update the metrics of the "Ingress Response Times (avg)" dashboard widget"""
results = []
for mp_name in mp_channel_names:
entry = ["AWS/MediaPackage", "IngressResponseTime", "Channel", mp_name]
results.append(entry)
return results
def update_egress_req_bytes_metric(mp_endpoint_names):
"""Update the metrics of the "Egress Request Bytes (sum)" dashboard widget"""
results = []
for mp_name in mp_endpoint_names:
endpoints = mp_endpoint_names[mp_name]
for endpoint in endpoints:
entry = ["AWS/MediaPackage", "EgressBytes", "Channel", mp_name, "OriginEndpoint", endpoint]
results.append(entry)
return results
def update_egress_req_count_metric(mp_endpoint_names):
"""Update the metrics of the "Egress Request Count (sum)" dashboard widget"""
results = []
for mp_name in mp_endpoint_names:
endpoints = mp_endpoint_names[mp_name]
for endpoint in endpoints:
entry = ["AWS/MediaPackage", "EgressRequestCount", "Channel", mp_name, "OriginEndpoint", endpoint]
results.append(entry)
return results
def update_status_code_range_2xx4xx_metric(mp_endpoint_names):
"""Update the metrics of the "Status Code Range (sum)" dashboard widget"""
results = []
for mp_name in mp_endpoint_names:
endpoints = mp_endpoint_names[mp_name]
for endpoint in endpoints:
entry = ["AWS/MediaPackage", "EgressRequestCount", "Channel", mp_name, "OriginEndpoint", endpoint,
"StatusCodeRange", "2xx"]
results.append(entry)
entry = ["AWS/MediaPackage", "EgressRequestCount", "Channel", mp_name, "OriginEndpoint", endpoint,
"StatusCodeRange", "4xx", {"yAxis": "right"}]
results.append(entry)
return results
def update_status_code_range_3xx5xx_metric(mp_endpoint_names):
"""Update the metrics of the "Status Code Range (sum)" dashboard widget"""
results = []
for mp_name in mp_endpoint_names:
endpoints = mp_endpoint_names[mp_name]
for endpoint in endpoints:
entry = ["AWS/MediaPackage", "EgressRequestCount", "Channel", mp_name, "OriginEndpoint", endpoint,
"StatusCodeRange", "3xx"]
results.append(entry)
entry = ["AWS/MediaPackage", "EgressRequestCount", "Channel", mp_name, "OriginEndpoint", endpoint,
"StatusCodeRange", "5xx", {"yAxis": "right"}]
results.append(entry)
return results
def update_input_video_frame_rate_metric(ml_channel_id, ml_channel_name):
"""Update the metrics of the "Input Video Frame Rate (avg)" dashboard widget"""
result = []
entry = ["MediaLive", "InputVideoFrameRate", "ChannelId", ml_channel_id, "Pipeline", "0",
{"label": ml_channel_name + "-0"}]
result.append(entry)
entry = ["MediaLive", "InputVideoFrameRate", "ChannelId", ml_channel_id, "Pipeline", "1",
{"yAxis": "right", "label": ml_channel_name + "-1"}]
result.append(entry)
return result
def update_network_in_metric(ml_channel_id, ml_channel_name):
"""Update the metrics of the "Network In (sum)" dashboard dashboard widget"""
result = []
entry = ["MediaLive", "NetworkIn", "ChannelId", ml_channel_id, "Pipeline", "0", {"label": ml_channel_name + "-0"}]
result.append(entry)
entry = ["MediaLive", "NetworkIn", "ChannelId", ml_channel_id, "Pipeline", "1", {"yAxis": "right",
"label": ml_channel_name + "-1"}]
result.append(entry)
return result
def update_dropped_frames_metric(ml_channel_id, ml_channel_name):
"""Update the metrics of the "Dropped Frames (sum)" dashboard dashboard widget"""
result = []
entry = ["MediaLive", "DroppedFrames", "ChannelId", ml_channel_id, "Pipeline", "0",
{"label": ml_channel_name + "-0"}]
result.append(entry)
entry = ["MediaLive", "DroppedFrames", "ChannelId", ml_channel_id, "Pipeline", "1",
{"yAxis": "right", "label": ml_channel_name + "-1"}]
result.append(entry)
return result
def update_fill_msec_metric(ml_channel_id, ml_channel_name):
"""Update the metrics of the "Fill Milliseconds (sum)" dashboard dashboard widget"""
result = []
entry = ["MediaLive", "FillMsec", "ChannelId", ml_channel_id, "Pipeline", "0", {"label": ml_channel_name + "-0"}]
result.append(entry)
entry = ["MediaLive", "FillMsec", "ChannelId", ml_channel_id, "Pipeline", "1", {"yAxis": "right",
"label": ml_channel_name + "-1"}]
result.append(entry)
return result
def update_svq_time_metric(ml_channel_id, ml_channel_name):
"""Update the metrics of the "SVQ Time (percentage)" dashboard dashboard widget"""
result = []
entry = ["MediaLive", "SvqTime", "ChannelId", ml_channel_id, "Pipeline", "0", {"label": ml_channel_name + "-0"}]
result.append(entry)
entry = ["MediaLive", "SvqTime", "ChannelId", ml_channel_id, "Pipeline", "1", {"yAxis": "right",
"label": ml_channel_name + "-1"}]
result.append(entry)
return result
def update_output_frame_video_rate_metric(ml_output_names):
"""Update the metrics of the "Output Video | |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.1
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (3,0,0):
new_instancemethod = lambda func, inst, cls: _BOPTools.SWIG_PyInstanceMethod_New(func)
else:
from new import instancemethod as new_instancemethod
if version_info >= (2,6,0):
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_BOPTools', [dirname(__file__)])
except ImportError:
import _BOPTools
return _BOPTools
if fp is not None:
try:
_mod = imp.load_module('_BOPTools', fp, pathname, description)
finally:
fp.close()
return _mod
_BOPTools = swig_import_helper()
del swig_import_helper
else:
import _BOPTools
del version_info
try:
_swig_property = property
except NameError:
pass # Python < 2.2 doesn't have 'property'.
def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
if (name == "thisown"): return self.this.own(value)
if (name == "this"):
if type(value).__name__ == 'SwigPyObject':
self.__dict__[name] = value
return
method = class_type.__swig_setmethods__.get(name,None)
if method: return method(self,value)
if (not static):
self.__dict__[name] = value
else:
raise AttributeError("You cannot add attributes to %s" % self)
def _swig_setattr(self,class_type,name,value):
return _swig_setattr_nondynamic(self,class_type,name,value,0)
def _swig_getattr(self,class_type,name):
if (name == "thisown"): return self.this.own()
method = class_type.__swig_getmethods__.get(name,None)
if method: return method(self)
raise AttributeError(name)
def _swig_repr(self):
try: strthis = "proxy of " + self.this.__repr__()
except: strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
try:
_object = object
_newclass = 1
except AttributeError:
class _object : pass
_newclass = 0
def _swig_setattr_nondynamic_method(set):
def set_attr(self,name,value):
if (name == "thisown"): return self.this.own(value)
if hasattr(self,name) or (name == "this"):
set(self,name,value)
else:
raise AttributeError("You cannot add attributes to %s" % self)
return set_attr
class SwigPyIterator(object):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract")
__repr__ = _swig_repr
__swig_destroy__ = _BOPTools.delete_SwigPyIterator
def __iter__(self): return self
SwigPyIterator.value = new_instancemethod(_BOPTools.SwigPyIterator_value,None,SwigPyIterator)
SwigPyIterator.incr = new_instancemethod(_BOPTools.SwigPyIterator_incr,None,SwigPyIterator)
SwigPyIterator.decr = new_instancemethod(_BOPTools.SwigPyIterator_decr,None,SwigPyIterator)
SwigPyIterator.distance = new_instancemethod(_BOPTools.SwigPyIterator_distance,None,SwigPyIterator)
SwigPyIterator.equal = new_instancemethod(_BOPTools.SwigPyIterator_equal,None,SwigPyIterator)
SwigPyIterator.copy = new_instancemethod(_BOPTools.SwigPyIterator_copy,None,SwigPyIterator)
SwigPyIterator.next = new_instancemethod(_BOPTools.SwigPyIterator_next,None,SwigPyIterator)
SwigPyIterator.__next__ = new_instancemethod(_BOPTools.SwigPyIterator___next__,None,SwigPyIterator)
SwigPyIterator.previous = new_instancemethod(_BOPTools.SwigPyIterator_previous,None,SwigPyIterator)
SwigPyIterator.advance = new_instancemethod(_BOPTools.SwigPyIterator_advance,None,SwigPyIterator)
SwigPyIterator.__eq__ = new_instancemethod(_BOPTools.SwigPyIterator___eq__,None,SwigPyIterator)
SwigPyIterator.__ne__ = new_instancemethod(_BOPTools.SwigPyIterator___ne__,None,SwigPyIterator)
SwigPyIterator.__iadd__ = new_instancemethod(_BOPTools.SwigPyIterator___iadd__,None,SwigPyIterator)
SwigPyIterator.__isub__ = new_instancemethod(_BOPTools.SwigPyIterator___isub__,None,SwigPyIterator)
SwigPyIterator.__add__ = new_instancemethod(_BOPTools.SwigPyIterator___add__,None,SwigPyIterator)
SwigPyIterator.__sub__ = new_instancemethod(_BOPTools.SwigPyIterator___sub__,None,SwigPyIterator)
SwigPyIterator_swigregister = _BOPTools.SwigPyIterator_swigregister
SwigPyIterator_swigregister(SwigPyIterator)
import OCC.TopoDS
import OCC.MMgt
import OCC.Standard
import OCC.TCollection
import OCC.TopLoc
import OCC.gp
import OCC.TopAbs
import OCC.BOPCol
import OCC.IntTools
import OCC.Geom
import OCC.GeomAbs
import OCC.TColgp
import OCC.TColStd
import OCC.BRepAdaptor
import OCC.Adaptor3d
import OCC.Adaptor2d
import OCC.Geom2d
import OCC.math
import OCC.GeomAdaptor
import OCC.Geom2dAdaptor
import OCC.BOPInt
import OCC.GeomAPI
import OCC.Quantity
import OCC.Extrema
import OCC.Approx
import OCC.AppCont
import OCC.AppParCurves
import OCC.BRepClass3d
import OCC.IntCurveSurface
import OCC.Intf
import OCC.Bnd
import OCC.IntSurf
import OCC.IntCurvesFace
import OCC.Geom2dHatch
import OCC.IntRes2d
import OCC.HatchGen
import OCC.Geom2dInt
import OCC.IntCurve
import OCC.ProjLib
import OCC.NCollection
class boptools(object):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def MapShapes(*args):
"""
:param S:
:type S: TopoDS_Shape &
:param M:
:type M: BOPCol_MapOfShape &
:rtype: void
:param S:
:type S: TopoDS_Shape &
:param M:
:type M: BOPCol_IndexedMapOfShape &
:rtype: void
:param S:
:type S: TopoDS_Shape &
:param T:
:type T: TopAbs_ShapeEnum
:param M:
:type M: BOPCol_IndexedMapOfShape &
:rtype: void
"""
return _BOPTools.boptools_MapShapes(*args)
MapShapes = staticmethod(MapShapes)
def MapShapesAndAncestors(*args):
"""
:param S:
:type S: TopoDS_Shape &
:param TS:
:type TS: TopAbs_ShapeEnum
:param TA:
:type TA: TopAbs_ShapeEnum
:param M:
:type M: BOPCol_IndexedDataMapOfShapeListOfShape &
:rtype: void
"""
return _BOPTools.boptools_MapShapesAndAncestors(*args)
MapShapesAndAncestors = staticmethod(MapShapesAndAncestors)
def __init__(self):
_BOPTools.boptools_swiginit(self,_BOPTools.new_boptools())
def __del__(self):
try:
self.thisown = False
GarbageCollector.garbage.collect_object(self)
except:
pass
boptools._kill_pointed = new_instancemethod(_BOPTools.boptools__kill_pointed,None,boptools)
boptools_swigregister = _BOPTools.boptools_swigregister
boptools_swigregister(boptools)
def boptools_MapShapes(*args):
"""
:param S:
:type S: TopoDS_Shape &
:param M:
:type M: BOPCol_MapOfShape &
:rtype: void
:param S:
:type S: TopoDS_Shape &
:param M:
:type M: BOPCol_IndexedMapOfShape &
:rtype: void
:param S:
:type S: TopoDS_Shape &
:param T:
:type T: TopAbs_ShapeEnum
:param M:
:type M: BOPCol_IndexedMapOfShape &
:rtype: void
"""
return _BOPTools.boptools_MapShapes(*args)
def boptools_MapShapesAndAncestors(*args):
"""
:param S:
:type S: TopoDS_Shape &
:param TS:
:type TS: TopAbs_ShapeEnum
:param TA:
:type TA: TopAbs_ShapeEnum
:param M:
:type M: BOPCol_IndexedDataMapOfShapeListOfShape &
:rtype: void
"""
return _BOPTools.boptools_MapShapesAndAncestors(*args)
class BOPTools_AlgoTools(object):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def ComputeVV(*args):
"""
:param aV1:
:type aV1: TopoDS_Vertex &
:param aP2:
:type aP2: gp_Pnt
:param aTolP2:
:type aTolP2: float
:rtype: int
:param aV1:
:type aV1: TopoDS_Vertex &
:param aV2:
:type aV2: TopoDS_Vertex &
:rtype: int
"""
return _BOPTools.BOPTools_AlgoTools_ComputeVV(*args)
ComputeVV = staticmethod(ComputeVV)
def MakeVertex(*args):
"""
:param aLV:
:type aLV: BOPCol_ListOfShape &
:param aV:
:type aV: TopoDS_Vertex &
:rtype: void
"""
return _BOPTools.BOPTools_AlgoTools_MakeVertex(*args)
MakeVertex = staticmethod(MakeVertex)
def MakeEdge(*args):
"""
:param theCurve:
:type theCurve: IntTools_Curve &
:param theV1:
:type theV1: TopoDS_Vertex &
:param theT1:
:type theT1: float
:param theV2:
:type theV2: TopoDS_Vertex &
:param theT2:
:type theT2: float
:param theTolR3D:
:type theTolR3D: float
:param theE:
:type theE: TopoDS_Edge &
:rtype: void
"""
return _BOPTools.BOPTools_AlgoTools_MakeEdge(*args)
MakeEdge = staticmethod(MakeEdge)
def MakePCurve(*args):
"""
:param theE:
:type theE: TopoDS_Edge &
:param theF1:
:type theF1: TopoDS_Face &
:param theF2:
:type theF2: TopoDS_Face &
:param theCurve:
:type theCurve: IntTools_Curve &
:param thePC1:
:type thePC1: bool
:param thePC2:
:type thePC2: bool
:rtype: void
"""
return _BOPTools.BOPTools_AlgoTools_MakePCurve(*args)
MakePCurve = staticmethod(MakePCurve)
def MakeContainer(*args):
"""
:param theType:
:type theType: TopAbs_ShapeEnum
:param theShape:
:type theShape: TopoDS_Shape &
:rtype: void
"""
return _BOPTools.BOPTools_AlgoTools_MakeContainer(*args)
MakeContainer = staticmethod(MakeContainer)
def IsHole(*args):
"""
:param aW:
:type aW: TopoDS_Shape &
:param aF:
:type aF: TopoDS_Shape &
:rtype: bool
"""
return _BOPTools.BOPTools_AlgoTools_IsHole(*args)
IsHole = staticmethod(IsHole)
def IsSplitToReverse(*args):
"""
* Returns True if the shape theSplit has opposite direction than theShape theContext - cashed geometrical tools
:param theSplit:
:type theSplit: TopoDS_Shape &
:param theShape:
:type theShape: TopoDS_Shape &
:param theContext:
:type theContext: Handle_BOPInt_Context &
:rtype: bool
* Returns True if normal direction of the face theShape is not the same as for the face theSplit theContext - cashed geometrical tools
:param theSplit:
:type theSplit: TopoDS_Face &
:param theShape:
:type theShape: TopoDS_Face &
:param theContext:
:type theContext: Handle_BOPInt_Context &
:rtype: bool
:param aE1:
:type aE1: TopoDS_Edge &
:param aE2:
:type aE2: TopoDS_Edge &
:param aContext:
:type aContext: Handle_BOPInt_Context &
:rtype: bool
"""
return _BOPTools.BOPTools_AlgoTools_IsSplitToReverse(*args)
IsSplitToReverse = staticmethod(IsSplitToReverse)
def AreFacesSameDomain(*args):
"""
:param theF1:
:type theF1: TopoDS_Face &
:param theF2:
:type theF2: TopoDS_Face &
:param theContext:
:type theContext: Handle_BOPInt_Context &
:rtype: bool
"""
return _BOPTools.BOPTools_AlgoTools_AreFacesSameDomain(*args)
AreFacesSameDomain = staticmethod(AreFacesSameDomain)
def CheckSameGeom(*args):
"""
:param theF1:
:type theF1: TopoDS_Face &
:param theF2:
:type theF2: TopoDS_Face &
:param theContext:
:type theContext: Handle_BOPInt_Context &
:rtype: bool
"""
return _BOPTools.BOPTools_AlgoTools_CheckSameGeom(*args)
CheckSameGeom = staticmethod(CheckSameGeom)
def Sense(*args):
"""
:param theF1:
:type theF1: TopoDS_Face &
:param theF2:
:type theF2: TopoDS_Face &
:rtype: int
"""
return _BOPTools.BOPTools_AlgoTools_Sense(*args)
Sense = staticmethod(Sense)
def GetEdgeOff(*args):
"""
* Returns True if the face theFace contains the edge theEdge but with opposite orientation. If the method returns True theEdgeOff is the edge founded
:param theEdge:
:type theEdge: TopoDS_Edge &
:param theFace:
:type theFace: TopoDS_Face &
:param theEdgeOff:
:type theEdgeOff: TopoDS_Edge &
:rtype: bool
"""
return _BOPTools.BOPTools_AlgoTools_GetEdgeOff(*args)
GetEdgeOff = staticmethod(GetEdgeOff)
def GetFaceOff(*args):
"""
* For the face theFace and its edge theEdge finds the face suitable to produce shell. theLCEF - set of faces to search. All faces from theLCEF must share edge theEdge
:param theEdge:
:type theEdge: TopoDS_Edge &
:param theFace:
:type theFace: TopoDS_Face &
:param theLCEF:
:type theLCEF: BOPTools_ListOfCoupleOfShape &
:param theFaceOff:
:type theFaceOff: TopoDS_Face &
:param theContext:
:type theContext: Handle_BOPInt_Context &
:rtype: bool
"""
return _BOPTools.BOPTools_AlgoTools_GetFaceOff(*args)
GetFaceOff = staticmethod(GetFaceOff)
def IsInternalFace(*args):
"""
* Returns True if the face theFace is inside of the couple of faces theFace1, theFace2. The faces theFace, theFace1, theFace2 must share the edge theEdge
:param theFace:
:type theFace: TopoDS_Face &
:param theEdge:
:type theEdge: TopoDS_Edge &
:param theFace1:
:type theFace1: TopoDS_Face &
:param theFace2:
:type theFace2: TopoDS_Face &
:param theContext:
:type theContext: Handle_BOPInt_Context &
:rtype: int
* Returns True if the face theFace is inside of the appropriate couple of faces (from the set theLF) . The faces of the set theLF and theFace must share the edge theEdge
:param theFace:
:type theFace: TopoDS_Face &
:param theEdge:
:type theEdge: TopoDS_Edge &
:param theLF:
:type theLF: BOPCol_ListOfShape &
:param theContext:
:type theContext: Handle_BOPInt_Context &
:rtype: int
* Returns True if the face theFace is inside the solid theSolid. theMEF - Map Edge/Faces for theSolid theTol - value of precision of computation theContext- cahed geometrical tools
:param theFace:
:type theFace: TopoDS_Face &
:param theSolid:
:type theSolid: TopoDS_Solid &
:param theMEF:
:type theMEF: BOPCol_IndexedDataMapOfShapeListOfShape &
:param theTol:
:type theTol: float
:param theContext:
:type theContext: Handle_BOPInt_Context &
:rtype: int
"""
return _BOPTools.BOPTools_AlgoTools_IsInternalFace(*args)
IsInternalFace = staticmethod(IsInternalFace)
def GetEdgeOnFace(*args):
"""
* For the face theFace gets | |
"""Trains a tensorflow.keras model for car following behavior."""
import tensorflow as tf
import numpy as np
from havsim import helper
import math
from IPython import embed
def generate_lane_data(veh_data):
"""
Generates Labels for Lane-Changing Model for a given vehicle
Args:
veh_data: (helper.VehicleData) represents vehicle we're analyzing
Returns:
lane_data: python list of 0/1/2, 0 is lane changing to the left, 1 is
staying in the same lane, and 2 is lane changing to the right
"""
lane_data = []
for time in range(veh_data.start + 1, veh_data.end + 1):
if veh_data.lanemem[time] < veh_data.lanemem[time - 1]:
lane_data.append(0)
elif veh_data.lanemem[time] == veh_data.lanemem[time - 1]:
lane_data.append(1)
else:
lane_data.append(2)
return lane_data
def make_dataset(veh_dict, veh_list, dt=.1):
"""Makes dataset from meas and platooninfo.
Args:
veh_dict: see havsim.helper.load_dataset
dt: timestep
Returns:
ds: (reads as dataset) dictionary of vehicles, values are a dictionary with keys
'IC' - (initial conditions) list of starting position/speed for vehicle
'times' - list of two int times. First is the first time with an observed leader. Second is the
last time with an observed leader +1. The number of times we call the model is equal to
times[1] - times[0], which is the length of the lead measurements.
'posmem' - (1d,) numpy array of observed positions for vehicle, 0 index corresponds to times[0].
Typically this has a longer length than the lead posmem/speedmem.
'speedmem' - (1d,) numpy array of observed speeds for vehicle
'lead posmem' - (1d,) numpy array of positions for leaders, 0 index corresponds to times[0].
length is subtracted from the lead position.
'lead speedmem' - (1d,) numpy array of speeds for leaders.
'lfolpos' - (1d,) numpy array of positions for lfol
'lfolspeed' - (1d,) numpy array of speeds for lfol
'rfolpos' - (1d,) numpy array of positions for rfol
'rfolspeed' - (1d,) numpy array of speeds for rfol
'lleadpos' - (1d,) numpy array of positions for llead
'lleadspeed' - (1d,) numpy array of speeds for llead
'rleadpos' - (1d,) numpy array of positions for rlead
'rleadspeed' - (1d,) numpy array of speeds for rlead
normalization amounts: tuple of
maxheadway: max headway observed in training set
maxspeed: max velocity observed in training set
minacc: minimum acceleration observed in training set
maxacc: maximum acceleration observed in training set
"""
ds = {}
maxheadway, maxspeed = 0, 0
minacc, maxacc = 1e4, -1e4
for veh in veh_list:
veh_data = veh_dict[veh]
start, end = int(veh_data.start), int(veh_data.end)
start_sim, end_sim = veh_data.longest_lead_times
leadpos = np.array(veh_data.leadmem.pos[start_sim:end_sim + 1])
leadspeed = np.array(veh_data.leadmem.speed[start_sim:end_sim + 1])
# indexing for pos/spd
vehpos = np.array(veh_data.posmem[start_sim-start:])
vehspd = np.array(veh_data.speedmem[start_sim-start:])
lanemem = np.array(generate_lane_data(veh_data)[start_sim - start:])
# lfol rfol llead rllead
pos_and_spd = [ [[], []] for _ in range(len(veh_data.lcmems))]
lc_weights = [1] * (len(vehpos))
for time in range(start_sim, end + 1):
for mem_idx, lc_mem in enumerate(veh_data.lcmems):
if lc_mem[time] is not None:
pos_and_spd[mem_idx][1].append(lc_mem.speed[time])
pos_and_spd[mem_idx][0].append(lc_mem.pos[time])
else:
pos_and_spd[mem_idx][1].append(0)
pos_and_spd[mem_idx][0].append(0)
lc_weights[time - start_sim] = 0
# convert to np.ndarray
for mem_idx in range(len(pos_and_spd)):
for j in range(2):
pos_and_spd[mem_idx][j] = np.array(pos_and_spd[mem_idx][j])
IC = [vehpos[0], vehspd[0]]
if end_sim != start_sim:
headway = leadpos - vehpos[:end_sim + 1 - start_sim]
maxheadway = max(max(headway), maxheadway)
maxspeed = max(max(leadspeed), maxspeed)
else:
# if there never was a leader, there never was a headway
headway = []
vehacc = [(vehpos[i+2] - 2*vehpos[i+1] + vehpos[i])/(dt**2) for i in range(len(vehpos)-2)]
minacc, maxacc = min(minacc, min(vehacc)), max(maxacc, max(vehacc))
ds[veh] = {'IC': IC, 'times': [start_sim, min(int(end_sim + 1), end)], 'posmem': vehpos, \
'speedmem': vehspd, 'lanemem': lanemem, 'lead posmem': leadpos,'lead speedmem': leadspeed, \
'lfolpos': pos_and_spd[0][0],'lfolspeed': pos_and_spd[0][1], \
'rfolpos': pos_and_spd[1][0], 'rfolspeed': pos_and_spd[1][1], \
'lleadpos': pos_and_spd[2][0], 'lleadspeed': pos_and_spd[2][1], \
'rleadpos': pos_and_spd[3][0], 'rleadspeed': pos_and_spd[3][1], \
'lc_weights': np.array(lc_weights)}
return ds, (maxheadway, maxspeed, minacc, maxacc)
class RNNCFModel(tf.keras.Model):
"""Simple RNN based CF model."""
def __init__(self, maxhd, maxv, mina, maxa, lstm_units=20, dt=.1):
"""Inits RNN based CF model.
Args:
maxhd: max headway (for nomalization of inputs)
maxv: max velocity (for nomalization of inputs)
mina: minimum acceleration (for nomalization of outputs)
maxa: maximum acceleration (for nomalization of outputs)
dt: timestep
"""
super().__init__()
# architecture
self.lstm_cell = tf.keras.layers.LSTMCell(lstm_units, dropout=.3,
kernel_regularizer=tf.keras.regularizers.l2(l=.02),
recurrent_regularizer=tf.keras.regularizers.l2(l=.02))
self.dense1 = tf.keras.layers.Dense(1)
self.dense2 = tf.keras.layers.Dense(10, activation='relu',
kernel_regularizer=tf.keras.regularizers.l2(l=.02))
self.lc_action = tf.keras.layers.Dense(3, activation='softmax')
# normalization constants
self.maxhd = maxhd
self.maxv = maxv
self.mina = mina
self.maxa = maxa
# other constants
self.dt = dt
self.lstm_units = lstm_units
def call(self, inputs, training=False):
"""Updates states for a batch of vehicles.
Args:
inputs: list of lead_inputs, cur_state, hidden_states.
lead_inputs - tensor with shape (nveh, nt, 10), giving the position and speed of the
the leader, lfol, rfol, llead, rllead at each timestep.
cur_state - tensor with shape (nveh, 2) giving the vehicle position and speed at the
starting timestep.
hidden_states - list of the two hidden states, each hidden state is a tensor with shape
of (nveh, lstm_units). Initialized as all zeros for the first timestep.
training: Whether to run in training or inference mode. Need to pass training=True if training
with dropout.
Returns:
outputs: tensor of vehicle positions, shape of (number of vehicles, number of timesteps). Note
that these are 1 timestep after lead_inputs. E.g. if nt = 2 and lead_inputs has the lead
measurements for time 0 and 1. Then cur_state has the vehicle position/speed for time 0, and
outputs has the vehicle positions for time 1 and 2. curspeed would have the speed for time 2,
and you can differentiate the outputs to get the speed at time 1 if it's needed.
curspeed: tensor of current vehicle speeds, shape of (number of vehicles, 1)
hidden_states: last hidden states for LSTM. Tuple of tensors, where each tensor has shape of
(number of vehicles, number of LSTM units)
"""
# prepare data for call
lead_inputs, init_state, hidden_states = inputs
lead_inputs = tf.unstack(lead_inputs, axis=1) # unpacked over time dimension
cur_pos, cur_speed = tf.unstack(init_state, axis=1)
outputs = []
for cur_lead_input in lead_inputs:
# normalize data for current timestep
cur_lead_pos, cur_lead_speed, lfol_pos, lfol_speed, rfol_pos, rfol_speed, \
llead_pos, llead_speed, rlead_pos, rlead_speed = \
tf.unstack(cur_lead_input, axis=1)
# headway
curhd = cur_lead_pos-cur_pos
curhd = curhd/self.maxhd
cur_lfol_hd = (lfol_pos - cur_pos)/self.maxhd
cur_rfol_hd = (rfol_pos - cur_pos)/self.maxhd
cur_llead_hd = (llead_pos - cur_pos)/self.maxhd
cur_rlead_hd = (rlead_pos - cur_pos)/self.maxhd
# speed
cur_lead_speed = cur_lead_speed/self.maxv
norm_veh_speed = cur_speed/self.maxv
cur_lfol_speed = lfol_speed/self.maxv
cur_rfol_speed = rfol_speed/self.maxv
cur_llead_speed = llead_speed/self.maxv
cur_rlead_speed = rlead_speed/self.maxv
cur_inputs = tf.stack([curhd, norm_veh_speed, cur_lead_speed, cur_lfol_hd, \
cur_lfol_speed, cur_rfol_hd, cur_rfol_speed, cur_llead_hd, cur_llead_speed, \
cur_rlead_hd, cur_rlead_speed], axis=1)
# call to model
self.lstm_cell.reset_dropout_mask()
x, hidden_states = self.lstm_cell(cur_inputs, hidden_states, training)
x = self.dense2(x)
cur_lc = self.lc_actions(x) # get outputed probabilities for LC
cur_lc = cur_lc * lc_weights # TODO mask output probabilities
# TODO save cur_lc to list which we output so the loss can be calculated
x = self.dense1(x) # output of the model is current acceleration for the batch
# update vehicle states
x = tf.squeeze(x, axis=1)
cur_acc = (self.maxa-self.mina)*x + self.mina
cur_pos = cur_pos + self.dt*cur_speed
cur_speed = cur_speed + self.dt*cur_acc
outputs.append(cur_pos)
outputs = tf.stack(outputs, 1)
return outputs, cur_speed, hidden_states
def get_config(self):
return {'pos_args': (self.maxhd, self.maxv, self.mina, self.maxa,), 'lstm_units': self.lstm_units, 'dt': self.dt}
@classmethod
def from_config(self, config):
pos_args = config.pop('pos_args')
return self(*pos_args, **config)
def make_batch(vehs, vehs_counter, ds, nt=5, rp=None, relax_args=None):
"""Create batch of data to send to model.
Args:
vehs: list of vehicles in current batch
vehs_counter: dictionary where keys are indexes, values are tuples of (current time index,
max time index)
ds: dataset, from make_dataset
nt: number of timesteps in batch
rp: if not None, we apply relaxation using helper.get_fixed_relaxation with parameter rp.
relax_args: if rp is not None, pass in a tuple of (meas, platooninfo, dt) so the relaxation
can be calculated
Returns:
lead_inputs - tensor with shape (nveh, nt, 10), giving the position and speed of the
the leader, lfol, rfol, llead, rllead at each timestep. Padded with zeros.
nveh = len(vehs)
true_traj: nested python list with shape (nveh, nt) giving the true vehicle position at each time.
Padded with zeros
loss_weights: nested python list with shape (nveh, nt) with either 1 or 0, used to weight each sample
of the loss | |
green;')
return True, nom
def guardar(self):
control, nom = self.validar_nom()
if control == True:
dia = str(self.data.date().day())
mes = str(self.data.date().month())
ano = str(self.data.date().year())
total = self.importe.value()
IVA = self.iva.value()
if total != 0 and IVA != 0:
base_imponible = round(total/(100+IVA) * 100, 2)
os.chdir(carpeta_data)
create_database_factures('factures_rebudes')
fill_database_factures('factures_rebudes', dia, mes, ano, nom, base_imponible, IVA, total)
if self.pujar_drive_check.isChecked():
upload_to_drive_database('factures_rebudes')
QMessageBox.information(self, 'Information', 'Dades enregistrades correctament')
self.reinit_dialog()
else:
QMessageBox.warning(self, 'Warning!', 'L\' import i l\'I.V.A. no poden ser 0')
else:
QMessageBox.warning(self, 'Warning!', 'Dades incorrectes')
def delete(self):
control, nom = self.validar_nom()
if control == True:
dia = str(self.data.date().day())
mes = str(self.data.date().month())
ano = str(self.data.date().year())
total = self.importe.value()
IVA = self.iva.value()
if total != 0 and IVA != 0:
base_imponible = round(total/(100+IVA) * 100, 2)
os.chdir(carpeta_data)
create_database_factures('factures_rebudes')
delete_database_factures('factures_rebudes', dia, mes, ano, base_imponible, IVA, total)
if self.pujar_drive_check.isChecked():
upload_to_drive_database('factures_rebudes')
QMessageBox.information(self, 'Information', 'Dades enregistrades correctament')
self.reinit_dialog()
else:
QMessageBox.warning(self, 'Warning!', 'L\' import i l\'I.V.A. no poden ser 0')
else:
QMessageBox.warning(self, 'Warning!', 'Dades incorrectes')
def upload_database(self):
upload_to_drive_database('factures_rebudes')
QMessageBox.information(self, 'Information', 'Dades pujades correctament')
def reinit_dialog(self):
self.data.setDate(QDate.currentDate())
self.nom.setText('')
self.iva.setValue(0.)
self.importe.setValue(0.)
self.nom.setStyleSheet('')
def closeEvent(self, event):
result = QMessageBox.question(self, 'Sortint...','Segur que vols sortir?', QMessageBox.Yes | QMessageBox.No)
if result == QMessageBox.Yes:
event.accept()
self.reinit_dialog()
self.pujar_drive_check.setChecked(True)
else:
event.ignore()
class Factures_rebudes(QDialog):
def __init__(self):
QDialog.__init__(self)
os.chdir(carpeta_data)
uic.loadUi('FacturesRebudes.ui', self)
current_date = QDate.currentDate()
day = current_date.day()
self.data_final.setDate(current_date)
self.data_inicial.setDate(current_date.addDays(-day+1))
self.seleccionar.clicked.connect(self.show_table)
def show_table(self):
dia_inicial = int(self.data_inicial.date().day())
mes_inicial = int(self.data_inicial.date().month())
ano_inicial = int(self.data_inicial.date().year())
dia_final = int(self.data_final.date().day())
mes_final = int(self.data_final.date().month())
ano_final = int(self.data_final.date().year())
os.chdir(carpeta_data)
if not os.path.exists('factures_rebudes.db'):
QMessageBox.warning(self, 'Warning!', 'No existeix cap factura rebuda!')
else:
lines = read_database_factures('factures_rebudes', 'ASC')
matches = []
for i in range(len(lines)):
if ano_inicial < ano_final :
if int(lines[i][2]) < ano_final and int(lines[i][2]) > ano_inicial: #Si esta en mig es veuran complets
matches.append(lines[i])
elif int(lines[i][2]) == ano_inicial: #Si l'any es el mateix comprovar el mes
if int(lines[i][1]) > mes_inicial :
matches.append(lines[i])
elif int(lines[i][2]) == mes_inicial and int(lines[i][0]) >= dia_inicial: #Comprovar el dia
matches.append(lines[i])
elif int(lines[i][2]) == ano_final: #Si l'any es el mateix comprovar el mes
if int(lines[i][1]) < mes_final:
matches.append(lines[i])
elif int(lines[i][1]) == mes_final and int(lines[i][0]) <= dia_final: #Comprovar el dia
matches.append(lines[i])
elif ano_inicial == ano_final and mes_inicial != mes_final:
if int(lines[i][1]) > mes_inicial and int(lines[i][1]) < mes_final:
matches.append(lines[i])
elif int(lines[i][1]) == mes_inicial and int(lines[i][0]) >= dia_inicial:
matches.append(lines[i])
elif int(lines[i][1]) == mes_final and int(lines[i][0]) <= dia_final:
matches.append(lines[i])
elif ano_inicial == ano_final and mes_inicial == mes_final:
if int(lines[i][1]) == mes_inicial and int(lines[i][0]) >= dia_inicial and int(lines[i][0]) <= dia_final:
matches.append(lines[i])
self.table.setRowCount(len(matches))
self.table.setColumnCount(6)
self.table.setHorizontalHeaderLabels(['DATA', 'ESTABLIMENT', 'BASE IMPONIBLE', 'IVA %', 'IVA \u20ac', 'TOTAL'])
font = QFont()
font.setFamily('Segoe UI Black')
font.setPointSize(9)
for i in range(6):
self.table.horizontalHeaderItem(i).setFont(font)
llista = []
suma_bi = 0
suma_iva = 0
suma_total = 0
#display in the table
for i in range(len(matches)):
llista.append('')
suma_bi += matches[i][4]
suma_total += matches[i][6]
for j in range(6):
if j == 0:
data = str(matches[i][0]).zfill(2) + '/' + str(matches[i][1]).zfill(2) + '/' + str(matches[i][2])
item = QTableWidgetItem(data)
item.setTextAlignment(Qt.AlignHCenter)
self.table.setItem(i,j, item)
elif j == 4:
iva = matches[i][5] / 100
iva_euros = round(iva * matches[i][4], 2)
suma_iva += iva_euros
item = QTableWidgetItem(str(iva_euros))
item.setTextAlignment(Qt.AlignHCenter)
self.table.setItem(i,j, item)
elif j == 5:
item = QTableWidgetItem(str(matches[i][6]))
item.setTextAlignment(Qt.AlignHCenter)
self.table.setItem(i,j, item)
else:
item = QTableWidgetItem(str(matches[i][j+2]))
item.setTextAlignment(Qt.AlignHCenter)
self.table.setItem(i,j, item)
self.table.setVerticalHeaderLabels(llista)
header = self.table.horizontalHeader()
header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
header.setSectionResizeMode(1, QHeaderView.Stretch)
header.setSectionResizeMode(2, QHeaderView.ResizeToContents)
header.setSectionResizeMode(3, QHeaderView.ResizeToContents)
header.setSectionResizeMode(4, QHeaderView.ResizeToContents)
header.setSectionResizeMode(5, QHeaderView.ResizeToContents)
self.bi_tot.setText(str(round(suma_bi, 2)) + ' \u20ac')
self.iva_tot.setText(str(round(suma_iva, 2)) + ' \u20ac')
self.total_tot.setText(str(round(suma_total, 2)) + ' \u20ac')
self.bi_tot.setStyleSheet('border: 1px solid red;')
self.iva_tot.setStyleSheet('border: 1px solid red;')
self.total_tot.setStyleSheet('border: 1px solid red;')
def reinit_dialog(self):
self.table.clearContents()
self.bi_tot.setText('')
self.iva_tot.setText('')
self.total_tot.setText('')
self.bi_tot.setStyleSheet('')
self.iva_tot.setStyleSheet('')
self.total_tot.setStyleSheet('')
def closeEvent(self, event):
result = QMessageBox.question(self, 'Sortint...','Segur que vols sortir?', QMessageBox.Yes | QMessageBox.No)
if result == QMessageBox.Yes:
event.accept()
self.reinit_dialog()
else:
event.ignore()
class Factures_emeses(QDialog):
def __init__(self):
QDialog.__init__(self)
os.chdir(carpeta_data)
uic.loadUi('FacturesRebudes.ui', self)
self.setWindowTitle('Factures emeses')
current_date = QDate.currentDate()
day = current_date.day()
self.data_final.setDate(current_date)
self.data_inicial.setDate(current_date.addDays(-day+1))
self.seleccionar.clicked.connect(self.show_table)
def show_table(self):
dia_inicial = int(self.data_inicial.date().day())
mes_inicial = int(self.data_inicial.date().month())
ano_inicial = int(self.data_inicial.date().year())
dia_final = int(self.data_final.date().day())
mes_final = int(self.data_final.date().month())
ano_final = int(self.data_final.date().year())
os.chdir(carpeta_data)
if not os.path.exists('factures_emeses.db'):
QMessageBox.warning(self, 'Warning!', 'No existeix cap factura emesa')
else:
lines = read_database_factures('factures_emeses', 'ASC')
matches = []
for i in range(len(lines)):
if ano_inicial < ano_final :
if int(lines[i][2]) < ano_final and int(lines[i][2]) > ano_inicial: #Si esta en mig es veuran complets
matches.append(lines[i])
elif int(lines[i][2]) == ano_inicial: #Si l'any es el mateix comprovar el mes
if int(lines[i][1]) > mes_inicial :
matches.append(lines[i])
elif int(lines[i][2]) == mes_inicial and int(lines[i][0]) >= dia_inicial: #Comprovar el dia
matches.append(lines[i])
elif int(lines[i][2]) == ano_final: #Si l'any es el mateix comprovar el mes
if int(lines[i][1]) < mes_final:
matches.append(lines[i])
elif int(lines[i][1]) == mes_final and int(lines[i][0]) <= dia_final: #Comprovar el dia
matches.append(lines[i])
elif ano_inicial == ano_final and mes_inicial != mes_final:
if int(lines[i][1]) > mes_inicial and int(lines[i][1]) < mes_final:
matches.append(lines[i])
elif int(lines[i][1]) == mes_inicial and int(lines[i][0]) >= dia_inicial:
matches.append(lines[i])
elif int(lines[i][1]) == mes_final and int(lines[i][0]) <= dia_final:
matches.append(lines[i])
elif ano_inicial == ano_final and mes_inicial == mes_final:
if int(lines[i][1]) == mes_inicial and int(lines[i][0]) >= dia_inicial and int(lines[i][0]) <= dia_final:
matches.append(lines[i])
self.table.setRowCount(len(matches))
self.table.setColumnCount(6)
self.table.setHorizontalHeaderLabels(['DATA', 'NUM FACTURA', 'BASE IMPONIBLE', 'IVA %', 'IVA \u20ac', 'TOTAL'])
font = QFont()
font.setFamily('Segoe UI Black')
font.setPointSize(9)
for i in range(6):
self.table.horizontalHeaderItem(i).setFont(font)
llista = []
suma_bi = 0
suma_iva = 0
suma_total = 0
#display in the table
for i in range(len(matches)):
llista.append('')
suma_bi += matches[i][4]
suma_total += matches[i][6]
for j in range(6):
if j == 0:
data = str(matches[i][0]).zfill(2) + '/' + str(matches[i][1]).zfill(2) + '/' + str(matches[i][2])
item = QTableWidgetItem(data)
item.setTextAlignment(Qt.AlignHCenter)
self.table.setItem(i,j, item)
j = 2
elif j == 4:
iva = matches[i][5] / 100
iva_euros = round(iva * matches[i][4], 2)
suma_iva += iva_euros
item = QTableWidgetItem(str(iva_euros))
item.setTextAlignment(Qt.AlignHCenter)
self.table.setItem(i,j, item)
elif j == 5:
item = QTableWidgetItem(str(matches[i][6]))
item.setTextAlignment(Qt.AlignHCenter)
self.table.setItem(i,j, item)
else:
item = QTableWidgetItem(str(matches[i][j+2]))
item.setTextAlignment(Qt.AlignHCenter)
self.table.setItem(i,j, item)
self.table.setVerticalHeaderLabels(llista)
header = self.table.horizontalHeader()
header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
header.setSectionResizeMode(1, QHeaderView.Stretch)
header.setSectionResizeMode(2, QHeaderView.ResizeToContents)
header.setSectionResizeMode(3, QHeaderView.ResizeToContents)
header.setSectionResizeMode(4, QHeaderView.ResizeToContents)
header.setSectionResizeMode(5, QHeaderView.ResizeToContents)
self.bi_tot.setText(str(round(suma_bi, 2)) + ' \u20ac')
self.iva_tot.setText(str(round(suma_iva, 2)) + ' \u20ac')
self.total_tot.setText(str(round(suma_total, 2)) + ' \u20ac')
self.bi_tot.setStyleSheet('border: 1px solid green;')
self.iva_tot.setStyleSheet('border: 1px solid green;')
self.total_tot.setStyleSheet('border: 1px solid green;')
def reinit_dialog(self):
self.table.clearContents()
self.bi_tot.setText('')
self.iva_tot.setText('')
self.total_tot.setText('')
self.bi_tot.setStyleSheet('')
self.iva_tot.setStyleSheet('')
self.total_tot.setStyleSheet('')
def closeEvent(self, event):
result = QMessageBox.question(self, 'Sortint...','Segur que vols sortir?', QMessageBox.Yes | QMessageBox.No)
if result == QMessageBox.Yes:
event.accept()
self.reinit_dialog()
else:
event.ignore()
class Marge(QDialog):
def __init__(self):
QDialog.__init__(self)
os.chdir(carpeta_data)
uic.loadUi('Marge.ui', self)
current_date = QDate.currentDate()
day = current_date.day()
self.data_final.setDate(current_date)
self.data_inicial.setDate(current_date.addDays(-day+1))
self.dif_bi.textChanged.connect(self.validar_diferencia_bi)
self.dif_iva.textChanged.connect(self.validar_diferencia_iva)
self.dif_tot.textChanged.connect(self.validar_diferencia_tot)
self.beneficis_stock.textChanged.connect(self.validar_beneficis_stock)
self.bi_tot_1.setStyleSheet('border: 1px solid red;')
self.iva_tot_1.setStyleSheet('border: 1px solid red;')
self.total_tot_1.setStyleSheet('border: 1px solid red;')
self.bi_tot_2.setStyleSheet('border: 1px solid green;')
self.iva_tot_2.setStyleSheet('border: 1px solid green;')
self.total_tot_2.setStyleSheet('border: 1px solid green;')
self.stock.setStyleSheet('border: 1px solid green')
self.seleccionar.clicked.connect(self.show_table)
def validar_beneficis_stock(self):
x = self.beneficis_stock.text()
if float(x[0:len(x)-2].replace(',', '.')) < 0: #Si es negatiu son perdues
self.beneficis_stock.setStyleSheet('border: 1px solid red;')
elif float(x[0:len(x)-2].replace(',', '.')) == 0:
self.beneficis_stock.setStyleSheet('border: 1px solid yellow;')
else:
self.beneficis_stock.setStyleSheet('border: 1px solid green;')
def validar_diferencia_bi(self):
x = self.dif_bi.text()
x = float(x[0:len(x)-2].replace(',', '.'))
if x < 0: #Si es negatiu son perdues
self.dif_bi.setStyleSheet('border: 1px solid red;')
elif x == 0:
self.dif_bi.setStyleSheet('border: 1px solid yellow;')
else:
self.dif_bi.setStyleSheet('border: 1px solid green;')
def validar_diferencia_iva(self):
x = self.dif_iva.text()
if float(x[0:len(x)-2].replace(',', '.')) < 0: #Si es negatiu son perdues
self.dif_iva.setStyleSheet('border: 1px solid red;')
elif float(x[0:len(x)-2].replace(',', '.')) == 0:
self.dif_iva.setStyleSheet('border: 1px solid yellow;')
else:
self.dif_iva.setStyleSheet('border: 1px solid green;')
def validar_diferencia_tot(self):
x = self.dif_tot.text()
if float(x[0:len(x)-2].replace(',', '.')) < 0: #Si es negatiu son perdues
self.dif_tot.setStyleSheet('border: 1px solid red;')
elif float(x[0:len(x)-2].replace(',', '.')) == 0:
self.dif_tot.setStyleSheet('border: 1px solid yellow;')
else:
self.dif_tot.setStyleSheet('border: 1px solid green;')
def factures_taula(self, nom, headerlabel_array, table, bi, y, total):
dia_inicial = int(self.data_inicial.date().day())
mes_inicial = int(self.data_inicial.date().month())
ano_inicial = int(self.data_inicial.date().year())
dia_final = int(self.data_final.date().day())
mes_final = int(self.data_final.date().month())
ano_final = int(self.data_final.date().year())
os.chdir(carpeta_data)
lines = read_database_factures('%s' % nom, 'ASC')
matches = []
for i in range(len(lines)):
if ano_inicial < ano_final :
if int(lines[i][2]) < ano_final and int(lines[i][2]) > ano_inicial: #Si esta en mig es veuran complets
matches.append(lines[i])
elif int(lines[i][2]) == ano_inicial: #Si l'any es el mateix comprovar el mes
if int(lines[i][1]) > mes_inicial :
matches.append(lines[i])
elif int(lines[i][2]) == mes_inicial and int(lines[i][0]) >= dia_inicial: #Comprovar el dia
matches.append(lines[i])
elif int(lines[i][2]) == ano_final: #Si l'any es el mateix comprovar el mes
if int(lines[i][1]) < mes_final:
matches.append(lines[i])
elif int(lines[i][1]) == mes_final and int(lines[i][0]) <= dia_final: #Comprovar el dia
matches.append(lines[i])
elif ano_inicial == ano_final and mes_inicial != mes_final:
if int(lines[i][1]) > mes_inicial and int(lines[i][1]) < mes_final:
matches.append(lines[i])
elif int(lines[i][1]) == mes_inicial and int(lines[i][0]) >= dia_inicial:
matches.append(lines[i])
elif int(lines[i][1]) == mes_final and int(lines[i][0]) <= dia_final:
matches.append(lines[i])
elif ano_inicial == ano_final and mes_inicial == mes_final:
if int(lines[i][1]) == mes_inicial and int(lines[i][0]) >= dia_inicial and int(lines[i][0]) <= dia_final:
matches.append(lines[i])
table.setRowCount(len(matches))
table.setColumnCount(6)
table.setHorizontalHeaderLabels(headerlabel_array)
font = QFont()
font.setFamily('Segoe UI Black')
font.setPointSize(9)
for i in range(6):
table.horizontalHeaderItem(i).setFont(font)
llista = []
suma_bi_reb = 0
suma_iva_reb = 0
suma_total_reb = 0
#display in the table
for i in range(len(matches)):
llista.append('')
suma_bi_reb += matches[i][4]
suma_total_reb += matches[i][6]
for j in range(6):
if j == 0:
data = str(matches[i][0]).zfill(2) + '/' + str(matches[i][1]).zfill(2) + '/' + str(matches[i][2])
item = QTableWidgetItem(data)
item.setTextAlignment(Qt.AlignHCenter)
table.setItem(i,j, item)
j = 2
elif j == 4:
iva = matches[i][5] / 100
iva_euros = round(iva * matches[i][4], 2)
suma_iva_reb += iva_euros
item = QTableWidgetItem(str(iva_euros))
item.setTextAlignment(Qt.AlignHCenter)
table.setItem(i,j, item)
elif j == 5:
item = QTableWidgetItem(str(matches[i][6]))
item.setTextAlignment(Qt.AlignHCenter)
table.setItem(i,j, item)
else:
item = QTableWidgetItem(str(matches[i][j+2]))
item.setTextAlignment(Qt.AlignHCenter)
table.setItem(i,j, item)
table.setVerticalHeaderLabels(llista)
header = table.horizontalHeader()
header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
header.setSectionResizeMode(1, QHeaderView.ResizeToContents)
header.setSectionResizeMode(2, QHeaderView.ResizeToContents)
header.setSectionResizeMode(3, QHeaderView.ResizeToContents)
header.setSectionResizeMode(4, QHeaderView.ResizeToContents)
header.setSectionResizeMode(5, QHeaderView.ResizeToContents)
bi.setText(str(round(suma_bi_reb, 2)) + ' \u20ac')
y.setText(str(round(suma_iva_reb, 2)) + ' \u20ac')
total.setText(str(round(suma_total_reb, 2)) + ' \u20ac')
return suma_bi_reb, suma_iva_reb, suma_total_reb
def show_table(self):
os.chdir(carpeta_data)
if not os.path.exists('factures_rebudes.db') and not os.path.exists('factures_emeses.db'):
QMessageBox.warning(self, 'Warning!', 'No existeix cap factura emesa o rebuda')
elif os.path.exists('factures_rebudes.db') and not os.path.exists('factures_emeses.db'):
QMessageBox.warning(self, 'Warning!', 'Només existeixen factures rebudes')
self.factures_taula('factures_rebudes', ['DATA', 'ESTABLIMENT', 'BASE IMPONIBLE', 'IVA %', 'IVA \u20ac', 'TOTAL'], self.table_1, self.bi_tot_1, self.iva_tot_1, self.total_tot_1)
elif os.path.exists('factures_emeses.db') and not os.path.exists('factures_rebudes.db'):
QMessageBox.warning(self, 'Warning!', 'Només existeixen factures emeses')
self.factures_taula('factures_emeses', ['DATA', 'NUM FACTURA', 'BASE IMPONIBLE', 'IVA %', 'IVA \u20ac', 'TOTAL'], self.table_2, self.bi_tot_2, self.iva_tot_2, self.total_tot_2)
else:
suma_bi_reb, suma_iva_reb, suma_total_reb = self.factures_taula('factures_rebudes', ['DATA', 'ESTABLIMENT', 'BASE IMPONIBLE', 'IVA %', 'IVA \u20ac', 'TOTAL'], self.table_1, self.bi_tot_1, self.iva_tot_1, self.total_tot_1)
suma_bi_eme, suma_iva_eme, suma_total_eme = self.factures_taula('factures_emeses', ['DATA', 'NUM FACTURA', 'BASE IMPONIBLE', 'IVA %', 'IVA \u20ac', 'TOTAL'], self.table_2, self.bi_tot_2, self.iva_tot_2, self.total_tot_2)
#Calcular diferencies i beneficis
diferencia_bi = suma_bi_eme - suma_bi_reb
diferencia_iva = suma_iva_eme - suma_iva_reb
diferencia_tot = suma_total_eme - suma_total_reb
self.dif_bi.setText(str(round(diferencia_bi, 2)) + ' \u20ac')
self.dif_iva.setText(str(round(diferencia_iva, 2)) + ' \u20ac')
self.dif_tot.setText(str(round(diferencia_tot, 2)) + ' \u20ac')
tableExists = check_table_exists('CompanyName', 'stock')
if os.path.exists('CompanyName.db') and tableExists == True:
lines = read_database('CompanyName', 'stock', 'REF', 'ASC')
total_stock_price = 0
for i in range(len(lines)):
total_stock_price += lines[i][4]
self.stock.setText(str(round(total_stock_price, 2)) + ' \u20ac')
self.beneficis_stock.setText(str(round(diferencia_bi+total_stock_price, 2)) + ' \u20ac')
else:
self.beneficis_stock.setText(str(round(diferencia_bi, 2)) + ' \u20ac')
def reinit_dialog(self):
self.table_1.clearContents()
self.table_2.clearContents()
self.bi_tot_1.setText('0,0' + ' \u20ac')
self.iva_tot_1.setText('0,0' + ' \u20ac')
self.total_tot_1.setText('0,0' + ' \u20ac')
self.bi_tot_2.setText('0,0' + ' \u20ac')
self.iva_tot_2.setText('0,0' + ' \u20ac')
self.total_tot_2.setText('0,0' + ' \u20ac')
self.dif_bi.setText('0,0' + ' \u20ac')
self.dif_iva.setText('0,0' + ' \u20ac')
self.dif_tot.setText('0,0' + ' \u20ac')
def closeEvent(self, event):
result = QMessageBox.question(self, 'Sortint...','Segur que vols sortir?', QMessageBox.Yes | QMessageBox.No)
if result == QMessageBox.Yes:
event.accept()
self.reinit_dialog()
else:
event.ignore()
#VENTES
class Facturacio_clients(QDialog):
def __init__(self):
QDialog.__init__(self)
os.chdir(carpeta_data)
uic.loadUi('Facturacio_clients.ui', self)
self.seleccionar.clicked.connect(self.show_table)
self.numclient.textChanged.connect(self.validar_num_client)
self.result.textChanged.connect(self.change_color_result)
self.total.textChanged.connect(self.change_color_total)
self.percentatge_variacio.textChanged.connect(self.change_color_estadistiques)
self.veure.clicked.connect(self.facturacio_client)
self.veure_total.clicked.connect(self.show_total)
self.estadistica.clicked.connect(self.show_statistics)
def change_color_total(self):
if self.total.text() != '':
self.total.setStyleSheet('border: 1px solid orange;')
def change_color_result(self):
if self.result.text() != '':
self.result.setStyleSheet('border: 1px solid orange;')
def change_color_estadistiques(self):
x = self.percentatge_variacio.text()
if x != '':
if float(x[0:len(x)-1]) < 0:
self.percentatge_variacio.setStyleSheet('border: 1px solid red;')
self.percentatge_fact.setStyleSheet('border: 1px solid red;')
self.posicio.setStyleSheet('border: 1px solid red;')
elif float(x[0:len(x)-1]) > | |
@property
def angles(self) -> Optional[List[Tuple[int, int, int]]]:
"""A List of angles from the topology."""
angles = []
topology = self.to_topology()
for node in topology.nodes:
bonded = sorted(list(nx.neighbors(topology, node)))
# Check that the atom has more than one bond
if len(bonded) < 2:
continue
# Find all possible angle combinations from the list
for i in range(len(bonded)):
for j in range(i + 1, len(bonded)):
atom1, atom3 = bonded[i], bonded[j]
angles.append((atom1, node, atom3))
return angles or None
@property
def charge(self) -> int:
"""
Return the integer charge of the molecule as the sum of the formal charge.
"""
return sum([atom.formal_charge for atom in self.atoms])
@property
def n_angles(self) -> int:
"""The number of angles in the molecule."""
angles = self.angles
if angles is None:
return 0
return len(angles)
def measure_bonds(self) -> Dict[Tuple[int, int], float]:
"""
Find the length of all bonds in the molecule for the given conformer in angstroms.
Returns:
A dictionary of the bond lengths stored by bond tuple.
"""
bond_lengths = {}
for bond in self.bonds:
atom1 = self.coordinates[bond.atom1_index]
atom2 = self.coordinates[bond.atom2_index]
edge = (bond.atom1_index, bond.atom2_index)
bond_lengths[edge] = np.linalg.norm(atom2 - atom1)
return bond_lengths
@property
def n_bonds(self) -> int:
"""The number of bonds in the topology."""
bonds = self.bonds
if bonds is None:
return 0
return len(bonds)
@property
def dihedrals(
self,
) -> Optional[Dict[Tuple[int, int], List[Tuple[int, int, int, int]]]]:
"""A list of all possible dihedrals that can be found in the topology."""
dihedrals = {}
topology = self.to_topology()
# Work through the network using each edge as a central dihedral bond
for edge in topology.edges:
for start in list(nx.neighbors(topology, edge[0])):
# Check atom not in main bond
if start != edge[0] and start != edge[1]:
for end in list(nx.neighbors(topology, edge[1])):
# Check atom not in main bond
if end != edge[0] and end != edge[1]:
if edge not in dihedrals:
# Add the central edge as a key the first time it is used
dihedrals[edge] = [(start, edge[0], edge[1], end)]
else:
# Add the tuple to the correct key.
dihedrals[edge].append((start, edge[0], edge[1], end))
return dihedrals or None
@property
def n_dihedrals(self) -> int:
"""The total number of dihedrals in the molecule."""
dihedrals = self.dihedrals
if dihedrals is None:
return 0
return sum([len(torsions) for torsions in dihedrals.values()])
def find_rotatable_bonds(
self, smirks_to_remove: Optional[List[str]] = None
) -> Optional[List[Bond]]:
"""
Args:
smirks_to_remove:
Optional list of smirks patterns which will be discarded
from the rotatable bonds
Find all rotatable bonds in the molecule.
Remove any groups which are not relevant for torsion scans.
e.g. methyl / amine groups
return:
The rotatable bonds in the molecule to be used for torsion scans.
"""
rotatable_bond_smarts = "[!$(*#*)&!D1:1]-&!@[!$(*#*)&!D1:2]"
rotatable_matches = self.get_smarts_matches(rotatable_bond_smarts)
if rotatable_matches is None:
return None
if smirks_to_remove is not None:
for smirk in smirks_to_remove:
matches_to_remove = self.get_smarts_matches(smirk)
if matches_to_remove is not None:
for match in matches_to_remove:
try:
rotatable_matches.remove(match)
except ValueError:
try:
# If the match is not in the list, it may be in backwards
rotatable_matches.remove(tuple(reversed(match)))
except ValueError:
continue
# gather a list of bond instances to return
rotatable_bonds = [self.get_bond_between(*bond) for bond in rotatable_matches]
return rotatable_bonds or None
@property
def n_rotatable_bonds(self) -> int:
"""The number of rotatable bonds."""
rotatable_bonds = self.find_rotatable_bonds()
if rotatable_bonds is None:
return 0
return len(rotatable_bonds)
def symmetrise_nonbonded_parameters(self) -> bool:
"""
Symmetrise all non-bonded force group parameters.
Using the CIP rankings from RDKit apply symmetry to the non-bonded force group.
Important:
We respect the predefined parameters in the non-bonded force group which can be symmetrised.
"""
# group atom types as they are in a different format to other types
atom_types = {}
for atom_index, cip_type in self.atom_types.items():
atom_types.setdefault(cip_type, []).append((atom_index,))
for atoms in atom_types.items():
self._symmetrise_parameters(
force_group=self.NonbondedForce, parameter_keys=atoms
)
return True
def symmetrise_bonded_parameters(self) -> bool:
"""
Symmetrise all bond and angle force group parameters.
Using the CIP rankings from RDKit apply symmetry to the bond and angle force groups.
Important:
We respect the predefined parameters in the bond/angle force group which can be symmetrised.
"""
for bonds in self.bond_types.values():
self._symmetrise_parameters(
force_group=self.BondForce, parameter_keys=bonds
)
for angles in self.angle_types.values():
self._symmetrise_parameters(
force_group=self.AngleForce, parameter_keys=angles
)
return True
def _symmetrise_parameters(
self, force_group: BaseForceGroup, parameter_keys: List[Tuple[int, ...]]
):
"""
Internal method which applies symmetry to a group of parameter references in a particular force group.
Args:
force_group: The force group we should query for parameters.
parameter_keys: The list of atom indices tuples that the symmetry should be applied to.
"""
symmetry_attrs = force_group.symmetry_parameters()
raw_parameter_values = {}
for parameter_key in parameter_keys:
param = force_group[parameter_key]
for attr in symmetry_attrs:
raw_parameter_values.setdefault(attr, []).append(getattr(param, attr))
# now average the raw values
for key, value in raw_parameter_values.items():
raw_parameter_values[key] = np.array(value).mean()
# now set back
for parameter_key in parameter_keys:
force_group.create_parameter(atoms=parameter_key, **raw_parameter_values)
def measure_dihedrals(self) -> Optional[Dict[Tuple[int, int, int, int], float]]:
"""
For the given conformation measure the dihedrals in the topology in degrees.
"""
dihedrals = self.dihedrals
if dihedrals is None:
return None
dih_phis = {}
for val in dihedrals.values():
for torsion in val:
# Calculate the dihedral angle in the molecule using the molecule data array.
x1, x2, x3, x4 = [self.coordinates[torsion[i]] for i in range(4)]
b1, b2, b3 = x2 - x1, x3 - x2, x4 - x3
t1 = np.linalg.norm(b2) * np.dot(b1, np.cross(b2, b3))
t2 = np.dot(np.cross(b1, b2), np.cross(b2, b3))
dih_phis[torsion] = np.degrees(np.arctan2(t1, t2))
return dih_phis
def measure_angles(self) -> Optional[Dict[Tuple[int, int, int], float]]:
"""
For the given conformation measure the angles in the topology in degrees.
"""
angles = self.angles
if angles is None:
return None
angle_values = {}
for angle in angles:
x1 = self.coordinates[angle[0]]
x2 = self.coordinates[angle[1]]
x3 = self.coordinates[angle[2]]
b1, b2 = x1 - x2, x3 - x2
cosine_angle = np.dot(b1, b2) / (np.linalg.norm(b1) * np.linalg.norm(b2))
angle_values[angle] = np.degrees(np.arccos(cosine_angle))
return angle_values
@property
def n_atoms(self) -> int:
"""
Calculate the number of atoms.
"""
return len(self.atoms)
def write_parameters(self, file_name: str):
"""
Take the molecule's parameter set and write an xml file for the molecule.
"""
tree = self._build_forcefield().getroot()
messy = ET.tostring(tree, "utf-8")
pretty_xml_as_string = parseString(messy).toprettyxml(indent="")
with open(file_name, "w") as xml_doc:
xml_doc.write(pretty_xml_as_string)
def _build_forcefield(self):
"""
Separates the parameters and builds an xml tree ready to be used.
TODO how do we support OPLS combination rules.
Important:
The ordering here should not be changed due to the way sites have to be added.
"""
# Create XML layout
root = ET.Element("ForceField")
ET.SubElement(
root,
"QUBEKit",
attrib={
"Version": qubekit.__version__,
"Date": datetime.now().strftime("%Y_%m_%d"),
},
)
AtomTypes = ET.SubElement(root, "AtomTypes")
Residues = ET.SubElement(root, "Residues")
resname = "QUP" if self.__class__.__name__ == "Protein" else "MOL"
Residue = ET.SubElement(Residues, "Residue", name=resname)
# declare atom `types` and properties
for atom in self.atoms:
atom_type = f"QUBE_{atom.atom_index}"
ET.SubElement(
AtomTypes,
"Type",
attrib={
"name": atom_type,
"class": str(atom.atom_index),
"element": atom.atomic_symbol,
"mass": str(atom.atomic_mass),
},
)
ET.SubElement(
Residue, "Atom", attrib={"name": atom.atom_name, "type": atom_type}
)
# add sites to Atomtypes, topology and nonbonded
for i, site in enumerate(self.extra_sites, start=1):
site_name = f"v-site{i}"
site_class = f"X{i}"
ET.SubElement(
AtomTypes,
"Type",
attrib={"name": site_name, "class": site_class, "mass": "0"},
)
# for some reason we swap name and class here but it works !
ET.SubElement(
Residue, "Atom", attrib={"name": site_class, "type": site_name}
)
BondForce = ET.SubElement(
root, self.BondForce.openmm_group(), attrib=self.BondForce.xml_data()
)
for parameter in self.BondForce:
ET.SubElement(
BondForce, parameter.openmm_type(), attrib=parameter.xml_data()
)
ET.SubElement(
Residue,
"Bond",
attrib={"from": str(parameter.atoms[0]), "to": str(parameter.atoms[1])},
)
AngleForce = ET.SubElement(
root, self.AngleForce.openmm_group(), attrib=self.AngleForce.xml_data()
)
for parameter in self.AngleForce:
ET.SubElement(
AngleForce, parameter.openmm_type(), attrib=parameter.xml_data()
)
if (
self.TorsionForce.n_parameters > 0
or self.ImproperTorsionForce.n_parameters > 0
):
TorsionForce = ET.SubElement(
root,
self.TorsionForce.openmm_group(),
attrib=self.TorsionForce.xml_data(),
)
for parameter in self.TorsionForce:
ET.SubElement(
TorsionForce, parameter.openmm_type(), attrib=parameter.xml_data()
)
for parameter in self.ImproperTorsionForce:
ET.SubElement(
TorsionForce, parameter.openmm_type(), attrib=parameter.xml_data()
)
if (
self.RBTorsionForce.n_parameters > 0
or self.ImproperRBTorsionForce.n_parameters > 0
):
RBTorsion = ET.SubElement(
root,
self.RBTorsionForce.openmm_group(),
attrib=self.RBTorsionForce.xml_data(),
)
for parameter in self.RBTorsionForce:
ET.SubElement(
RBTorsion, parameter.openmm_type(), attrib=parameter.xml_data()
)
for parameter in self.ImproperRBTorsionForce:
ET.SubElement(
RBTorsion, parameter.openmm_type(), attrib=parameter.xml_data()
)
# now we add more site info after general bonding
for i, site in enumerate(self.extra_sites):
site_data = site.xml_data()
# we have to add its global index
site_data["index"] = str(i + self.n_atoms)
ET.SubElement(Residue, site.openmm_type(), attrib=site_data)
NonbondedForce | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import mxnet as mx
import numpy as np
from config import config
def Conv(**kwargs):
body = mx.sym.Convolution(**kwargs)
return body
def Act(data, act_type, name):
if act_type=='prelu':
body = mx.sym.LeakyReLU(data = data, act_type='prelu', name = name)
else:
body = mx.symbol.Activation(data=data, act_type=act_type, name=name)
return body
def ConvFactory(data, num_filter, kernel, stride=(1, 1), pad=(0, 0), act_type="relu", mirror_attr={}, with_act=True, dcn=False, name=''):
bn_mom = config.bn_mom
workspace = config.workspace
if not dcn:
conv = mx.symbol.Convolution(
data=data, num_filter=num_filter, kernel=kernel, stride=stride, pad=pad, no_bias=True, workspace=workspace, name=name+'_conv')
else:
conv_offset = mx.symbol.Convolution(name=name+'_conv_offset', data = data,
num_filter=18, pad=(1, 1), kernel=(3, 3), stride=(1, 1))
conv = mx.contrib.symbol.DeformableConvolution(name=name+"_conv", data=data, offset=conv_offset,
num_filter=num_filter, pad=(1,1), kernel=(3,3), num_deformable_group=1, stride=stride, dilate=(1, 1), no_bias=False)
bn = mx.symbol.BatchNorm(data=conv, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name+'_bn')
if with_act:
act = Act(bn, act_type, name=name+'_relu')
#act = mx.symbol.Activation(
# data=bn, act_type=act_type, attr=mirror_attr, name=name+'_relu')
return act
else:
return bn
def conv_resnet(data, num_filter, stride, dim_match, name, binarize, dcn, dilate, **kwargs):
bit = 1
ACT_BIT = config.ACT_BIT
bn_mom = config.bn_mom
workspace = config.workspace
memonger = config.memonger
#print('in unit2')
# the same as https://github.com/facebook/fb.resnet.torch#notes, a bit difference with origin paper
bn1 = mx.sym.BatchNorm(data=data, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn1')
if not binarize:
act1 = Act(data=bn1, act_type='relu', name=name + '_relu1')
conv1 = Conv(data=act1, num_filter=int(num_filter*0.5), kernel=(1,1), stride=(1,1), pad=(0,0),
no_bias=True, workspace=workspace, name=name + '_conv1')
else:
act1 = mx.sym.QActivation(data=bn1, act_bit=ACT_BIT, name=name + '_relu1', backward_only=True)
conv1 = mx.sym.QConvolution(data=act1, num_filter=int(num_filter*0.5), kernel=(1,1), stride=(1,1), pad=(0,0),
no_bias=True, workspace=workspace, name=name + '_conv1', act_bit=ACT_BIT, weight_bit=bit)
bn2 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn2')
if not binarize:
act2 = Act(data=bn2, act_type='relu', name=name + '_relu2')
conv2 = Conv(data=act2, num_filter=int(num_filter*0.5), kernel=(3,3), stride=(1,1), pad=(1,1),
no_bias=True, workspace=workspace, name=name + '_conv2')
else:
act2 = mx.sym.QActivation(data=bn2, act_bit=ACT_BIT, name=name + '_relu2', backward_only=True)
conv2 = mx.sym.QConvolution(data=act2, num_filter=int(num_filter*0.5), kernel=(3,3), stride=(1,1), pad=(1,1),
no_bias=True, workspace=workspace, name=name + '_conv2', act_bit=ACT_BIT, weight_bit=bit)
bn3 = mx.sym.BatchNorm(data=conv2, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn3')
if not binarize:
act3 = Act(data=bn3, act_type='relu', name=name + '_relu3')
conv3 = Conv(data=act3, num_filter=num_filter, kernel=(1,1), stride=(1,1), pad=(0,0), no_bias=True,
workspace=workspace, name=name + '_conv3')
else:
act3 = mx.sym.QActivation(data=bn3, act_bit=ACT_BIT, name=name + '_relu3', backward_only=True)
conv3 = mx.sym.QConvolution(data=act3, num_filter=num_filter, kernel=(1,1), stride=(1,1), pad=(0,0),
no_bias=True, workspace=workspace, name=name + '_conv3', act_bit=ACT_BIT, weight_bit=bit)
#if binarize:
# conv3 = mx.sym.BatchNorm(data=conv3, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn4')
if dim_match:
shortcut = data
else:
if not binarize:
shortcut = Conv(data=act1, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True,
workspace=workspace, name=name+'_sc')
else:
shortcut = mx.sym.QConvolution(data=act1, num_filter=num_filter, kernel=(1,1), stride=stride, pad=(0,0),
no_bias=True, workspace=workspace, name=name + '_sc', act_bit=ACT_BIT, weight_bit=bit)
if memonger:
shortcut._set_attr(mirror_stage='True')
return conv3 + shortcut
def conv_hpm(data, num_filter, stride, dim_match, name, binarize, dcn, dilation, **kwargs):
bit = 1
ACT_BIT = config.ACT_BIT
bn_mom = config.bn_mom
workspace = config.workspace
memonger = config.memonger
#print('in unit2')
# the same as https://github.com/facebook/fb.resnet.torch#notes, a bit difference with origin paper
bn1 = mx.sym.BatchNorm(data=data, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn1')
if not binarize:
act1 = Act(data=bn1, act_type='relu', name=name + '_relu1')
if not dcn:
conv1 = Conv(data=act1, num_filter=int(num_filter*0.5), kernel=(3,3), stride=(1,1), pad=(dilation,dilation), dilate=(dilation,dilation),
no_bias=True, workspace=workspace, name=name + '_conv1')
else:
conv1_offset = mx.symbol.Convolution(name=name+'_conv1_offset', data = act1,
num_filter=18, pad=(1, 1), kernel=(3, 3), stride=(1, 1))
conv1 = mx.contrib.symbol.DeformableConvolution(name=name+'_conv1', data=act1, offset=conv1_offset,
num_filter=int(num_filter*0.5), pad=(1,1), kernel=(3, 3), num_deformable_group=1, stride=(1, 1), dilate=(1, 1), no_bias=True)
else:
act1 = mx.sym.QActivation(data=bn1, act_bit=ACT_BIT, name=name + '_relu1', backward_only=True)
conv1 = mx.sym.QConvolution_v1(data=act1, num_filter=int(num_filter*0.5), kernel=(3,3), stride=(1,1), pad=(1,1),
no_bias=True, workspace=workspace, name=name + '_conv1', act_bit=ACT_BIT, weight_bit=bit)
bn2 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn2')
if not binarize:
act2 = Act(data=bn2, act_type='relu', name=name + '_relu2')
if not dcn:
conv2 = Conv(data=act2, num_filter=int(num_filter*0.25), kernel=(3,3), stride=(1,1), pad=(dilation,dilation), dilate=(dilation,dilation),
no_bias=True, workspace=workspace, name=name + '_conv2')
else:
conv2_offset = mx.symbol.Convolution(name=name+'_conv2_offset', data = act2,
num_filter=18, pad=(1, 1), kernel=(3, 3), stride=(1, 1))
conv2 = mx.contrib.symbol.DeformableConvolution(name=name+'_conv2', data=act2, offset=conv2_offset,
num_filter=int(num_filter*0.25), pad=(1,1), kernel=(3, 3), num_deformable_group=1, stride=(1, 1), dilate=(1, 1), no_bias=True)
else:
act2 = mx.sym.QActivation(data=bn2, act_bit=ACT_BIT, name=name + '_relu2', backward_only=True)
conv2 = mx.sym.QConvolution_v1(data=act2, num_filter=int(num_filter*0.25), kernel=(3,3), stride=(1,1), pad=(1,1),
no_bias=True, workspace=workspace, name=name + '_conv2', act_bit=ACT_BIT, weight_bit=bit)
bn3 = mx.sym.BatchNorm(data=conv2, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn3')
if not binarize:
act3 = Act(data=bn3, act_type='relu', name=name + '_relu3')
if not dcn:
conv3 = Conv(data=act3, num_filter=int(num_filter*0.25), kernel=(3,3), stride=(1,1), pad=(dilation,dilation), dilate=(dilation,dilation),
no_bias=True, workspace=workspace, name=name + '_conv3')
else:
conv3_offset = mx.symbol.Convolution(name=name+'_conv3_offset', data = act3,
num_filter=18, pad=(1, 1), kernel=(3, 3), stride=(1, 1))
conv3 = mx.contrib.symbol.DeformableConvolution(name=name+'_conv3', data=act3, offset=conv3_offset,
num_filter=int(num_filter*0.25), pad=(1,1), kernel=(3, 3), num_deformable_group=1, stride=(1, 1), dilate=(1, 1), no_bias=True)
else:
act3 = mx.sym.QActivation(data=bn3, act_bit=ACT_BIT, name=name + '_relu3', backward_only=True)
conv3 = mx.sym.QConvolution_v1(data=act3, num_filter=int(num_filter*0.25), kernel=(3,3), stride=(1,1), pad=(1,1),
no_bias=True, workspace=workspace, name=name + '_conv3', act_bit=ACT_BIT, weight_bit=bit)
conv4 = mx.symbol.Concat(*[conv1, conv2, conv3])
if binarize:
conv4 = mx.sym.BatchNorm(data=conv4, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_bn4')
if dim_match:
shortcut = data
else:
if not binarize:
shortcut = Conv(data=act1, num_filter=num_filter, kernel=(1,1), stride=stride, no_bias=True,
workspace=workspace, name=name+'_sc')
else:
#assert(False)
shortcut = mx.sym.QConvolution_v1(data=act1, num_filter=num_filter, kernel=(1,1), stride=stride, pad=(0,0),
no_bias=True, workspace=workspace, name=name + '_sc', act_bit=ACT_BIT, weight_bit=bit)
shortcut = mx.sym.BatchNorm(data=shortcut, fix_gamma=False, eps=2e-5, momentum=bn_mom, name=name + '_sc_bn')
if memonger:
shortcut._set_attr(mirror_stage='True')
return conv4 + shortcut
#return bn4 + shortcut
#return act4 + shortcut
def block17(net, input_num_channels, scale=1.0, with_act=True, act_type='relu', mirror_attr={}, name=''):
tower_conv = ConvFactory(net, 192, (1, 1), name=name+'_conv')
tower_conv1_0 = ConvFactory(net, 129, (1, 1), name=name+'_conv1_0')
tower_conv1_1 = ConvFactory(tower_conv1_0, 160, (1, 7), pad=(1, 2), name=name+'_conv1_1')
tower_conv1_2 = ConvFactory(tower_conv1_1, 192, (7, 1), pad=(2, 1), name=name+'_conv1_2')
tower_mixed = mx.symbol.Concat(*[tower_conv, tower_conv1_2])
tower_out = ConvFactory(
tower_mixed, input_num_channels, (1, 1), with_act=False, name=name+'_conv_out')
net = net+scale * tower_out
if with_act:
act = mx.symbol.Activation(
data=net, act_type=act_type, attr=mirror_attr)
return act
else:
return net
def block35(net, input_num_channels, scale=1.0, with_act=True, act_type='relu', mirror_attr={}, name=''):
M = 1.0
tower_conv = ConvFactory(net, int(input_num_channels*0.25*M), (1, 1), name=name+'_conv')
tower_conv1_0 = ConvFactory(net, int(input_num_channels*0.25*M), (1, 1), name=name+'_conv1_0')
tower_conv1_1 = ConvFactory(tower_conv1_0, int(input_num_channels*0.25*M), (3, 3), pad=(1, 1), name=name+'_conv1_1')
tower_conv2_0 = ConvFactory(net, int(input_num_channels*0.25*M), (1, 1), name=name+'_conv2_0')
tower_conv2_1 = ConvFactory(tower_conv2_0, int(input_num_channels*0.375*M), (3, 3), pad=(1, 1), name=name+'_conv2_1')
tower_conv2_2 = ConvFactory(tower_conv2_1, int(input_num_channels*0.5*M), (3, 3), pad=(1, 1), name=name+'_conv2_2')
tower_mixed = mx.symbol.Concat(*[tower_conv, tower_conv1_1, tower_conv2_2])
tower_out = ConvFactory(
tower_mixed, input_num_channels, (1, 1), with_act=False, name=name+'_conv_out')
net = net+scale * tower_out
if with_act:
act = mx.symbol.Activation(
data=net, act_type=act_type, attr=mirror_attr)
return act
else:
return net
def conv_inception(data, num_filter, stride, dim_match, name, binarize, dcn, dilate, **kwargs):
assert not binarize
if stride[0]>1 or not dim_match:
return conv_resnet(data, num_filter, stride, dim_match, name, binarize, dcn, dilate, **kwargs)
conv4 = block35(data, num_filter, name=name+'_block35')
return conv4
def conv_cab(data, num_filter, stride, dim_match, name, binarize, dcn, dilate, **kwargs):
workspace = config.workspace
if stride[0]>1 or not dim_match:
return conv_hpm(data, num_filter, stride, dim_match, name, binarize, dcn, dilate, **kwargs)
cab = CAB(data, num_filter, 1, 4, workspace, name, dilate, 1)
return cab.get()
def conv_block(data, num_filter, stride, dim_match, name, binarize, dcn, dilate):
if config.net_block=='resnet':
return conv_resnet(data, num_filter, stride, dim_match, name, binarize, dcn, dilate)
elif config.net_block=='inception':
return conv_inception(data, num_filter, stride, dim_match, name, binarize, dcn, dilate)
elif config.net_block=='hpm':
return conv_hpm(data, num_filter, stride, dim_match, name, binarize, dcn, dilate)
elif config.net_block=='cab':
return conv_cab(data, num_filter, stride, dim_match, name, binarize, dcn, dilate)
#def lin(data, num_filter, workspace, name, binarize, dcn):
# bit = 1
# ACT_BIT = config.ACT_BIT
# bn_mom = config.bn_mom
# workspace = config.workspace
# if not binarize:
# if not dcn:
# conv1 = Conv(data=data, num_filter=num_filter, kernel=(1,1), stride=(1,1), pad=(0,0),
# no_bias=True, workspace=workspace, name=name + '_conv')
# bn1 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn')
# act1 = Act(data=bn1, act_type='relu', name=name + '_relu')
# return act1
# else:
# bn1 = mx.sym.BatchNorm(data=data, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn')
# act1 = Act(data=bn1, act_type='relu', name=name + '_relu')
# conv1_offset = mx.symbol.Convolution(name=name+'_conv_offset', data = act1,
# num_filter=18, pad=(1, 1), kernel=(3, 3), stride=(1, 1))
# conv1 = mx.contrib.symbol.DeformableConvolution(name=name+"_conv", data=act1, offset=conv1_offset,
# num_filter=num_filter, pad=(1,1), kernel=(3, 3), num_deformable_group=1, stride=(1, 1), dilate=(1, 1), no_bias=False)
# #conv1 = Conv(data=act1, num_filter=num_filter, kernel=(3,3), stride=(1,1), pad=(1,1),
# # no_bias=False, workspace=workspace, name=name + '_conv')
# return conv1
# else:
# bn1 = mx.sym.BatchNorm(data=data, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn')
# act1 = Act(data=bn1, act_type='relu', name=name + '_relu')
# conv1 = mx.sym.QConvolution_v1(data=act1, num_filter=num_filter, kernel=(1,1), stride=(1,1), pad=(0,0),
# no_bias=True, workspace=workspace, name=name + '_conv', act_bit=ACT_BIT, weight_bit=bit)
# conv1 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn2')
# return conv1
def lin3(data, num_filter, workspace, name, k, g=1, d=1):
bn_mom = config.bn_mom
workspace = config.workspace
if k!=3:
conv1 = Conv(data=data, num_filter=num_filter, kernel=(k,k), stride=(1,1), pad=((k-1)//2,(k-1)//2), num_group=g,
no_bias=True, workspace=workspace, name=name + '_conv')
else:
conv1 = Conv(data=data, num_filter=num_filter, kernel=(k,k), stride=(1,1), pad=(d,d), num_group=g, dilate=(d, d),
no_bias=True, workspace=workspace, name=name + '_conv')
bn1 = mx.sym.BatchNorm(data=conv1, fix_gamma=False, momentum=bn_mom, eps=2e-5, name=name + '_bn')
act1 = Act(data=bn1, act_type='relu', name=name + '_relu')
ret = act1
return ret
class CAB:
def __init__(self, data, nFilters, nModules, n, workspace, name, dilate, group):
self.data = data
self.nFilters = nFilters
| |
with gaps in fewer
than `maximum_gap_frequency` fraction of the sequences.
Examples
--------
>>> from skbio.alignment import Alignment
>>> from skbio.sequence import DNA
>>> sequences = [DNA('AC--', id="seq1"),
... DNA('AT-C', id="seq2"),
... DNA('TT-C', id="seq3")]
>>> a1 = Alignment(sequences)
>>> a2 = a1.omit_gap_positions(0.50)
>>> a2
<Alignment: n=3; mean +/- std length=3.00 +/- 0.00>
>>> print(a2[0])
AC-
>>> print(a2[1])
ATC
>>> print(a2[2])
TTC
"""
# handle empty Alignment case
if self.is_empty():
return self.__class__([])
position_frequencies = self.position_frequencies()
gap_alphabet = self[0].gap_alphabet()
positions_to_keep = []
for i, f in enumerate(position_frequencies):
gap_frequency = sum([f[c] for c in gap_alphabet])
if gap_frequency <= maximum_gap_frequency:
positions_to_keep.append(i)
return self.subalignment(positions_to_keep=positions_to_keep)
def omit_gap_sequences(self, maximum_gap_frequency):
"""Returns Alignment with sequences filtered based on gap frequency
Parameters
----------
maximum_gap_frequency : float
The maximum fraction of the positions that can contain a gap in a
given sequence for that sequence to be retained in the resulting
`Alignment`.
Returns
-------
Alignment
The subalignment containing only the sequences with gaps in fewer
than `maximum_gap_frequency` fraction of the positions.
Examples
--------
>>> from skbio.alignment import Alignment
>>> from skbio.sequence import DNA
>>> sequences = [DNA('AC--', id="seq1"),
... DNA('AT-C', id="seq2"),
... DNA('TT-C', id="seq3")]
>>> a1 = Alignment(sequences)
>>> a2 = a1.omit_gap_sequences(0.49)
>>> a2
<Alignment: n=2; mean +/- std length=4.00 +/- 0.00>
>>> print(a2[0])
AT-C
>>> print(a2[1])
TT-C
"""
# handle empty Alignment case
if self.is_empty():
return self.__class__([])
base_frequencies = self.k_word_frequencies(k=1)
gap_alphabet = self[0].gap_alphabet()
seqs_to_keep = []
for seq, f in zip(self, base_frequencies):
gap_frequency = sum([f[c] for c in gap_alphabet])
if gap_frequency <= maximum_gap_frequency:
seqs_to_keep.append(seq.id)
return self.subalignment(seqs_to_keep=seqs_to_keep)
def position_counters(self):
"""Return collection.Counter object for positions in Alignment
Returns
-------
list
List of ``collection.Counter`` objects, one for each position in
the `Alignment`.
See Also
--------
position_frequencies
position_entropies
Examples
--------
>>> from skbio.alignment import Alignment
>>> from skbio.sequence import DNA
>>> sequences = [DNA('AC--', id="seq1"),
... DNA('AT-C', id="seq2"),
... DNA('TT-C', id="seq3")]
>>> a1 = Alignment(sequences)
>>> for counter in a1.position_counters():
... print(counter)
Counter({'A': 2, 'T': 1})
Counter({'T': 2, 'C': 1})
Counter({'-': 3})
Counter({'C': 2, '-': 1})
"""
return [Counter(p) for p in self.iter_positions(constructor=str)]
def position_frequencies(self):
"""Return frequencies of characters for positions in Alignment
Returns
-------
list
List of ``collection.defaultdict`` objects, one for each position
in the `Alignment`, representing the frequency of each character in
the `Alignment` at that position.
See Also
--------
position_counters
position_entropies
k_word_frequencies
Examples
--------
>>> from skbio.alignment import Alignment
>>> from skbio.sequence import DNA
>>> sequences = [DNA('AC--', id="seq1"),
... DNA('AT-C', id="seq2"),
... DNA('TT-C', id="seq3")]
>>> a1 = Alignment(sequences)
>>> position_freqs = a1.position_frequencies()
>>> print(round(position_freqs[0]['A'],3))
0.667
>>> print(round(position_freqs[1]['A'],3))
0.0
"""
result = []
# handle the empty Alignment case
if self.is_empty():
return result
count = 1 / self.sequence_count()
for p in self.iter_positions(constructor=str):
current_freqs = defaultdict(float)
for c in p:
current_freqs[c] += count
result.append(current_freqs)
return result
def position_entropies(self, base=None,
nan_on_non_standard_chars=True):
"""Return Shannon entropy of positions in Alignment
Parameters
----------
base : float, optional
log base for entropy calculation. If not passed, default will be e
(i.e., natural log will be computed).
nan_on_non_standard_chars : bool, optional
if True, the entropy at positions containing characters outside of
the first sequence's `iupac_standard_characters` will be `np.nan`.
This is useful, and the default behavior, as it's not clear how a
gap or degenerate character should contribute to a positional
entropy. This issue was described in [1]_.
Returns
-------
list
List of floats of Shannon entropy at `Alignment` positions. Shannon
entropy is defined in [2]_.
See Also
--------
position_counters
position_frequencies
References
----------
.. [1] Identifying DNA and protein patterns with statistically
significant alignments of multiple sequences.
<NAME>, <NAME>.
Bioinformatics. 1999 Jul-Aug;15(7-8):563-77.
.. [2] A Mathematical Theory of Communication
CE Shannon
The Bell System Technical Journal (1948).
Examples
--------
>>> from skbio.alignment import Alignment
>>> from skbio.sequence import DNA
>>> sequences = [DNA('AC--', id="seq1"),
... DNA('AT-C', id="seq2"),
... DNA('TT-C', id="seq3")]
>>> a1 = Alignment(sequences)
>>> print(a1.position_entropies())
[0.63651416829481278, 0.63651416829481278, nan, nan]
"""
result = []
# handle empty Alignment case
if self.is_empty():
return result
iupac_standard_characters = self[0].iupac_standard_characters()
for f in self.position_frequencies():
if (nan_on_non_standard_chars and
len(viewkeys(f) - iupac_standard_characters) > 0):
result.append(np.nan)
else:
result.append(entropy(list(f.values()), base=base))
return result
def sequence_length(self):
"""Return the number of positions in Alignment
Returns
-------
int
The number of positions in `Alignment`.
See Also
--------
sequence_lengths
sequence_count
Examples
--------
>>> from skbio.alignment import Alignment
>>> from skbio.sequence import DNA
>>> sequences = [DNA('AC--', id="seq1"),
... DNA('AT-C', id="seq2"),
... DNA('TT-C', id="seq3")]
>>> a1 = Alignment(sequences)
>>> a1.sequence_length()
4
"""
# handle the empty Alignment case
if self.is_empty():
return 0
else:
return len(self._data[0])
def to_phylip(self, map_labels=False, label_prefix=""):
"""Return phylip-formatted string representing the `SequenceCollection`
Returns
-------
str
A phylip-formatted string representing the `SequenceCollection`.
"""
if not self._validate_lengths():
raise SequenceCollectionError("PHYLIP-formatted string can only "
"be generated if all sequences are "
"of equal length.")
if self.is_empty():
raise SequenceCollectionError("PHYLIP-formatted string can only "
"be generated if there is at least "
"one sequence in the Alignment.")
sequence_length = self.sequence_length()
if sequence_length == 0:
raise SequenceCollectionError("PHYLIP-formatted string can only "
"be generated if there is at least "
"one position in the Alignment.")
ids = self.ids()
sequence_count = self.sequence_count()
result = ["%d %d" % (sequence_count, sequence_length)]
if map_labels:
_, new_id_to_old_id = self.int_map(prefix=label_prefix)
old_id_to_new_id = {v: k for k, v in new_id_to_old_id.items()}
else:
new_id_to_old_id = {seq_id: seq_id for seq_id in ids}
old_id_to_new_id = new_id_to_old_id
for seq_id in ids:
new_id = old_id_to_new_id[seq_id]
seq = self[seq_id]
result.append("%s %s" % (new_id, str(seq)))
return '\n'.join(result), new_id_to_old_id
def _validate_lengths(self):
"""Return ``True`` if all sequences same length, ``False`` otherwise
"""
seq1_length = self.sequence_length()
for seq in self:
if seq1_length != len(seq):
return False
return True
class StockholmAlignment(Alignment):
"""Contains the metadata information in a Stockholm file alignment
Parameters
----------
seqs : list of `skbio.sequence.BiologicalSequence` objects
The `skbio.sequence.BiologicalSequence` objects to load.
gf : dict, optional
GF info in the format {feature: info}
gs : dict of dicts, optional
GS info in the format {feature: {seqlabel: info}}
gr : dict of dicts, optional
GR info in the format {feature: {seqlabel: info}}
gc : dict, optional
GC info in the format {feature: info}
Notes
-----
The Stockholm format is described in [1]_ and [2]_.
If there are multiple references, include information for each R* line
as a list, with reference 0 information in position 0 for all lists,
etc. This list will be broken up into the appropriate bits for each
reference on string formatting.
If there are multiple trees included, use a list to store identifiers
and trees, with position 0 holding identifier for tree in position 0,
etc.
References
----------
.. [1] http://sonnhammer.sbc.su.se/Stockholm.html
.. [2] http://en.wikipedia.org/wiki/Stockholm_format
Examples
--------
Assume we have a basic stockholm file with the following contents::
# STOCKHOLM 1.0
seq1 ACC--G-GGGU
seq2 TCC--G-GGGA
#=GC SS_cons (((.....)))
//
>>> from skbio.sequence import RNA
>>> from skbio.alignment import StockholmAlignment
>>> from StringIO import StringIO
>>> sto_in = StringIO("# STOCKHOLM 1.0\\n"
... "seq1 ACC--G-GGGU\\nseq2 TCC--G-GGGA\\n"
... "#=GC SS_cons (((.....)))\\n//")
>>> sto_records = StockholmAlignment.from_file(sto_in, RNA)
>>> sto = next(sto_records)
>>> print(sto)
# STOCKHOLM 1.0
seq1 ACC--G-GGGU
seq2 TCC--G-GGGA
#=GC SS_cons (((.....)))
//
>>> sto.gc
{'SS_cons': '(((.....)))'}
We can also write out information by instantiating the StockholmAlignment
object and then printing it.
>>> from skbio.sequence import RNA
>>> from skbio.alignment import StockholmAlignment
>>> seqs = [RNA("ACC--G-GGGU", id="seq1"),
... RNA("TCC--G-GGGA", id="seq2")]
>>> gf = {
... "RT": ["TITLE1", "TITLE2"],
... "RA": ["Auth1;", "Auth2;"],
... "RL": ["J Mol Biol", "Cell"],
... "RM": ["11469857", "12007400"]}
>>> sto = StockholmAlignment(seqs, gf=gf)
>>> print(sto)
# STOCKHOLM 1.0
#=GF RN [1]
#=GF RM 11469857
#=GF RT TITLE1
#=GF RA Auth1;
#=GF RL J Mol Biol
#=GF RN [2]
#=GF RM 12007400
#=GF RT TITLE2
#=GF RA Auth2;
#=GF RL Cell
seq1 ACC--G-GGGU
seq2 TCC--G-GGGA
//
"""
def __init__(self, seqs, gf=None, gs=None, gr=None, gc=None,
validate=False):
self.gf = gf if gf else {}
self.gs = gs if gs else {}
self.gr = gr if gr else {}
self.gc = gc if gc else {}
super(StockholmAlignment, self).__init__(seqs, validate)
def __str__(self):
"""Parses StockholmAlignment into a string with stockholm | |
<reponame>RHolmewood/FetchRobot_Project2<gh_stars>0
# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from grasping_msgs/FindGraspableObjectsAction.msg. Do not edit."""
import codecs
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import actionlib_msgs.msg
import genpy
import geometry_msgs.msg
import grasping_msgs.msg
import moveit_msgs.msg
import sensor_msgs.msg
import shape_msgs.msg
import std_msgs.msg
import trajectory_msgs.msg
class FindGraspableObjectsAction(genpy.Message):
_md5sum = "ee328bdfce4619bf201b406a666b5877"
_type = "grasping_msgs/FindGraspableObjectsAction"
_has_header = False # flag to mark the presence of a Header object
_full_text = """# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======
FindGraspableObjectsActionGoal action_goal
FindGraspableObjectsActionResult action_result
FindGraspableObjectsActionFeedback action_feedback
================================================================================
MSG: grasping_msgs/FindGraspableObjectsActionGoal
# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======
Header header
actionlib_msgs/GoalID goal_id
FindGraspableObjectsGoal goal
================================================================================
MSG: std_msgs/Header
# Standard metadata for higher-level stamped data types.
# This is generally used to communicate timestamped data
# in a particular coordinate frame.
#
# sequence ID: consecutively increasing ID
uint32 seq
#Two-integer timestamp that is expressed as:
# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')
# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')
# time-handling sugar is provided by the client library
time stamp
#Frame this data is associated with
string frame_id
================================================================================
MSG: actionlib_msgs/GoalID
# The stamp should store the time at which this goal was requested.
# It is used by an action server when it tries to preempt all
# goals that were requested before a certain time
time stamp
# The id provides a way to associate feedback and
# result message with specific goal requests. The id
# specified must be unique.
string id
================================================================================
MSG: grasping_msgs/FindGraspableObjectsGoal
# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======
###########################################################
# This action is called for integrated object detection and
# grasp planning, such as in base_grasping_perception
# Set to false to disable grasp planning, returning only the objects found
bool plan_grasps
================================================================================
MSG: grasping_msgs/FindGraspableObjectsActionResult
# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======
Header header
actionlib_msgs/GoalStatus status
FindGraspableObjectsResult result
================================================================================
MSG: actionlib_msgs/GoalStatus
GoalID goal_id
uint8 status
uint8 PENDING = 0 # The goal has yet to be processed by the action server
uint8 ACTIVE = 1 # The goal is currently being processed by the action server
uint8 PREEMPTED = 2 # The goal received a cancel request after it started executing
# and has since completed its execution (Terminal State)
uint8 SUCCEEDED = 3 # The goal was achieved successfully by the action server (Terminal State)
uint8 ABORTED = 4 # The goal was aborted during execution by the action server due
# to some failure (Terminal State)
uint8 REJECTED = 5 # The goal was rejected by the action server without being processed,
# because the goal was unattainable or invalid (Terminal State)
uint8 PREEMPTING = 6 # The goal received a cancel request after it started executing
# and has not yet completed execution
uint8 RECALLING = 7 # The goal received a cancel request before it started executing,
# but the action server has not yet confirmed that the goal is canceled
uint8 RECALLED = 8 # The goal received a cancel request before it started executing
# and was successfully cancelled (Terminal State)
uint8 LOST = 9 # An action client can determine that a goal is LOST. This should not be
# sent over the wire by an action server
#Allow for the user to associate a string with GoalStatus for debugging
string text
================================================================================
MSG: grasping_msgs/FindGraspableObjectsResult
# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======
# Graspable objects found
GraspableObject[] objects
# Additional, non-graspable objects which may be support surfaces
Object[] support_surfaces
================================================================================
MSG: grasping_msgs/GraspableObject
###########################################################
# This message describes an object + grasp data
Object object
moveit_msgs/Grasp[] grasps
================================================================================
MSG: grasping_msgs/Object
###########################################################
# This message describes an object.
# Many of the geometric items below lack a stamp/frame_id,
# header stamp/frame_id should be used there
std_msgs/Header header
# An object might have a name
string name
# An object might have a known (named) support surface
string support_surface
# Objects might have properties, such as type/class, or color, etc.
ObjectProperty[] properties
###########################################################
# Objects have many possible descriptions
# The following are the possible description formats
# Perception modules often represent an object as a cluster of points
# Is considered valid if number of points > 0
sensor_msgs/PointCloud2 point_cluster
# MoveIt prefers solid primitives or meshes as a description of objects
shape_msgs/SolidPrimitive[] primitives
geometry_msgs/Pose[] primitive_poses
shape_msgs/Mesh[] meshes
geometry_msgs/Pose[] mesh_poses
# An object representing a support surface might be described by a plane
# Is considered valid if coefficients are not all 0s.
shape_msgs/Plane surface
================================================================================
MSG: grasping_msgs/ObjectProperty
###########################################################
# Other generic properties of an object
string name
string value
================================================================================
MSG: sensor_msgs/PointCloud2
# This message holds a collection of N-dimensional points, which may
# contain additional information such as normals, intensity, etc. The
# point data is stored as a binary blob, its layout described by the
# contents of the "fields" array.
# The point cloud data may be organized 2d (image-like) or 1d
# (unordered). Point clouds organized as 2d images may be produced by
# camera depth sensors such as stereo or time-of-flight.
# Time of sensor data acquisition, and the coordinate frame ID (for 3d
# points).
Header header
# 2D structure of the point cloud. If the cloud is unordered, height is
# 1 and width is the length of the point cloud.
uint32 height
uint32 width
# Describes the channels and their layout in the binary data blob.
PointField[] fields
bool is_bigendian # Is this data bigendian?
uint32 point_step # Length of a point in bytes
uint32 row_step # Length of a row in bytes
uint8[] data # Actual point data, size is (row_step*height)
bool is_dense # True if there are no invalid points
================================================================================
MSG: sensor_msgs/PointField
# This message holds the description of one point entry in the
# PointCloud2 message format.
uint8 INT8 = 1
uint8 UINT8 = 2
uint8 INT16 = 3
uint8 UINT16 = 4
uint8 INT32 = 5
uint8 UINT32 = 6
uint8 FLOAT32 = 7
uint8 FLOAT64 = 8
string name # Name of field
uint32 offset # Offset from start of point struct
uint8 datatype # Datatype enumeration, see above
uint32 count # How many elements in the field
================================================================================
MSG: shape_msgs/SolidPrimitive
# Define box, sphere, cylinder, cone
# All shapes are defined to have their bounding boxes centered around 0,0,0.
uint8 BOX=1
uint8 SPHERE=2
uint8 CYLINDER=3
uint8 CONE=4
# The type of the shape
uint8 type
# The dimensions of the shape
float64[] dimensions
# The meaning of the shape dimensions: each constant defines the index in the 'dimensions' array
# For the BOX type, the X, Y, and Z dimensions are the length of the corresponding
# sides of the box.
uint8 BOX_X=0
uint8 BOX_Y=1
uint8 BOX_Z=2
# For the SPHERE type, only one component is used, and it gives the radius of
# the sphere.
uint8 SPHERE_RADIUS=0
# For the CYLINDER and CONE types, the center line is oriented along
# the Z axis. Therefore the CYLINDER_HEIGHT (CONE_HEIGHT) component
# of dimensions gives the height of the cylinder (cone). The
# CYLINDER_RADIUS (CONE_RADIUS) component of dimensions gives the
# radius of the base of the cylinder (cone). Cone and cylinder
# primitives are defined to be circular. The tip of the cone is
# pointing up, along +Z axis.
uint8 CYLINDER_HEIGHT=0
uint8 CYLINDER_RADIUS=1
uint8 CONE_HEIGHT=0
uint8 CONE_RADIUS=1
================================================================================
MSG: geometry_msgs/Pose
# A representation of pose in free space, composed of position and orientation.
Point position
Quaternion orientation
================================================================================
MSG: geometry_msgs/Point
# This contains the position of a point in free space
float64 x
float64 y
float64 z
================================================================================
MSG: geometry_msgs/Quaternion
# This represents an orientation in free space in quaternion form.
float64 x
float64 y
float64 z
float64 w
================================================================================
MSG: shape_msgs/Mesh
# Definition of a mesh
# list of triangles; the index values refer to positions in vertices[]
MeshTriangle[] triangles
# the actual vertices that make up the mesh
geometry_msgs/Point[] vertices
================================================================================
MSG: shape_msgs/MeshTriangle
# Definition of a triangle's vertices
uint32[3] vertex_indices
================================================================================
MSG: shape_msgs/Plane
# Representation of a plane, using the plane equation ax + by + cz + d = 0
# a := coef[0]
# b := coef[1]
# c := coef[2]
# d := coef[3]
float64[4] coef
================================================================================
MSG: moveit_msgs/Grasp
# This message contains a description of a grasp that would be used
# with a particular end-effector to grasp an object, including how to
# approach it, grip it, etc. This message does not contain any
# information about a "grasp point" (a position ON the object).
# Whatever generates this message should have already combined
# information about grasp points with information about the geometry
# of the end-effector to compute the grasp_pose in this message.
# A name for this grasp
string id
# The internal posture of the hand for the pre-grasp
# only positions are used
trajectory_msgs/JointTrajectory pre_grasp_posture
# The internal posture of the hand for the grasp
# positions and efforts are used
trajectory_msgs/JointTrajectory grasp_posture
# The position of the end-effector for the grasp. This is the pose of
# the "parent_link" of the end-effector, not | |
'''
datetime.tzinfo timezone definitions generated from the
Olson timezone database:
ftp://elsie.nci.nih.gov/pub/tz*.tar.gz
See the datetime section of the Python Library Reference for information
on how to use these modules.
'''
# The IANA (nee Olson) database is updated several times a year.
OLSON_VERSION = '2016j'
VERSION = '2016.10' # Switching to pip compatible version numbering.
__version__ = VERSION
OLSEN_VERSION = OLSON_VERSION # Old releases had this misspelling
__all__ = [
'timezone', 'utc', 'country_timezones', 'country_names',
'AmbiguousTimeError', 'InvalidTimeError',
'NonExistentTimeError', 'UnknownTimeZoneError',
'all_timezones', 'all_timezones_set',
'common_timezones', 'common_timezones_set',
]
import sys, datetime, os.path, gettext
from pytz.exceptions import AmbiguousTimeError
from pytz.exceptions import InvalidTimeError
from pytz.exceptions import NonExistentTimeError
from pytz.exceptions import UnknownTimeZoneError
from pytz.lazy import LazyDict, LazyList, LazySet
from pytz.tzinfo import unpickler
from pytz.tzfile import build_tzinfo, _byte_string
try:
unicode
except NameError: # Python 3.x
# Python 3.x doesn't have unicode(), making writing code
# for Python 2.3 and Python 3.x a pain.
unicode = str
def ascii(s):
r"""
>>> ascii('Hello')
'Hello'
>>> ascii('\N{TRADE MARK SIGN}') #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
UnicodeEncodeError: ...
"""
s.encode('ASCII') # Raise an exception if not ASCII
return s # But return the original string - not a byte string.
else: # Python 2.x
def ascii(s):
r"""
>>> ascii('Hello')
'Hello'
>>> ascii(u'Hello')
'Hello'
>>> ascii(u'\N{TRADE MARK SIGN}') #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
UnicodeEncodeError: ...
"""
return s.encode('ASCII')
_tzinfo_dir = os.getenv("TZDIR") or "/usr/share/zoneinfo"
if _tzinfo_dir.endswith(os.sep):
_tzinfo_dir = _tzinfo_dir[:-1]
def open_resource(name):
"""Open a resource from the zoneinfo subdir for reading.
Uses the pkg_resources module if available and no standard file
found at the calculated location.
"""
name_parts = name.lstrip('/').split('/')
for part in name_parts:
if part == os.path.pardir or os.path.sep in part:
raise ValueError('Bad path segment: %r' % part)
filename = os.path.join(_tzinfo_dir, *name_parts)
return open(filename, 'rb')
def resource_exists(name):
"""Return true if the given resource exists"""
try:
open_resource(name).close()
return True
except IOError:
return False
# Enable this when we get some translations?
# We want an i18n API that is useful to programs using Python's gettext
# module, as well as the Zope3 i18n package. Perhaps we should just provide
# the POT file and translations, and leave it up to callers to make use
# of them.
#
# t = gettext.translation(
# 'pytz', os.path.join(os.path.dirname(__file__), 'locales'),
# fallback=True
# )
# def _(timezone_name):
# """Translate a timezone name using the current locale, returning Unicode"""
# return t.ugettext(timezone_name)
_tzinfo_cache = {}
def timezone(zone):
r''' Return a datetime.tzinfo implementation for the given timezone
>>> from datetime import datetime, timedelta
>>> utc = timezone('UTC')
>>> eastern = timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
>>> timezone(unicode('US/Eastern')) is eastern
True
>>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)
>>> loc_dt = utc_dt.astimezone(eastern)
>>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'
>>> loc_dt.strftime(fmt)
'2002-10-27 01:00:00 EST (-0500)'
>>> (loc_dt - timedelta(minutes=10)).strftime(fmt)
'2002-10-27 00:50:00 EST (-0500)'
>>> eastern.normalize(loc_dt - timedelta(minutes=10)).strftime(fmt)
'2002-10-27 01:50:00 EDT (-0400)'
>>> (loc_dt + timedelta(minutes=10)).strftime(fmt)
'2002-10-27 01:10:00 EST (-0500)'
Raises UnknownTimeZoneError if passed an unknown zone.
>>> try:
... timezone('Asia/Shangri-La')
... except UnknownTimeZoneError:
... print('Unknown')
Unknown
>>> try:
... timezone(unicode('\N{TRADE MARK SIGN}'))
... except UnknownTimeZoneError:
... print('Unknown')
Unknown
'''
if zone.upper() == 'UTC':
return utc
try:
zone = ascii(zone)
except UnicodeEncodeError:
# All valid timezones are ASCII
raise UnknownTimeZoneError(zone)
zone = _unmunge_zone(zone)
if zone not in _tzinfo_cache:
if zone in all_timezones_set:
fp = open_resource(zone)
try:
_tzinfo_cache[zone] = build_tzinfo(zone, fp)
finally:
fp.close()
else:
raise UnknownTimeZoneError(zone)
return _tzinfo_cache[zone]
def _unmunge_zone(zone):
"""Undo the time zone name munging done by older versions of pytz."""
return zone.replace('_plus_', '+').replace('_minus_', '-')
ZERO = datetime.timedelta(0)
HOUR = datetime.timedelta(hours=1)
class UTC(datetime.tzinfo):
"""UTC
Optimized UTC implementation. It unpickles using the single module global
instance defined beneath this class declaration.
"""
zone = "UTC"
_utcoffset = ZERO
_dst = ZERO
_tzname = zone
def fromutc(self, dt):
if dt.tzinfo is None:
return self.localize(dt)
return super(utc.__class__, self).fromutc(dt)
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
def __reduce__(self):
return _UTC, ()
def localize(self, dt, is_dst=False):
'''Convert naive time to local time'''
if dt.tzinfo is not None:
raise ValueError('Not naive datetime (tzinfo is already set)')
return dt.replace(tzinfo=self)
def normalize(self, dt, is_dst=False):
'''Correct the timezone information on the given datetime'''
if dt.tzinfo is self:
return dt
if dt.tzinfo is None:
raise ValueError('Naive time - no tzinfo set')
return dt.astimezone(self)
def __repr__(self):
return "<UTC>"
def __str__(self):
return "UTC"
UTC = utc = UTC() # UTC is a singleton
def _UTC():
"""Factory function for utc unpickling.
Makes sure that unpickling a utc instance always returns the same
module global.
These examples belong in the UTC class above, but it is obscured; or in
the README.txt, but we are not depending on Python 2.4 so integrating
the README.txt examples with the unit tests is not trivial.
>>> import datetime, pickle
>>> dt = datetime.datetime(2005, 3, 1, 14, 13, 21, tzinfo=utc)
>>> naive = dt.replace(tzinfo=None)
>>> p = pickle.dumps(dt, 1)
>>> naive_p = pickle.dumps(naive, 1)
>>> len(p) - len(naive_p)
17
>>> new = pickle.loads(p)
>>> new == dt
True
>>> new is dt
False
>>> new.tzinfo is dt.tzinfo
True
>>> utc is UTC is timezone('UTC')
True
>>> utc is timezone('GMT')
False
"""
return utc
_UTC.__safe_for_unpickling__ = True
def _p(*args):
"""Factory function for unpickling pytz tzinfo instances.
Just a wrapper around tzinfo.unpickler to save a few bytes in each pickle
by shortening the path.
"""
return unpickler(*args)
_p.__safe_for_unpickling__ = True
class _CountryTimezoneDict(LazyDict):
"""Map ISO 3166 country code to a list of timezone names commonly used
in that country.
iso3166_code is the two letter code used to identify the country.
>>> def print_list(list_of_strings):
... 'We use a helper so doctests work under Python 2.3 -> 3.x'
... for s in list_of_strings:
... print(s)
>>> print_list(country_timezones['nz'])
Pacific/Auckland
Pacific/Chatham
>>> print_list(country_timezones['ch'])
Europe/Zurich
>>> print_list(country_timezones['CH'])
Europe/Zurich
>>> print_list(country_timezones[unicode('ch')])
Europe/Zurich
>>> print_list(country_timezones['XXX'])
Traceback (most recent call last):
...
KeyError: 'XXX'
Previously, this information was exposed as a function rather than a
dictionary. This is still supported::
>>> print_list(country_timezones('nz'))
Pacific/Auckland
Pacific/Chatham
"""
def __call__(self, iso3166_code):
"""Backwards compatibility."""
return self[iso3166_code]
def _fill(self):
data = {}
zone_tab = open_resource('zone.tab')
try:
for line in zone_tab:
line = line.decode('UTF-8')
if line.startswith('#'):
continue
code, coordinates, zone = line.split(None, 4)[:3]
if zone not in all_timezones_set:
continue
try:
data[code].append(zone)
except KeyError:
data[code] = [zone]
self.data = data
finally:
zone_tab.close()
country_timezones = _CountryTimezoneDict()
class _CountryNameDict(LazyDict):
'''Dictionary proving ISO3166 code -> English name.
>>> print(country_names['au'])
Australia
'''
def _fill(self):
data = {}
zone_tab = open_resource('iso3166.tab')
try:
for line in zone_tab.readlines():
line = line.decode('UTF-8')
if line.startswith('#'):
continue
code, name = line.split(None, 1)
data[code] = name.strip()
self.data = data
finally:
zone_tab.close()
country_names = _CountryNameDict()
# Time-zone info based solely on fixed offsets
class _FixedOffset(datetime.tzinfo):
zone = None # to match the standard pytz API
def __init__(self, minutes):
if abs(minutes) >= 1440:
raise ValueError("absolute offset is too large", minutes)
self._minutes = minutes
self._offset = datetime.timedelta(minutes=minutes)
def utcoffset(self, dt):
return self._offset
def __reduce__(self):
return FixedOffset, (self._minutes, )
def dst(self, dt):
return ZERO
def tzname(self, dt):
return None
def __repr__(self):
return 'pytz.FixedOffset(%d)' % self._minutes
def localize(self, dt, is_dst=False):
'''Convert naive time to local time'''
if dt.tzinfo is not None:
raise ValueError('Not naive datetime (tzinfo is already set)')
return dt.replace(tzinfo=self)
def normalize(self, dt, is_dst=False):
'''Correct the timezone information on the given datetime'''
if dt.tzinfo is self:
return dt
if dt.tzinfo is None:
raise ValueError('Naive time - no tzinfo set')
return dt.astimezone(self)
def FixedOffset(offset, _tzinfos = {}):
"""return a fixed-offset timezone based off a number of minutes.
>>> one = FixedOffset(-330)
>>> one
pytz.FixedOffset(-330)
>>> one.utcoffset(datetime.datetime.now())
datetime.timedelta(-1, 66600)
>>> one.dst(datetime.datetime.now())
datetime.timedelta(0)
>>> two = FixedOffset(1380)
>>> two
pytz.FixedOffset(1380)
>>> two.utcoffset(datetime.datetime.now())
datetime.timedelta(0, 82800)
>>> two.dst(datetime.datetime.now())
datetime.timedelta(0)
The datetime.timedelta must be between the range of -1 and 1 day,
non-inclusive.
>>> FixedOffset(1440)
Traceback (most recent call last):
...
ValueError: ('absolute offset is too large', 1440)
>>> FixedOffset(-1440)
Traceback (most recent call last):
...
ValueError: ('absolute offset is too large', -1440)
An offset of 0 is special-cased to return UTC.
>>> FixedOffset(0) is UTC
True
There should always be only one instance of a FixedOffset per timedelta.
This should be true for multiple creation calls.
>>> FixedOffset(-330) is one
True
>>> FixedOffset(1380) is two
True
It should also be true for pickling.
>>> import pickle
>>> pickle.loads(pickle.dumps(one)) is one
True
>>> pickle.loads(pickle.dumps(two)) is | |
'24' in question:
pass
else:
break
if candidate in question:
anno_value = candidate
break
if anno_type == '流量' or anno_type == '价格':
l, r = anno_start_index, anno_index
while r < len(question) and question[r] == '0':
anno_value = anno_value + '0'
r += 1
while l > 0 and question[l-1].isdigit():
anno_value = question[l-1] + anno_value
l -= 1
if anno_type not in anno_map:
anno_map[anno_type] = []
# 去除 同一个属性值 出现两次的现象(如果是合约版(比较句出现)、20(价格20流量20)、18(train.xlsx出现),则是正常现象)
# enhence版 不需要去重
# if anno_value in anno_map[anno_type]:
# if anno_value == '合约版' or anno_value == '20' or anno_value == '18':
# pass
# else: continue
anno_map[anno_type].append([anno_value, pos])
return anno_map
def pred_collate_fn(batch_data):
"""
用于用于预测的collate函数
:param batch_data:
:return:
"""
input_ids, token_type_ids, attention_mask = [], [], []
questions = []
for instance in copy.deepcopy(batch_data):
questions.append(instance['question'])
input_ids.append(instance['token']['input_ids'][0].squeeze(0))
token_type_ids.append(instance['token']['token_type_ids'][0].squeeze(0))
attention_mask.append(instance['token']['attention_mask'][0].squeeze(0))
return torch.stack(input_ids), torch.stack(token_type_ids), \
torch.stack(attention_mask), questions
def bert_collate_fn(batch_data):
"""
用于BERT训练的collate函数
:param batch_data:
:return:
"""
input_ids, token_type_ids, attention_mask = [], [], []
ans_labels, prop_labels, entity_labels = [], [], []
efficiency_list = []
for instance in copy.deepcopy(batch_data):
input_ids.append(instance['token']['input_ids'][0].squeeze(0))
token_type_ids.append(instance['token']['token_type_ids'][0].squeeze(0))
attention_mask.append(instance['token']['attention_mask'][0].squeeze(0))
ans_labels.append(instance['ans_label'])
prop_labels.append(torch.tensor(instance['prop_label']))
entity_labels.append(instance['entity_label'])
efficiency_list.append(instance['efficiency'])
return torch.stack(input_ids), torch.stack(token_type_ids), \
torch.stack(attention_mask), torch.tensor(ans_labels), \
torch.stack(prop_labels), torch.tensor(entity_labels), \
torch.tensor(efficiency_list, dtype=torch.float)
def binary_collate_fn(batch_data):
"""
用于二类训练的collate函数
"""
input_ids, token_type_ids, attention_mask = [], [], []
labels = []
efficiency_list = []
for instance in copy.deepcopy(batch_data):
input_ids.append(instance['token']['input_ids'][0].squeeze(0))
token_type_ids.append(instance['token']['token_type_ids'][0].squeeze(0))
attention_mask.append(instance['token']['attention_mask'][0].squeeze(0))
labels.append(instance['label'])
efficiency_list.append(instance['efficiency'])
return torch.stack(input_ids), torch.stack(token_type_ids), \
torch.stack(attention_mask), torch.tensor(labels), \
torch.tensor(efficiency_list, dtype=torch.float)
class LabelHub(object):
"""
分类任务的Label数据中心
"""
def __init__(self, label_file):
super(LabelHub, self).__init__()
self.label_file = label_file
self.ans_label2id = {}
self.ans_id2label = {}
self.prop_label2id = {}
self.prop_id2label = {}
self.entity_label2id = {}
self.entity_id2label = {}
self.binary_label2id = {}
self.binary_id2label = {}
self.load_label()
def load_label(self):
with open(self.label_file, 'r', encoding='utf-8') as f:
label_dict = json.load(f)
self.ans_label2id = label_dict['ans_type']
self.prop_label2id = label_dict['main_property']
self.entity_label2id = label_dict['entity']
self.binary_label2id = label_dict['binary_type']
for k, v in self.ans_label2id.items():
self.ans_id2label[v] = k
for k, v in self.prop_label2id.items():
self.prop_id2label[v] = k
for k, v in self.entity_label2id.items():
self.entity_id2label[v] = k
for k, v in self.binary_label2id.items():
self.binary_id2label[v] = k
def create_test_BIEO(excel_path, test = True):
"""
由excel生成对应的bieo标注,并保存,同时测试标注方法的准确性
@param excel_path: 数据路径
@return:
"""
def get_bieo(data):
'''
得到bmes
:param data: train_denoised.xlsx的dataframe
:return: dict ['question': ['O','B','E']]
'''
# TODO
# 标注失败:最便宜最优惠的标注 应该为 价格1;
# 三十、四十、 十元(先改三十元)、 六块、 一个月
# 有效期太少了
type_map = {'价格': 'PRICE', '流量': 'FLOW', '子业务': 'SERVICE'}
result_dict = {}
for index, row in data.iterrows():
question = row['用户问题']
char_list = ['O' for _ in range(len(question))]
constraint_names = row['约束属性名']
constraint_values = row['约束属性值']
constraint_names_list = re.split(r'[|\|]', str(constraint_names))
constraint_values_list = re.split(r'[|\|]', str(constraint_values))
constraint_names_list = [name.strip() for name in constraint_names_list]
constraint_values_list = [value.strip() for value in constraint_values_list]
question_len = len(question)
question_index = 0
# 在句子中标注constraint
for cons_index in range(len(constraint_values_list)):
name = constraint_names_list[cons_index]
if name == '有效期': continue
value = constraint_values_list[cons_index]
if value in question[question_index:]:
temp_index = question[question_index:].find(value) + question_index
if len(value) == 1:
char_list[temp_index] = 'S-' + type_map[name]
continue
else:
for temp_i in range(temp_index + 1, temp_index + len(value) - 1):
char_list[temp_i] = 'I-' + type_map[name]
char_list[temp_index] = 'B-' + type_map[name]
char_list[temp_index + len(value) - 1] = 'E-' + type_map[name]
question_index = min(temp_index + len(value), question_len)
elif value in question:
temp_index = question.find(value)
if len(value) == 1:
char_list[temp_index] = 'S-' + type_map[name]
continue
else:
for temp_i in range(temp_index + 1, temp_index + len(value) - 1):
char_list[temp_i] = 'I-' + type_map[name]
char_list[temp_index] = 'B-' + type_map[name]
char_list[temp_index + len(value) - 1] = 'E-' + type_map[name]
result_dict[question] = char_list
return result_dict
def test_bieo(excel_data):
'''
用来测试正则化生成的bieo相比于excel中的真值,准确度如何
:param: excel中读取的dataframe
:return:
'''
annos = get_bieo(excel_data)
TP, TN, FP = 0, 0, 0
for index, row in excel_data.iterrows():
question = row['用户问题']
# 获取约束的标注
anno_list = annos[question]
anno_dict = get_anno_dict(question, anno_list)
# 获取约束的真值
constraint_names = row['约束属性名']
constraint_values = row['约束属性值']
constraint_names_list = re.split(r'[|\|]', str(constraint_names))
constraint_values_list = re.split(r'[|\|]', str(constraint_values))
constraint_dict = {}
for constraint_index in range(len(constraint_names_list)):
constraint_name = constraint_names_list[constraint_index].strip()
if constraint_name == '有效期': continue
constraint_value = constraint_values_list[constraint_index].strip()
if constraint_name not in constraint_dict:
constraint_dict[constraint_name] = []
constraint_dict[constraint_name].append(constraint_value)
# 比较约束的真值和标注
tp = 0
anno_kv = []
constraint_kv = []
for k, vs in anno_dict.items():
for v in vs:
anno_kv.append(k + v)
for k, vs in constraint_dict.items():
for v in vs:
constraint_kv.append(k + v)
# 排除 二者均为空 的情况和 比较句 的情况
if len(anno_kv) == 0 and constraint_kv[0] == 'nannan': continue
if len(anno_kv) == 0 and (constraint_kv[0] == '价格1' or constraint_kv[0] == '流量1'): continue
anno_len = len(anno_kv)
cons_len = len(constraint_kv)
for kv in constraint_kv:
if kv in anno_kv:
tp += 1
anno_kv.remove(kv)
if tp != cons_len:
print('-------')
print(question)
print('anno: ', anno_kv)
print('cons: ', constraint_kv)
TP += tp
FP += (cons_len - tp)
TN += (anno_len - tp)
print('测试bmes结果:' + 'TP: {} FP: {} TN:{} '.format(TP, FP, TN))
def add_lost_anno(bieo_dict):
from triples import KnowledgeGraph
kg = KnowledgeGraph('../data/process_data/triples.rdf')
df = pd.read_excel('../data/raw_data/train_denoised.xlsx')
df.fillna('')
id_list = set()
ans_list = []
for iter, row in df.iterrows():
ans_true = list(set(row['答案'].split('|')))
question = row['用户问题']
ans_type = row['答案类型']
# 只对属性值的句子做处理
if ans_type != '属性值':
continue
entity = row['实体']
main_property = row['属性名'].split('|')
# 排除属性中没有'-'的情况,只要'档位介绍-xx'的情况
if '-' not in main_property[0]:
continue
operator = row['约束算子']
# 排除operator为min或max的情况
if operator != 'min' and operator != 'max':
operator == 'other'
else:
continue
sub_properties = {}
cons_names = str(row['约束属性名']).split('|')
cons_values = str(row['约束属性值']).split('|')
if cons_names == ['nan']: cons_names = []
for index in range(len(cons_names)):
if cons_names[index] not in sub_properties:
sub_properties[cons_names[index]] = []
sub_properties[cons_names[index]].append(cons_values[index])
price_ans, flow_ans, service_ans = kg.fetch_wrong_ans(question, ans_type, entity, main_property, operator,
[])
rdf_properties = {}
rdf_properties['价格'] = price_ans
rdf_properties['流量'] = flow_ans
rdf_properties['子业务'] = service_ans
compare_result = []
for name, values in rdf_properties.items():
for value in values:
if value in question:
if name in sub_properties and value in sub_properties[name]:
continue
elif name in sub_properties:
if value == '年包' and '半年包' in sub_properties[name]:
continue
if value == '百度' and '百度包' in sub_properties[name]:
continue
elif value in entity:
continue
else:
compare_result.append(name + '_' + value)
id_list.add(iter)
if compare_result != []:
ans_list.append(compare_result)
raw_data = pd.read_excel(excel_path)
if test:
test_bieo(raw_data)
bieo_dict = get_bieo(raw_data)
with open(r'../data/file/train_bieo.json', 'w') as f:
json.dump(bieo_dict, f, indent=2, ensure_ascii=False)
return bieo_dict
def create_test_BIO(excel_path, test = True):
"""
由excel生成对应的BIO标注,并保存,同时测试标注方法的准确性
@param excel_path: 数据路径
@return:
"""
def get_bio(data):
'''
得到bmes
:param data: train_denoised.xlsx的dataframe
:return: dict ['question': ['O','B','I']]
'''
# TODO
# 标注失败:最便宜最优惠的标注 应该为 价格1;
# 三十、四十、 十元(先改三十元)、 六块、 一个月
# 有效期太少了 可用规则处理
type_map = {'价格': 'PRICE', '流量': 'FLOW', '子业务': 'SERVICE'}
result_dict = {}
for index, row in data.iterrows():
question = row['用户问题']
char_list = ['O' for _ in range(len(question))]
constraint_names = row['约束属性名']
constraint_values = row['约束属性值']
constraint_names_list = re.split(r'[|\|]', str(constraint_names))
constraint_values_list = re.split(r'[|\|]', str(constraint_values))
constraint_names_list = [name.strip() for name in constraint_names_list]
constraint_values_list = [value.strip() for value in constraint_values_list]
question_len = len(question)
question_index = 0
# 在句子中标注constraint
for cons_index in range(len(constraint_values_list)):
name = constraint_names_list[cons_index]
if name == '有效期':
continue
value = constraint_values_list[cons_index]
if value in question[question_index:]:
temp_index = question[question_index:].find(value) + question_index
char_list[temp_index] = 'B-' + type_map[name]
for temp_i in range(temp_index + 1, temp_index + len(value)):
char_list[temp_i] = 'I-' + type_map[name]
question_index = min(temp_index + len(value), question_len)
elif value in question:
temp_index = question.find(value)
if char_list[temp_index] == 'O':
char_list[temp_index] = 'B-' + type_map[name]
for temp_i in range(temp_index + 1, temp_index + len(value)):
if char_list[temp_i] == 'O':
char_list[temp_i] = 'I-' + type_map[name]
else:
print('标注冲突:"{}"'.format(question))
break
else:
print('标注冲突。"{}"'.format(question))
result_dict[question] = char_list
return result_dict
def test_bio(excel_data):
'''
用来测试正则化生成的BIO相比于excel中的真值,准确度如何
:param: excel中读取的dataframe
:return:
'''
annos = get_bio(excel_data)
TP, TN, FP = 0, 0, 0
for index, row in excel_data.iterrows():
question = row['用户问题']
# 获取约束的标注
anno_list = annos[question]
anno_dict = get_anno_dict(question, anno_list)
# 获取约束的真值
constraint_names = row['约束属性名']
constraint_values = row['约束属性值']
constraint_names_list = re.split(r'[|\|]', str(constraint_names))
constraint_values_list = re.split(r'[|\|]', str(constraint_values))
constraint_dict = {}
for constraint_index in range(len(constraint_names_list)):
constraint_name = constraint_names_list[constraint_index].strip()
if constraint_name == '有效期':
continue
constraint_value = constraint_values_list[constraint_index].strip()
if constraint_name not in constraint_dict:
constraint_dict[constraint_name] = []
constraint_dict[constraint_name].append(constraint_value)
# 比较约束的真值和标注
tp = 0
anno_kv = []
constraint_kv = []
for k, vs in anno_dict.items():
for v in vs:
anno_kv.append(k + v)
for k, vs in constraint_dict.items():
for v in vs:
constraint_kv.append(k + v)
# 排除 二者均为空 的情况和 比较句 的情况
if len(anno_kv) == 0 and constraint_kv[0] == 'nannan':
continue
if len(anno_kv) == 0 and (constraint_kv[0] == '价格1' or constraint_kv[0] == '流量1'):
continue
anno_len = len(anno_kv)
cons_len = len(constraint_kv)
for kv in constraint_kv:
if kv in anno_kv:
tp += 1
anno_kv.remove(kv)
if tp | |
550
},
"7": {
"level": 7,
"exp": 500,
"cost": 0,
"order_good_min": 1,
"order_good_max": 3,
"order_refresh_min": 120,
"order_refresh_max": 120,
"worker_gold": 0.7,
"video_gold": 600
},
"8": {
"level": 8,
"exp": 600,
"cost": 0,
"order_good_min": 1,
"order_good_max": 3,
"order_refresh_min": 120,
"order_refresh_max": 120,
"worker_gold": 0.8,
"video_gold": 650
},
"9": {
"level": 9,
"exp": 700,
"cost": 0,
"order_good_min": 1,
"order_good_max": 3,
"order_refresh_min": 120,
"order_refresh_max": 120,
"worker_gold": 0.9,
"video_gold": 700
},
"10": {
"level": 10,
"exp": 800,
"cost": 500,
"order_good_min": 1,
"order_good_max": 5,
"order_refresh_min": 120,
"order_refresh_max": 120,
"worker_gold": 1,
"video_gold": 750
},
"11": {
"level": 11,
"exp": 900,
"cost": 1000,
"order_good_min": 1,
"order_good_max": 5,
"order_refresh_min": 120,
"order_refresh_max": 120,
"worker_gold": 1.1,
"video_gold": 800
},
"12": {
"level": 12,
"exp": 1000,
"cost": 1500,
"order_good_min": 1,
"order_good_max": 5,
"order_refresh_min": 120,
"order_refresh_max": 120,
"worker_gold": 1.2,
"video_gold": 850
},
"13": {
"level": 13,
"exp": 1200,
"cost": 2000,
"order_good_min": 1,
"order_good_max": 5,
"order_refresh_min": 120,
"order_refresh_max": 120,
"worker_gold": 1.3,
"video_gold": 900
},
"14": {
"level": 14,
"exp": 1400,
"cost": 2500,
"order_good_min": 1,
"order_good_max": 5,
"order_refresh_min": 120,
"order_refresh_max": 120,
"worker_gold": 1.4,
"video_gold": 950
},
"15": {
"level": 15,
"exp": 1600,
"cost": 3000,
"order_good_min": 1,
"order_good_max": 5,
"order_refresh_min": 120,
"order_refresh_max": 120,
"worker_gold": 1.5,
"video_gold": 1000
},
"16": {
"level": 16,
"exp": 1800,
"cost": 3500,
"order_good_min": 1,
"order_good_max": 5,
"order_refresh_min": 120,
"order_refresh_max": 300,
"worker_gold": 1.6,
"video_gold": 1050
},
"17": {
"level": 17,
"exp": 2000,
"cost": 4000,
"order_good_min": 1,
"order_good_max": 5,
"order_refresh_min": 120,
"order_refresh_max": 300,
"worker_gold": 1.7,
"video_gold": 1100
},
"18": {
"level": 18,
"exp": 2200,
"cost": 4500,
"order_good_min": 1,
"order_good_max": 5,
"order_refresh_min": 120,
"order_refresh_max": 300,
"worker_gold": 1.8,
"video_gold": 1150
},
"19": {
"level": 19,
"exp": 2400,
"cost": 5000,
"order_good_min": 1,
"order_good_max": 5,
"order_refresh_min": 120,
"order_refresh_max": 300,
"worker_gold": 1.9,
"video_gold": 1200
},
"20": {
"level": 20,
"exp": 2600,
"cost": 5500,
"order_good_min": 1,
"order_good_max": 10,
"order_refresh_min": 120,
"order_refresh_max": 300,
"worker_gold": 2,
"video_gold": 1250
},
"21": {
"level": 21,
"exp": 2800,
"cost": 6000,
"order_good_min": 1,
"order_good_max": 10,
"order_refresh_min": 120,
"order_refresh_max": 300,
"worker_gold": 2.1,
"video_gold": 1300
},
"22": {
"level": 22,
"exp": 3000,
"cost": 6500,
"order_good_min": 1,
"order_good_max": 10,
"order_refresh_min": 120,
"order_refresh_max": 300,
"worker_gold": 2.2,
"video_gold": 1350
},
"23": {
"level": 23,
"exp": 3500,
"cost": 7000,
"order_good_min": 1,
"order_good_max": 10,
"order_refresh_min": 120,
"order_refresh_max": 300,
"worker_gold": 2.3,
"video_gold": 1400
},
"24": {
"level": 24,
"exp": 4000,
"cost": 7500,
"order_good_min": 1,
"order_good_max": 10,
"order_refresh_min": 120,
"order_refresh_max": 300,
"worker_gold": 2.4,
"video_gold": 1450
},
"25": {
"level": 25,
"exp": 4500,
"cost": 8000,
"order_good_min": 1,
"order_good_max": 10,
"order_refresh_min": 120,
"order_refresh_max": 300,
"worker_gold": 2.5,
"video_gold": 1500
},
"26": {
"level": 26,
"exp": 5000,
"cost": 8500,
"order_good_min": 1,
"order_good_max": 10,
"order_refresh_min": 120,
"order_refresh_max": 300,
"worker_gold": 2.6,
"video_gold": 1550
},
"27": {
"level": 27,
"exp": 5500,
"cost": 9000,
"order_good_min": 1,
"order_good_max": 10,
"order_refresh_min": 120,
"order_refresh_max": 300,
"worker_gold": 2.7,
"video_gold": 1600
},
"28": {
"level": 28,
"exp": 6000,
"cost": 9500,
"order_good_min": 1,
"order_good_max": 10,
"order_refresh_min": 120,
"order_refresh_max": 300,
"worker_gold": 2.8,
"video_gold": 1650
},
"29": {
"level": 29,
"exp": 6500,
"cost": 10000,
"order_good_min": 1,
"order_good_max": 10,
"order_refresh_min": 120,
"order_refresh_max": 300,
"worker_gold": 2.9,
"video_gold": 1700
},
"30": {
"level": 30,
"exp": 7000,
"cost": 11000,
"order_good_min": 2,
"order_good_max": 15,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 3,
"video_gold": 1750
},
"31": {
"level": 31,
"exp": 7500,
"cost": 12000,
"order_good_min": 2,
"order_good_max": 15,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 3.1,
"video_gold": 1800
},
"32": {
"level": 32,
"exp": 8000,
"cost": 13000,
"order_good_min": 2,
"order_good_max": 15,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 3.2,
"video_gold": 1850
},
"33": {
"level": 33,
"exp": 8500,
"cost": 14000,
"order_good_min": 2,
"order_good_max": 15,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 3.3,
"video_gold": 1900
},
"34": {
"level": 34,
"exp": 9000,
"cost": 15000,
"order_good_min": 2,
"order_good_max": 15,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 3.4,
"video_gold": 1950
},
"35": {
"level": 35,
"exp": 9500,
"cost": 16000,
"order_good_min": 2,
"order_good_max": 15,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 3.5,
"video_gold": 2000
},
"36": {
"level": 36,
"exp": 10000,
"cost": 17000,
"order_good_min": 2,
"order_good_max": 15,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 3.6,
"video_gold": 2050
},
"37": {
"level": 37,
"exp": 11000,
"cost": 18000,
"order_good_min": 2,
"order_good_max": 15,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 3.7,
"video_gold": 2100
},
"38": {
"level": 38,
"exp": 12000,
"cost": 19000,
"order_good_min": 2,
"order_good_max": 15,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 3.8,
"video_gold": 2150
},
"39": {
"level": 39,
"exp": 13000,
"cost": 20000,
"order_good_min": 2,
"order_good_max": 15,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 3.9,
"video_gold": 2200
},
"40": {
"level": 40,
"exp": 14000,
"cost": 21000,
"order_good_min": 2,
"order_good_max": 15,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 4,
"video_gold": 2250
},
"41": {
"level": 41,
"exp": 15000,
"cost": 22000,
"order_good_min": 2,
"order_good_max": 15,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 4.1,
"video_gold": 2300
},
"42": {
"level": 42,
"exp": 16000,
"cost": 23000,
"order_good_min": 2,
"order_good_max": 15,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 4.2,
"video_gold": 2350
},
"43": {
"level": 43,
"exp": 17000,
"cost": 24000,
"order_good_min": 2,
"order_good_max": 15,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 4.3,
"video_gold": 2400
},
"44": {
"level": 44,
"exp": 18000,
"cost": 25000,
"order_good_min": 2,
"order_good_max": 15,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 4.4,
"video_gold": 2450
},
"45": {
"level": 45,
"exp": 19000,
"cost": 26000,
"order_good_min": 2,
"order_good_max": 15,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 4.5,
"video_gold": 2500
},
"46": {
"level": 46,
"exp": 20000,
"cost": 27000,
"order_good_min": 2,
"order_good_max": 15,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 4.6,
"video_gold": 2550
},
"47": {
"level": 47,
"exp": 21000,
"cost": 28000,
"order_good_min": 2,
"order_good_max": 15,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 4.7,
"video_gold": 2600
},
"48": {
"level": 48,
"exp": 22000,
"cost": 29000,
"order_good_min": 2,
"order_good_max": 15,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 4.8,
"video_gold": 2650
},
"49": {
"level": 49,
"exp": 23000,
"cost": 30000,
"order_good_min": 2,
"order_good_max": 15,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 4.9,
"video_gold": 2700
},
"50": {
"level": 50,
"exp": 24000,
"cost": 31000,
"order_good_min": 2,
"order_good_max": 20,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 5,
"video_gold": 2750
},
"51": {
"level": 51,
"exp": 25000,
"cost": 32000,
"order_good_min": 2,
"order_good_max": 20,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 5.1,
"video_gold": 2800
},
"52": {
"level": 52,
"exp": 26000,
"cost": 33000,
"order_good_min": 2,
"order_good_max": 20,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 5.2,
"video_gold": 2850
},
"53": {
"level": 53,
"exp": 27000,
"cost": 34000,
"order_good_min": 2,
"order_good_max": 20,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 5.3,
"video_gold": 2900
},
"54": {
"level": 54,
"exp": 28000,
"cost": 35000,
"order_good_min": 2,
"order_good_max": 20,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 5.4,
"video_gold": 2950
},
"55": {
"level": 55,
"exp": 29000,
"cost": 36000,
"order_good_min": 2,
"order_good_max": 20,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 5.5,
"video_gold": 3000
},
"56": {
"level": 56,
"exp": 30000,
"cost": 37000,
"order_good_min": 2,
"order_good_max": 20,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 5.6,
"video_gold": 3050
},
"57": {
"level": 57,
"exp": 31000,
"cost": 38000,
"order_good_min": 2,
"order_good_max": 20,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 5.7,
"video_gold": 3100
},
"58": {
"level": 58,
"exp": 32000,
"cost": 39000,
"order_good_min": 2,
"order_good_max": 20,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 5.8,
"video_gold": 3150
},
"59": {
"level": 59,
"exp": 33000,
"cost": 40000,
"order_good_min": 2,
"order_good_max": 20,
"order_refresh_min": 300,
"order_refresh_max": 600,
"worker_gold": 5.9,
"video_gold": 3200
},
"60": {
"level": 60,
"exp": 34000,
"cost": 41000,
"order_good_min": 3,
"order_good_max": 20,
"order_refresh_min": 600,
"order_refresh_max": 900,
"worker_gold": 5.99999999999999,
"video_gold": 3250
},
"61": {
"level": 61,
"exp": 35000,
"cost": 42000,
"order_good_min": 3,
"order_good_max": 20,
"order_refresh_min": 600,
"order_refresh_max": 900,
"worker_gold": 6.09999999999999,
"video_gold": 3300
},
"62": {
"level": 62,
"exp": 36000,
"cost": 43000,
"order_good_min": 3,
"order_good_max": 20,
"order_refresh_min": 600,
"order_refresh_max": 900,
"worker_gold": 6.19999999999999,
"video_gold": 3350
},
"63": {
"level": 63,
"exp": 37000,
"cost": 44000,
"order_good_min": 3,
"order_good_max": 20,
"order_refresh_min": 600,
"order_refresh_max": 900,
"worker_gold": 6.29999999999999,
"video_gold": 3400
},
"64": {
"level": 64,
"exp": 38000,
"cost": 45000,
"order_good_min": 3,
"order_good_max": 20,
"order_refresh_min": 600,
"order_refresh_max": 900,
"worker_gold": 6.39999999999999,
"video_gold": 3450
},
"65": {
"level": 65,
"exp": 39000,
"cost": 46000,
"order_good_min": 3,
"order_good_max": 20,
"order_refresh_min": 600,
"order_refresh_max": 900,
"worker_gold": 6.49999999999999,
"video_gold": 3500
},
"66": {
"level": 66,
"exp": 40000,
"cost": 47000,
"order_good_min": 3,
"order_good_max": 20,
"order_refresh_min": 600,
"order_refresh_max": 900,
"worker_gold": 6.59999999999999,
"video_gold": 3550
},
"67": {
"level": 67,
"exp": 41000,
"cost": 48000,
"order_good_min": 3,
"order_good_max": 20,
"order_refresh_min": 600,
"order_refresh_max": 900,
"worker_gold": 6.69999999999999,
| |
import json
import threading
import time
import os
import stat
import ssl
from decimal import Decimal
from typing import Union, Optional, Dict, Sequence, Tuple
from numbers import Real
from copy import deepcopy
from aiorpcx import NetAddress
from . import util
from . import constants
from .util import base_units, base_unit_name_to_decimal_point, decimal_point_to_base_unit_name, UnknownBaseUnit, DECIMAL_POINT_DEFAULT
from .util import format_satoshis, format_fee_satoshis
from .util import user_dir, make_dir, NoDynamicFeeEstimates, quantize_feerate
from .i18n import _
from .logging import get_logger, Logger
FEE_ETA_TARGETS = [25, 10, 5, 2]
FEE_DEPTH_TARGETS = [10_000_000, 5_000_000, 2_000_000, 1_000_000,
800_000, 600_000, 400_000, 250_000, 100_000]
FEE_LN_ETA_TARGET = 2 # note: make sure the network is asking for estimates for this target
# satoshi per kbyte
FEERATE_MAX_DYNAMIC = 1500000
FEERATE_WARNING_HIGH_FEE = 600000
FEERATE_FALLBACK_STATIC_FEE = 150000
FEERATE_DEFAULT_RELAY = 1000
FEERATE_MAX_RELAY = 50000
FEERATE_STATIC_VALUES = [1000, 2000, 5000, 10000, 20000, 30000,
50000, 70000, 100000, 150000, 200000, 300000]
FEERATE_REGTEST_HARDCODED = 180000 # for eclair compat
# The min feerate_per_kw that can be used in lightning so that
# the resulting onchain tx pays the min relay fee.
# This would be FEERATE_DEFAULT_RELAY / 4 if not for rounding errors,
# see https://github.com/ElementsProject/lightning/commit/2e687b9b352c9092b5e8bd4a688916ac50b44af0
FEERATE_PER_KW_MIN_RELAY_LIGHTNING = 253
FEE_RATIO_HIGH_WARNING = 0.05 # warn user if fee/amount for on-chain tx is higher than this
_logger = get_logger(__name__)
FINAL_CONFIG_VERSION = 3
class SimpleConfig(Logger):
"""
The SimpleConfig class is responsible for handling operations involving
configuration files.
There are two different sources of possible configuration values:
1. Command line options.
2. User configuration (in the user's config directory)
They are taken in order (1. overrides config options set in 2.)
"""
def __init__(self, options=None, read_user_config_function=None,
read_user_dir_function=None):
if options is None:
options = {}
Logger.__init__(self)
# This lock needs to be acquired for updating and reading the config in
# a thread-safe way.
self.lock = threading.RLock()
self.mempool_fees = None # type: Optional[Sequence[Tuple[Union[float, int], int]]]
self.fee_estimates = {} # type: Dict[int, int]
self.last_time_fee_estimates_requested = 0 # zero ensures immediate fees
# The following two functions are there for dependency injection when
# testing.
if read_user_config_function is None:
read_user_config_function = read_user_config
if read_user_dir_function is None:
self.user_dir = user_dir
else:
self.user_dir = read_user_dir_function
# The command line options
self.cmdline_options = deepcopy(options)
# don't allow to be set on CLI:
self.cmdline_options.pop('config_version', None)
# Set self.path and read the user config
self.user_config = {} # for self.get in electrum_path()
self.path = self.electrum_path()
self.user_config = read_user_config_function(self.path)
if not self.user_config:
# avoid new config getting upgraded
self.user_config = {'config_version': FINAL_CONFIG_VERSION}
self._not_modifiable_keys = set()
# config "upgrade" - CLI options
self.rename_config_keys(
self.cmdline_options, {'auto_cycle': 'auto_connect'}, True)
# config upgrade - user config
if self.requires_upgrade():
self.upgrade()
self._check_dependent_keys()
# units and formatting
self.decimal_point = self.get('decimal_point', DECIMAL_POINT_DEFAULT)
try:
decimal_point_to_base_unit_name(self.decimal_point)
except UnknownBaseUnit:
self.decimal_point = DECIMAL_POINT_DEFAULT
self.num_zeros = int(self.get('num_zeros', 0))
self.amt_precision_post_satoshi = int(self.get('amt_precision_post_satoshi', 0))
self.amt_add_thousands_sep = bool(self.get('amt_add_thousands_sep', False))
def electrum_path(self):
# Read electrum_path from command line
# Otherwise use the user's default data directory.
path = self.get('electrum_path')
if path is None:
path = self.user_dir()
make_dir(path, allow_symlink=False)
if self.get('testnet'):
path = os.path.join(path, 'testnet')
make_dir(path, allow_symlink=False)
elif self.get('regtest'):
path = os.path.join(path, 'regtest')
make_dir(path, allow_symlink=False)
elif self.get('simnet'):
path = os.path.join(path, 'simnet')
make_dir(path, allow_symlink=False)
elif self.get('signet'):
path = os.path.join(path, 'signet')
make_dir(path, allow_symlink=False)
self.logger.info(f"electrum directory {path}")
return path
def rename_config_keys(self, config, keypairs, deprecation_warning=False):
"""Migrate old key names to new ones"""
updated = False
for old_key, new_key in keypairs.items():
if old_key in config:
if new_key not in config:
config[new_key] = config[old_key]
if deprecation_warning:
self.logger.warning('Note that the {} variable has been deprecated. '
'You should use {} instead.'.format(old_key, new_key))
del config[old_key]
updated = True
return updated
def set_key(self, key, value, save=True):
if not self.is_modifiable(key):
self.logger.warning(f"not changing config key '{key}' set on the command line")
return
try:
json.dumps(key)
json.dumps(value)
except:
self.logger.info(f"json error: cannot save {repr(key)} ({repr(value)})")
return
self._set_key_in_user_config(key, value, save)
def _set_key_in_user_config(self, key, value, save=True):
with self.lock:
if value is not None:
self.user_config[key] = value
else:
self.user_config.pop(key, None)
if save:
self.save_user_config()
def get(self, key, default=None):
with self.lock:
out = self.cmdline_options.get(key)
if out is None:
out = self.user_config.get(key, default)
return out
def _check_dependent_keys(self) -> None:
if self.get('serverfingerprint'):
if not self.get('server'):
raise Exception("config key 'serverfingerprint' requires 'server' to also be set")
self.make_key_not_modifiable('server')
def requires_upgrade(self):
return self.get_config_version() < FINAL_CONFIG_VERSION
def upgrade(self):
with self.lock:
self.logger.info('upgrading config')
self.convert_version_2()
self.convert_version_3()
self.set_key('config_version', FINAL_CONFIG_VERSION, save=True)
def convert_version_2(self):
if not self._is_upgrade_method_needed(1, 1):
return
self.rename_config_keys(self.user_config, {'auto_cycle': 'auto_connect'})
try:
# change server string FROM host:port:proto TO host:port:s
server_str = self.user_config.get('server')
host, port, protocol = str(server_str).rsplit(':', 2)
assert protocol in ('s', 't')
int(port) # Throw if cannot be converted to int
server_str = '{}:{}:s'.format(host, port)
self._set_key_in_user_config('server', server_str)
except BaseException:
self._set_key_in_user_config('server', None)
self.set_key('config_version', 2)
def convert_version_3(self):
if not self._is_upgrade_method_needed(2, 2):
return
base_unit = self.user_config.get('base_unit')
if isinstance(base_unit, str):
self._set_key_in_user_config('base_unit', None)
map_ = {'btc':8, 'mbtc':5, 'ubtc':2, 'bits':2, 'sat':0}
decimal_point = map_.get(base_unit.lower())
self._set_key_in_user_config('decimal_point', decimal_point)
self.set_key('config_version', 3)
def _is_upgrade_method_needed(self, min_version, max_version):
cur_version = self.get_config_version()
if cur_version > max_version:
return False
elif cur_version < min_version:
raise Exception(
('config upgrade: unexpected version %d (should be %d-%d)'
% (cur_version, min_version, max_version)))
else:
return True
def get_config_version(self):
config_version = self.get('config_version', 1)
if config_version > FINAL_CONFIG_VERSION:
self.logger.warning('config version ({}) is higher than latest ({})'
.format(config_version, FINAL_CONFIG_VERSION))
return config_version
def is_modifiable(self, key) -> bool:
return (key not in self.cmdline_options
and key not in self._not_modifiable_keys)
def make_key_not_modifiable(self, key) -> None:
self._not_modifiable_keys.add(key)
def save_user_config(self):
if self.get('forget_config'):
return
if not self.path:
return
path = os.path.join(self.path, "config")
s = json.dumps(self.user_config, indent=4, sort_keys=True)
try:
with open(path, "w", encoding='utf-8') as f:
f.write(s)
os.chmod(path, stat.S_IREAD | stat.S_IWRITE)
except FileNotFoundError:
# datadir probably deleted while running...
if os.path.exists(self.path): # or maybe not?
raise
def get_backup_dir(self):
# this is used to save wallet file backups (without active lightning channels)
# on Android, the export backup button uses android_backup_dir()
if 'ANDROID_DATA' in os.environ:
return None
else:
return self.get('backup_dir')
def get_wallet_path(self, *, use_gui_last_wallet=False):
"""Set the path of the wallet."""
# command line -w option
if self.get('wallet_path'):
return os.path.join(self.get('cwd', ''), self.get('wallet_path'))
if use_gui_last_wallet:
path = self.get('gui_last_wallet')
if path and os.path.exists(path):
return path
new_path = self.get_fallback_wallet_path()
# default path in pre 1.9 versions
old_path = os.path.join(self.path, "electrum.dat")
if os.path.exists(old_path) and not os.path.exists(new_path):
os.rename(old_path, new_path)
return new_path
def get_fallback_wallet_path(self):
util.assert_datadir_available(self.path)
dirpath = os.path.join(self.path, "wallets")
make_dir(dirpath, allow_symlink=False)
path = os.path.join(self.path, "wallets", "default_wallet")
return path
def remove_from_recently_open(self, filename):
recent = self.get('recently_open', [])
if filename in recent:
recent.remove(filename)
self.set_key('recently_open', recent)
def set_session_timeout(self, seconds):
self.logger.info(f"session timeout -> {seconds} seconds")
self.set_key('session_timeout', seconds)
def get_session_timeout(self):
return self.get('session_timeout', 300)
def save_last_wallet(self, wallet):
if self.get('wallet_path') is None:
path = wallet.storage.path
self.set_key('gui_last_wallet', path)
def impose_hard_limits_on_fee(func):
def get_fee_within_limits(self, *args, **kwargs):
fee = func(self, *args, **kwargs)
if fee is None:
return fee
fee = min(FEERATE_MAX_DYNAMIC, fee)
fee = max(FEERATE_DEFAULT_RELAY, fee)
return fee
return get_fee_within_limits
def eta_to_fee(self, slider_pos) -> Optional[int]:
"""Returns fee in sat/kbyte."""
slider_pos = max(slider_pos, 0)
slider_pos = min(slider_pos, len(FEE_ETA_TARGETS))
if slider_pos < len(FEE_ETA_TARGETS):
num_blocks = FEE_ETA_TARGETS[int(slider_pos)]
fee = self.eta_target_to_fee(num_blocks)
else:
fee = self.eta_target_to_fee(1)
return fee
@impose_hard_limits_on_fee
def eta_target_to_fee(self, num_blocks: int) -> Optional[int]:
"""Returns fee in sat/kbyte."""
if num_blocks == 1:
fee = self.fee_estimates.get(2)
if fee is not None:
fee += fee / 2
fee = int(fee)
else:
fee = self.fee_estimates.get(num_blocks)
if fee is not None:
fee = int(fee)
return fee
def fee_to_depth(self, target_fee: Real) -> Optional[int]:
"""For a given sat/vbyte fee, returns an estimate of how deep
it would be in the current mempool in vbytes.
Pessimistic == overestimates the depth.
"""
if self.mempool_fees is None:
return None
depth = 0
for fee, s in self.mempool_fees:
depth += s
if fee <= target_fee:
break
return depth
def depth_to_fee(self, slider_pos) -> Optional[int]:
"""Returns fee in sat/kbyte."""
target = self.depth_target(slider_pos)
return self.depth_target_to_fee(target)
@impose_hard_limits_on_fee
def depth_target_to_fee(self, target: int) -> Optional[int]:
"""Returns fee in sat/kbyte.
target: desired mempool depth in vbytes
"""
if self.mempool_fees is None:
return None
depth = 0
for fee, s in self.mempool_fees:
depth += s
if depth > target:
break
else:
return 0
# add one sat/byte as currently that is the max precision of the histogram
# note: precision depends on server.
# old ElectrumX <1.16 has 1 s/b prec, >=1.16 has 0.1 s/b prec.
# electrs seems to use untruncated double-precision floating points.
# # TODO decrease this to 0.1 s/b next time we bump the required protocol version
fee += 1
# convert to sat/kbyte
return int(fee * 1000)
| |
"""Parsers for pw.x output."""
import re
from pathlib import Path
from typing import (
Any,
Dict,
Generic,
Iterable,
List,
Mapping,
Match,
MutableMapping,
Optional,
Pattern,
Sequence,
Tuple,
TypeVar,
Union,
)
import numpy as np
from pwproc.geometry import Basis, GeometryData, RelaxData, Species, Tau
from pwproc.util import LookaheadIter, parse_vector
class ParserError(RuntimeError): pass
T = TypeVar('T')
# pos_type, basis, species, tau
RawGeometry = Tuple[str, Sequence[Basis], Species, Sequence[Tau]]
def get_save_file(path):
# type: (Path) -> str
"""Extract the prefix from pw.x output."""
from pwproc.util import parser_one_line
save_re = re.compile(r"^[ \t]+Writing output data file (?:\./)?([-.\w]+).save/?$")
save_parser = parser_one_line(save_re, lambda m: m.group(1))
with open(path) as f:
prefix = save_parser(f)
if prefix is None:
raise ParserError("Could not find calculation prefix")
return prefix
def get_init_basis(path):
# type: (Path) -> Tuple[float, Basis]
"""Extracts the initial basis in angstrom from pw.x output."""
from scipy import constants
from pwproc.util import parser_one_line, parser_with_header
bohr_to_ang = constants.value('Bohr radius') / constants.angstrom
alat_re = re.compile(r"[ \t]+lattice parameter \(alat\)[ \t]+=[ \t]+([\d.]+)[ \t]+a\.u\.")
basis_head_re = re.compile(r"[ \t]+crystal axes: \(cart. coord. in units of alat\)")
basis_line_re = re.compile(r"[ \t]+a\([\d]\) = \(((?:[ \t]+[-.\d]+){3}[ \t]+)\)")
alat_parser = parser_one_line(alat_re, lambda m: float(m.group(1)))
basis_parser = parser_with_header(basis_head_re, basis_line_re, lambda m: parse_vector(m.group(1)))
with open(path) as f:
alat: float = alat_parser(f)
# TODO: Remove seek and run parsers in correct order
f.seek(0)
basis = basis_parser(f)
# Convert basis from alat to angstrom
assert len(basis) == 3
basis = Basis(np.array(basis))
basis *= alat * bohr_to_ang
return alat, basis
def get_init_coord(path):
# type: (Path) -> Tuple[str, Species, Tau]
"""Extracts starting atomic positions."""
from pwproc.util import parser_with_header
header_re = re.compile(r"[ \t]+site n\.[ \t]+atom[ \t]+positions \((cryst\. coord\.|alat units)\)")
line_re = re.compile(r"[ \t]+[\d]+[ \t]+([\w]{1,2})[ \t]+tau\([ \d\t]+\) = \(((?:[ \t]+[-.\d]+){3}[ \t]+)\)")
# Translate the tags in the output header to coordinate types
coord_types = {"cryst. coord.": 'crystal', "alat units": 'alat'}
# Precedence for coord types when multiple are present
ctype_order = ('crystal', 'alat')
coord_parser = parser_with_header(header_re, line_re, lambda m: m.groups(),
header_proc=lambda m: m.group(1), find_multiple=True)
with open(path) as f:
init_coords = {coord_types[c_tag]: coords for c_tag, coords in coord_parser(f)}
for ct in ctype_order:
try:
atom_coords = init_coords[ct]
except KeyError:
pass
else:
coord_type = ct
break
else:
raise ParserError("Initial coordinates not found.")
spec, pos = zip(*atom_coords)
pos = np.array(tuple(map(parse_vector, pos)))
return coord_type, Species(spec), Tau(pos)
def _count_relax_steps(path):
# type: (Path) -> Tuple[int, int, int, bool]
"""Count the number of completed steps."""
scf_re = re.compile(r"^ +number of scf cycles += +(?P<scf>[\d]+)$")
bfgs_re = re.compile(r"^ +number of bfgs steps += +(?P<bfgs>[\d]+)$")
last_step_re = re.compile(r"^ +bfgs converged in +(?P<scf>[\d]+) scf cycles and +(?P<bfgs>[\d]+) bfgs steps$")
zero_mag_re = re.compile(r"^ +lsda relaxation : a final configuration with zero *$")
steps = []
last_step = None
zero_mag_relax = False
with open(path) as f:
lines = iter(f)
for line in lines:
m1 = scf_re.match(line)
if m1 is not None:
n_scf = int(m1.group('scf'))
m2 = bfgs_re.match(next(lines))
if m2 is None:
raise ParserError("Malformed step count")
n_bfgs = int(m2.group('bfgs'))
steps.append((n_scf, n_bfgs))
m3 = last_step_re.match(line)
if m3 is not None:
last_step = (int(m3.group('scf')), int(m3.group('bfgs')))
break
m4 = zero_mag_re.match(line)
if m4 is not None:
if zero_mag_relax:
raise ParserError("Two zero-magnetization relaxations")
zero_mag_relax = True
if last_step is not None:
steps.append(last_step)
return len(steps), steps[0][0], steps[-1][0], zero_mag_relax
class ParserBase(Generic[T]):
"""Base class for local parsers."""
header_re: Pattern
def __init__(self):
# type: () -> None
self._buffer: List[T] = []
def __call__(self, lines):
# type: (LookaheadIter[str]) -> bool
line = lines.top()
match = self.header_re.match(line)
if match:
# Consume the matched line
next(lines)
self.complete_match(match, lines)
return True
return False
@property
def buffer(self):
# type: () -> List[T]
return self._buffer
def complete_match(self, match, lines):
# type: (Match, LookaheadIter[str]) -> None
raise NotImplementedError
class EnergyParser(ParserBase[float]):
header_re = re.compile(r"![\s]+total energy[\s]+=[\s]+(-[\d.]+) Ry")
def complete_match(self, match, _):
# type: (Match, LookaheadIter[str]) -> None
self.buffer.append(float(match.group(1)))
class FEnergyParser(ParserBase[Tuple[str, float]]):
header_re = re.compile(r"[ \t]+Final (energy|enthalpy)[ \t]+=[ \t]+(-[.\d]+) Ry")
def complete_match(self, match, _):
# type: (Match, LookaheadIter[str]) -> None
self.buffer.append((match.group(1), float(match.group(2))))
class GeometryParser(ParserBase[Tuple[str, Species, Tau]]):
header_re = re.compile(r"ATOMIC_POSITIONS \((angstrom|crystal|alat|bohr)\)")
atom_re = re.compile(r"([a-zA-Z]{1,2})((?:[\s]+[-\d.]+){3})")
def complete_match(self, match, lines):
# type: (Match, LookaheadIter[str]) -> None
pos_type = match.group(1)
species = []
tau = []
m = self.atom_re.match(lines.top())
while m:
lines.pop()
s, pos = m.groups()
species.append(s)
tau.append(parse_vector(pos))
m = self.atom_re.match(lines.top())
species = tuple(species)
tau = np.array(tau)
self.buffer.append((pos_type, Species(species), Tau(tau)))
class BasisParser(ParserBase[Basis]):
"""Capture basis converted to angstrom."""
header_re = re.compile(
r"CELL_PARAMETERS (\()?(?P<coord>angstrom|bohr|alat= [.\d]+)(?(1)\))"
)
basis_row_re = re.compile(r"(?:[\s]+-?[\d.]+){3}")
def complete_match(self, match, lines):
# type: (Match, LookaheadIter[str]) -> None
coord_type = match.group("coord")
basis_tmp = []
while self.basis_row_re.match(lines.top()):
line = lines.pop()
basis_tmp.append(parse_vector(line))
assert len(basis_tmp) == 3
basis = np.array(basis_tmp)
if coord_type != "angstrom":
# pylint: disable=import-outside-toplevel
from pwproc.geometry.util import convert_basis
basis = convert_basis(basis, coord_type.strip(), "angstrom")
self.buffer.append(Basis(basis))
class ForceParser(ParserBase[Tuple[float, float]]):
header_re = re.compile(r"^ *Total force = +([.\d]+) +Total SCF correction = +([.\d]+) *$")
def complete_match(self, match, _):
# type: (Match, LookaheadIter[str]) -> None
self.buffer.append((float(match.group(1)), float(match.group(2))))
class PressParser(ParserBase[Tuple[float, np.array, np.array]]):
header_re = re.compile(r"^ *total {3}stress .* \(kbar\) +P= +(-?[.\d]+) *$")
press_row_re = re.compile(r"^(?: +-?[.\d]+){6} *$")
def complete_match(self, match, lines):
# type: (Match, LookaheadIter[str]) -> None
tot_p = float(match.group(1))
press_tmp = []
line = next(lines)
while self.press_row_re.match(line):
press_tmp.append(parse_vector(line))
line = next(lines)
assert(len(press_tmp) == 3)
press_tmp = np.array(press_tmp)
press_au = press_tmp[:, :3]
press_bar = press_tmp[:, 3:]
self.buffer.append((tot_p, press_au, press_bar))
class MagParser(ParserBase[Tuple[float, float]]):
header_re = re.compile(r"^ *total magnetization += +(-?[.\d]+) +Bohr mag/cell *$")
abs_mag_re = re.compile(r"^ * absolute magnetization += +(-?[.\d]+) +Bohr mag/cell *$")
conv_re = re.compile(r"^ +convergence has been achieved in +[\d]+ iterations *$")
def complete_match(self, match, lines):
# type: (Match, LookaheadIter[str]) -> None
m_tot = float(match.group(1))
line = next(lines)
m = self.abs_mag_re.match(line)
assert(m is not None)
m_abs = float(m.group(1))
assert(next(lines).strip() == '')
line = next(lines)
m_conv = self.conv_re.match(line)
if m_conv:
self.buffer.append((m_tot, m_abs))
class FermiParser(ParserBase[float]):
header_re = re.compile(r"[ \t]+the Fermi energy is[ \t]+(-?[.\d]+) ev")
def complete_match(self, match, _):
# type: (Match, LookaheadIter[str]) -> None
self.buffer.append(float(match.group(1)))
def _run_relax_parsers(path, parsers):
# type: (Path, Mapping[str, ParserBase]) -> Mapping[str, List[Any]]
"""Run arbitrary parsers on the pw.x output."""
# Iterate through file
with open(path) as f:
lines = LookaheadIter(f)
while True:
try:
parser_matched = False
for parser in parsers.values():
parser_matched &= parser(lines)
if not parser_matched:
next(lines)
except StopIteration:
break
return {tag: parser.buffer for tag, parser in parsers.items()}
_base_tags = frozenset(('energy', 'fenergy', 'geom', 'basis'))
_all_tags = frozenset(['energy', 'fenergy', 'geom', 'basis', 'force', 'press', 'mag', 'fermi'])
_parser_map = {'energy': EnergyParser, 'fenergy': FEnergyParser, 'geom': GeometryParser,
'basis': BasisParser, 'force': ForceParser, 'press': PressParser,
'mag': MagParser, 'fermi': FermiParser}
# energy, final_en, relax_kind, geometry, data_buffers, zmag_relax
_RawParsed = Tuple[Sequence[float], Optional[float], Optional[str], RawGeometry, Dict[str, Sequence], bool]
# n_steps, _relax_kind, _relax_done, _zmag_relax
_RelaxDims = Tuple[int, Optional[str], bool, bool]
def _proc_relax_data(buffers, n_steps, zmag_relax):
# type: (Mapping[str, Sequence[Any]], int, bool) -> _RawParsed
tags = set(buffers)
assert(_base_tags <= tags)
assert(tags <= _all_tags)
# Deal with energies first
energy: Sequence[float] = buffers['energy']
final_en: Optional[float] = None
relax_kind: Optional[str] = None
assert(len(buffers['fenergy']) < 2)
if len(buffers['fenergy']) == 1:
final_type, final_en = buffers['fenergy'][0]
# If vc-relax, the true final energy is run in a new scf calculation,
# which is captured in the `energy` buffer. The `fenergy` buffer has
# a duplicate of last relaxation SCF step, which is discarded.
# A zero-magnetization check occurs before the BFGS completes, so it
# is possible to have an extra entry even if the final energy parsers
# are not triggered. Thus, we strip this entry after the final energy
# routine but before the buffer length check.
if final_type == 'enthalpy':
relax_kind = 'vcrelax'
expected_len = n_steps + 1 if not zmag_relax else n_steps + 2
if len(energy) == expected_len:
final_en = energy[-1]
energy = energy[:-1]
else:
# In this case, the final SCF step was interrupted
final_en = None
elif final_type == 'energy':
relax_kind = 'relax'
else:
raise ParserError("Unknown final energy type")
if zmag_relax:
if len(energy) == n_steps + 1:
energy = energy[:-1]
else:
# The magnetization check was interrupted
zmag_relax = False
if len(energy) != n_steps:
raise ParserError("Incorrect length in energy buffer")
def all_equal(seq):
# type: (List) -> bool
return seq.count(seq[0]) == len(seq)
# Re-package geometry
pos_type, species, pos = zip(*buffers['geom'])
assert(all_equal(pos_type) and all_equal(species))
pos_type, species = pos_type[0], species[0]
bases = buffers['basis']
if len(bases) > 0:
assert(len(bases) == len(pos))
geometry: RawGeometry = (pos_type, bases, species, pos)
# Save the other buffers
data_buffers = {}
for t in tags - _base_tags:
| |
share is not None:
pulumi.set(__self__, "share", share)
@property
@pulumi.getter(name="dbName")
def db_name(self) -> Optional[pulumi.Input[str]]:
"""
The display name of the database to be created from the backup. It must begin with an alphabetic character and can contain a maximum of eight alphanumeric characters. Special characters are not permitted.
"""
return pulumi.get(self, "db_name")
@db_name.setter
def db_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "db_name", value)
@property
@pulumi.getter(name="flashCacheLimit")
def flash_cache_limit(self) -> Optional[pulumi.Input[str]]:
"""
The flash cache limit for this database. This value is internally configured based on the share value assigned to the database.
"""
return pulumi.get(self, "flash_cache_limit")
@flash_cache_limit.setter
def flash_cache_limit(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "flash_cache_limit", value)
@property
@pulumi.getter
def share(self) -> Optional[pulumi.Input[int]]:
"""
The relative priority of this database.
"""
return pulumi.get(self, "share")
@share.setter
def share(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "share", value)
@pulumi.input_type
class DbSystemMaintenanceWindowArgs:
def __init__(__self__, *,
days_of_weeks: Optional[pulumi.Input[Sequence[pulumi.Input['DbSystemMaintenanceWindowDaysOfWeekArgs']]]] = None,
hours_of_days: Optional[pulumi.Input[Sequence[pulumi.Input[int]]]] = None,
lead_time_in_weeks: Optional[pulumi.Input[int]] = None,
months: Optional[pulumi.Input[Sequence[pulumi.Input['DbSystemMaintenanceWindowMonthArgs']]]] = None,
preference: Optional[pulumi.Input[str]] = None,
weeks_of_months: Optional[pulumi.Input[Sequence[pulumi.Input[int]]]] = None):
"""
:param pulumi.Input[Sequence[pulumi.Input['DbSystemMaintenanceWindowDaysOfWeekArgs']]] days_of_weeks: (Updatable) Days during the week when maintenance should be performed.
:param pulumi.Input[Sequence[pulumi.Input[int]]] hours_of_days: (Updatable) The window of hours during the day when maintenance should be performed. The window is a 4 hour slot. Valid values are
* 0 - represents time slot 0:00 - 3:59 UTC - 4 - represents time slot 4:00 - 7:59 UTC - 8 - represents time slot 8:00 - 11:59 UTC - 12 - represents time slot 12:00 - 15:59 UTC - 16 - represents time slot 16:00 - 19:59 UTC - 20 - represents time slot 20:00 - 23:59 UTC
:param pulumi.Input[int] lead_time_in_weeks: (Updatable) Lead time window allows user to set a lead time to prepare for a down time. The lead time is in weeks and valid value is between 1 to 4.
:param pulumi.Input[Sequence[pulumi.Input['DbSystemMaintenanceWindowMonthArgs']]] months: (Updatable) Months during the year when maintenance should be performed.
:param pulumi.Input[str] preference: (Updatable) The maintenance window scheduling preference.
:param pulumi.Input[Sequence[pulumi.Input[int]]] weeks_of_months: (Updatable) Weeks during the month when maintenance should be performed. Weeks start on the 1st, 8th, 15th, and 22nd days of the month, and have a duration of 7 days. Weeks start and end based on calendar dates, not days of the week. For example, to allow maintenance during the 2nd week of the month (from the 8th day to the 14th day of the month), use the value 2. Maintenance cannot be scheduled for the fifth week of months that contain more than 28 days. Note that this parameter works in conjunction with the daysOfWeek and hoursOfDay parameters to allow you to specify specific days of the week and hours that maintenance will be performed.
"""
if days_of_weeks is not None:
pulumi.set(__self__, "days_of_weeks", days_of_weeks)
if hours_of_days is not None:
pulumi.set(__self__, "hours_of_days", hours_of_days)
if lead_time_in_weeks is not None:
pulumi.set(__self__, "lead_time_in_weeks", lead_time_in_weeks)
if months is not None:
pulumi.set(__self__, "months", months)
if preference is not None:
pulumi.set(__self__, "preference", preference)
if weeks_of_months is not None:
pulumi.set(__self__, "weeks_of_months", weeks_of_months)
@property
@pulumi.getter(name="daysOfWeeks")
def days_of_weeks(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['DbSystemMaintenanceWindowDaysOfWeekArgs']]]]:
"""
(Updatable) Days during the week when maintenance should be performed.
"""
return pulumi.get(self, "days_of_weeks")
@days_of_weeks.setter
def days_of_weeks(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['DbSystemMaintenanceWindowDaysOfWeekArgs']]]]):
pulumi.set(self, "days_of_weeks", value)
@property
@pulumi.getter(name="hoursOfDays")
def hours_of_days(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[int]]]]:
"""
(Updatable) The window of hours during the day when maintenance should be performed. The window is a 4 hour slot. Valid values are
* 0 - represents time slot 0:00 - 3:59 UTC - 4 - represents time slot 4:00 - 7:59 UTC - 8 - represents time slot 8:00 - 11:59 UTC - 12 - represents time slot 12:00 - 15:59 UTC - 16 - represents time slot 16:00 - 19:59 UTC - 20 - represents time slot 20:00 - 23:59 UTC
"""
return pulumi.get(self, "hours_of_days")
@hours_of_days.setter
def hours_of_days(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[int]]]]):
pulumi.set(self, "hours_of_days", value)
@property
@pulumi.getter(name="leadTimeInWeeks")
def lead_time_in_weeks(self) -> Optional[pulumi.Input[int]]:
"""
(Updatable) Lead time window allows user to set a lead time to prepare for a down time. The lead time is in weeks and valid value is between 1 to 4.
"""
return pulumi.get(self, "lead_time_in_weeks")
@lead_time_in_weeks.setter
def lead_time_in_weeks(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "lead_time_in_weeks", value)
@property
@pulumi.getter
def months(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['DbSystemMaintenanceWindowMonthArgs']]]]:
"""
(Updatable) Months during the year when maintenance should be performed.
"""
return pulumi.get(self, "months")
@months.setter
def months(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['DbSystemMaintenanceWindowMonthArgs']]]]):
pulumi.set(self, "months", value)
@property
@pulumi.getter
def preference(self) -> Optional[pulumi.Input[str]]:
"""
(Updatable) The maintenance window scheduling preference.
"""
return pulumi.get(self, "preference")
@preference.setter
def preference(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "preference", value)
@property
@pulumi.getter(name="weeksOfMonths")
def weeks_of_months(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[int]]]]:
"""
(Updatable) Weeks during the month when maintenance should be performed. Weeks start on the 1st, 8th, 15th, and 22nd days of the month, and have a duration of 7 days. Weeks start and end based on calendar dates, not days of the week. For example, to allow maintenance during the 2nd week of the month (from the 8th day to the 14th day of the month), use the value 2. Maintenance cannot be scheduled for the fifth week of months that contain more than 28 days. Note that this parameter works in conjunction with the daysOfWeek and hoursOfDay parameters to allow you to specify specific days of the week and hours that maintenance will be performed.
"""
return pulumi.get(self, "weeks_of_months")
@weeks_of_months.setter
def weeks_of_months(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[int]]]]):
pulumi.set(self, "weeks_of_months", value)
@pulumi.input_type
class DbSystemMaintenanceWindowDaysOfWeekArgs:
def __init__(__self__, *,
name: Optional[pulumi.Input[str]] = None):
"""
:param pulumi.Input[str] name: (Updatable) Name of the month of the year.
"""
if name is not None:
pulumi.set(__self__, "name", name)
@property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
"""
(Updatable) Name of the month of the year.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "name", value)
@pulumi.input_type
class DbSystemMaintenanceWindowDetailsArgs:
def __init__(__self__, *,
days_of_weeks: Optional[pulumi.Input[Sequence[pulumi.Input['DbSystemMaintenanceWindowDetailsDaysOfWeekArgs']]]] = None,
hours_of_days: Optional[pulumi.Input[Sequence[pulumi.Input[int]]]] = None,
lead_time_in_weeks: Optional[pulumi.Input[int]] = None,
months: Optional[pulumi.Input[Sequence[pulumi.Input['DbSystemMaintenanceWindowDetailsMonthArgs']]]] = None,
preference: Optional[pulumi.Input[str]] = None,
weeks_of_months: Optional[pulumi.Input[Sequence[pulumi.Input[int]]]] = None):
"""
:param pulumi.Input[Sequence[pulumi.Input['DbSystemMaintenanceWindowDetailsDaysOfWeekArgs']]] days_of_weeks: (Updatable) Days during the week when maintenance should be performed.
:param pulumi.Input[Sequence[pulumi.Input[int]]] hours_of_days: (Updatable) The window of hours during the day when maintenance should be performed. The window is a 4 hour slot. Valid values are
* 0 - represents time slot 0:00 - 3:59 UTC - 4 - represents time slot 4:00 - 7:59 UTC - 8 - represents time slot 8:00 - 11:59 UTC - 12 - represents time slot 12:00 - 15:59 UTC - 16 - represents time slot 16:00 - 19:59 UTC - 20 - represents time slot 20:00 - 23:59 UTC
:param pulumi.Input[int] lead_time_in_weeks: (Updatable) Lead time window allows user to set a lead time to prepare for a down time. The lead time is in weeks and valid value is between 1 to 4.
:param pulumi.Input[Sequence[pulumi.Input['DbSystemMaintenanceWindowDetailsMonthArgs']]] months: (Updatable) Months during the year when maintenance should be performed.
:param pulumi.Input[str] preference: (Updatable) The maintenance window scheduling preference.
:param pulumi.Input[Sequence[pulumi.Input[int]]] weeks_of_months: (Updatable) Weeks during the month when maintenance should be performed. Weeks start on the 1st, 8th, 15th, and 22nd days of the month, and have a duration of 7 days. Weeks start and end based on calendar dates, not days of the week. For example, to allow maintenance during the 2nd week of the month (from the 8th day to the 14th day of the month), use the value 2. Maintenance cannot be scheduled for the fifth week of months that contain more than 28 days. Note that this parameter works in conjunction with the daysOfWeek and hoursOfDay parameters to allow you to specify specific days of the week and hours that maintenance will be performed.
"""
if days_of_weeks is not None:
pulumi.set(__self__, "days_of_weeks", days_of_weeks)
if hours_of_days is not None:
pulumi.set(__self__, "hours_of_days", hours_of_days)
if lead_time_in_weeks is not None:
pulumi.set(__self__, "lead_time_in_weeks", lead_time_in_weeks)
if months is not None:
pulumi.set(__self__, "months", months)
if preference is not None:
pulumi.set(__self__, "preference", preference)
if weeks_of_months is not None:
pulumi.set(__self__, "weeks_of_months", weeks_of_months)
@property
@pulumi.getter(name="daysOfWeeks")
def days_of_weeks(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['DbSystemMaintenanceWindowDetailsDaysOfWeekArgs']]]]:
"""
(Updatable) Days during the week when maintenance should be performed.
"""
return pulumi.get(self, "days_of_weeks")
@days_of_weeks.setter
def days_of_weeks(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['DbSystemMaintenanceWindowDetailsDaysOfWeekArgs']]]]):
| |
<filename>electroncash/synchronizer.py
#!/usr/bin/env python3
#
# Electrum ABC - lightweight eCash client
# Copyright (C) 2020 The Electrum ABC developers
# Copyright (C) 2017-2022 The Electron Cash Developers
# Copyright (C) 2014 <NAME>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
from collections import defaultdict
from threading import Lock
from typing import DefaultDict, Dict, Iterable, Optional, Set, Tuple, TYPE_CHECKING
import hashlib
import traceback
from .address import Address
from .transaction import Transaction
from .util import Monotonic, ThreadJob, bh2u
from . import networks
from .bitcoin import InvalidXKeyFormat
if TYPE_CHECKING:
from .wallet import Abstract_Wallet
class Synchronizer(ThreadJob):
"""The synchronizer keeps the wallet up-to-date with its set of
addresses and their transactions. It subscribes over the network
to wallet addresses, gets the wallet to generate new addresses
when necessary, requests the transaction history of any addresses
we don't have the full history of, and requests binary transaction
data of any transactions the wallet doesn't have.
External interface: __init__() and add() member functions.
"""
def __init__(self, wallet: Abstract_Wallet, network):
self.wallet = wallet
self.network = network
assert self.wallet and self.wallet.storage and self.network
self.cleaned_up = False
self._need_release = False
self.new_addresses: Set[Address] = set()
self.new_addresses_for_change: Dict[Address, type(None)] = dict()
"""Basically, an ordered set of Addresses
(this assumes that dictionaries are ordered, so Python > 3.6)
"""
self.requested_tx: Dict[str, int] = dict()
"""Mapping of tx_hash -> tx_height"""
self.requested_tx_by_sh: DefaultDict[str, Set[str]] = defaultdict(set)
"""Mapping of scripthash -> set of requested tx_hashes"""
self.requested_histories = {}
self.requested_hashes = set()
self.change_sh_ctr = Monotonic(locking=True)
self.change_scripthashes: DefaultDict[str, int] = defaultdict(self.change_sh_ctr)
"""all known change address scripthashes -> their order seen"""
self.change_subs: Set[str] = set()
"""set of all change address scripthashes that we are currently subscribed to"""
self.change_subs_expiry_candidates: Set[str] = set()
"""set of all "used", 0 balance change sh's"""
self.h2addr: Dict[str, Address] = {}
"""mapping of scripthash -> Address"""
self.lock = Lock()
self._tick_ct = 0
# Disallow negatives; they create problems
self.limit_change_subs = max(self.wallet.limit_change_addr_subs, 0)
self.change_scripthashes_that_are_retired = set()
"""set of all change address scripthashes that are retired and should be ignored
"""
if self.limit_change_subs:
self.change_scripthashes_that_are_retired = set(
self.wallet.storage.get('synchronizer_retired_change_scripthashes', [])
)
self._initialize()
def clear_retired_change_addrs(self):
self.change_scripthashes_that_are_retired.clear()
def save(self):
self.wallet.storage.put('synchronizer_retired_change_scripthashes',
list(self.change_scripthashes_that_are_retired))
def diagnostic_name(self):
return f"{__class__.__name__}/{self.wallet.diagnostic_name()}"
def _parse_response(self, response):
error = True
try:
if not response: return None, None, error
error = response.get('error')
return response['params'], response.get('result'), error
finally:
if error:
self.print_error("response error:", response)
def is_up_to_date(self):
return not self.requested_tx and not self.requested_histories and not self.requested_hashes
def _release(self):
""" Called from the Network (DaemonThread) -- to prevent race conditions
with network, we remove data structures related to the network and
unregister ourselves as a job from within the Network thread itself. """
self._need_release = False
self.cleaned_up = True
self.network.unsubscribe_from_scripthashes(self.h2addr.keys(), self._on_address_status)
self.network.cancel_requests(self._on_address_status)
self.network.cancel_requests(self._on_address_history)
self.network.cancel_requests(self._tx_response)
self.network.remove_jobs([self])
def release(self):
""" Called from main thread, enqueues a 'release' to happen in the
Network thread. """
self._need_release = True
def add(self, address, *, for_change=False):
"""This can be called from the proxy or GUI threads."""
with self.lock:
if not for_change:
self.new_addresses.add(address)
else:
self.new_addresses_for_change[address] = None
def _check_change_subs_limits(self):
if not self.limit_change_subs:
return
active = self.change_subs_active
ctr = len(active) - self.limit_change_subs
if ctr <= 0:
return
huge_int = 2 ** 64
candidates = sorted(self.change_subs_expiry_candidates, key=lambda x: self.change_scripthashes.get(x, huge_int))
unsubs = []
for scripthash in candidates:
if ctr <= 0:
break
if scripthash not in active:
continue
unsubs.append(scripthash)
self.change_scripthashes_that_are_retired.add(scripthash)
self.change_subs_expiry_candidates.discard(scripthash)
self.change_subs.discard(scripthash)
ctr -= 1
if unsubs:
self.print_error(f"change_subs limit reached ({self.limit_change_subs}), unsubscribing from"
f" {len(unsubs)} old change scripthashes,"
f" change scripthash subs ct now: {len(self.change_subs)}")
self.network.unsubscribe_from_scripthashes(unsubs, self._on_address_status)
def _subscribe_to_addresses(self, addresses: Iterable[Address], *, for_change=False):
hashes2addr = {addr.to_scripthash_hex(): addr for addr in addresses}
if not hashes2addr:
return # Nothing to do!
# Keep a hash -> address mapping
self.h2addr.update(hashes2addr)
hashes_set = set(hashes2addr.keys())
skipped_ct = 0
if for_change and self.limit_change_subs:
for sh in list(hashes2addr.keys()): # Iterate in order (dicts are ordered)
# This is a defaultdict, accessing it will add a counted item if not there
self.change_scripthashes[sh]
if sh in self.change_scripthashes_that_are_retired:
# this scripthash was "retired", do not subscribe to it
hashes_set.discard(sh)
hashes2addr.pop(sh, None)
skipped_ct += 1
self.change_subs |= hashes_set
self.requested_hashes |= hashes_set
# Nit: we use hashes2addr.keys() here to preserve order
self.network.subscribe_to_scripthashes(hashes2addr.keys(), self._on_address_status)
if for_change:
self._check_change_subs_limits()
if skipped_ct:
self.print_error(f"Skipped {skipped_ct} change address scripthashes because they are in the"
f" \"retired\" set (set size: {len(self.change_scripthashes_that_are_retired)})")
@staticmethod
def get_status(hist: Iterable[Tuple[str, int]]):
if not hist:
return None
status = bytearray()
for tx_hash, height in hist:
status.extend(f"{tx_hash}:{height:d}:".encode('ascii'))
return bh2u(hashlib.sha256(status).digest())
@property
def change_subs_active(self) -> Set[str]:
return self.change_subs - self.requested_hashes
def _check_change_scripthash(self, sh: str):
if not self.limit_change_subs:
# If not limiting change subs, this subsystem is not used so no need to maintain data structures below...
return
if (not sh or sh not in self.change_scripthashes or sh in self.requested_tx_by_sh
or sh in self.requested_histories or sh not in self.change_subs_active):
# this scripthash is either not change or is not subbed or is not yet "stable", discard and abort early
self.change_subs_expiry_candidates.discard(sh)
return
addr = self.h2addr.get(sh)
if not addr:
return
hlen = len(self.wallet.get_address_history(addr)) # O(1) lookup into a dict
if hlen == 2: # Only "expire" old change address with precisely 1 input tx and 1 spending tx
bal = self.wallet.get_addr_balance(addr) # Potentially fast lookup since addr_balance gets cached
else:
bal = None
if bal is not None and not any(bal):
# Candidate for expiry: has history of size 2 and also 0 balance
self.change_subs_expiry_candidates.add(sh)
else:
# Not a candidate for expiry
self.change_subs_expiry_candidates.discard(sh)
def _on_address_status(self, response):
if self.cleaned_up:
self.print_error("Already cleaned-up, ignoring stale reponse:", response)
# defensive programming: make doubly sure we aren't registered to receive
# any callbacks from netwok class and cancel subscriptions again.
self._release()
return
params, result, error = self._parse_response(response)
if error:
return
scripthash = params[0]
addr = self.h2addr.get(scripthash, None)
if not addr:
return # Bad server response?
history = self.wallet.get_address_history(addr)
if self.get_status(history) != result:
if self.requested_histories.get(scripthash) is None:
self.requested_histories[scripthash] = result
self.network.request_scripthash_history(scripthash, self._on_address_history)
# remove addr from list only after it is added to requested_histories
self.requested_hashes.discard(scripthash) # Notifications won't be in
# See if now the change address needs to be recategorized
self._check_change_scripthash(scripthash)
def _on_address_history(self, response):
if self.cleaned_up:
return
params, result, error = self._parse_response(response)
if error:
return
scripthash = params[0]
addr = self.h2addr.get(scripthash, None)
if not addr or not scripthash in self.requested_histories:
return # Bad server response?
self.print_error("receiving history {} {}".format(addr, len(result)))
# Remove request; this allows up_to_date to be True
server_status = self.requested_histories.pop(scripthash)
hashes = set(map(lambda item: item['tx_hash'], result))
hist = list(map(lambda item: (item['tx_hash'], item['height']), result))
# tx_fees
tx_fees = [(item['tx_hash'], item.get('fee')) for item in result]
tx_fees = dict(filter(lambda x:x[1] is not None, tx_fees))
# Check that txids are unique
if len(hashes) != len(result):
self.print_error("error: server history has non-unique txids: {}"
.format(addr))
# Check that the status corresponds to what was announced
elif self.get_status(hist) != server_status:
self.print_error("error: status mismatch: {}".format(addr))
else:
# Store received history
self.wallet.receive_history_callback(addr, hist, tx_fees)
# Request transactions we don't have
self._request_missing_txs(hist, scripthash)
# Check that this scripthash is a candidate for purge
self._check_change_scripthash(scripthash)
def _tx_response(self, response, scripthash: Optional[str]):
if self.cleaned_up:
return
params, result, error = self._parse_response(response)
tx_hash = params[0] or ''
# unconditionally pop. so we don't end up in a "not up to date" state
# on bad | |
$t/$i
"""
tags = {}
categories = {}
context = []
context_stack = []
format_string = mapping_string
use_expression = False
if mapping_string[0] in ("'", '"'):
use_expression = True
format_string, mapping_string = mapping_string.split("#", 1)
for key, replacement in cls.filetypes:
mapping_string = mapping_string.replace(key, replacement)
for m in cls.map_re.finditer(mapping_string):
key = m[0]
replacement = cls.maps[key]
mapping_string = mapping_string.replace(key, replacement)
key = key[-1]
context.append(key)
if key == "Y":
context_stack.append([post.date_published.year])
elif key == "m":
context_stack.append([post.date_published.month])
elif key == "A":
context_stack.append([post.author_id])
elif key == "C":
c_stack = []
for c in post.categories:
c_stack.append(c.id)
categories[c.id] = c
context_stack.append(c_stack)
elif key == "t":
t_stack = []
for t in post.tags:
t_stack.append(t.id)
tags[t.id] = t
context_stack.append(t_stack)
context_str = "".join(context)
final_stack = []
data_dict = {"post": post}
for _ in product(*context_stack):
data_stack = []
for data, ctx in zip(_, context):
if ctx == "t":
data_dict["tag"] = tags[data]
elif ctx == "C":
data_dict["category"] = categories[data]
data_stack.append(data)
try:
if use_expression:
context_path = format_string
for key, replacement in cls.all_replacements.items():
if key in context_path:
context_path = context_path.replace(
key, replacement.format(**data_dict)
)
context_path = eval(context_path, None, data_dict)
# context_path = context_path.format(**data_dict)
else:
context_path = mapping_string.format(**data_dict)
if context_path == "":
continue
final_stack.append([context_path, data_stack, context_str])
except IndexError as e:
raise e
return final_stack
@classmethod
def build_fileinfos(cls, posts, blog, templates, mappings):
if posts is None:
posts = [Post(blog=blog)]
for p in posts:
for template in templates:
for mapping in mappings[template.id]:
filepaths = cls.make_filepaths(p, mapping.mapping)
for filepath, archive_context, context_id in filepaths:
fi, created = FileInfo.get_or_create(
unique_path=f"{blog.id},{filepath}",
defaults={
"filepath": filepath,
"templatemapping": mapping,
"template": template,
"blog": blog,
},
)
if created:
for idx, context_data in enumerate(archive_context):
# print ("FIID", fi.id)
Context.create(
fileinfo=fi,
context_type=context_id[idx],
context_id=context_data,
sort=idx,
)
FileInfoMapping.create(
fileinfo=fi, post=p,
)
@classmethod
def build_archive_fileinfos_from_posts(cls, posts, blog):
templates = [
t
for t in blog.templates.where(
Template.template_type << (TemplateType.ARCHIVE, TemplateType.POST)
)
]
mappings = {
template.id: [m for m in template.mappings] for template in templates
}
cls.build_fileinfos(posts, blog, templates, mappings)
@classmethod
def build_index_fileinfos_for_blog(cls, blog):
templates = [
t
for t in blog.templates.where(
Template.template_type << (TemplateType.INDEX, TemplateType.SSI)
)
]
mappings = {
template.id: [m for m in template.mappings] for template in templates
}
cls.build_fileinfos(None, blog, templates, mappings)
@property
def mappings(self):
return FileInfoMapping.select().where(FileInfoMapping.fileinfo == self)
@property
def context(self):
return (
Context.select()
.where(Context.fileinfo == self)
.order_by(Context.sort.asc())
)
@property
def preview_filepath(self):
return f"{self.filepath}.preview.{self.blog.base_filetype}"
def write_preview_file(self):
# print(self.id)
self.write_file(True)
self.update(preview_built=True).where(FileInfo.id == self).execute()
def clear_preview_file(self):
p = pathlib.Path(self.blog.base_filepath, self.preview_filepath)
if p.exists():
os.remove(str(p))
self.update(preview_built=False).where(FileInfo.id == self).execute()
def write_file(self, as_preview=False):
output_template = self.template
if output_template.template_type == TemplateType.POST:
ctx = ArchiveContext(self.mappings.get().post, self.templatemapping)
else:
ctx = ArchiveContext(self, self.templatemapping)
output_text = output_template.render(post=ctx.post, blog=ctx.blog, archive=ctx)
output_path = pathlib.Path(
ctx.blog.base_filepath,
self.preview_filepath if as_preview else self.filepath,
)
output_path_parent = output_path.parents[0]
if not output_path_parent.exists():
os.makedirs(output_path_parent)
with open(output_path, "w", encoding="utf8") as f:
f.write(output_text)
def remove_file(self):
output_path = pathlib.Path(self.blog.base_filepath, self.filepath)
if output_path.exists():
os.remove(output_path)
def enqueue(self, manual_ok=False):
t = Template._dbcache(self.template_id).publishing_mode
if t == TemplatePublishingMode.QUEUE or (
manual_ok and t == TemplatePublishingMode.MANUAL
):
return Queue.add_fileinfo_job(self, self.blog)
return None, 0
def dequeue(self):
Queue.delete().where(
Queue.blog == self.blog,
Queue.obj_type == QueueObjType.WRITE_FILEINFO,
Queue.fileinfo == self,
).execute()
class FileInfoMapping(BaseModel):
"""
Describes which fileinfos are used to write all the files associated
with a given blog post, include template, or index template.
"""
fileinfo = ForeignKeyField(FileInfo, index=True,)
post = ForeignKeyField(Post, null=True, index=True,)
class Context(BaseModel):
"""
Describes the context associated with a given fileinfo/post combination.
There must only be one set of these for each fileinfo.
"""
fileinfo = ForeignKeyField(FileInfo, index=True)
context_type = CharField(max_length=1, index=True)
context_id = IntegerField(index=True)
sort = IntegerField()
class Queue(BaseModel):
obj_type = QueueObjTypeField(null=False, index=True)
status = QueueStatusField(index=True, default=QueueStatus.WAITING)
priority = IntegerField(null=False, default=10, index=True)
blog = ForeignKeyField(Blog, index=True)
fileinfo = ForeignKeyField(FileInfo, index=True, null=True)
text_data = TextField(null=True)
integer_data = IntegerField(null=True)
failure_data = TextField(null=True)
date_inserted = DateTimeField(default=datetime.datetime.utcnow)
date_updated = DateTimeField(default=datetime.datetime.utcnow)
# profiler = None
worker = None
state = None
# Listing methods
@property
def date_inserted_str(self):
return date_to_str(self.date_inserted)
@classmethod
def listing_columns(cls):
return "ID", "Type", "Fileinfo", "Template", "Status", "Priority", "Date"
def listing(self):
return (
self.id,
QueueObjType.txt[self.obj_type],
self.fileinfo.filepath if self.fileinfo else "",
self.fileinfo.template.title if self.fileinfo else "",
""
if self.status is None
else f'<a href="{self.manage_item_link}">{QueueStatus.txt[self.status]}</a>',
self.priority,
self.date_inserted_str
# date_to_str(self.date_inserted),
)
@property
def manage_item_link(self):
return f"{self.blog.manage_link}/queue-item/{self.id}"
@classmethod
def failures(cls, blog=None):
failures = cls.select().where(cls.status == QueueStatus.FAILED)
if blog is not None:
failures = failures.where(cls.blog == blog)
return failures
@classmethod
def add_fileinfo_job(cls, fileinfo: FileInfo, blog: Blog):
now = datetime.datetime.utcnow()
return cls.get_or_create(
obj_type=QueueObjType.WRITE_FILEINFO,
fileinfo=fileinfo,
defaults={
"priority": fileinfo.priority,
"blog": blog,
"date_inserted": now,
"date_updated": now,
},
)
@classmethod
def add_delete_fileinfo_job(cls, fileinfo: FileInfo, blog: Blog):
with db.atomic():
try:
existing_job = cls.get(
obj_type=QueueObjType.DEL_FILEINFO, fileinfo=fileinfo
)
except Queue.DoesNotExist:
now = datetime.datetime.utcnow()
new_job = cls.create(
obj_type=QueueObjType.DEL_FILEINFO,
priority=0,
blog=blog,
fileinfo=fileinfo,
date_inserted=now,
date_updated=now,
)
return new_job
else:
return existing_job
@classmethod
def add_delete_file_job(cls, file_path: str, blog: Blog):
with db.atomic():
try:
existing_job = cls.get(
obj_type=QueueObjType.DEL_FILE, text_data=file_path, blog=blog
)
except Queue.DoesNotExist:
now = datetime.datetime.utcnow()
new_job = cls.create(
obj_type=QueueObjType.DEL_FILE,
text_data=file_path,
priority=11,
blog=blog,
date_inserted=now,
date_updated=now,
)
return new_job
return existing_job
def lock(self):
self.status = QueueStatus.RUNNING
self.save()
def unlock(self):
self.status = QueueStatus.WAITING
self.save()
@classmethod
def stop(cls, blog):
p = cls.control_jobs(blog)
if p:
p.status = QueueStatus.STOPPED
p.save()
@classmethod
def restart(cls, blog):
p = cls.control_jobs(blog)
if p:
p.status = QueueStatus.WAITING
p.save()
cls.start(force_start=True)
@classmethod
def start(cls, force_start=False):
if Queue.is_locked():
if not force_start:
return
force = "--force" if force_start else ""
subprocess.Popen(
[
sys.executable,
str(pathlib.Path(APP_DIR, "scripts", "schedule.py")),
force,
]
)
@classmethod
def jobs(cls):
return cls.select().where(cls.obj_type != QueueObjType.CONTROL)
@classmethod
def reset_failed(cls, blog):
now = datetime.datetime.utcnow()
Queue.update(
status=QueueStatus.WAITING, date_inserted=now, date_updated=now,
).where(Queue.status == QueueStatus.FAILED, Queue.blog == blog,).execute()
@classmethod
def add_control(cls, blog):
return Queue.create(
obj_type=QueueObjType.CONTROL, blog=blog, status=QueueStatus.WAITING
)
@classmethod
def _control_jobs(cls, blog=None):
jobs = (
cls.select()
.where(cls.obj_type == QueueObjType.CONTROL)
.order_by(cls.date_inserted.asc())
)
if blog is not None:
jobs = jobs.where(cls.blog == blog)
return jobs
@classmethod
def control_jobs(cls, blog=None):
jobs = cls._control_jobs()
if blog is not None:
try:
jobs = jobs.where(cls.blog == blog).get()
except Queue.DoesNotExist:
return None
return jobs
@classmethod
def is_locked(cls, blog=None):
ctl = cls.control_jobs(blog)
if blog is None:
try:
ctl = ctl.get()
except Queue.DoesNotExist:
return False
if ctl is None:
return False
return ctl.status == QueueStatus.RUNNING
@classmethod
def run_queue_(cls, blog=None):
if blog is not None:
cls.add_control(blog)
print(f"Adding control job for blog {blog.id}.")
while True:
try:
job = cls.control_jobs().get()
except Queue.DoesNotExist:
print("No more control jobs.")
break
blog = job.blog
total = 0
print(f"Starting run for blog {blog.id}")
job.lock()
begin = clock()
while True:
count, timer = cls.run(job, batch_time_limit=2.0)
if not count:
break
try:
job = Queue.get_by_id(job.id)
except Queue.DoesNotExist:
print("Queue run interrupted.")
break
if job.status != QueueStatus.RUNNING:
print("Queue run interrupted.")
break
total += count
print(
f"{count} jobs in {timer:.3f} secs. {blog.queue_jobs().count()} remaining."
)
job.date_updated = datetime.datetime.utcnow()
job.save()
sleep(random.random())
print(
f"Finished {total} jobs for blog {blog.id} in {clock()-begin:.3f} secs."
)
failures = cls.failures(blog).count()
if failures:
print(f"WARNING: {failures} job(s) failed to publish.")
if job.status == QueueStatus.RUNNING:
job.delete_instance()
else:
break
@classmethod
def run_immediately(cls, blog):
# This must be called from within a db context!
job = Queue.add_control(blog)
cls.run.__wrapped__(cls, job)
job.delete_instance()
@classmethod
@db_context
def run(cls, job, batch_count=None, batch_time_limit=None):
gc.disable()
blog = job.blog
batch = (
cls.select()
.where(
cls.blog == blog,
cls.obj_type != QueueObjType.CONTROL,
cls.status != QueueStatus.FAILED,
cls.date_inserted <= job.date_inserted,
)
.order_by(cls.priority.desc())
)
if batch_count:
batch = batch.limit(batch_count)
start_time = clock()
last_time = 0.0
count = 0
item: Queue
for item in batch:
try:
f = item.fileinfo
t = item.obj_type
if t == QueueObjType.WRITE_FILEINFO:
if f.preview_built:
f.clear_preview_file()
f.write_file()
elif t == QueueObjType.DEL_FILEINFO:
if f.preview_built:
f.clear_preview_file()
f.remove_file()
elif t == QueueObjType.DEL_FILE:
delpath = pathlib.Path(blog.base_filepath, item.text_data)
if delpath.exists():
os.remove(str(delpath))
except TemplateError as e:
item.status = QueueStatus.FAILED
try:
item.failure_data = str(e)
# ? don't know if we need this anymore, test it
except Exception as ee:
item.failure_data = str(ee)
item.save()
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
item.status = QueueStatus.FAILED
item.failure_data = (
"".join(traceback.format_tb(exc_traceback)) + "\n" + str(e)
)
item.save()
else:
item.delete_instance()
count += 1
last_time = clock() - start_time
if batch_time_limit:
if last_time > batch_time_limit:
break
gc.enable()
return count, last_time
class ArchiveContext:
settings = settings
# TODO: consolidate all next/previous into a single property on the post itself.
context_cache = {}
def __init__(self, context_obj, template_mapping):
self.mapping = template_mapping
# self.template = template_mapping.template
self.template = Template._dbcache(template_mapping.template_id)
self._context_obj = context_obj
self.types = | |
plugin is always deployed.
# - The image format plugins are always deployed.
# - The print support plugin is always deployed.
# - SQL driver plugins are deployed if the application uses the Qt SQL
# module.
# - Script plugins are deployed if the application uses the Qt Script
# module.
# - The SVG icon plugin is deployed if the application uses the Qt SVG
# module.
# - The accessibility plugin is always deployed.
#
# - Per the `Deploying QML Applications <http://doc.qt.io/qt-5/qtquick-deployment.html>`_
# page, QML-based applications need the ``qml/`` directory available.
# This is handled by ``hook-PyQt5.QtQuick.py``.
# - Per the `Deploying Qt WebEngine Applications <https://doc.qt.io/qt-5.10/qtwebengine-deploying.html>`_
# page, deployment may include:
#
# - Libraries (handled when PyInstaller following dependencies).
# - QML imports (if Qt Quick integration is used).
# - Qt WebEngine process, which should be located at
# ``QLibraryInfo::location(QLibraryInfo::LibraryExecutablesPath)``
# for Windows and Linux, and in ``.app/Helpers/QtWebEngineProcess``
# for Mac.
# - Resources: the files listed in deployWebEngineCore_.
# - Translations: on macOS: ``.app/Content/Resources``; on Linux and
# Windows: ``qtwebengine_locales`` directory in the directory
# specified by ``QLibraryInfo::location(QLibraryInfo::TranslationsPath)``.
# - Audio and video codecs: Probably covered if Qt5Multimedia is
# referenced?
#
# This is handled by ``hook-PyQt5.QtWebEngineWidgets.py``.
#
# - Since `QAxContainer <http://doc.qt.io/qt-5/activeqt-index.html>`_ is a
# statically-linked library, it doesn't need any special handling.
#
# - Sources for the `Windows Deployment Tool <http://doc.qt.io/qt-5/windows-deployment.html#the-windows-deployment-tool>`_
# show more detail:
#
# - The `PluginModuleMapping struct <https://code.woboq.org/qt5/qttools/src/windeployqt/main.cpp.html#PluginModuleMapping>`_
# and the following ``pluginModuleMappings`` global provide a mapping
# between a plugin directory name and an `enum of Qt plugin names
# <https://code.woboq.org/qt5/qttools/src/windeployqt/main.cpp.html#QtModule>`_.
# - The `QtModuleEntry struct <https://code.woboq.org/qt5/qttools/src/windeployqt/main.cpp.html#QtModuleEntry>`_
# and ``qtModuleEntries`` global connect this enum to the name of the Qt5
# library it represents and to the translation files this library
# requires. (Ignore the ``option`` member -- it's just for command-line
# parsing.)
#
# Manually combining these two provides a mapping of Qt library names to the
# translation and plugin(s) needed by the library. The process is: take the
# key of the dict below from ``QtModuleEntry.libraryName``, but make it
# lowercase (since Windows files will be normalized to lowercase). The
# ``QtModuleEntry.translation`` provides the ``translation_base``. Match the
# ``QtModuleEntry.module`` with ``PluginModuleMapping.module`` to find the
# ``PluginModuleMapping.directoryName`` for the required plugin(s).
#
# - The `deployWebEngineCore <https://code.woboq.org/qt5/qttools/src/windeployqt/main.cpp.html#_ZL19deployWebEngineCoreRK4QMapI7QStringS0_ERK7OptionsbPS0_>`_
# function copies the following files from ``resources/``, and also copies
# the web engine process executable.
#
# - ``icudtl.dat``
# - ``qtwebengine_devtools_resources.pak``
# - ``qtwebengine_resources.pak``
# - ``qtwebengine_resources_100p.pak``
# - ``qtwebengine_resources_200p.pak``
#
# - Sources for the `Mac deployment tool`_ are less helpful. The `deployPlugins
# <https://code.woboq.org/qt5/qttools/src/macdeployqt/shared/shared.cpp.html#_Z13deployPluginsRK21ApplicationBundleInfoRK7QStringS2_14DeploymentInfob>`_
# function seems to:
#
# - Always include ``platforms/libqcocoa.dylib``.
# - Always include ``printsupport/libcocoaprintersupport.dylib``
# - Include ``bearer/`` if ``QtNetwork`` is included (and some other
# condition I didn't look up).
# - Always include ``imageformats/``, except for ``qsvg``.
# - Include ``imageformats/qsvg`` if ``QtSvg`` is included.
# - Always include ``iconengines/``.
# - Include ``sqldrivers/`` if ``QtSql`` is included.
# - Include ``mediaservice/`` and ``audio/`` if ``QtMultimedia`` is
# included.
#
# The always includes will be handled by ``hook-PyQt5.py`` or
# ``hook-PySide2.py``; optional includes are already covered by the dict
# below.
#
_qt5_dynamic_dependencies_dict = {
## "lib_name": (.hiddenimports, translations_base, zero or more plugins...)
"qt5bluetooth": (".QtBluetooth", None, ), # noqa: E241,E202
"qt5concurrent": (None, "qtbase", ),
"qt5core": (".QtCore", "qtbase", ),
# This entry generated by hand -- it's not present in the Windows deployment tool sources.
"qtdbus": (".QtDBus", None, ),
"qt5declarative": (None, "qtquick1", "qml1tooling"),
"qt5designer": (".QtDesigner", None, ),
"qt5designercomponents": (None, None, ),
"enginio": (None, None, ),
"qt5gamepad": (None, None, "gamepads"),
# Note: The ``platformthemes`` plugin is for Linux only, and comes from earlier PyInstaller code in ``hook-PyQt5.QtGui.py``. The ``styles`` plugin comes from the suggestion at https://github.com/pyinstaller/pyinstaller/issues/2156.
# ``xcbglintegrations`` and ``egldeviceintegrations`` were added manually
# for linux
"qt5gui": (".QtGui", "qtbase", "accessible", "iconengines", "imageformats", "platforms", "platforminputcontexts", "platformthemes", "styles", "xcbglintegrations", "egldeviceintegrations"), # noqa
"qt5help": (".QtHelp", "qt_help", ),
# This entry generated by hand -- it's not present in the Windows deployment tool sources.
"qt5macextras": (".QtMacExtras", None, ),
"qt5multimedia": (".QtMultimedia", "qtmultimedia", "audio", "mediaservice", "playlistformats"),
"qt5multimediawidgets": (".QtMultimediaWidgets", "qtmultimedia", ),
"qt5multimediaquick_p": (None, "qtmultimedia", ),
"qt5network": (".QtNetwork", "qtbase", "bearer"),
"qt5nfc": (".QtNfc", None, ),
"qt5opengl": (".QtOpenGL", None, ), # noqa
"qt5positioning": (".QtPositioning", None, "position"),
"qt5printsupport": (".QtPrintSupport", None, "printsupport"),
"qt5qml": (".QtQml", "qtdeclarative", ),
"qmltooling": (None, None, "qmltooling"),
"qt5quick": (".QtQuick", "qtdeclarative", "scenegraph", "qmltooling"), # noqa
"qt5quickparticles": (None, None, ),
"qt5quickwidgets": (".QtQuickWidgets", None, ),
"qt5script": (None, "qtscript", ),
"qt5scripttools": (None, "qtscript", ),
"qt5sensors": (".QtSensors", None, "sensors", "sensorgestures"),
"qt5serialport": (".QtSerialPort", "qtserialport", ),
"qt5sql": (".QtSql", "qtbase", "sqldrivers"),
"qt5svg": (".QtSvg", None, ),
"qt5test": (".QtTest", "qtbase", ),
"qt5webkit": (None, None, ),
"qt5webkitwidgets": (None, None, ),
"qt5websockets": (".QtWebSockets", None, ),
"qt5widgets": (".QtWidgets", "qtbase", ),
"qt5winextras": (".QtWinExtras", None, ),
"qt5xml": (".QtXml", "qtbase", ),
"qt5xmlpatterns": (".QXmlPatterns", "qtxmlpatterns", ),
"qt5webenginecore": (".QtWebEngineCore", None, "qtwebengine"), # noqa
"qt5webengine": (".QtWebEngine", "qtwebengine", "qtwebengine"),
"qt5webenginewidgets": (".QtWebEngineWidgets", None, "qtwebengine"),
"qt53dcore": (None, None, ),
"qt53drender": (None, None, "sceneparsers", "renderplugins", "geometryloaders"),
"qt53dquick": (None, None, ),
"qt53dquickRender": (None, None, ),
"qt53dinput": (None, None, ),
"qt5location": (".QtLocation", None, "geoservices"),
"qt5webchannel": (".QtWebChannel", None, ),
"qt5texttospeech": (None, None, "texttospeech"),
"qt5serialbus": (None, None, "canbus"),
}
# The dynamic dependency dictionary for Qt6 is constructed automatically
# from its Qt5 counterpart, by copying the entries and substituting
# qt5 in the name with qt6. If the entry already exists in the dictionary,
# it is not copied, which allows us to provide Qt6-specific overrides,
# should they prove necessary.
_qt6_dynamic_dependencies_dict = {}
for lib_name, content in _qt5_dynamic_dependencies_dict.items():
if lib_name.startswith('qt5'):
lib_name = 'qt6' + lib_name[3:]
if lib_name not in _qt6_dynamic_dependencies_dict:
_qt6_dynamic_dependencies_dict[lib_name] = content
del lib_name, content
# add_qt_dependencies
# --------------------
# Generic implemnentation that finds the Qt 5/6 dependencies based on
# the hook name of a PyQt5/PyQt6/PySide2/PySide6 hook. Returns
# (hiddenimports, binaries, datas). Typical usage: ``hiddenimports, binaries,
# datas = add_qt5_dependencies(__file__)``.
def add_qt_dependencies(hook_file):
# Accumulate all dependencies in a set to avoid duplicates.
hiddenimports = set()
translations_base = set()
plugins = set()
# Find the module underlying this Qt hook: change
# ``/path/to/hook-PyQt5.blah.py`` to ``PyQt5.blah``.
hook_name, hook_ext = os.path.splitext(os.path.basename(hook_file))
assert hook_ext.startswith('.py')
assert hook_name.startswith('hook-')
module_name = hook_name[5:]
namespace = module_name.split('.')[0]
# Retrieve Qt library info structure
qt_info = get_qt_library_info(namespace)
# Exit if the requested library can't be imported. NOTE: qt_info.version
# can be empty list on older Qt5 versions (#5381)
if qt_info.version is None:
return [], [], []
# Look up the module returned by this import.
module = hooks.get_module_file_attribute(module_name)
logger.debug('add_qt%d_dependencies: Examining %s, based on hook of %s.',
qt_info.qt_major, module, hook_file)
# Walk through all the static dependencies of a dynamically-linked library
# (``.so``/``.dll``/``.dylib``).
imports = set(bindepend.getImports(module))
while imports:
imp = imports.pop()
# On Windows, find this library; other platforms already provide the
# full path.
if compat.is_win:
# First, look for Qt binaries in the local Qt install.
imp = bindepend.getfullnameof(
imp, qt_info.location['BinariesPath'])
# Strip off the extension and ``lib`` prefix (Linux/Mac) to give the raw
# name. Lowercase (since Windows always normalized names to lowercase).
lib_name = os.path.splitext(os.path.basename(imp))[0].lower()
# Linux libraries sometimes have a dotted version number --
# ``libfoo.so.3``. It's now ''libfoo.so``, but the ``.so`` must also be
# removed.
if compat.is_linux and os.path.splitext(lib_name)[1] == '.so':
lib_name = os.path.splitext(lib_name)[0]
if lib_name.startswith('lib'):
lib_name = lib_name[3:]
# Mac: rename from ``qt`` to ``qt5`` or ``qt6`` to match names in
# Windows/Linux.
if compat.is_darwin and lib_name.startswith('qt'):
lib_name = 'qt' + str(qt_info.qt_major) + lib_name[2:]
# match libs with QT_LIBINFIX set to '_conda', i.e. conda-forge builds
if lib_name.endswith('_conda'):
lib_name = lib_name[:-6]
logger.debug('add_qt%d_dependencies: raw lib %s -> parsed lib %s',
qt_info.qt_major, imp, lib_name)
# Follow only Qt dependencies.
_qt_dynamic_dependencies_dict = (
_qt5_dynamic_dependencies_dict if qt_info.qt_major == 5
else _qt6_dynamic_dependencies_dict)
if lib_name in _qt_dynamic_dependencies_dict:
# Follow these to find additional dependencies.
logger.debug('add_qt%d_dependencies: Import of %s.',
qt_info.qt_major, imp)
imports.update(bindepend.getImports(imp))
# Look up which plugins and translations are needed.
dd = _qt_dynamic_dependencies_dict[lib_name]
lib_name_hiddenimports, lib_name_translations_base = dd[:2]
lib_name_plugins = dd[2:]
# Add them in.
if lib_name_hiddenimports:
hiddenimports.update([namespace + lib_name_hiddenimports])
plugins.update(lib_name_plugins)
if lib_name_translations_base:
translations_base.update([lib_name_translations_base])
# Change plugins into binaries.
binaries = []
for plugin in plugins:
more_binaries = qt_plugins_binaries(plugin, namespace=namespace)
binaries.extend(more_binaries)
# Change translation_base to datas.
tp = qt_info.location['TranslationsPath']
tp_dst = os.path.join(qt_info.qt_rel_dir, 'translations')
datas = []
for tb in translations_base:
src = os.path.join(tp, tb + '_*.qm')
# Not all PyQt5 installations include translations. See
# https://github.com/pyinstaller/pyinstaller/pull/3229#issuecomment-359479893
# and
# https://github.com/pyinstaller/pyinstaller/issues/2857#issuecomment-368744341.
if glob.glob(src):
datas.append((src, tp_dst))
else:
logger.warning('Unable to find Qt%d translations %s. These '
'translations were not packaged.',
qt_info.qt_major, src)
# Change hiddenimports to a list.
hiddenimports | |
<filename>haskell/private/cc_libraries.bzl
"""Tools for handling and linking static and dynamic libraries.
This includes C and Haskell libraries as both are tracked in CcInfo
providers.
"""
load("@bazel_skylib//lib:dicts.bzl", "dicts")
load("@bazel_skylib//lib:paths.bzl", "paths")
load(
":private/packages.bzl",
"ghc_pkg_recache",
"write_package_conf",
)
load(
":private/path_utils.bzl",
"create_rpath_entry",
"get_lib_name",
"is_hs_library",
"make_library_path",
"mangle_static_library",
"rel_to_pkgroot",
"target_unique_name",
)
load(
":providers.bzl",
"HaskellCcLibrariesInfo",
"HaskellCcLibraryInfo",
"HaskellInfo",
"HaskellProtobufInfo",
)
def _min_lib_to_link(a, b):
"""Return the smaller of two LibraryToLink objects.
Determined by component-wise comparison.
"""
a_tuple = (
a.dynamic_library,
a.interface_library,
a.static_library,
a.pic_static_library,
)
b_tuple = (
b.dynamic_library,
b.interface_library,
b.static_library,
b.pic_static_library,
)
if a_tuple < b_tuple:
return a
else:
return b
def _get_unique_lib_files(cc_info):
"""Deduplicate library dependencies.
This function removes duplicate filenames in the list of library
dependencies to avoid clashes when creating symlinks. Such duplicates can
occur due to dependencies on haskell_toolchain_library targets which each
duplicate their core library dependencies. See
https://github.com/tweag/rules_haskell/issues/917.
This function preserves correct static linking order.
This function is deterministic in which LibraryToLink is chosen as the
unique representative independent of their order of appearance.
Args:
cc_info: Combined CcInfo provider of dependencies.
Returns:
List of LibraryToLink: list of unique libraries to link.
"""
libs_to_link = cc_info.linking_context.libraries_to_link
# This is a workaround for duplicated libraries due to
# haskell_toolchain_library dependencies. See
# https://github.com/tweag/rules_haskell/issues/917
libs_by_filename = {}
filenames = []
for lib_to_link in libs_to_link.to_list():
if lib_to_link.dynamic_library:
lib = lib_to_link.dynamic_library
elif lib_to_link.interface_library:
lib = lib_to_link.interface_library
elif lib_to_link.static_library:
lib = lib_to_link.static_library
elif lib_to_link.pic_static_library:
lib = lib_to_link.pic_static_library
else:
fail("Empty CcInfo.linking_context.libraries_to_link entry.")
prev = libs_by_filename.get(lib.basename)
if prev:
# To be deterministic we always use File that compares smaller.
# This is so that this function can be used multiple times for the
# same target without generating conflicting actions. E.g. for the
# compilation step as well as the runghc generation step.
libs_by_filename[lib.basename] = _min_lib_to_link(prev, lib_to_link)
else:
libs_by_filename[lib.basename] = lib_to_link
filenames.append(lib.basename)
# Deduplicate the library names. Make sure to preserve static linking order.
filenames = depset(
transitive = [depset(direct = [filename]) for filename in filenames],
order = "topological",
).to_list()
return [
libs_by_filename[filename]
for filename in filenames
]
def get_ghci_extra_libs(hs, posix, cc_libraries_info, cc_info, path_prefix = None):
"""Get libraries appropriate for GHCi's linker.
GHC expects dynamic and static versions of the same library to have the
same library name. Static libraries for which this is not the case will be
symlinked to a matching name.
Furthermore, dynamic libraries will be symbolically linked into a common
directory to allow for less RPATH entries and to fix file extensions that
GHCi does not support.
GHCi can load PIC static libraries (-fPIC -fexternal-dynamic-refs) with a
dynamic RTS and dynamic libraries with a dynamic RTS.
Args:
hs: Haskell context.
cc_libraries_info: Combined HaskellCcLibrariesInfo of dependencies.
cc_info: Combined CcInfo provider of dependencies.
path_prefix: (optional) Prefix for the entries in the generated library path.
Returns:
(libs, ghc_env):
libs: depset of File, the libraries that should be passed to GHCi.
ghc_env: dict, environment variables to set for GHCi.
"""
(static_libs, dynamic_libs) = get_extra_libs(
hs,
posix,
cc_libraries_info,
cc_info,
dynamic = not hs.toolchain.is_static,
pic = True,
fixup_dir = "_ghci_libs",
)
libs = depset(transitive = [static_libs, dynamic_libs])
# NOTE: We can avoid constructing these in the future by instead generating
# a dedicated package configuration file defining the required libraries.
library_path = make_library_path(hs, libs, prefix = path_prefix)
ghc_env = {
"LIBRARY_PATH": library_path,
"LD_LIBRARY_PATH": library_path,
}
return (libs, ghc_env)
def get_extra_libs(hs, posix, cc_libraries_info, cc_info, dynamic = False, pic = None, fixup_dir = "_libs"):
"""Get libraries appropriate for linking with GHC.
GHC expects dynamic and static versions of the same library to have the
same library name. Static libraries for which this is not the case will be
symlinked to a matching name.
Furthermore, dynamic libraries will be symbolically linked into a common
directory to allow for less RPATH entries.
Args:
hs: Haskell context.
dynamic: Whether to prefer dynamic libraries.
cc_libraries_info: Combined HaskellCcLibrariesInfo of dependencies.
cc_info: Combined CcInfo provider of dependencies.
dynamic: Whether dynamic libraries are preferred.
pic: Whether position independent code is required.
fixup_dir: Generate symbolic links to libraries in this directory.
Returns:
depset of File: the libraries that should be passed to GHC for linking.
"""
fixed_lib_dir = target_unique_name(hs, fixup_dir)
libs_to_link = _get_unique_lib_files(cc_info)
static_libs = []
dynamic_libs = []
if pic == None:
pic = dynamic
# PIC is irrelevant on static GHC.
pic_required = pic and not hs.toolchain.is_static
for lib_to_link in libs_to_link:
cc_library_info = cc_libraries_info.libraries[cc_library_key(lib_to_link)]
dynamic_lib = None
if lib_to_link.dynamic_library:
dynamic_lib = lib_to_link.dynamic_library
elif lib_to_link.interface_library:
dynamic_lib = lib_to_link.interface_library
static_lib = None
if lib_to_link.pic_static_library:
static_lib = cc_library_info.pic_static_library_link
if static_lib == None:
static_lib = lib_to_link.pic_static_library
elif lib_to_link.static_library and not pic_required:
static_lib = cc_library_info.static_library_link
if static_lib == None:
static_lib = lib_to_link.static_library
if static_lib and not (dynamic and dynamic_lib):
static_libs.append(static_lib)
elif dynamic_lib:
dynamic_libs.append(dynamic_lib)
else:
# Fall back if no PIC static library is available. This typically
# happens during profiling builds.
static_libs.append(lib_to_link.static_library)
static_libs = depset(direct = static_libs)
dynamic_libs = depset(direct = dynamic_libs)
return (static_libs, dynamic_libs)
def create_link_config(hs, posix, cc_libraries_info, cc_info, binary, args, dynamic = None, pic = None):
"""Configure linker flags and inputs.
Configure linker flags for C library dependencies and runtime dynamic
library dependencies. And collect the C libraries to pass as inputs to
the linking action. Creates a package configuration file that captures
these flags.
Args:
hs: Haskell context.
cc_libraries_info: Combined HaskellCcLibrariesInfo of dependencies.
cc_info: Combined CcInfo of dependencies.
binary: Final linked binary.
args: Arguments to the linking action.
dynamic: Whether to link dynamically, or statically.
pic: Whether position independent code is required.
Returns:
(cache_file, static_libs, dynamic_libs):
cache_file: File, the cached package configuration.
static_libs: depset of File, static library files.
dynamic_libs: depset of File, dynamic library files.
"""
(static_libs, dynamic_libs) = get_extra_libs(
hs,
posix,
cc_libraries_info,
cc_info,
dynamic = dynamic,
pic = pic,
)
# This test is a hack. When a CC library has a Haskell library
# as a dependency, we need to be careful to filter it out,
# otherwise it will end up polluting the linker flags. GHC
# already uses hs-libraries to link all Haskell libraries.
#
# TODO Get rid of this hack. See
# https://github.com/tweag/rules_haskell/issues/873.
cc_static_libs = depset(direct = [
lib
for lib in static_libs.to_list()
if not is_hs_library(lib)
])
cc_dynamic_libs = depset(direct = [
lib
for lib in dynamic_libs.to_list()
if not is_hs_library(lib)
])
package_name = target_unique_name(hs, "link-config").replace("_", "-").replace("@", "-")
conf_path = paths.join(package_name, package_name + ".conf")
conf_file = hs.actions.declare_file(conf_path)
libs = cc_static_libs.to_list() + cc_dynamic_libs.to_list()
write_package_conf(hs, conf_file, {
"name": package_name,
"extra-libraries": [
get_lib_name(lib)
for lib in libs
],
"library-dirs": depset(direct = [
rel_to_pkgroot(lib.dirname, conf_file.dirname)
for lib in libs
]),
"dynamic-library-dirs": depset(direct = [
rel_to_pkgroot(lib.dirname, conf_file.dirname)
for lib in libs
]),
# XXX: Set user_link_flags.
"ld-options": depset(direct = [
"-Wl,-rpath,%s" % create_rpath_entry(
binary = binary,
dependency = lib,
keep_filename = False,
prefix = "@loader_path" if hs.toolchain.is_darwin else "$ORIGIN",
)
for lib in dynamic_libs.to_list()
]),
})
cache_file = ghc_pkg_recache(hs, posix, conf_file)
args.add_all([
"-package-db",
cache_file.dirname,
"-package",
package_name,
])
return (cache_file, static_libs, dynamic_libs)
def cc_library_key(library_to_link):
"""Convert a LibraryToLink into a hashable dictionary key."""
return struct(
dynamic_library = library_to_link.dynamic_library,
interface_library = library_to_link.interface_library,
static_library = library_to_link.static_library,
pic_static_library = library_to_link.pic_static_library,
)
def deps_HaskellCcLibrariesInfo(deps):
"""Merge the HaskellCcLibrariesInfo over all given dependencies.
Works on proto_library dependencies as well, where HaskellCcLibrariesInfo
needs to be constructed by _haskell_proto_aspect.
Args:
deps: list of Target, extracts HaskellCcLibrariesInfo from the target
directly, or from HaskellProtobufInfo if present.
Returns:
HaskellCcLibrariesInfo
"""
infos = []
for dep in deps:
if HaskellCcLibrariesInfo in dep:
infos.append(dep[HaskellCcLibrariesInfo])
elif HaskellProtobufInfo in dep:
infos.append(dep[HaskellProtobufInfo].cc_libraries_info)
return merge_HaskellCcLibrariesInfo(infos = infos)
def merge_HaskellCcLibrariesInfo(infos):
"""Merge multiple HaskellCcLibrariesInfo.
Prefer deps_HaskellCcLibrariesInfo if possible.
"""
return HaskellCcLibrariesInfo(
libraries = dicts.add(*[info.libraries for info in infos]),
)
def extend_HaskellCcLibrariesInfo(
ctx,
cc_libraries_info,
cc_info,
is_haskell):
"""Adapt new LibraryToLink and add to HaskellCcLibrariesInfo.
Generate a new HaskellCcLibraryInfo for each LibraryToLink in cc_info that
is not already contained in cc_libraries_info and return a new extended
CcLibrariesInfo.
Args:
ctx: Aspect or rule context.
cc_libraries_info: HaskellCcLibrariesInfo of all dependencies.
cc_info: CcInfo of the current target.
is_haskell: Bool, whether the current target is a Haskell library.
Returns:
HaskellCcLibrariesInfo
"""
hs = ctx.toolchains["@rules_haskell//haskell:toolchain"]
posix = ctx.toolchains["@rules_sh//sh/posix:toolchain_type"]
libraries = dict(cc_libraries_info.libraries)
for lib_to_link in cc_info.linking_context.libraries_to_link.to_list():
key = cc_library_key(lib_to_link)
if key in libraries:
continue
if is_haskell:
| |
intents=intents.Intents.ALL,
token="lol",
http_settings=http_settings,
proxy_settings=proxy_settings,
)
@pytest.mark.parametrize(
("compression", "expect"),
[
(None, f"v={shard._VERSION}&encoding=json"),
("transport_zlib_stream", f"v={shard._VERSION}&encoding=json&compress=zlib-stream"),
],
)
def test__init__sets_url_is_correct_json(self, compression, expect, http_settings, proxy_settings):
g = shard.GatewayShardImpl(
event_manager=mock.Mock(),
event_factory=mock.Mock(),
http_settings=http_settings,
proxy_settings=proxy_settings,
intents=intents.Intents.ALL,
url="wss://gaytewhuy.discord.meh",
data_format="json",
compression=compression,
token="12345",
)
assert g._url == f"wss://gaytewhuy.discord.meh?{expect}"
def test_using_etf_is_unsupported(self, http_settings, proxy_settings):
with pytest.raises(NotImplementedError, match="Unsupported gateway data format: etf"):
shard.GatewayShardImpl(
event_manager=mock.Mock(),
event_factory=mock.Mock(),
http_settings=http_settings,
proxy_settings=proxy_settings,
token=mock.Mock(),
url="wss://erlpack-is-broken-lol.discord.meh",
intents=intents.Intents.ALL,
data_format="etf",
compression=True,
)
def test_heartbeat_latency_property(self, client):
client._heartbeat_latency = 420
assert client.heartbeat_latency == 420
def test_id_property(self, client):
client._shard_id = 101
assert client.id == 101
def test_intents_property(self, client):
intents = object()
client._intents = intents
assert client.intents is intents
def test_is_alive_property(self, client):
client._run_task = None
assert client.is_alive is False
@pytest.mark.asyncio()
async def test_is_alive_property_with_active_future(self, client):
client._run_task = asyncio.get_running_loop().create_future()
assert client.is_alive is True
@pytest.mark.asyncio()
async def test_is_alive_property_with_finished_future(self, client):
client._run_task = aio.completed_future()
assert client.is_alive is False
def test_shard_count_property(self, client):
client._shard_count = 69
assert client.shard_count == 69
def test_shard__check_if_alive_when_not_alive(self, client):
with mock.patch.object(shard.GatewayShardImpl, "is_alive", new=False):
with pytest.raises(errors.ComponentStateConflictError):
client._check_if_alive()
def test_shard__check_if_alive_when_alive(self, client):
with mock.patch.object(shard.GatewayShardImpl, "is_alive", new=True):
client._check_if_alive()
async def test_close_when_closing_event_set(self, client):
client._closing_event = mock.Mock(is_set=mock.Mock(return_value=True))
client._closed_event = mock.Mock(wait=mock.AsyncMock())
client._send_close = mock.Mock()
client._chunking_rate_limit = mock.Mock()
client._total_rate_limit = mock.Mock()
await client.close()
client._closing_event.set.assert_not_called()
client._send_close.assert_not_called()
client._chunking_rate_limit.close.assert_not_called()
client._total_rate_limit.close.assert_not_called()
client._closed_event.wait.assert_awaited_once_with()
async def test_close_when_closing_event_not_set(self, client):
client._closing_event = mock.Mock(is_set=mock.Mock(return_value=False))
client._closed_event = mock.Mock(wait=mock.AsyncMock())
client._ws = mock.Mock(send_close=mock.AsyncMock())
client._chunking_rate_limit = mock.Mock()
client._total_rate_limit = mock.Mock()
await client.close()
client._closing_event.set.assert_called_once_with()
client._ws.send_close.assert_awaited_once_with(
code=errors.ShardCloseCode.GOING_AWAY, message=b"shard disconnecting"
)
client._chunking_rate_limit.close.assert_called_once_with()
client._total_rate_limit.close.assert_called_once_with()
client._closed_event.wait.assert_awaited_once_with()
async def test_close_when_closing_event_not_set_and_ws_is_None(self, client):
client._closing_event = mock.Mock(is_set=mock.Mock(return_value=False))
client._closed_event = mock.Mock(wait=mock.AsyncMock())
client._ws = None
client._chunking_rate_limit = mock.Mock()
client._total_rate_limit = mock.Mock()
await client.close()
client._closing_event.set.assert_called_once_with()
client._chunking_rate_limit.close.assert_called_once_with()
client._total_rate_limit.close.assert_called_once_with()
client._closed_event.wait.assert_awaited_once_with()
async def test_when__user_id_is_None(self, client):
client._handshake_completed = mock.Mock(wait=mock.AsyncMock())
client._user_id = None
with pytest.raises(RuntimeError):
assert await client.get_user_id()
async def test_when__user_id_is_not_None(self, client):
client._handshake_completed = mock.Mock(wait=mock.AsyncMock())
client._user_id = 123
assert await client.get_user_id() == 123
def test__get_ws_when_active(self, client):
mock_ws = client._ws = object()
assert client._get_ws() is mock_ws
def test__get_ws_when_inactive(self, client):
client._ws = None
with pytest.raises(errors.ComponentStateConflictError):
client._get_ws()
async def test_join(self, client):
client._closed_event = mock.Mock(wait=mock.AsyncMock())
await client.join()
client._closed_event.wait.assert_awaited_once_with()
async def test_request_guild_members_when_no_query_and_no_limit_and_GUILD_MEMBERS_not_enabled(self, client):
client._check_if_alive = mock.Mock()
client._intents = intents.Intents.GUILD_INTEGRATIONS
with pytest.raises(errors.MissingIntentError):
await client.request_guild_members(123, query="", limit=0)
client._check_if_alive.assert_called_once_with()
async def test_request_guild_members_when_presences_and_GUILD_PRESENCES_not_enabled(self, client):
client._check_if_alive = mock.Mock()
client._intents = intents.Intents.GUILD_INTEGRATIONS
with pytest.raises(errors.MissingIntentError):
await client.request_guild_members(123, query="test", limit=1, include_presences=True)
client._check_if_alive.assert_called_once_with()
async def test_request_guild_members_when_presences_false_and_GUILD_PRESENCES_not_enabled(self, client):
client._check_if_alive = mock.Mock()
client._intents = intents.Intents.GUILD_INTEGRATIONS
client._send_json = mock.AsyncMock()
await client.request_guild_members(123, query="test", limit=1, include_presences=False)
client._send_json.assert_awaited_once_with(
{
"op": 8,
"d": {"guild_id": "123", "query": "test", "presences": False, "limit": 1},
}
)
client._check_if_alive.assert_called_once_with()
@pytest.mark.parametrize("kwargs", [{"query": "some query"}, {"limit": 1}])
async def test_request_guild_members_when_specifiying_users_with_limit_or_query(self, client, kwargs):
client._check_if_alive = mock.Mock()
client._intents = intents.Intents.GUILD_INTEGRATIONS
with pytest.raises(ValueError, match="Cannot specify limit/query with users"):
await client.request_guild_members(123, users=[], **kwargs)
client._check_if_alive.assert_called_once_with()
@pytest.mark.parametrize("limit", [-1, 101])
async def test_request_guild_members_when_limit_under_0_or_over_100(self, client, limit):
client._check_if_alive = mock.Mock()
client._intents = intents.Intents.ALL
with pytest.raises(ValueError, match="'limit' must be between 0 and 100, both inclusive"):
await client.request_guild_members(123, limit=limit)
client._check_if_alive.assert_called_once_with()
async def test_request_guild_members_when_users_over_100(self, client):
client._check_if_alive = mock.Mock()
client._intents = intents.Intents.ALL
with pytest.raises(ValueError, match="'users' is limited to 100 users"):
await client.request_guild_members(123, users=range(101))
client._check_if_alive.assert_called_once_with()
async def test_request_guild_members_when_nonce_over_32_chars(self, client):
client._check_if_alive = mock.Mock()
client._intents = intents.Intents.ALL
with pytest.raises(ValueError, match="'nonce' can be no longer than 32 byte characters long."):
await client.request_guild_members(123, nonce="x" * 33)
client._check_if_alive.assert_called_once_with()
@pytest.mark.parametrize("include_presences", [True, False])
async def test_request_guild_members(self, client, include_presences):
client._intents = intents.Intents.ALL
client._check_if_alive = mock.Mock()
client._send_json = mock.AsyncMock()
await client.request_guild_members(123, include_presences=include_presences)
client._send_json.assert_awaited_once_with(
{
"op": 8,
"d": {"guild_id": "123", "query": "", "presences": include_presences, "limit": 0},
}
)
client._check_if_alive.assert_called_once_with()
async def test_start_when_already_running(self, client):
client._run_task = object()
with pytest.raises(errors.ComponentStateConflictError):
await client.start()
async def test_start_when_shard_closed_before_starting(self, client):
client._run_task = None
client._shard_id = 20
client._run = mock.Mock()
client._handshake_completed = mock.Mock(wait=mock.Mock())
run_task = mock.Mock()
waiter = mock.Mock()
stack = contextlib.ExitStack()
create_task = stack.enter_context(mock.patch.object(asyncio, "create_task", side_effect=[run_task, waiter]))
wait = stack.enter_context(mock.patch.object(asyncio, "wait", return_value=([run_task], [waiter])))
stack.enter_context(
pytest.raises(asyncio.CancelledError, match="shard 20 was closed before it could start successfully")
)
with stack:
await client.start()
assert client._run_task is None
assert create_task.call_count == 2
create_task.has_call(mock.call(client._run(), name="run shard 20"))
create_task.has_call(mock.call(client._handshake_completed.wait(), name="wait for shard 20 to start"))
run_task.result.assert_called_once_with()
waiter.cancel.assert_called_once_with()
wait.assert_awaited_once_with((waiter, run_task), return_when=asyncio.FIRST_COMPLETED)
async def test_start(self, client):
client._run_task = None
client._shard_id = 20
client._run = mock.Mock()
client._handshake_completed = mock.Mock(wait=mock.Mock())
run_task = mock.Mock()
waiter = mock.Mock()
with mock.patch.object(asyncio, "create_task", side_effect=[run_task, waiter]) as create_task:
with mock.patch.object(asyncio, "wait", return_value=([waiter], [run_task])) as wait:
await client.start()
assert client._run_task == run_task
assert create_task.call_count == 2
create_task.has_call(mock.call(client._run(), name="run shard 20"))
create_task.has_call(mock.call(client._handshake_completed.wait(), name="wait for shard 20 to start"))
run_task.result.assert_not_called()
waiter.cancel.assert_called_once_with()
wait.assert_awaited_once_with((waiter, run_task), return_when=asyncio.FIRST_COMPLETED)
async def test_update_presence(self, client):
client._check_if_alive = mock.Mock()
presence_payload = object()
client._serialize_and_store_presence_payload = mock.Mock(return_value=presence_payload)
client._send_json = mock.AsyncMock()
await client.update_presence(
idle_since=datetime.datetime.now(),
afk=True,
status=presences.Status.IDLE,
activity=None,
)
client._send_json.assert_awaited_once_with({"op": 3, "d": presence_payload})
client._check_if_alive.assert_called_once_with()
async def test_update_voice_state(self, client):
client._check_if_alive = mock.Mock()
client._send_json = mock.AsyncMock()
payload = {
"guild_id": "123456",
"channel_id": "6969420",
"self_mute": False,
"self_deaf": True,
}
await client.update_voice_state(123456, 6969420, self_mute=False, self_deaf=True)
client._send_json.assert_awaited_once_with({"op": 4, "d": payload})
async def test_update_voice_state_without_optionals(self, client):
client._check_if_alive = mock.Mock()
client._send_json = mock.AsyncMock()
payload = {"guild_id": "123456", "channel_id": "6969420"}
await client.update_voice_state(123456, 6969420)
client._send_json.assert_awaited_once_with({"op": 4, "d": payload})
def test_dispatch_when_READY(self, client):
client._seq = 0
client._session_id = 0
client._user_id = 0
client._logger = mock.Mock()
client._handshake_completed = mock.Mock()
client._event_manager = mock.Mock()
pl = {
"session_id": 101,
"user": {"id": 123, "username": "hikari", "discriminator": "5863"},
"guilds": [
{"id": "123"},
{"id": "456"},
{"id": "789"},
],
"v": 8,
}
client._dispatch(
"READY",
10,
pl,
)
assert client._seq == 10
assert client._session_id == 101
assert client._user_id == 123
client._logger.info.assert_called_once_with(
"shard is ready: %s guilds, %s (%s), session %r on v%s gateway",
3,
"hikari#5863",
123,
101,
8,
)
client._handshake_completed.set.assert_called_once_with()
client._event_manager.consume_raw_event.assert_called_once_with(
"READY",
client,
pl,
)
def test__dipatch_when_RESUME(self, client):
client._seq = 0
client._session_id = 123
client._logger = mock.Mock()
client._handshake_completed = mock.Mock()
client._event_manager = mock.Mock()
client._dispatch("RESUME", 10, {})
assert client._seq == 10
client._logger.info.assert_called_once_with("shard has resumed [session:%s, seq:%s]", 123, 10)
client._handshake_completed.set.assert_called_once_with()
client._event_manager.consume_raw_event.assert_called_once_with("RESUME", client, {})
def test__dipatch(self, client):
client._logger = mock.Mock()
client._handshake_completed = mock.Mock()
client._event_manager = mock.Mock()
client._dispatch("EVENT NAME", 10, {"payload": None})
client._logger.info.assert_not_called()
client._logger.debug.assert_not_called()
client._handshake_completed.set.assert_not_called()
client._event_manager.consume_raw_event.assert_called_once_with("EVENT NAME", client, {"payload": None})
async def test__dispatch_for_unknown_event(self, client):
client._logger = mock.Mock()
client._handshake_completed = mock.Mock()
client._event_manager = mock.Mock(consume_raw_event=mock.Mock(side_effect=LookupError))
client._dispatch("UNEXISTING_EVENT", 10, {"payload": None})
client._logger.info.assert_not_called()
client._handshake_completed.set.assert_not_called()
client._event_manager.consume_raw_event.assert_called_once_with("UNEXISTING_EVENT", client, {"payload": None})
client._logger.debug.assert_called_once_with(
"ignoring unknown event %s:\n %r", "UNEXISTING_EVENT", {"payload": None}
)
async def test__identify(self, client):
client._token = "token"
client._intents = intents.Intents.ALL
client._large_threshold = 123
client._shard_id = 0
client._shard_count = 1
client._serialize_and_store_presence_payload = mock.Mock(return_value={"presence": "payload"})
client._send_json = mock.AsyncMock()
stack = contextlib.ExitStack()
stack.enter_context(mock.patch.object(platform, "system", return_value="Potato PC"))
stack.enter_context(mock.patch.object(platform, "architecture", return_value=["ARM64"]))
stack.enter_context(mock.patch.object(aiohttp, "__version__", new="v0.0.1"))
stack.enter_context(mock.patch.object(_about, "__version__", new="v1.0.0"))
with stack:
await client._identify()
expected_json = {
"op": 2,
"d": {
"token": "token",
"compress": False,
"large_threshold": 123,
"properties": {
"$os": "Potato PC ARM64",
"$browser": "aiohttp v0.0.1",
"$device": "hikari v1.0.0",
},
"shard": [0, 1],
"intents": 32767,
"presence": {"presence": "payload"},
},
}
client._send_json.assert_awaited_once_with(expected_json)
@hikari_test_helpers.timeout()
async def test__heartbeat(self, client):
client._last_heartbeat_sent = 5
client._logger = mock.Mock()
client._closing_event = mock.Mock(is_set=mock.Mock(return_value=False))
client._closed_event = mock.Mock(is_set=mock.Mock(return_value=False))
client._send_heartbeat = mock.AsyncMock()
with mock.patch.object(time, "monotonic", return_value=10):
with mock.patch.object(asyncio, "wait_for", side_effect=[asyncio.TimeoutError, None]) as wait_for:
assert await client._heartbeat(20) is False
wait_for.assert_awaited_with(client._closing_event.wait(), timeout=20)
@hikari_test_helpers.timeout()
async def test__heartbeat_when_zombie(self, client):
client._last_heartbeat_sent = 10
client._logger = mock.Mock()
with mock.patch.object(time, "monotonic", return_value=5):
with mock.patch.object(asyncio, "wait_for") as wait_for:
assert await client._heartbeat(20) is True
wait_for.assert_not_called()
async def test__resume(self, client):
client._token = "token"
client._seq = 123
client._session_id = 456
client._send_json = mock.AsyncMock()
await client._resume()
expected_json = {
"op": 6,
"d": {"token": "token", "seq": 123, "session_id": 456},
}
client._send_json.assert_awaited_once_with(expected_json)
@pytest.mark.skip("TODO")
async def test__run(self, client):
...
@pytest.mark.skip("TODO")
async def test__run_once(self, client):
...
async def test__send_heartbeat(self, client):
client._send_json = mock.AsyncMock()
client._last_heartbeat_sent = 0
client._seq = 10
with mock.patch.object(time, "monotonic", return_value=200):
await client._send_heartbeat()
client._send_json.assert_awaited_once_with({"op": 1, "d": 10})
assert client._last_heartbeat_sent == 200
def test__serialize_activity_when_activity_is_None(self, client):
assert client._serialize_activity(None) is None
def test__serialize_activity_when_activity_is_not_None(self, client):
activity = mock.Mock(type="0", url="https://some.url")
activity.name = "<NAME>" # This has to be set separate because if not, its set as the mock's name
assert client._serialize_activity(activity) == {"name": "<NAME>", "type": 0, "url": "https://some.url"}
@pytest.mark.parametrize("idle_since", [datetime.datetime.now(), None])
@pytest.mark.parametrize("afk", [True, False])
@pytest.mark.parametrize(
"status",
[presences.Status.DO_NOT_DISTURB, presences.Status.IDLE, presences.Status.ONLINE, presences.Status.OFFLINE],
)
@pytest.mark.parametrize("activity", [presences.Activity(name="foo"), None])
def test__serialize_and_store_presence_payload_when_all_args_undefined(
self, client, idle_since, afk, status, activity
):
client._activity = activity
client._idle_since = idle_since
client._is_afk = afk
client._status = status
actual_result = client._serialize_and_store_presence_payload()
if activity is not undefined.UNDEFINED and activity is not None:
expected_activity = {
"name": activity.name,
"type": activity.type,
"url": activity.url,
}
else:
expected_activity = None
if status == presences.Status.OFFLINE:
expected_status = "invisible"
else:
expected_status = status.value
expected_result = {
"game": expected_activity,
"since": int(idle_since.timestamp() * 1_000) if idle_since is not None else None,
"afk": afk if afk is not | |
"""library functions for pipelines
"""
#--- standard library imports
#
import os
import sys
import subprocess
import logging
import shutil
import smtplib
from email.mime.text import MIMEText
from getpass import getuser
#import socket
import time
from datetime import datetime
from datetime import timedelta
import calendar
import json
import tarfile
import glob
#import argparse
import copy
from collections import deque
#--- third-party imports
#
import yaml
import requests
import dateutil.relativedelta
#--- project specific imports
#
from config import site_cfg
from config import rest_services
from utils import generate_timestamp
from utils import chroms_and_lens_from_fasta
from utils import bed_and_fa_are_compat
import configargparse
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__copyright__ = "2016 Genome Institute of Singapore"
__license__ = "The MIT License (MIT)"
# only dump() and following do not automatically create aliases
yaml.Dumper.ignore_aliases = lambda *args: True
# global logger
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(
'[{asctime}] {levelname:8s} {filename} {message}', style='{'))
logger.addHandler(handler)
# dir relative to Snakefile where configs are to be found
# from address, i.e. users should reply to to this
# instead of rpd@gis to which we send email
# FIXME both to config or external file
RPD_MAIL = "<EMAIL>"
RPD_SIGNATURE = """
--
Research Pipeline Development Team
Scientific & Research Computing
<{}>
""".format(RPD_MAIL)
# ugly
PIPELINE_ROOTDIR = os.path.join(os.path.dirname(__file__), "..")
assert os.path.exists(os.path.join(PIPELINE_ROOTDIR, "VERSION"))
WORKFLOW_COMPLETION_FLAGFILE = "WORKFLOW_COMPLETE"
DOWNSTREAM_OUTDIR_TEMPLATE = "{basedir}/{user}/{pipelinename}-version-{pipelineversion}/{timestamp}"
def snakemake_log_status(log):
"""
Return exit status and timestamp (isoformat string) as tuple.
Exit status is either "SUCCESS" or "ERROR" or None
If exit status is None timestamp will be last seen timestamp or empty and the status unknown
Parses last lines of log, which could look like
[Fri Jun 17 11:13:16 2016] Exiting because a job execution failed. Look above for error message
[Fri Jul 15 01:29:12 2016] 17 of 17 steps (100%) done
[Thu Nov 10 22:45:27 2016] Nothing to be done.
"""
# this is by design a bit fuzzy
with open(log) as fh:
last_lines = deque(fh, maxlen=60)
status = None
last_etime = None
while last_lines: # iterate from end
line = last_lines.pop()
if "Refusing to overwrite existing log bundle" in line:
continue
if line.startswith("["):# time stamp required
estr = line[1:].split("]")[0]
try:
etime = str(datetime.strptime(estr, '%a %b %d %H:%M:%S %Y'))
except:
continue
if not last_etime:
last_etime = etime# first is last. useful for undefined status
if 'steps (100%) done' in line or "Nothing to be done" in line:
status = "SUCCESS"
break
elif 'Exiting' in line or "Error" in line:
status = "ERROR"
break
return status, etime
def get_downstream_outdir(requestor, pipeline_name, pipeline_version=None):
"""generate downstream output directory
"""
if is_devel_version():
basedir = site_cfg['downstream_outdir_base']['devel']
else:
basedir = site_cfg['downstream_outdir_base']['production']
if pipeline_version:
pversion = pipeline_version
else:
pversion = get_pipeline_version(nospace=True)
outdir = DOWNSTREAM_OUTDIR_TEMPLATE.format(
basedir=basedir, user=requestor, pipelineversion=pversion,
pipelinename=pipeline_name, timestamp=generate_timestamp())
return outdir
class PipelineHandler(object):
"""Class that handles setting up and calling pipelines
"""
# output
PIPELINE_CFGFILE = "conf.yaml"
RC_DIR = "rc"
RC_FILES = {
# used to load snakemake
'SNAKEMAKE_INIT' : os.path.join(RC_DIR, 'snakemake_init.rc'),
# used as bash prefix within snakemakejobs
'SNAKEMAKE_ENV' : os.path.join(RC_DIR, 'snakemake_env.rc'),
}
LOG_DIR_REL = "logs"
MASTERLOG = os.path.join(LOG_DIR_REL, "snakemake.log")
SUBMISSIONLOG = os.path.join(LOG_DIR_REL, "submission.log")
# master max walltime in hours
# note, this includes waiting for jobs in q
MASTER_WALLTIME_H = 96
def __init__(self, pipeline_name, pipeline_subdir,
def_args,
cfg_dict,
cluster_cfgfile=None,
logger_cmd=None,
site=None,
master_walltime_h=MASTER_WALLTIME_H):
"""init function
- pipeline_subdir: where default configs can be found, i.e pipeline subdir
- def_args: argparser args. only default_argparser handled, i.e. must be subset of that
- logger_cmd: the logger command used in run.sh. bash's 'true' doesn't do anything. Uses downstream default with conf db-id if set to None and logging is on.
"""
if is_devel_version():
logger.info("Running in non-production mode")
self.pipeline_name = pipeline_name
self.pipeline_version = get_pipeline_version()# external function
self.pipeline_subdir = pipeline_subdir
self.log_dir_rel = self.LOG_DIR_REL
self.masterlog = self.MASTERLOG
self.submissionlog = self.SUBMISSIONLOG
self.master_q = def_args.master_q
self.slave_q = def_args.slave_q
self.outdir = def_args.outdir
self.restarts = def_args.restarts
self.cfg_dict = copy.deepcopy(cfg_dict)
self.cfg_dict['mail_on_completion'] = not def_args.no_mail
self.cfg_dict['mail_address'] = def_args.mail_address
if def_args.name:
self.cfg_dict['analysis_name'] = def_args.name
if def_args.extra_conf:
for keyvalue in def_args.extra_conf:
assert keyvalue.count(":") == 1, ("Invalid argument for extra-conf")
k, v = keyvalue.split(":")
self.cfg_dict[k] = v
if def_args.modules_cfg:
assert os.path.exists(def_args.modules_cfg)
self.modules_cfgfile = def_args.modules_cfg
if def_args.references_cfg:
assert os.path.exists(def_args.references_cfg)
self.refs_cfgfile = def_args.references_cfg
if cluster_cfgfile:
assert os.path.exists(cluster_cfgfile)
self.cluster_cfgfile = cluster_cfgfile
self.pipeline_cfgfile_out = os.path.join(
self.outdir, self.PIPELINE_CFGFILE)
# RCs
self.snakemake_init_file = os.path.join(
self.outdir, self.RC_FILES['SNAKEMAKE_INIT'])
self.snakemake_env_file = os.path.join(
self.outdir, self.RC_FILES['SNAKEMAKE_ENV'])
if site is None:
try:
site = get_site()
except ValueError:
logger.warning("Unknown site")
site = "local"
# DB logging of execution
if def_args.db_logging in ['n', 'no', 'off']:
# use bash's true, which doesn't do anything
if logger_cmd:
sys.stderr.write("WARN: Got logger command but logging is off\n")
self.logger_cmd = 'true'
elif def_args.db_logging in ['y', 'yes', 'on']:
# if logger_cmd is given use that, otherwise use the default logger which depends on db-id
if not logger_cmd:
assert self.cfg_dict['db-id'], ("Need db-id config value for logging")
# run.sh has a path to snakemake so should contain a path to python3
scr = os.path.join(PIPELINE_ROOTDIR, 'downstream-handlers', 'downstream_started.py')
logger_cmd = "{} -d {} -o {}".format(scr, self.cfg_dict['db-id'], self.outdir)
self.logger_cmd = logger_cmd
else:
raise ValueError(def_args.db_logging)
self.site = site
self.master_walltime_h = master_walltime_h
self.snakefile_abs = os.path.abspath(
os.path.join(pipeline_subdir, "Snakefile"))
assert os.path.exists(self.snakefile_abs)
# cluster configs
if self.cluster_cfgfile:
self.cluster_cfgfile_out = os.path.join(self.outdir, "cluster.yaml")
# else: local
# run template
self.run_template = os.path.join(
PIPELINE_ROOTDIR, "lib", "run.template.{}.sh".format(self.site))
self.run_out = os.path.join(self.outdir, "run.sh")
assert os.path.exists(self.run_template)
# we don't know for sure who's going to actually exectute
# but it's very likely the current user, who needs to be notified
# on qsub kills etc
self.toaddr = email_for_user()
log_path = os.path.abspath(os.path.join(self.outdir, self.masterlog))
self.elm_data = {'pipeline_name': self.pipeline_name,
'pipeline_version': self.pipeline_version,
'site': self.site,
'instance_id': 'SET_ON_EXEC',# dummy
'submitter': 'SET_ON_EXEC',# dummy
'log_path': log_path}
@staticmethod
def write_snakemake_init(rc_file, overwrite=False):
"""write snakemake init rc (loads miniconda and, activate source')
"""
if not overwrite:
assert not os.path.exists(rc_file), rc_file
with open(rc_file, 'w') as fh:
# init first so that modules are present
fh.write("{}\n".format(" ".join(get_init_call())))
fh.write("module load miniconda3\n")
fh.write("source activate {}\n".format(site_cfg['snakemake_env']))
def write_snakemake_env(self, overwrite=False):
"""creates rc file for use as 'bash prefix', which also loads modules defined in cfgfile
"""
if not overwrite:
assert not os.path.exists(self.snakemake_env_file), self.snakemake_env_file
with open(self.snakemake_env_file, 'w') as fh_rc:
fh_rc.write("# used as bash prefix within snakemake\n\n")
fh_rc.write("# make sure module command is defined (non-login shell). see http://lmod.readthedocs.io/en/latest/030_installing.html\n")
fh_rc.write("{}\n".format(" ".join(get_init_call())))
fh_rc.write("# load modules\n")
with open(self.pipeline_cfgfile_out) as fh_cfg:
yaml_data = yaml.safe_load(fh_cfg)
assert "modules" in yaml_data
for k, v in yaml_data["modules"].items():
fh_rc.write("module load {}/{}\n".format(k, v))
fh_rc.write("\n")
fh_rc.write("# unofficial bash strict has to come last\n")
fh_rc.write("set -euo pipefail;\n")
def write_cluster_cfg(self):
"""writes site dependend cluster config
"""
shutil.copyfile(self.cluster_cfgfile, self.cluster_cfgfile_out)
def write_run_template(self):
"""writes run template replacing placeholder with variables defined in
instance
"""
d = {'SNAKEFILE': self.snakefile_abs,
'LOGDIR': self.log_dir_rel,
'MASTERLOG': self.masterlog,
'PIPELINE_NAME': self.pipeline_name,
'MAILTO': self.toaddr,
'DEFAULT_RESTARTS': self.restarts,
'MASTER_WALLTIME_H': self.master_walltime_h,
'DEFAULT_SLAVE_Q': self.slave_q if self.slave_q else "",
'LOGGER_CMD': self.logger_cmd}
with open(self.run_template) as fh:
templ = fh.read()
with open(self.run_out, 'w') as fh:
fh.write(templ.format(**d))
def read_cfgfiles(self):
"""parse default config and replace all RPD env vars
"""
merged_cfg = dict()
rpd_vars = get_rpd_vars()
for cfgkey, cfgfile in [('references', self.refs_cfgfile),
('modules', self.modules_cfgfile)]:
if not cfgfile:
continue
with open(cfgfile) as fh:
try:
d = yaml.safe_load(fh)
if not d:
# allow empty files
continue
cfg = dict(d)
except:
logger.fatal("Loading %s failed", cfgfile)
raise
# to replace rpd vars the trick is to traverse
# dictionary fully and replace all instances
dump = json.dumps(cfg)
for k, v in rpd_vars.items():
dump = dump.replace("${}".format(k), v)
cfg = dict(json.loads(dump))
if cfgkey == 'global':
merged_cfg.update(cfg)
else:
assert cfgkey not in merged_cfg
merged_cfg[cfgkey] = cfg
# determine num_chroms needed by some pipelines
# FIXME ugly because sometimes not needed
if merged_cfg.get('references'):
reffa = merged_cfg['references'].get('genome')
if reffa:
assert 'num_chroms' not in merged_cfg['references']
merged_cfg['references']['num_chroms'] = len(list(
chroms_and_lens_from_fasta(reffa)))
return merged_cfg
def write_merged_cfg(self, force_overwrite=False):
"""writes config file for use in snakemake becaused on default config
"""
master_cfg = self.read_cfgfiles()
master_cfg.update(self.cfg_dict)
b = master_cfg.get('intervals')
# sanity check: bed only makes sense if we have a reference
if b:
f = master_cfg['references'].get('genome')
assert bed_and_fa_are_compat(b, f), (
"{} not compatible with {}".format(b, f))
assert 'ELM' not in master_cfg
master_cfg['ELM'] = self.elm_data
if not force_overwrite:
assert not os.path.exists(self.pipeline_cfgfile_out)
with open(self.pipeline_cfgfile_out, 'w') as fh:
# default_flow_style=None(default)|True(least readable)|False(most readable)
yaml.dump(master_cfg, fh, default_flow_style=False)
def setup_env(self):
"""create run environment
"""
logger.info("Creating run environment in %s", self.outdir)
# create log dir recursively so that parent is created as well
os.makedirs(os.path.join(self.outdir, self.log_dir_rel))
os.makedirs(os.path.join(self.outdir, self.RC_DIR))
if self.site != "local":
self.write_cluster_cfg()
self.write_merged_cfg()
self.write_snakemake_env()
self.write_snakemake_init(self.snakemake_init_file)
self.write_run_template()
def submit(self, no_run=False):
"""submit pipeline run
"""
if self.master_q:
master_q_arg = "-q {}".format(self.master_q)
else:
| |
rad to °
Pi = 3.141592653589793
results[k]['value'] = results[k]['value'] * 180 / Pi
elif ('nOpa' in resSplit[-1]) or ('nTot' in resSplit[-1]):
# Sky coverage from [0-1] to tenth of sky
results[k]['value'] = results[k]['value'] * 10
k += 1
map_dymola_and_json(results, dic['case'], res_fin, case_dict)
return res_fin
def map_dymola_and_json(results, case, res_fin, case_dict):
"""
This function couples the .mat file variable with the final .json variable
:param results: Result obtained from the _extract_data function
:param case: Dictionary that specifies the BESTEST case
:param res_fin: Dictionary with the same format as the desired json file
:param case_dict: in case_dict is stored TestN (which .json file format\
should be used)"
"""
dict_hourly = [{'json': 'dry_bulb_temperature',
'mat': 'weaBusHHorIR.TDryBul'},
{'json': 'relative_humidity',
'mat': 'weaBusHHorIR.relHum'},
{'json': 'humidity_ratio',
'mat': 'toDryAir.XiDry'},
{'json': 'dewpoint_temperature',
'mat': 'weaBusHHorIR.TDewPoi'},
{'json': 'wet_bulb_temperature',
'mat': 'weaBusHHorIR.TWetBul'},
{'json': 'wind_speed',
'mat': 'weaBusHHorIR.winSpe'},
{'json': 'wind_direction',
'mat': 'weaBusHHorIR.winDir'},
{'json': 'station_pressure',
'mat': 'weaBusHHorIR.pAtm'},
{'json': 'total_cloud_cover',
'mat': 'weaBusHHorIR.nTot'},
{'json': 'opaque_cloud_cover',
'mat': 'weaBusHHorIR.nOpa'},
{'json': 'sky_temperature',
'matHor': 'weaBusHHorIR.TBlaSky',
'matDew': 'weaBusTDryBulTDewPoiOpa.TBlaSky'},
{'json': 'total_horizontal_radiation',
'matIso': 'azi000til00.H',
'matPer': 'azi000til00.HPer'},
{'json': 'beam_horizontal_radiation',
'mat': 'azi000til00.HDir.H'},
{'json': 'diffuse_horizontal_radiation',
'matIso': 'azi000til00.HDiffIso.H',
'matPer': 'azi000til00.HDiffPer.H'},
{'json': 'total_radiation_s_90',
'matIso': 'azi000til90.H',
'matPer': 'azi000til90.HPer'},
{'json': 'beam_radiation_s_90',
'mat': 'azi000til90.HDir.H'},
{'json': 'diffuse_radiation_s_90',
'matIso': 'azi000til90.HDiffIso.H',
'matPer': 'azi000til90.HDiffPer.H'},
{'json': 'total_radiation_e_90',
'matIso': 'azi270til90.H',
'matPer': 'azi270til90.HPer'},
{'json': 'beam_radiation_e_90',
'mat': 'azi270til90.HDir.H'},
{'json': 'diffuse_radiation_e_90',
'matIso': 'azi270til90.HDiffIso.H',
'matPer': 'azi270til90.HDiffPer.H'},
{'json': 'total_radiation_n_90',
'matIso': 'azi180til90.H',
'matPer': 'azi180til90.HPer'},
{'json': 'beam_radiation_n_90',
'mat': 'azi180til90.HDir.H'},
{'json': 'diffuse_radiation_n_90',
'matIso': 'azi180til90.HDiffIso.H',
'matPer': 'azi180til90.HDiffPer.H'},
{'json': 'total_radiation_w_90',
'matIso': 'azi090til90.H',
'matPer': 'azi090til90.HPer'},
{'json': 'beam_radiation_w_90',
'mat': 'azi090til90.HDir.H'},
{'json': 'diffuse_radiation_w_90',
'matIso': 'azi090til90.HDiffIso.H',
'matPer': 'azi090til90.HDiffPer.H'},
{'json': 'total_radiation_45_e_90',
'matIso': 'azi315til90.H',
'matPer': 'azi315til90.HPer'},
{'json': 'beam_radiation_45_e_90',
'mat': 'azi315til90.HDir.H'},
{'json': 'diffuse_radiation_45_e_90',
'matIso': 'azi315til90.HDiffIso.H',
'matPer': 'azi315til90.HDiffPer.H'},
{'json': 'total_radiation_45_w_90',
'matIso': 'azi045til90.H',
'matPer': 'azi045til90.HPer'},
{'json': 'beam_radiation_45_w_90',
'mat': 'azi045til90.HDir.H'},
{'json': 'diffuse_radiation_45_w_90',
'matIso': 'azi045til90.HDiffIso.H',
'matPer': 'azi045til90.HDiffPer.H'},
{'json': 'total_radiation_e_30',
'matIso': 'azi270til30.H',
'matPer': 'azi270til30.HPer'},
{'json': 'beam_radiation_e_30',
'mat': 'azi270til30.HDir.H'},
{'json': 'diffuse_radiation_e_30',
'matIso': 'azi270til30.HDiffIso.H',
'matPer': 'azi270til30.HDiffPer.H'},
{'json': 'total_radiation_s_30',
'matIso': 'azi000til30.H',
'matPer': 'azi000til30.HPer'},
{'json': 'beam_radiation_s_30',
'mat': 'azi000til30.HDir.H'},
{'json': 'diffuse_radiation_s_30',
'matIso': 'azi000til30.HDiffIso.H',
'matPer': 'azi000til30.HDiffPer.H'},
{'json': 'total_radiation_w_30',
'matIso': 'azi090til30.H',
'matPer': 'azi090til30.HPer'},
{'json': 'beam_radiation_w_30',
'mat': 'azi090til30.HDir.H'},
{'json': 'diffuse_radiation_w_30',
'matIso': 'azi090til30.HDiffIso.H',
'matPer': 'azi090til30.HDiffPer.H'}]
dict_sub_hourly = [{'json': 'dry_bulb_temperature',
'mat': 'weaBusHHorIR.TDryBul'},
{'json': 'relative_humidity',
'mat': 'weaBusHHorIR.relHum'},
{'json': 'total_horizontal_radiation',
'matIso': 'azi000til00.H',
'matPer': 'azi000til00.HPer'},
{'json': 'beam_horizontal_radiation',
'mat': 'azi000til00.HDir.H'},
{'json': 'diffuse_horizontal_radiation',
'matIso': 'azi000til00.HDiffIso.H',
'matPer': 'azi000til00.HDiffPer.H'},
{'json': 'total_radiation_s_90',
'matIso': 'azi000til90.H',
'matPer': 'azi000til90.HPer'},
{'json': 'beam_radiation_s_90',
'mat': 'azi000til90.HDir.H'},
{'json': 'diffuse_radiation_s_90',
'matIso': 'azi000til90.HDiffIso.H',
'matPer': 'azi000til90.HDiffPer.H'},
{'json': 'total_radiation_e_90',
'matIso': 'azi270til90.H',
'matPer': 'azi270til90.HPer'},
{'json': 'beam_radiation_e_90',
'mat': 'azi270til90.HDir.H'},
{'json': 'diffuse_radiation_e_90',
'matIso': 'azi270til90.HDiffIso.H',
'matPer': 'azi270til90.HDiffPer.H'},
{'json': 'total_radiation_n_90',
'matIso': 'azi180til90.H',
'matPer': 'azi180til90.HPer'},
{'json': 'beam_radiation_n_90',
'mat': 'azi180til90.HDir.H'},
{'json': 'diffuse_radiation_n_90',
'matIso': 'azi180til90.HDiffIso.H',
'matPer': 'azi180til90.HDiffPer.H'},
{'json': 'total_radiation_w_90',
'matIso': 'azi090til90.H',
'matPer': 'azi090til90.HPer'},
{'json': 'beam_radiation_w_90',
'mat': 'azi090til90.HDir.H'},
{'json': 'diffuse_radiation_w_90',
'matIso': 'azi090til90.HDiffIso.H',
'matPer': 'azi090til90.HDiffPer.H'},
{'json': 'total_radiation_45_e_90',
'matIso': 'azi315til90.H',
'matPer': 'azi315til90.HPer'},
{'json': 'beam_radiation_45_e_90',
'mat': 'azi315til90.HDir.H'},
{'json': 'diffuse_radiation_45_e_90',
'matIso': 'azi315til90.HDiffIso.H',
'matPer': 'azi315til90.HDiffPer.H'},
{'json': 'total_radiation_45_w_90',
'matIso': 'azi045til90.H',
'matPer': 'azi045til90.HPer'},
{'json': 'beam_radiation_45_w_90',
'mat': 'azi045til90.HDir.H'},
{'json': 'diffuse_radiation_45_w_90',
'matIso': 'azi045til90.HDiffIso.H',
'matPer': 'azi045til90.HDiffPer.H'},
{'json': 'total_radiation_e_30',
'matIso': 'azi270til30.H',
'matPer': 'azi270til30.HPer'},
{'json': 'beam_radiation_e_30',
'mat': 'azi270til30.HDir.H'},
{'json': 'diffuse_radiation_e_30',
'matIso': 'azi270til30.HDiffIso.H',
'matPer': 'azi270til30.HDiffPer.H'},
{'json': 'total_radiation_s_30',
'matIso': 'azi000til30.H',
'matPer': 'azi000til30.HPer'},
{'json': 'beam_radiation_s_30',
'mat': 'azi000til30.HDir.H'},
{'json': 'diffuse_radiation_s_30',
'matIso': 'azi000til30.HDiffIso.H',
'matPer': 'azi000til30.HDiffPer.H'},
{'json': 'total_radiation_w_30',
'matIso': 'azi090til30.H',
'matPer': 'azi090til30.HPer'},
{'json': 'beam_radiation_w_30',
'mat': 'azi090til30.HDir.H'},
{'json': 'diffuse_radiation_w_30',
'matIso': 'azi090til30.HDiffIso.H',
'matPer': 'azi090til30.HDiffPer.H'},
{'json': 'integrated_total_horizontal_radiation',
'matIso': 'azi000til00.H',
'matPer': 'azi000til00.HPer'},
{'json': 'integrated_beam_horizontal_radiation',
'mat': 'azi000til00.HDir.H'},
{'json': 'integrated_diffuse_horizontal_radiation',
'matIso': 'azi000til00.HDiffIso.H',
'matPer': 'azi000til00.HDiffPer.H'}]
dict_yearly = [{'json': 'average_dry_bulb_temperature',
'mat': 'weaBusHHorIR.TDryBul'},
{'json': 'average_relative_humidity',
'mat': 'weaBusHHorIR.relHum'},
{'json': 'average_humidity_ratio',
'mat': 'toDryAir.XiDry'},
{'json': 'average_wet_bulb_temperature',
'mat': 'weaBusHHorIR.TWetBul'},
{'json': 'average_dew_point_temperature',
'mat': 'weaBusHHorIR.TDewPoi'},
{'json': 'total_horizontal_solar_radiation',
'matIso': 'azi000til00.H',
'matPer': 'azi000til00.HPer'},
{'json': 'total_horizontal_beam_solar_radiation',
'mat': 'azi000til00.HDir.H'},
{'json': 'total_horizontal_diffuse_solar_radiation',
'matIso': 'azi000til00.HDiffIso.H',
'matPer': 'azi000til00.HDiffPer.H'},
{'json': 'total_radiation_s_90',
'matIso': 'azi000til90.H',
'matPer': 'azi000til90.HPer'},
{'json': 'total_beam_radiation_s_90',
'mat': 'azi000til90.HDir.H'},
{'json': 'total_diffuse_radiation_s_90',
'matIso': 'azi000til90.HDiffIso.H',
'matPer': 'azi000til90.HDiffPer.H'},
{'json': 'total_radiation_e_90',
'matIso': 'azi270til90.H',
'matPer': 'azi270til90.HPer'},
{'json': 'total_beam_radiation_e_90',
'mat': 'azi270til90.HDir.H'},
{'json': 'total_diffuse_radiation_e_90',
'matIso': 'azi270til90.HDiffIso.H',
'matPer': 'azi270til90.HDiffPer.H'},
{'json': 'total_radiation_n_90',
'matIso': 'azi180til90.H',
'matPer': 'azi180til90.HPer'},
{'json': 'total_beam_radiation_n_90',
'mat': 'azi180til90.HDir.H'},
{'json': 'total_diffuse_radiation_n_90',
'matIso': 'azi180til90.HDiffIso.H',
'matPer': 'azi180til90.HDiffPer.H'},
{'json': 'total_radiation_w_90',
'matIso': 'azi090til90.H',
'matPer': 'azi090til90.HPer'},
{'json': 'total_beam_radiation_w_90',
'mat': 'azi090til90.HDir.H'},
{'json': 'total_diffuse_radiation_w_90',
'matIso': 'azi090til90.HDiffIso.H',
'matPer': 'azi090til90.HDiffPer.H'},
{'json': 'total_radiation_45_e_90',
'matIso': 'azi315til90.H',
'matPer': 'azi315til90.HPer'},
{'json': 'total_beam_radiation_45_e_90',
'mat': 'azi315til90.HDir.H'},
{'json': 'total_diffuse_radiation_45_e_90',
'matIso': 'azi315til90.HDiffIso.H',
'matPer': 'azi315til90.HDiffPer.H'},
{'json': 'total_radiation_45_w_90',
'matIso': 'azi045til90.H',
'matPer': 'azi045til90.HPer'},
{'json': 'total_beam_radiation_45_w_90',
'mat': 'azi045til90.HDir.H'},
{'json': 'total_diffuse_radiation_45_w_90',
'matIso': 'azi045til90.HDiffIso.H',
'matPer': 'azi045til90.HDiffPer.H'},
{'json': 'total_radiation_e_30',
'matIso': 'azi270til30.H',
'matPer': 'azi270til30.HPer'},
{'json': 'total_beam_radiation_e_30',
'mat': 'azi270til30.HDir.H'},
{'json': 'total_diffuse_radiation_e_30',
'matIso': 'azi270til30.HDiffIso.H',
'matPer': 'azi270til30.HDiffPer.H'},
{'json': 'total_radiation_s_30',
'matIso': 'azi000til30.H',
'matPer': 'azi000til30.HPer'},
{'json': 'total_beam_radiation_s_30',
'mat': 'azi000til30.HDir.H'},
{'json': 'total_diffuse_radiation_s_30',
'matIso': 'azi000til30.HDiffIso.H',
'matPer': 'azi000til30.HDiffPer.H'},
{'json': 'total_radiation_w_30',
'matIso': 'azi090til30.H',
'matPer': 'azi090til30.HPer'},
{'json': 'total_beam_radiation_w_30',
'mat': 'azi090til30.HDir.H'},
{'json': 'total_diffuse_radiation_w_30',
'matIso': 'azi090til30.HDiffIso.H',
'matPer': 'azi090til30.HDiffPer.H'}]
Days = {'WD100': {'days': ['yearly', 'may4', 'jul14', 'sep6'],
'tstart': [0, 10627200, 16761600, 21427200],
'tstop': [0, 10713600, 16848000, 21513600]},
'WD200': {'days': ['yearly', 'may24', 'aug26'],
'tstart': [0, 12355200, 20476800, 0],
'tstop': [0, 12441600, 20563200, 31536000]},
'WD300': {'days': ['yearly', 'feb7', 'aug13'],
'tstart': [0, 3196800, 19353600],
'tstop': [0, 3283200, 19440000]},
'WD400': {'days': ['yearly', 'jan24', 'jul1'],
'tstart': [0, 1987200, 15638400],
'tstop': [0, 2073600, 15724800]},
'WD500': {'days': ['yearly', 'mar1', 'sep14'],
'tstart': [0, 5097600, 22118400],
'tstop': [0, 5184000, 22204800]},
'WD600': {'days': ['yearly', 'may4', 'jul14', 'sep6'],
'tstart': [0, 10627200, 16761600, 21427200],
'tstop': [0, 10713600, 16848000, 21513600]}}
Days2 = {'WD100': {'days': ['test2'],
'tstart': [0],
'tstop': [31536000+3600]},
'WD200': {'days': ['test2'],
'tstart': [0],
'tstop': [31536000+3600]},
'WD300': {'days': ['test2'],
'tstart': [0],
'tstop': [31536000+3600]},
'WD400': {'days': ['test2'],
'tstart': [0],
'tstop': [31536000+3600]},
'WD500': {'days': ['test2'],
'tstart': [0],
'tstop': [31536000+3600]},
'WD600': {'days': ['test2'],
'tstart': [0],
'tstop': [31536000+3600]}}
dictTest2 = [{'json': 'dry_bulb_temperature',
'mat': 'weaBusHHorIR.TDryBul'},
{'json': 'relative_humidity',
'mat': 'weaBusHHorIR.relHum'},
{'json': 'humidity_ratio',
'mat': 'toDryAir.XiDry'},
{'json': 'dewpoint_temperature',
'mat': 'weaBusHHorIR.TDewPoi'},
{'json': 'wet_bulb_temperature',
'mat': 'weaBusHHorIR.TWetBul'},
{'json': 'wind_speed',
'mat': 'weaBusHHorIR.winSpe'},
{'json': 'wind_direction',
'mat': 'weaBusHHorIR.winDir'},
{'json': 'station_pressure',
'mat': 'weaBusHHorIR.pAtm'},
{'json': 'total_cloud_cover',
'mat': 'weaBusHHorIR.nTot'},
{'json': 'opaque_cloud_cover',
'mat': 'weaBusHHorIR.nOpa'},
{'json': 'sky_temperature',
'matHor': 'weaBusHHorIR.TBlaSky',
'matDew': 'weaBusTDryBulTDewPoiOpa.TBlaSky'},
{'json': 'total_horizontal_radiation',
'matIso': 'azi000til00.H',
'matPer': 'azi000til00.HPer'},
{'json': 'beam_horizontal_radiation',
'mat': 'azi000til00.HDir.H'},
{'json': 'diffuse_horizontal_radiation',
'matIso': 'azi000til00.HDiffIso.H',
'matPer': 'azi000til00.HDiffPer.H'},
{'json': 'total_radiation_s_90',
'matIso': 'azi000til90.H',
'matPer': 'azi000til90.HPer'},
{'json': 'beam_radiation_s_90',
'mat': 'azi000til90.HDir.H'},
{'json': 'diffuse_radiation_s_90',
'matIso': 'azi000til90.HDiffIso.H',
'matPer': 'azi000til90.HDiffPer.H'},
{'json': 'total_radiation_e_90',
'matIso': 'azi270til90.H',
'matPer': 'azi270til90.HPer'},
{'json': 'beam_radiation_e_90',
'mat': 'azi270til90.HDir.H'},
{'json': 'diffuse_radiation_e_90',
'matIso': 'azi270til90.HDiffIso.H',
'matPer': 'azi270til90.HDiffPer.H'},
{'json': 'total_radiation_n_90',
'matIso': 'azi180til90.H',
'matPer': 'azi180til90.HPer'},
{'json': 'beam_radiation_n_90',
'mat': 'azi180til90.HDir.H'},
{'json': 'diffuse_radiation_n_90',
'matIso': 'azi180til90.HDiffIso.H',
'matPer': 'azi180til90.HDiffPer.H'},
{'json': 'total_radiation_w_90',
'matIso': 'azi090til90.H',
'matPer': 'azi090til90.HPer'},
{'json': 'beam_radiation_w_90',
'mat': 'azi090til90.HDir.H'},
{'json': 'diffuse_radiation_w_90',
'matIso': 'azi090til90.HDiffIso.H',
'matPer': 'azi090til90.HDiffPer.H'},
{'json': 'total_radiation_45_e_90',
'matIso': 'azi315til90.H',
'matPer': 'azi315til90.HPer'},
{'json': 'beam_radiation_45_e_90',
'mat': 'azi315til90.HDir.H'},
{'json': 'diffuse_radiation_45_e_90',
'matIso': 'azi315til90.HDiffIso.H',
'matPer': 'azi315til90.HDiffPer.H'},
{'json': 'total_radiation_45_w_90',
'matIso': 'azi045til90.H',
'matPer': 'azi045til90.HPer'},
{'json': 'beam_radiation_45_w_90',
'mat': 'azi045til90.HDir.H'},
{'json': 'diffuse_radiation_45_w_90',
'matIso': 'azi045til90.HDiffIso.H',
'matPer': 'azi045til90.HDiffPer.H'},
{'json': 'total_radiation_e_30',
'matIso': 'azi270til30.H',
'matPer': 'azi270til30.HPer'},
{'json': 'beam_radiation_e_30',
'mat': 'azi270til30.HDir.H'},
{'json': 'diffuse_radiation_e_30',
'matIso': 'azi270til30.HDiffIso.H',
'matPer': 'azi270til30.HDiffPer.H'},
{'json': 'total_radiation_s_30',
'matIso': 'azi000til30.H',
'matPer': 'azi000til30.HPer'},
{'json': 'beam_radiation_s_30',
'mat': 'azi000til30.HDir.H'},
{'json': 'diffuse_radiation_s_30',
'matIso': 'azi000til30.HDiffIso.H',
'matPer': 'azi000til30.HDiffPer.H'},
{'json': 'total_radiation_w_30',
'matIso': 'azi090til30.H',
'matPer': 'azi090til30.HPer'},
{'json': 'beam_radiation_w_30',
'mat': 'azi090til30.HDir.H'},
{'json': 'diffuse_radiation_w_30',
'matIso': 'azi090til30.HDiffIso.H',
'matPer': 'azi090til30.HDiffPer.H'}]
if case_dict['TestN']:
caseDays = [{key: value[i] for key, value in Days2[case].items()}
for i in range(len(Days2[case]['days']))]
else:
caseDays = [{key: value[i] for key, value in Days[case].items()}
for i in range(len(Days[case]['days']))]
out_dir = res_fin
missing = list()
for dR in results:
for day in caseDays:
if day['days'] in 'yearly':
res = extrapolate_results(dict_yearly, dR, day)
if not res:
missing.append(day['days'] + '_' + dR['variable'])
else:
# float(res['res'])
out_dir[case]['annual_results'][res['json']] =\
float(res['res'])
elif day['days'] in 'test2':
ressH = extrapolate_results(dictTest2, dR, day)
if 'dry_bulb_temperature' in ressH['json']:
out_dir[case]['hour_of_year'] = (ressH['time']/
3600).tolist()
out_dir[case][ressH['json']] = ressH['res'].tolist()
else:
resH = extrapolate_results(dict_hourly, dR, day)
ressH = extrapolate_results(dict_sub_hourly, dR, day)
if not resH:
missing.append(day['days'] + '_hourly_' + dR['variable'])
else:
resH['res'] = resH['res'][0::4]
resH['time'] = resH['time'][0::4]
HRlist = list()
k = 0
for HR in resH['res']:
HRdict = {}
HRdict['time'] = float((resH['time'][k] -
resH['time'][0]) / 3600)
HRdict['value'] = float(HR)
HRlist.append(HRdict)
k += 1
out_dir[case]['hourly_results'][day['days']]\
[resH['json']] = HRlist
if not ressH:
missing.append(day['days'] + '_subhourly_' +
dR['variable'])
else:
sHRlist = list()
k = 0
for sHR in ressH['res']:
sHRdict = {}
sHRdict['time'] = float((ressH['time'][k] -
ressH['time'][0]) / 3600)
if 'radiation' in ressH['json']:
sHRdict['value'] = float(sHR)
else:
sHRdict['value'] = float(sHR)
sHRlist.append(sHRdict)
k += 1
out_dir[case]['subhourly_results'][day['days']]\
[ressH['json']] = sHRlist
# Manually update integrated values for 'integrated'
# variables for subhourly results
if 'horizontal_radiation' in ressH['json']:
ressH['time'] = ressH['time']
time_int = ressH['time'][0::4]
H_int = np.interp(time_int, ressH['time'],
ressH['res'])
sHRlist = list()
k = 0
for sHR in H_int:
sHRdict = {}
sHRdict['time'] = float((time_int[k] -
time_int[0]) / 3600)
sHRdict['value'] = float(sHR)
sHRlist.append(sHRdict)
k += 1
out_dir[case]['subhourly_results']\
[day['days']]['integrated_' +
ressH['json']] = sHRlist
return out_dir
def extrapolate_results(dicT, dR, day):
"""
This function takes | |
import os
import sys
import socket
import time
import thread
import threading
import multiprocessing
import shutil
import code
import ssl
import json
import traceback
import logging
from dynamo.core.components.appserver import AppServer
from dynamo.core.components.appmanager import AppManager
import dynamo.core.serverutils as serverutils
from dynamo.dataformat import ConfigurationError
SERVER_PORT = 39626
DN_TRANSLATION = {
'commonName': 'CN',
'localityName': 'L',
'stateOrProvinceName': 'ST',
'organizationName': 'O',
'organizationalUnitName': 'OU',
'countryName': 'C',
'streetAddress': 'STREET',
'domainComponent': 'DC',
'userId': 'UID'
}
# OpenSSL cannot authenticate with certificate proxies without this environment variable
os.environ['OPENSSL_ALLOW_PROXY_CERTS'] = '1'
LOG = logging.getLogger(__name__)
class SocketIO(object):
def __init__(self, conn, addr):
self.conn = conn
self.host = addr[0]
self.port = addr[1]
def send(self, status, content = ''):
"""
Send a JSON with format {'status': status, 'content': content}. If status is not OK, log
the content.
"""
if status != 'OK':
LOG.error('Response to %s:%d: %s', self.host, self.port, content)
bytes = json.dumps({'status': status, 'content': content})
try:
self.conn.sendall('%d %s' % (len(bytes), bytes))
except:
pass
def recv(self):
"""
Read a message possibly split in multiple transmissions. The message must have a form or a decimal
number corresponding to the length of the content, followed by a space, and the content in JSON.
"""
data = ''
while True:
try:
bytes = self.conn.recv(2048)
except socket.error:
break
if not bytes:
break
if not data:
# first communication
length, _, bytes = bytes.partition(' ')
length = int(length)
data += bytes
if len(data) >= length:
# really should be == but to be prepared for malfunction
break
try:
return json.loads(data)
except:
self.send('failed', 'Ill-formatted data')
raise RuntimeError()
def tail_follow(source_path, stream, stop_reading):
## tail -f emulation
while True:
if os.path.exists(source_path):
break
if stop_reading.is_set():
break
time.sleep(0.5)
try:
with open(source_path) as source:
while True:
pos = source.tell()
line = source.readline()
if not line:
if stop_reading.is_set():
return
source.seek(pos)
time.sleep(0.5)
else:
stream.sendall(line)
except:
pass
class SocketAppServer(AppServer):
"""
Sub-server owned by the main Dynamo server to serve application requests.
"""
def __init__(self, dynamo_server, config):
AppServer.__init__(self, dynamo_server, config)
try:
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
except AttributeError:
# python 2.6
if os.path.isdir(config.capath):
raise ConfigurationError('AppServer configuration parameter "capath" must point to a single file.')
self._sock = ssl.wrap_socket(socket.socket(socket.AF_INET), server_side = True,
certfile = config.certfile, keyfile = config.keyfile,
cert_reqs = ssl.CERT_REQUIRED, ca_certs = config.capath)
else:
# python 2.7
context.load_cert_chain(config.certfile, keyfile = config.keyfile)
if os.path.isdir(config.capath):
context.load_verify_locations(capath = config.capath)
else:
context.load_verify_locations(cafile = config.capath)
context.verify_mode = ssl.CERT_REQUIRED
self._sock = context.wrap_socket(socket.socket(socket.AF_INET), server_side = True)
# allow reconnect to the same port even when it is in TIME_WAIT
self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
port = int(os.environ['DYNAMO_SERVER_PORT'])
except:
port = SERVER_PORT
for _ in xrange(10):
try:
self._sock.bind(('', port))
break
except socket.error as err:
if err.errno == 98: # address already in use
# check the server status before retrying - could be shut down
dynamo_server.check_status_and_connection()
# then print and retry
LOG.warning('Cannot bind to port %d. Retrying..', port)
time.sleep(5)
else:
# exhausted attempts
LOG.error('Failed to bind to port %d.', port)
raise
self._sock.listen(5)
def _accept_applications(self): #override
while True:
# blocks until there is a connection
# keeps blocking when socket is closed
try:
conn, addr = self._sock.accept()
except Exception as ex:
if self._stop_flag.is_set():
return
else:
try:
if ex.errno == 9: # Bad file descriptor -> socket is closed
self.stop()
break
except:
pass
LOG.error('Application server connection failed with error: %s.' % str(sys.exc_info()[1]))
continue
thread.start_new_thread(self._process_application, (conn, addr))
def _stop_accepting(self): #override
"""Shut down the socket."""
try:
self._sock.shutdown(socket.SHUT_RDWR)
self._sock.close()
except:
pass
def _process_application(self, conn, addr):
"""
Communicate with the client and determine server actions.
Communication is always conversational, starting with the client. This means recvmsg()
can assume only one message will be sent in a single string (could still be split into
multiple transmissions). We use a rudimentary protocol of preceding the message with
the message length in decimal integer and a space (see SocketIO implementation).
"""
io = SocketIO(conn, addr)
master = self.dynamo_server.manager.master
try:
# check user authorization
user_cert_data = conn.getpeercert()
LOG.debug('New application request from %s:%s by %s' % (addr[0], addr[1], user_cert_data['subject']))
dn = ''
for rdn in user_cert_data['subject']:
dn += '/' + '+'.join('%s=%s' % (DN_TRANSLATION[key], value) for key, value in rdn)
user_info = master.identify_user(dn = dn, check_trunc = True)
if user_info is None:
io.send('failed', 'Unidentified user DN %s' % dn)
return
user_name, user_id = user_info[:2]
io.send('OK', 'Connected')
app_data = io.recv()
command = app_data.pop('command')
LOG.info('Accepted %s from %s:%s by %s' % (command, addr[0], addr[1], user_name))
def act_and_respond(resp):
success, msg = resp
if success:
io.send('OK', msg)
else:
io.send('failed', msg)
return resp
if command == 'poll':
act_and_respond(self._poll_app(app_data['appid']))
return
elif not master.check_user_auth(user_name, 'admin', 'application') and not master.check_user_auth(user_name, 'operator', 'application'):
io.send('failed', 'User not authorized')
return
if command == 'kill':
act_and_respond(self._kill_app(app_data['appid']))
elif command == 'add':
act_and_respond(self._add_sequences(app_data['schedule'], user_name))
elif command == 'remove':
act_and_respond(self._delete_sequence(app_data['sequence'], user_name))
elif command == 'start':
if 'sequence' in app_data:
act_and_respond(self._start_sequence(app_data['sequence'], user_name))
else:
act_and_respond(self._start_all_sequences())
elif command == 'stop':
if 'sequence' in app_data:
act_and_respond(self._stop_sequence(app_data['sequence'], user_name))
else:
act_and_respond(self._stop_all_sequences())
else:
# new single application - get the work area path
if 'path' in app_data:
# work area specified
workarea = app_data['path']
else:
workarea = self._make_workarea()
if not workarea:
io.send('failed', 'Failed to create work area')
if command == 'submit':
app_data['path'] = workarea
app_data['user_id'] = user_id
if io.host == 'localhost' or io.host == '127.0.0.1':
app_data['host'] = socket.gethostname()
else:
app_data['host'] = io.host
success, msg = act_and_respond(self._schedule_app(app_data))
if success and app_data['mode'] == 'synch':
# synchronous execution = client watches the app run
# client sends the socket address to connect stdout/err to
port_data = io.recv()
addr = (io.host, port_data['port'])
result = self._serve_synch_app(msg['appid'], msg['path'], addr)
io.send('OK', result)
elif command == 'interact':
self._interact(workarea, io)
# cleanup
if 'path' not in app_data:
shutil.rmtree(workarea)
except:
exc_type, exc, tb = sys.exc_info()
msg = '\n' + ''.join(traceback.format_tb(tb)) + '\n'
msg += '%s: %s' % (exc_type.__name__, str(exc))
io.send('failed', msg)
finally:
conn.close()
def _interact(self, workarea, io):
io.send('OK')
port_data = io.recv()
addr = (io.host, port_data['port'])
args = (addr, workarea)
proc = multiprocessing.Process(target = self._run_interactive_through_socket, name = 'interactive', args = args)
proc.start()
proc.join()
LOG.info('Finished interactive session.')
def _serve_synch_app(self, app_id, path, addr):
conns = (socket.create_connection(addr), socket.create_connection(addr))
stop_reading = threading.Event()
for conn, name in zip(conns, ('stdout', 'stderr')):
args = (path + '/_' + name, conn, stop_reading)
th = threading.Thread(target = tail_follow, name = name, args = args)
th.daemon = True
th.start()
msg = self.wait_synch_app_queue(app_id) # {'status': status, 'exit_code': exit_code}
self.remove_synch_app_queue(app_id)
# not an elegant solution but we need to keep the reader threads alive for just a bit longer
time.sleep(1)
stop_reading.set()
for conn in conns:
try:
conn.shutdown(socket.SHUT_RDWR)
except:
pass
conn.close()
return {'status': AppManager.status_name(msg['status']), 'exit_code': msg['exit_code']}
def _run_interactive_through_socket(self, addr, workarea):
conns = (socket.create_connection(addr), socket.create_connection(addr))
stdout = conns[0].makefile('w')
stderr = conns[1].makefile('w')
if addr[0] == 'localhost' or addr[0] == '127.0.0.1':
is_local = True
else:
is_local = (addr[0] == socket.gethostname())
# use the receive side of conns[0] for stdin
make_console = lambda l: SocketConsole(conns[0], l)
self.dynamo_server.run_interactive(workarea, is_local, make_console, stdout, stderr)
stdout.close()
stderr.close()
for conn in conns:
try:
conn.shutdown(socket.SHUT_RDWR)
except:
pass
conn.close()
class SocketConsole(code.InteractiveConsole):
"""
Console where input comes from a socket. Because the core of the console uses the python
exec statement, we cannot just re-implement write() to send to a socket, and have to replace
sys.stdout and sys.stderr with socket files.
"""
def __init__(self, conn, locals = None, filename = '<dynamo>'):
code.InteractiveConsole.__init__(self, locals, filename)
self._conn = conn
self._lines = []
self._last_line = ''
self._buffer = ''
self._expected_length = ''
def write(self, data):
# InteractiveConsole.write() only writes to stderr and does not flush.
# If stderr is actually a socket makefile(), no data will be sent unless flushed.
sys.stderr.write(data)
try:
sys.stderr.flush()
except:
pass
def raw_input(self, prompt = ''):
sys.stdout.write(prompt)
try:
sys.stdout.flush()
except:
return ''
data = ''
while len(self._lines) == 0 or len(data) != 0:
if len(data) == 0:
# receive data chunk
chunk = self._conn.recv(2048)
if not chunk:
# socket closed
raise EOFError()
data += chunk
if len(self._buffer) == 0:
# if we are at the beginning of the chunk
pos = data.find(' ')
if pos == -1:
# received chunk is not even the full word for the data length
self._expected_length += data
continue
self._expected_length += data[:pos]
data = data[pos + 1:]
expected_length = int(self._expected_length)
if expected_length == 0:
self._expected_length = ''
raise EOFError()
# read | |
assert gt_masks.dtype == np.bool_, "Expected bool but got {}".format(
gt_masks.dtype)
# It's common to add GT Boxes to ROIs but we don't do that here because
# according to <NAME> paper, it doesn't help.
# Trim empty padding in gt_boxes and gt_masks parts
instance_ids = np.where(gt_class_ids > 0)[0]
assert instance_ids.shape[0] > 0, "Image must contain instances."
gt_class_ids = gt_class_ids[instance_ids]
gt_boxes = gt_boxes[instance_ids]
gt_masks = gt_masks[:, :, instance_ids]
# Compute areas of ROIs and ground truth boxes.
rpn_roi_area = (rpn_rois[:, 2] - rpn_rois[:, 0]) * \
(rpn_rois[:, 3] - rpn_rois[:, 1])
gt_box_area = (gt_boxes[:, 2] - gt_boxes[:, 0]) * \
(gt_boxes[:, 3] - gt_boxes[:, 1])
# Compute overlaps [rpn_rois, gt_boxes]
overlaps = np.zeros((rpn_rois.shape[0], gt_boxes.shape[0]))
for i in range(overlaps.shape[1]):
gt = gt_boxes[i]
overlaps[:, i] = utils.compute_iou(
gt, rpn_rois, gt_box_area[i], rpn_roi_area)
# Assign ROIs to GT boxes
rpn_roi_iou_argmax = np.argmax(overlaps, axis=1)
rpn_roi_iou_max = overlaps[np.arange(
overlaps.shape[0]), rpn_roi_iou_argmax]
# GT box assigned to each ROI
rpn_roi_gt_boxes = gt_boxes[rpn_roi_iou_argmax]
rpn_roi_gt_class_ids = gt_class_ids[rpn_roi_iou_argmax]
# Positive ROIs are those with >= 0.5 IoU with a GT box.
fg_ids = np.where(rpn_roi_iou_max > 0.5)[0]
# Negative ROIs are those with max IoU 0.1-0.5 (hard example mining)
# TODO: To hard example mine or not to hard example mine, that's the question
# bg_ids = np.where((rpn_roi_iou_max >= 0.1) & (rpn_roi_iou_max < 0.5))[0]
bg_ids = np.where(rpn_roi_iou_max < 0.5)[0]
# Subsample ROIs. Aim for 33% foreground.
# FG
fg_roi_count = int(config.TRAIN_ROIS_PER_IMAGE * config.ROI_POSITIVE_RATIO)
if fg_ids.shape[0] > fg_roi_count:
keep_fg_ids = np.random.choice(fg_ids, fg_roi_count, replace=False)
else:
keep_fg_ids = fg_ids
# BG
remaining = config.TRAIN_ROIS_PER_IMAGE - keep_fg_ids.shape[0]
if bg_ids.shape[0] > remaining:
keep_bg_ids = np.random.choice(bg_ids, remaining, replace=False)
else:
keep_bg_ids = bg_ids
# Combine indices of ROIs to keep
keep = np.concatenate([keep_fg_ids, keep_bg_ids])
# Need more?
remaining = config.TRAIN_ROIS_PER_IMAGE - keep.shape[0]
if remaining > 0:
# Looks like we don't have enough samples to maintain the desired
# balance. Reduce requirements and fill in the rest. This is
# likely different from the Mask RCNN paper.
# There is a small chance we have neither fg nor bg samples.
if keep.shape[0] == 0:
# Pick bg regions with easier IoU threshold
bg_ids = np.where(rpn_roi_iou_max < 0.5)[0]
assert bg_ids.shape[0] >= remaining
keep_bg_ids = np.random.choice(bg_ids, remaining, replace=False)
assert keep_bg_ids.shape[0] == remaining
keep = np.concatenate([keep, keep_bg_ids])
else:
# Fill the rest with repeated bg rois.
keep_extra_ids = np.random.choice(
keep_bg_ids, remaining, replace=True)
keep = np.concatenate([keep, keep_extra_ids])
assert keep.shape[0] == config.TRAIN_ROIS_PER_IMAGE, \
"keep doesn't match ROI batch size {}, {}".format(
keep.shape[0], config.TRAIN_ROIS_PER_IMAGE)
# Reset the gt boxes assigned to BG ROIs.
rpn_roi_gt_boxes[keep_bg_ids, :] = 0
rpn_roi_gt_class_ids[keep_bg_ids] = 0
# For each kept ROI, assign a class_id, and for FG ROIs also add bbox refinement.
rois = rpn_rois[keep]
roi_gt_boxes = rpn_roi_gt_boxes[keep]
roi_gt_class_ids = rpn_roi_gt_class_ids[keep]
roi_gt_assignment = rpn_roi_iou_argmax[keep]
# Class-aware bbox deltas. [y, x, log(h), log(w)]
bboxes = np.zeros((config.TRAIN_ROIS_PER_IMAGE,
config.NUM_CLASSES, 4), dtype=np.float32)
pos_ids = np.where(roi_gt_class_ids > 0)[0]
bboxes[pos_ids, roi_gt_class_ids[pos_ids]] = utils.box_refinement(
rois[pos_ids], roi_gt_boxes[pos_ids, :4])
# Normalize bbox refinements
bboxes /= config.BBOX_STD_DEV
# Generate class-specific target masks
masks = np.zeros((config.TRAIN_ROIS_PER_IMAGE, config.MASK_SHAPE[0], config.MASK_SHAPE[1], config.NUM_CLASSES),
dtype=np.float32)
for i in pos_ids:
class_id = roi_gt_class_ids[i]
assert class_id > 0, "class id must be greater than 0"
gt_id = roi_gt_assignment[i]
class_mask = gt_masks[:, :, gt_id]
if config.USE_MINI_MASK:
# Create a mask placeholder, the size of the image
placeholder = np.zeros(config.IMAGE_SHAPE[:2], dtype=bool)
# GT box
gt_y1, gt_x1, gt_y2, gt_x2 = gt_boxes[gt_id]
gt_w = gt_x2 - gt_x1
gt_h = gt_y2 - gt_y1
# Resize mini mask to size of GT box
placeholder[gt_y1:gt_y2, gt_x1:gt_x2] = \
np.round(utils.resize(class_mask, (gt_h, gt_w))).astype(bool)
# Place the mini batch in the placeholder
class_mask = placeholder
# Pick part of the mask and resize it
y1, x1, y2, x2 = rois[i].astype(np.int32)
m = class_mask[y1:y2, x1:x2]
mask = utils.resize(m, config.MASK_SHAPE)
masks[i, :, :, class_id] = mask
return rois, roi_gt_class_ids, bboxes, masks
def build_rpn_targets(image_shape, anchors, gt_class_ids, gt_boxes, config):
"""Given the anchors and GT boxes, compute overlaps and identify positive
anchors and deltas to refine them to match their corresponding GT boxes.
anchors: [num_anchors, (y1, x1, y2, x2)]
gt_class_ids: [num_gt_boxes] Integer class IDs.
gt_boxes: [num_gt_boxes, (y1, x1, y2, x2)]
Returns:
rpn_match: [N] (int32) matches between anchors and GT boxes.
1 = positive anchor, -1 = negative anchor, 0 = neutral
rpn_bbox: [N, (dy, dx, log(dh), log(dw))] Anchor bbox deltas.
"""
# RPN Match: 1 = positive anchor, -1 = negative anchor, 0 = neutral
rpn_match = np.zeros([anchors.shape[0]], dtype=np.int32)
# RPN bounding boxes: [max anchors per image, (dy, dx, log(dh), log(dw))]
rpn_bbox = np.zeros((config.RPN_TRAIN_ANCHORS_PER_IMAGE, 4))
# Handle COCO crowds
# A crowd box in COCO is a bounding box around several instances. Exclude
# them from training. A crowd box is given a negative class ID.
crowd_ix = np.where(gt_class_ids < 0)[0]
if crowd_ix.shape[0] > 0:
# Filter out crowds from ground truth class IDs and boxes
non_crowd_ix = np.where(gt_class_ids > 0)[0]
crowd_boxes = gt_boxes[crowd_ix]
gt_class_ids = gt_class_ids[non_crowd_ix]
gt_boxes = gt_boxes[non_crowd_ix]
# Compute overlaps with crowd boxes [anchors, crowds]
crowd_overlaps = utils.compute_overlaps(anchors, crowd_boxes)
crowd_iou_max = np.amax(crowd_overlaps, axis=1)
no_crowd_bool = (crowd_iou_max < 0.001)
else:
# All anchors don't intersect a crowd
no_crowd_bool = np.ones([anchors.shape[0]], dtype=bool)
# Compute overlaps [num_anchors, num_gt_boxes]
overlaps = utils.compute_overlaps(anchors, gt_boxes)
# Match anchors to GT Boxes
# If an anchor overlaps a GT box with IoU >= 0.7 then it's positive.
# If an anchor overlaps a GT box with IoU < 0.3 then it's negative.
# Neutral anchors are those that don't match the conditions above,
# and they don't influence the loss function.
# However, don't keep any GT box unmatched (rare, but happens). Instead,
# match it to the closest anchor (even if its max IoU is < 0.3).
#
# 1. Set negative anchors first. They get overwritten below if a GT box is
# matched to them. Skip boxes in crowd areas.
anchor_iou_argmax = np.argmax(overlaps, axis=1)
anchor_iou_max = overlaps[np.arange(overlaps.shape[0]), anchor_iou_argmax]
rpn_match[(anchor_iou_max < 0.3) & (no_crowd_bool)] = -1
# 2. Set an anchor for each GT box (regardless of IoU value).
# If multiple anchors have the same IoU match all of them
gt_iou_argmax = np.argwhere(overlaps == np.max(overlaps, axis=0))[:,0]
rpn_match[gt_iou_argmax] = 1
# 3. Set anchors with high overlap as positive.
rpn_match[anchor_iou_max >= 0.7] = 1
# Subsample to balance positive and negative anchors
# Don't let positives be more than half the anchors
ids = np.where(rpn_match == 1)[0]
extra = len(ids) - (config.RPN_TRAIN_ANCHORS_PER_IMAGE // 2)
if extra > 0:
# Reset the extra ones to neutral
ids = np.random.choice(ids, extra, replace=False)
rpn_match[ids] = 0
# Same for negative proposals
ids = np.where(rpn_match == -1)[0]
extra = len(ids) - (config.RPN_TRAIN_ANCHORS_PER_IMAGE -
np.sum(rpn_match == 1))
if extra > 0:
# Rest the extra ones to neutral
ids = np.random.choice(ids, extra, replace=False)
rpn_match[ids] = 0
# For positive anchors, compute shift and scale needed to transform them
# to match the corresponding GT boxes.
ids = np.where(rpn_match == 1)[0]
ix = 0 # index into rpn_bbox
# TODO: use box_refinement() rather than duplicating the code here
for i, a in zip(ids, anchors[ids]):
# Closest gt box (it might have IoU < 0.7)
gt = gt_boxes[anchor_iou_argmax[i]]
# Convert coordinates to center plus width/height.
# GT Box
gt_h = gt[2] - gt[0]
gt_w = gt[3] - gt[1]
gt_center_y = gt[0] + 0.5 * gt_h
gt_center_x = gt[1] + 0.5 * gt_w
# Anchor
a_h = a[2] - a[0]
a_w = a[3] - a[1]
a_center_y = a[0] + 0.5 * a_h
a_center_x = a[1] + 0.5 * a_w
# Compute the bbox refinement that the RPN should predict.
rpn_bbox[ix] = [
(gt_center_y - a_center_y) / a_h,
(gt_center_x - a_center_x) / a_w,
np.log(gt_h / a_h),
np.log(gt_w / a_w),
]
# Normalize
rpn_bbox[ix] /= config.RPN_BBOX_STD_DEV
ix += 1
return rpn_match, rpn_bbox
def generate_random_rois(image_shape, count, gt_class_ids, gt_boxes):
"""Generates ROI proposals similar to what a region proposal network
would generate.
image_shape: [Height, Width, Depth]
count: Number of ROIs to generate
gt_class_ids: [N] Integer ground truth class IDs
gt_boxes: [N, (y1, | |
column_format + 'c|'
latex = df.to_latex(column_format=column_format)
# replace \toprule, \midrule, \bottomrule with \hline (looks better plus don't need to import \usepackage{booktabs}
rules = ['\\toprule', '\\midrule', '\\bottomrule']
latex = latex.replace(rules[0], '\\hline')
latex = latex.replace(rules[1], '\\hline')
latex = latex.replace(rules[2], '\\hline')
latex = latex.replace('+-', ' $\\pm$ ')
return latex
##
def create_logs_dir_and_load(opts):
from uutils import load_cluster_jobids_to
from datetime import datetime
load_cluster_jobids_to(opts)
# opts.log_root = Path('~/data/logs/').expanduser()
# create and load in args path to current experiments from log folder path
opts.current_time = datetime.now().strftime('%b%d_%H-%M-%S')
opts.log_experiment_dir = opts.log_root / f'logs_{opts.current_time}_jobid_{opts.jobid}'
opts.log_experiment_dir.mkdir(parents=True, exist_ok=True)
# create and load in args path to checkpoint (same as experiment log path)
opts.checkpoint_dir = opts.log_experiment_dir
def save_opts(opts: Namespace, args_filename: str = 'opts.json'):
""" Saves opts, crucially in sorted order. """
# save opts that was used for experiment
with open(opts.log_root / args_filename, 'w') as argsfile:
# in case some things can't be saved to json e.g. tb object, torch_uu.Tensors, etc.
args_data = {key: str(value) for key, value in opts.__dict__.items()}
json.dump(args_data, argsfile, indent=4, sort_keys=True)
def save_args(args: Namespace, args_filename: str = 'args.json'):
""" Saves args, crucially in sorted order. """
save_opts(args, args_filename)
def load_cluster_jobids_to(args):
import os
# Get Get job number of cluster
args.jobid = -1
args.slurm_jobid, args.slurm_array_task_id = -1, -1
args.condor_jobid = -1
args.hostname = str(gethostname())
if "SLURM_JOBID" in os.environ:
args.slurm_jobid = int(os.environ["SLURM_JOBID"])
args.jobid = args.slurm_jobid
if "SLURM_ARRAY_TASK_ID" in os.environ:
args.slurm_array_task_id = int(os.environ["SLURM_ARRAY_TASK_ID"])
# - note this is set manually in the .sub file so you might have a different name e.g. MY_CONDOR_JOB_ID
if "CONDOR_JOB_ID" in os.environ:
args.condor_jobid = int(os.environ["CONDOR_JOB_ID"])
args.jobid = args.condor_jobid
if "PBS_JOBID" in os.environ:
# args.num_workers = 8
try:
args.jobid = int(os.environ["PBS_JOBID"])
except:
args.jobid = os.environ["PBS_JOBID"]
if 'dgx' in str(gethostname()):
args.jobid = f'{args.jobid}_pid_{os.getpid()}'
def set_system_wide_force_flush():
"""
Force flushes the entire print function everywhere.
https://stackoverflow.com/questions/230751/how-to-flush-output-of-print-function
:return:
"""
import builtins
import functools
print2 = functools.partial(print, flush=True)
builtins.print = print2
# graph stuff
def draw_nx(g, labels=None):
import matplotlib.pyplot as plt
if labels is not None:
g = nx.relabel_nodes(g, labels)
pos = nx.kamada_kawai_layout(g)
nx.draw(g, pos, with_labels=True)
plt.show()
def draw_nx_attributes_as_labels(g, attribute):
# import pylab
import matplotlib.pyplot as plt
import networkx as nx
labels = nx.get_node_attributes(g, attribute)
pos = nx.kamada_kawai_layout(g)
nx.draw(g, pos, labels=labels, with_labels=True)
# nx.draw(g, labels=labels)
# pylab.show()
plt.show()
def draw_nx_with_pygraphviz(g, path2file=None, save_file=False):
attribute_name = None
draw_nx_with_pygraphviz_attribtes_as_labels(g, attribute_name, path2file, save_file)
def draw_nx_with_pygraphviz_attribtes_as_labels(g, attribute_name, path2file=None, save_file=False):
import pygraphviz as pgv
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# https://stackoverflow.com/questions/15345192/draw-more-information-on-graph-nodes-using-pygraphviz
# https://stackoverflow.com/a/67442702/1601580
if path2file is None:
path2file = './example.png'
path2file = Path(path2file).expanduser()
save_file = True
if type(path2file) == str:
path2file = Path(path2file).expanduser()
save_file = True
print(f'\n{g.is_directed()=}')
g = nx.nx_agraph.to_agraph(g)
if attribute_name is not None:
print(f'{g=}')
# to label in pygrapviz make sure to have the AGraph obj have the label attribute set on the nodes
g = str(g)
g = g.replace(attribute_name, 'label')
print(g)
# g = pgv.AGraph(g)
g = pgv.AGraph(g)
g.layout()
g.draw(path2file)
# https://stackoverflow.com/questions/20597088/display-a-png-image-from-python-on-mint-15-linux
img = mpimg.imread(path2file)
plt.imshow(img)
plt.show()
# remove file https://stackoverflow.com/questions/6996603/how-to-delete-a-file-or-folder
if not save_file:
path2file.unlink()
def visualize_lark(string: str, parser: Lark, path2filename: Union[str, Path]):
if type(path2filename) is str:
path2filename = Path(path2filename).expanduser()
else:
path2filename = path2filename.expanduser()
ast = parser.parse(string)
tree.pydot__tree_to_png(ast, path2filename)
# tree.pydot__tree_to_dot(parser.parse(sentence), filename)
def bfs(root_node: Tree, f) -> Tree:
"""
To do BFS you want to process the elements in the dequeue int he order of a queue i.e. the "fair" way - whoever
got first you process first and the next children go to the end of the line.
Thus: BFS = append + popleft = "append_end + pop_frent".
:param root_node: root_node (same as ast since ast object give pointers to top node & it's children)
:param f: function to apply to the nodes.
:return:
"""
dq = deque([root_node])
while len(dq) != 0:
current_node = dq.popleft() # pops from the front of the queue
current_node.data = f(current_node.data)
for child in current_node.children:
dq.append(child) # adds to the end
return root_node
def dfs(root_node: Tree, f) -> Tree:
"""
To do DFS we need to implement a stack. In other words we need to go down the depth until the depth has been
fully processed. In other words what you want is the the current child you are adding to the dequeue to be processed
first i.e. you want it to skip the line. To do that you can append to the front of the queue (with append_left and
then pop_left i.e. pop from that same side).
reference: https://codereview.stackexchange.com/questions/263604/how-does-one-write-dfs-in-python-with-a-deque-without-reversed-for-trees
:param root_node:
:param f:
:return:
"""
dq = deque([root_node])
while len(dq) != 0:
current_node = dq.popleft() # to make sure you pop from the front since you are adding at the front.
current_node.data = f(current_node.data)
# print(current_node.children)
for child in reversed(current_node.children):
dq.appendleft(child)
return root_node
def dfs_stack(ast: Tree, f) -> Tree:
stack = [ast]
while len(stack) != 0:
current_node = stack.pop() # pop from the end, from the side you are adding
current_node.data = f(current_node.data)
for child in reversed(current_node.children):
stack.append(child)
return ast
def dfs_recursive(ast: Tree, f) -> Tree:
"""
Go through the first child in children before processing the rest of the tree.
Note that you can apply f after you've processed all the children too to "colour" the nodes in a different order.
:param ast:
:param f:
:return:
"""
ast.data = f(ast.data)
for child in ast.children:
dfs_recursive(child, f)
def save_dataset_with_dill(path2data: str, dataset_name: str, data_set) -> None:
path2data: str = str(Path(path2data).expanduser())
with open(path2data / f'{dataset_name}.pt', 'wb') as f2dataset:
dill.dump(data_set, f2dataset)
def save_with_dill(path: str, filename: str, python_obj, mode: str = 'wb') -> None:
path: Path = Path(path).expanduser()
path.mkdir(parents=True, exist_ok=True)
filename: str = f'{filename}.pt' if filename[-3:] != '.pt' else filename
with open(path / filename, mode) as f:
dill.dump(python_obj, f)
def load_with_dill(path: str, filename: str, mode='rb') -> Any:
path: Path = Path(path).expanduser()
with open(path / filename, mode) as f:
python_obj = dill.load(f)
return python_obj
def load_json(path: str, filename: str, mode='r') -> dict:
from pathlib import Path
import json
path = Path(path).expanduser()
with open(path / filename, mode) as f:
data: dict = json.load(f)
return data
def load_json_list(path: str, filename: str, mode='r') -> list:
from pathlib import Path
import json
path = Path(path).expanduser()
with open(path / filename, mode) as f:
d: list = json.load(f)
return d
def write_str_to_file(path: str, filename: str, file_content: str, mode: str = 'w'):
path: Path = Path(path).expanduser()
path.mkdir(parents=True, exist_ok=True) # if it already exists it WONT raise an error (exists is ok!)
with open(path / filename, mode) as f:
f.write(file_content)
def namespace2dict(args: Namespace) -> dict:
"""
Retunrs a dictionary version of the namespace.
ref: - https://docs.python.org/3/library/functions.html#vars
- https://stackoverflow.com/questions/16878315/what-is-the-right-way-to-treat-argparse-namespace-as-a-dictionary
Note: Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.
:param args:
:return:
"""
# Note: Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.
return vars(args)
def dict2namespace(dict_args: dict) -> Namespace:
"""
Makes a dictionary of args to a Namespace args with the same values.
ref:
- https://stackoverflow.com/questions/2597278/python-load-variables-in-a-dict-into-namespace
"""
return Namespace(**dict_args)
def merge_two_dicts(starting_dict: dict, updater_dict: dict) -> dict:
"""
Starts from base starting dict and then adds the remaining key values from updater replacing the values from
the first starting dict with the second updater dict.
Thus, the update_dict has precedence as it updates and replaces the values from the first if there is a collision.
ref: https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-taking-union-of-dictiona
For later: how does d = {**d1, **d2} replace collision?
:param starting_dict:
:param updater_dict:
:return:
"""
new_dict: dict = starting_dict.copy() # start with keys and values of starting_dict
new_dict.update(updater_dict) # modifies starting_dict with keys and values of updater_dict
return new_dict
def merge_args_safe(args1: Namespace, args2: Namespace) -> Namespace:
"""
Merges two namespaces but throws an error if there are keys that collide.
Thus, args1 nor args2 will have precedence when returning the args if there is a collions.
This does not take the union.
ref: https://stackoverflow.com/questions/56136549/how-can-i-merge-two-argparse-namespaces-in-python-2-x
:param args1:
:param args2:
:return:
"""
# - the merged args
# The vars() function returns the __dict__ attribute to values of the given object e.g {field:value}.
args = Namespace(**vars(args1), **vars(args2))
return args
def merge_args(starting_args: Namespace, updater_args: Namespace) -> Namespace:
"""
Starts from base starting args and then adds the remaining key/fields values from updater replacing the values from
| |
<reponame>THU-luvision/Occuseg<filename>examples/ScanNet/train_instance.py
# import open3d
from datasets import ScanNet
from utils import evaluate_scannet, evaluate_stanford3D,WeightedCrossEntropyLoss, FocalLoss, label2color,evaluate_single_scan,cost2color
from model import ThreeVoxelKernel
from model import DenseUNet,InstanceDenseUNet,LearningBWDenseUNet,ClusterSegNet
from config import get_args
from config import ArgsToConfig
from scipy.io import savemat
import pdb
import sys
sys.path.insert(0, '../../../jsis3d/')
from lovasz_losses import lovasz_hinge,lovasz_softmax
from sklearn.cluster import MeanShift
import scipy.stats as stats
from model import *
from discriminative import DiscriminativeLoss,ClassificationLoss,DriftLoss
from torch_scatter import scatter_max,scatter_mean,scatter_std,scatter_sub,scatter_min,scatter_add,scatter_div
#from knn_cuda import KNN
import sparseconvnet as scn
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
from tensorboardX import SummaryWriter
import nvgpu
import sys, os, time
import logging
import json
# only holds when the optimization is zero! a bad cost function, could be further optimized?
# cannot explain well, how should we encourage the displacements to be correct?
#A larger v generalizes better
DISCRIMINATIVE_DELTA_V = 0.2
DISCRIMINATIVE_DELTA_D = 1.5
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('training logger')
logger.setLevel(logging.DEBUG)
Model = ThreeVoxelKernel
def visualize_point_cloud(batch,predictions):
tbl = batch['id']
for k,idx in enumerate(tbl):
index = batch['x'][0][:,3] == k
pos = batch['x'][0][index,0:3].data.cpu().numpy()
color = batch['x'][1][index,0:3].data.cpu().numpy() + 0.5
label = batch['y'][index,0].data.cpu().numpy()
if(label.shape[0] > 0):
predicted_label = predictions[index,:].max(1)[1]
prob = predictions[index,:]
cost_color = cost2color(prob,label)
predicted_colors = label2color(predicted_label)
label_colors = label2color(label)
ref = torch.from_numpy(pos).float().cuda()
pcd_ori = open3d.geometry.PointCloud()
pcd_ori.points = open3d.Vector3dVector(pos)
pcd_ori.colors = open3d.Vector3dVector(cost_color)
pcd_gt_label = open3d.geometry.PointCloud()
gt_pos = pos
gt_pos[:,0] = pos[:,0] + 400
pcd_gt_label.points = open3d.Vector3dVector(gt_pos)
pcd_gt_label.colors = open3d.Vector3dVector(label_colors)
pcd_predict_label = open3d.geometry.PointCloud()
predict_pos = gt_pos
predict_pos[:,0] = predict_pos[:,0] + 400
pcd_predict_label.points = open3d.Vector3dVector(predict_pos)
pcd_predict_label.colors = open3d.Vector3dVector(predicted_colors)
current_iou = iou_evaluate(predicted_label.numpy(), label, train_writer, 0,class_num = config['class_num'] , topic='valid')
#predictions
if config['dataset'] == 'stanford3d':
fileName = batch['pth_file'][k][0:batch['pth_file'][k].rfind('/')] + '_' + "%.2f" % current_iou
elif config['dataset'] == 'scannet':
fileName = batch['pth_file'][k][0:-4] + '_' + "%.2f" % current_iou
fori = fileName + '_ori.pcd'
fgt = fileName + '_gt.pcd'
fpredict = fileName + '_predict.pcd'
open3d.write_point_cloud(fori, pcd_ori)
open3d.write_point_cloud(fgt, pcd_gt_label)
open3d.write_point_cloud(fpredict, pcd_predict_label)
volumetric_sizes_per_category = np.loadtxt("sizes.txt")
def evaluate_instance(net, config, global_iter):
valOffsets = config['valOffsets']
val_data_loader = config['val_data_loader']
valLabels = config['valLabels']
pdict = {'semantics': [], 'instances': []}
total = np.zeros(config['class_num'])
fps = [[] for i in range(config['class_num'])]
tps = [[] for i in range(config['class_num'])]
criterion = {}
criterion['discriminative'] = DiscriminativeLoss(
DISCRIMINATIVE_DELTA_D,
DISCRIMINATIVE_DELTA_V
)
criterion['nll'] = nn.functional.cross_entropy
criterion['regression'] = nn.L1Loss()
with torch.no_grad():
net.eval()
store = torch.zeros(valOffsets[-1], config['class_num'])
scn.forward_pass_multiplyAdd_count = 0
scn.forward_pass_hidden_states = 0
time_val_start = time.time()
for rep in range(1, 2):
locs = None
pth_files = []
for i, batch in enumerate(val_data_loader):
batch['x'][1] = batch['x'][1].cuda()
torch.cuda.empty_cache()
predictions, feature, embeddings, offsets, displacements, bw, occupancy = net(batch['x'])
batch['y'] = batch['y'].cuda()
batch['region_masks'] = batch['region_masks'].cuda()
batch['offsets'] = batch['offsets'].cuda()
batch['displacements'] = batch['displacements'].cuda()
calculate_cost(predictions, embeddings, offsets, displacements, bw, criterion, batch, occupancy)
# print("computing semantic embedding test: ", i)
semantics = np.argmax(predictions.cpu().numpy(), axis=-1)
instances = []
tbl = batch['id']
predictions = predictions.cpu()
store.index_add_(0, batch['point_ids'], predictions)
averaged_predictions = store[batch['point_ids'],:] / rep
if(rep == 1):
for k,idx in enumerate(tbl):
index = (batch['x'][0][:,config['dimension']] == k)
embedding = embeddings[index,:].cpu().numpy()
semantic = averaged_predictions.max(1)[1][index].cpu().numpy()
size = batch['sizes'][k].item()
# y = MeanShift(1.5, n_jobs=8).fit_predict(embedding)
# instances.append(y)
offline_data = {}
offline_data['xyz'] = batch['x'][0][index,:config['dimension']].cpu().numpy()
offline_data['feature'] = batch['x'][1][index,:].cpu().numpy()
offline_data['occupancy'] = occupancy[index,0].cpu().numpy()
offline_data['true_occupancy'] = batch['instance_sizes'][index].cpu().numpy()
offline_data['pred_semantic'] = semantic
offline_data['pred_semantic_probability'] = averaged_predictions[index,:].cpu().numpy()
offline_data['pred_embedding'] = embedding
offline_data['regions'] = batch['regions'][index].cpu().numpy()
offline_data['true_semantic'] = batch['y'][index,0].cpu().numpy()
offline_data['true_instance'] = batch['y'][index,1].cpu().numpy()
offline_data['pred_offsets'] = offsets[index].cpu().numpy()
offline_data['true_offsets'] = batch['offsets'][index].cpu().numpy()
offline_data['pred_displacements'] = displacements[index].cpu().numpy()
offline_data['true_displacements'] = batch['displacements'][index].cpu().numpy()
offline_data['pred_bw'] = bw[index,:].cpu().numpy()
offline_data['scale'] = config['scale']
filename = batch['pth_file'][k]
filename = filename[:-3] + 'npz'
np.savez(filename , **offline_data)
print('save: ', filename)
print('infer', rep, 'Val MegaMulAdd=', scn.forward_pass_multiplyAdd_count / len(dataset.val) / 1e6,
'MegaHidden', scn.forward_pass_hidden_states / len(dataset.val) / 1e6, 'time=',
time.time() - time_val_start,
's')
predLabels = store.max(1)[1].numpy()
topic = 'valid_' + str(rep)
iou_evaluate(predLabels, valLabels, train_writer, global_iter, class_num = config['class_num'] , topic=topic)
train_writer.add_scalar("valid/MegaMulAdd", scn.forward_pass_multiplyAdd_count / len(dataset.val) / 1e6,
global_step=global_iter)
train_writer.add_scalar("valid/MegaHidden", scn.forward_pass_hidden_states / len(dataset.val) / 1e6,
global_step=global_iter)
if config['evaluate']:
savemat('pred.mat', {'p':store.numpy(),'val_offsets':np.hstack(valOffsets), 'v': valLabels})
predLabels = store.max(1)[1].numpy()
iou_evaluate(predLabels, valLabels, train_writer, global_iter,class_num = config['class_num'] , topic='valid')
train_writer.add_scalar("valid/time", time.time() - time_val_start, global_step=global_iter)
def calculate_cost(predictions, embeddings, offsets, displacements, bw, criterion, batch, occupancy):
tbl = batch['id']
#lovasz_softmax(predictions, batch['y'][:,0], ignore = -100)
SemanticLoss = criterion['nll'](predictions, batch['y'][:,0])
EmbeddingLoss = torch.zeros(1,dtype=torch.float32).cuda()
OccupancyLoss = torch.zeros(1,dtype=torch.float32).cuda()
DisplacementLoss = torch.zeros(1,dtype=torch.float32).cuda()
loss_classification = torch.zeros(1,dtype=torch.float32).cuda()
loss_drift = torch.zeros(1,dtype=torch.float32).cuda()
instance_iou = torch.zeros(1,dtype=torch.float32).cuda()
batchSize = 0
forground_indices = batch['y'][:,0] > 1
regressed_pose = batch['x'][0][:,0:3].cuda() / config['scale'] - displacements
pose = batch['x'][0][:,0:3].cuda() / config['scale']
displacements_gt = batch['displacements'].cuda()
occupancy_gt = batch['instance_sizes'].cuda().view(-1,1)
for count,idx in enumerate(tbl):
index = (batch['x'][0][:,config['dimension']] == count)
embedding = embeddings[index,:].view(1,-1,embeddings.shape[1])
instance_mask = batch['instance_masks'][index].view(1,-1).cuda().type(torch.long)
mask = batch['masks'][count].view(1,-1,batch['masks'][count].shape[1])
size = batch['sizes'][count:count+1]
pred_semantics = batch['y'][index,0]
EmbeddingLoss += criterion['discriminative'](embedding, instance_mask)
displacement_error = torch.zeros(1,dtype=torch.float32).cuda()
occupancy_error = torch.zeros(1,dtype=torch.float32).cuda()
cluster_size = 0
displacement_cluster_error = scatter_mean(torch.norm(displacements[index,:]- displacements_gt[index,:], dim = 1), instance_mask.view(-1),dim = 0)
# true_occupancy = scatter_mean(torch.norm(occupancy_gt[index,:], dim = 1 ), instance_mask.view(-1),dim = 0)
# pred_occupancy = scatter_mean(torch.norm(occupancy[index,:], dim = 1 ), instance_mask.view(-1),dim = 0)
occupancy_cluster_error = scatter_mean(torch.norm(occupancy[index,:] - occupancy_gt[index,:], dim = 1 ), instance_mask.view(-1),dim = 0)
occupancy_cluster_std = scatter_std(occupancy[index,:], instance_mask.view(-1),dim = 0)
mask_size = instance_mask[0,:].max() + 1
for mid in range(mask_size):
instance_indices = (instance_mask[0,:]==mid)
cls = pred_semantics[instance_indices][0]
if(cls > 1):
displacement_error += displacement_cluster_error[mid]
occupancy_error += occupancy_cluster_error[mid] + occupancy_cluster_std[mid]
# current_occupancy = occupancy[index,:]
# median_occupancy = torch.median(current_occupancy[instance_indices,:])
# print(cls.item(), torch.exp(pred_occupancy[mid]).item(),torch.exp(median_occupancy).item(), torch.exp(true_occupancy[mid]).item())
cluster_size += 1
if cluster_size > 0:
OccupancyLoss += occupancy_error / cluster_size
DisplacementLoss += displacement_error / cluster_size
loss_c, i_iou = ClassificationLoss(embedding,bw[index,:].view(1,-1,2), regressed_pose[index,:].view(1,-1,3), pose[index,:].view(1,-1,3), instance_mask,pred_semantics)
loss_classification += loss_c
instance_iou += i_iou
# loss_drift += 50 * DriftLoss(embedding,mask.cuda(),pred_semantics,regressed_pose[index,:].view(1,-1,3),batch['offsets'][index,:], pose[index,:].view(1,-1,3)) #We want to align anchor points to mu as close as possible
batchSize += 1
EmbeddingLoss /= batchSize
OccupancyLoss /= batchSize
DisplacementLoss /= batchSize
loss_classification /= batchSize
loss_drift /= batchSize
instance_iou /= batchSize
PreOccupancyLoss = criterion['regression'](occupancy[forground_indices].view(-1), batch['instance_sizes'].cuda()[forground_indices])
PreDisplacementLoss = criterion['regression'](displacements[forground_indices ,:], batch['displacements'].cuda()[forground_indices ,:]) * config['displacement_weight']
#print('previous occupancy loss: ', PreOccupancyLoss.item(),OccupancyLoss.item(),' ', PreDisplacementLoss.item(),DisplacementLoss.item())
RegressionLoss = criterion['regression'](offsets[forground_indices ], batch['offsets'].cuda()[forground_indices ]) * config['regress_weight']
#del RegressionLoss
return {'semantic_loss': SemanticLoss, 'embedding_loss':EmbeddingLoss, 'regression_loss':RegressionLoss, 'displacement_loss':DisplacementLoss,
'classification_loss':loss_classification, 'drift_loss':loss_drift, 'instance_iou':instance_iou, 'occupancy_loss': OccupancyLoss}
def evaluate(net, config, global_iter):
valOffsets = config['valOffsets']
val_data_loader = config['val_data_loader']
valLabels = config['valLabels']
criterion = {}
criterion['discriminative'] = DiscriminativeLoss(
DISCRIMINATIVE_DELTA_D,
DISCRIMINATIVE_DELTA_V
)
criterion['nll'] = nn.functional.cross_entropy
criterion['regression'] = nn.L1Loss()
with torch.no_grad():
net.eval()
store = torch.zeros(valOffsets[-1], config['class_num'])
scn.forward_pass_multiplyAdd_count = 0
scn.forward_pass_hidden_states = 0
time_val_start = time.time()
for rep in range(1, 1 + dataset.val_reps):
locs = None
pth_files = []
epoch_len = len(config['val_data_loader'])
regression_loss = 0
semantic_loss = 0
embedding_loss = 0
displacement_loss = 0
drift_loss = 0
classification_loss = 0
occupancy_loss = 0
instance_iou = 0
for i, batch in enumerate(val_data_loader):
torch.cuda.empty_cache()
# print("before net 0", nvgpu.gpu_info()[0]['mem_used'])
batch['x'][1] = batch['x'][1].cuda()
predictions, feature, embeddings, offsets, displacements, bw, occupancy = net(batch['x'])
# print("after net 0", nvgpu.gpu_info()[0]['mem_used'])
batch['y'] = batch['y'].cuda()
batch['region_masks'] = batch['region_masks'].cuda()
batch['offsets'] = batch['offsets'].cuda()
batch['displacements'] = batch['displacements'].cuda()
batch_size = 0
tbl = batch['id']
losses = calculate_cost(predictions,embeddings,offsets,displacements,bw, criterion,batch, occupancy)
regression_loss += losses['regression_loss'].item()
embedding_loss += losses['embedding_loss'].item()
semantic_loss += losses['semantic_loss'].item()
displacement_loss += losses['displacement_loss'].item()
classification_loss += losses['classification_loss'].item()
occupancy_loss += losses['occupancy_loss'].item()
drift_loss += losses['drift_loss'].item()
instance_iou += losses['instance_iou'].item()
predictions = predictions.cpu()
store.index_add_(0, batch['point_ids'], predictions)
#visualize based on predictions, use open3D for convinence
if config['evaluate']:
visualize_point_cloud(batch,predictions)
# open3d.visualization.draw_geometries([pcd_ori, pcd_gt_label, pcd_predict_label])
# loop for all val set every snap shot is tooooo slow, pls use val.py to check individually
# if save_ply:
# print("evaluate data: ", i)
# iou.visualize_label(batch, predictions, rep, save_dir=config['checkpoints_dir'] +)
predLabels = store.max(1)[1].numpy()
topic = 'valid_' + str(rep)
iou_evaluate(predLabels, valLabels, train_writer, global_iter, class_num = config['class_num'] , topic=topic)
train_writer.add_scalar(topic + "/epoch_avg_displacement_closs", displacement_loss / epoch_len, global_step=global_iter)
train_writer.add_scalar(topic + "/epoch_avg_regression_closs", regression_loss / epoch_len, global_step=global_iter)
train_writer.add_scalar(topic + "/epoch_avg_embedding_closs", embedding_loss / epoch_len, global_step=global_iter)
train_writer.add_scalar(topic + "/epoch_avg_semantic_closs", semantic_loss/ epoch_len, global_step=global_iter)
train_writer.add_scalar(topic + "/epoch_avg_classification_closs", classification_loss / epoch_len, global_step=global_iter)
train_writer.add_scalar(topic + "/epoch_avg_occupancy_loss", occupancy_loss / epoch_len, global_step=global_iter)
train_writer.add_scalar(topic + "/epoch_avg_drift_closs", drift_loss/ epoch_len, global_step=global_iter)
train_writer.add_scalar(topic + "/epoch_avg_instance_precision", instance_iou/ epoch_len, global_step=global_iter)
print('infer', rep, 'time=', time.time() - time_val_start, 's')
if config['evaluate']:
savemat('pred.mat', {'p':store.numpy(),'val_offsets':np.hstack(valOffsets), 'v': valLabels})
torch.cuda.empty_cache()
predLabels = store.max(1)[1].numpy()
iou_evaluate(predLabels, valLabels, train_writer, global_iter,class_num = config['class_num'] , topic='valid')
train_writer.add_scalar("valid/time", time.time() - time_val_start, global_step=global_iter)
def train_net(net, config):
if config['optim'] == 'SGD':
optimizer = optim.SGD(net.parameters(), lr=config['lr'])
elif config['optim'] == 'Adam':
optimizer = optim.Adam(net.parameters(), lr=config['lr'])
# optimizer = optim.Adam([{'params': net.fc_bw.parameters()}, {'params':net.linear_bw.parameters()}], lr=config['lr'])
"""
if config['loss'] == 'cross_entropy':
criterion = nn.functional.cross_entropy
elif config['loss'] == 'focal':
criterion = FocalLoss()
elif config['loss'] == 'weighted_cross_entropy':
if config['dataset'] == 'stanford3d':
weight = torch.from_numpy(np.hstack([0.1861, 0.1586,0.2663,0.0199,0.0039,0.0210,0.0210,0.0575,0.0332,0.0458,0.0052,0.0495 ,0.0123,0.1164,0.0032]))
elif config['dataset'] == 'scannet':
weight = torch.from_numpy(np.hstack([0.3005,0.2700,0.0418,0.0275,0.0810,0.0254,0.0462,0.0418,0.0297,0.0277,0.0061,0.0065,0.0194,0.0150,0.0060,0.0036,0.0029,0.0025,0.0029,0.0434]))
weight = weight.cuda().float()
criterion = WeightedCrossEntropyLoss(weight)
else:
raise NotImplementedError
"""
criterion = {}
criterion['discriminative'] = DiscriminativeLoss(
DISCRIMINATIVE_DELTA_D,
DISCRIMINATIVE_DELTA_V
)
weight = None
criterion['nll'] = nn.functional.cross_entropy
criterion['regression'] = nn.L1Loss()
for epoch in range(config['checkpoint'], config['max_epoch']):
net.train()
stats = {}
scn.forward_pass_multiplyAdd_count = 0
scn.forward_pass_hidden_states = 0
start | |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) 2020 <NAME>
# ## Train SparseChem on Chembl_mini
# Output to `experiments/SparseChem`
import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
import argparse
import sys
import os.path
import time
import json
import functools
import types
import wandb
import pprint
import csv
import copy
import warnings
import sparsechem as sc
from datetime import datetime
from contextlib import redirect_stdout
from sparsechem import Nothing
from sparsechem.notebook_modules import init_wandb,check_for_improvement, initialize
import scipy.io
import scipy.sparse
import numpy as np
import pandas as pd
import torch
from torch.utils.data import DataLoader
from torch.optim.lr_scheduler import MultiStepLR
from torch.utils.tensorboard import SummaryWriter
# from torch.serialization import SourceChangeWarning
from pytorch_memlab import MemReporter
from pynvml import *
pp = pprint.PrettyPrinter(indent=4)
np.set_printoptions(edgeitems=3, infstr='inf', linewidth=150, nanstr='nan')
torch.set_printoptions( linewidth=132)
# os.environ['WANDB_NOTEBOOK_NAME'] = 'SparseChem_Train_mini'
#warnings.filterwarnings("ignore", category=UserWarning)
warnings.filterwarnings("ignore", category=UserWarning)
if torch.cuda.is_available():
nvmlInit()
# import multiprocessing
# multiprocessing.set_start_method('fork', force=True)
#------------------------------------------------------------------
# ### Initialization
#------------------------------------------------------------------
args = initialize()
pp.pprint(vars(args))
#------------------------------------------------------------------
# ### Assertions
#------------------------------------------------------------------
if (args.last_hidden_sizes is not None) and ((args.last_hidden_sizes_class is not None) or (args.last_hidden_sizes_reg is not None)):
raise ValueError("Head specific and general last_hidden_sizes argument were both specified!")
if (args.last_hidden_sizes is not None):
args.last_hidden_sizes_class = args.last_hidden_sizes
args.last_hidden_sizes_reg = args.last_hidden_sizes
if args.last_hidden_sizes_reg is not None:
assert len(args.last_hidden_sizes_reg) == len(args.dropouts_reg), "Number of hiddens and number of dropout values specified must be equal in the regression head!"
if args.last_hidden_sizes_class is not None:
assert len(args.last_hidden_sizes_class) == len(args.dropouts_class), "Number of hiddens and number of dropout values specified must be equal in the classification head!"
if args.hidden_sizes is not None:
assert len(args.hidden_sizes) == len(args.dropouts_trunk), "Number of hiddens and number of dropout values specified must be equal in the trunk!"
if args.class_feature_size == -1:
args.class_feature_size = args.hidden_sizes[-1]
if args.regression_feature_size == -1:
args.regression_feature_size = args.hidden_sizes[-1]
assert args.regression_feature_size <= args.hidden_sizes[-1], "Regression feature size cannot be larger than the trunk output"
assert args.class_feature_size <= args.hidden_sizes[-1], "Classification feature size cannot be larger than the trunk output"
assert args.regression_feature_size + args.class_feature_size >= args.hidden_sizes[-1], "Unused features in the trunk! Set regression_feature_size + class_feature_size >= trunk output!"
#if args.regression_feature_size != args.hidden_sizes[-1] or args.class_feature_size != args.hidden_sizes[-1]:
# raise ValueError("Hidden spliting not implemented yet!")
assert args.input_size_freq is None, "Using tail compression not yet supported."
if (args.y_class is None) and (args.y_regr is None):
raise ValueError("No label data specified, please add --y_class and/or --y_regr.")
#------------------------------------------------------------------
# ### Summary writer
#------------------------------------------------------------------
if args.profile == 1:
assert (args.save_board==1), "Tensorboard should be enabled to be able to profile memory usage."
if args.save_board:
# tb_name = os.path.join(args.output_dir, "", args.name)
writer = SummaryWriter(args.output_dir)
else:
writer = Nothing()
#------------------------------------------------------------------
# ### Load datasets
#------------------------------------------------------------------
ecfp = sc.load_sparse(args.x)
y_class = sc.load_sparse(args.y_class)
y_regr = sc.load_sparse(args.y_regr)
y_censor = sc.load_sparse(args.y_censor)
if (y_regr is None) and (y_censor is not None):
raise ValueError("y_censor provided please also provide --y_regr.")
if y_class is None:
y_class = scipy.sparse.csr_matrix((ecfp.shape[0], 0))
if y_regr is None:
y_regr = scipy.sparse.csr_matrix((ecfp.shape[0], 0))
if y_censor is None:
y_censor = scipy.sparse.csr_matrix(y_regr.shape)
folding = np.load(args.folding)
assert ecfp.shape[0] == folding.shape[0], "x and folding must have same number of rows"
## Loading task weights
tasks_class = sc.load_task_weights(args.weights_class, y=y_class, label="y_class")
tasks_regr = sc.load_task_weights(args.weights_regr, y=y_regr, label="y_regr")
#------------------------------------------------------------------
## Input transformation
#------------------------------------------------------------------
ecfp = sc.fold_transform_inputs(ecfp, folding_size=args.fold_inputs, transform=args.input_transform)
print(f"count non zero:{ecfp[0].count_nonzero()}")
num_pos = np.array((y_class == +1).sum(0)).flatten()
num_neg = np.array((y_class == -1).sum(0)).flatten()
num_class = np.array((y_class != 0).sum(0)).flatten()
if (num_class != num_pos + num_neg).any():
raise ValueError("For classification all y values (--y_class/--y) must be 1 or -1.")
num_regr = np.bincount(y_regr.indices, minlength=y_regr.shape[1])
assert args.min_samples_auc is None, "Parameter 'min_samples_auc' is obsolete. Use '--min_samples_class' that specifies how many samples a task needs per FOLD and per CLASS to be aggregated."
if tasks_class.aggregation_weight is None:
## using min_samples rule
fold_pos, fold_neg = sc.class_fold_counts(y_class, folding)
n = args.min_samples_class
tasks_class.aggregation_weight = ((fold_pos >= n).all(0) & (fold_neg >= n)).all(0).astype(np.float64)
if tasks_regr.aggregation_weight is None:
if y_censor.nnz == 0:
y_regr2 = y_regr.copy()
y_regr2.data[:] = 1
else:
## only counting uncensored data
y_regr2 = y_censor.copy()
y_regr2.data = (y_regr2.data == 0).astype(np.int32)
fold_regr, _ = sc.class_fold_counts(y_regr2, folding)
del y_regr2
tasks_regr.aggregation_weight = (fold_regr >= args.min_samples_regr).all(0).astype(np.float64)
print(f"Input dimension : {ecfp.shape[1]}")
print(f"#samples : {ecfp.shape[0]}")
print(f"#classification tasks: {y_class.shape[1]}")
print(f"#regression tasks : {y_regr.shape[1]}")
print(f"Using {(tasks_class.aggregation_weight > 0).sum()} classification tasks for calculating aggregated metrics (AUCROC, F1_max, etc).")
print(f"Using {(tasks_regr.aggregation_weight > 0).sum()} regression tasks for calculating metrics (RMSE, Rsquared, correlation).")
if args.fold_te is not None and args.fold_te >= 0:
## removing test data
assert args.fold_te != args.fold_va, "fold_va and fold_te must not be equal."
keep = folding != args.fold_te
ecfp = ecfp[keep]
y_class = y_class[keep]
y_regr = y_regr[keep]
y_censor= y_censor[keep]
folding = folding[keep]
normalize_inv = None
if args.normalize_regression == 1 and args.normalize_regr_va == 1:
y_regr, mean_save, var_save = sc.normalize_regr(y_regr)
fold_va = args.fold_va
idx_tr = np.where(folding != fold_va)[0]
idx_va = np.where(folding == fold_va)[0]
y_class_tr = y_class[idx_tr]
y_regr_tr = y_regr[idx_tr]
y_censor_tr = y_censor[idx_tr]
y_class_va = y_class[idx_va]
y_regr_va = y_regr[idx_va]
y_censor_va = y_censor[idx_va]
if args.normalize_regression == 1 and args.normalize_regr_va == 0:
y_regr_tr, mean_save, var_save = sc.normalize_regr(y_regr_tr)
if args.inverse_normalization == 1:
normalize_inv = {}
normalize_inv["mean"] = mean_save
normalize_inv["var"] = var_save
num_pos_va = np.array((y_class_va == +1).sum(0)).flatten()
num_neg_va = np.array((y_class_va == -1).sum(0)).flatten()
num_regr_va = np.bincount(y_regr_va.indices, minlength=y_regr.shape[1])
pos_rate = num_pos_va/(num_pos_va+num_neg_va)
pos_rate_ref = args.pi_zero
pos_rate = np.clip(pos_rate, 0, 0.99)
cal_fact_aucpr = pos_rate*(1-pos_rate_ref)/(pos_rate_ref*(1-pos_rate))
print(f"Input dimension : {ecfp.shape[1]}")
print(f"Input dimension : {ecfp.shape[1]}")
print(f"Training dataset : {ecfp[idx_tr].shape}")
print(f"Validation dataset: {ecfp[idx_va].shape}")
print()
print(f"#classification tasks: {y_class.shape[1]}")
print(f"#regression tasks : {y_regr.shape[1]}")
print(f"Using {(tasks_class.aggregation_weight > 0).sum():3d} classification tasks for calculating aggregated metrics (AUCROC, F1_max, etc).")
print(f"Using {(tasks_regr.aggregation_weight > 0).sum():3d} regression tasks for calculating metrics (RMSE, Rsquared, correlation).")
##----------------------------------------------------------
## Batch Size
##----------------------------------------------------------
num_int_batches = 1
if args.batch_size is not None:
batch_size = args.batch_size
else:
batch_size = int(np.ceil(args.batch_ratio * idx_tr.shape[0]))
print(f"orig batch size: {batch_size}")
print(f"orig num int batches: {num_int_batches}")
if args.internal_batch_max is not None:
if args.internal_batch_max < batch_size:
num_int_batches = int(np.ceil(batch_size / args.internal_batch_max))
batch_size = int(np.ceil(batch_size / num_int_batches))
print(f"batch size: {batch_size}")
print(f"num_int_batches: {num_int_batches}")
tasks_cat_id_list = None
select_cat_ids = None
if tasks_class.cat_id is not None:
tasks_cat_id_list = [[x,i] for i,x in enumerate(tasks_class.cat_id) if str(x) != 'nan']
tasks_cat_ids = [i for i,x in enumerate(tasks_class.cat_id) if str(x) != 'nan']
select_cat_ids = np.array(tasks_cat_ids)
cat_id_size = len(tasks_cat_id_list)
else:
cat_id_size = 0
#------------------------------------------------------------------
# ### Dataloaders
#------------------------------------------------------------------
dataset_tr = sc.ClassRegrSparseDataset(x=ecfp[idx_tr], y_class=y_class_tr, y_regr=y_regr_tr, y_censor=y_censor_tr, y_cat_columns=select_cat_ids)
dataset_va = sc.ClassRegrSparseDataset(x=ecfp[idx_va], y_class=y_class_va, y_regr=y_regr_va, y_censor=y_censor_va, y_cat_columns=select_cat_ids)
loader_tr = DataLoader(dataset_tr, batch_size=batch_size, num_workers = 8, pin_memory=True, collate_fn=dataset_tr.collate, shuffle=True)
loader_va = DataLoader(dataset_va, batch_size=batch_size, num_workers = 4, pin_memory=True, collate_fn=dataset_va.collate, shuffle=False)
args.input_size = dataset_tr.input_size
args.output_size = dataset_tr.output_size
args.class_output_size = dataset_tr.class_output_size
args.regr_output_size = dataset_tr.regr_output_size
args.cat_id_size = cat_id_size
#------------------------------------------------------------------
# ### WandB setup
#------------------------------------------------------------------
ns = types.SimpleNamespace()
ns.current_epoch = 0
ns.current_iter = 0
ns.best_results = {}
ns.best_metrics = None
ns.best_value = 0
ns.best_iter = 0
ns.best_epoch = 0
ns.p_epoch = 0
ns.num_prints = 0
init_wandb(ns, args)
wandb.define_metric("best_accuracy", summary="last")
wandb.define_metric("best_epoch", summary="last")
#------------------------------------------------------------------
# ### Network
#------------------------------------------------------------------
dev = torch.device(args.dev)
net = sc.SparseFFN(args).to(dev)
loss_class = torch.nn.BCEWithLogitsLoss(reduction="none")
loss_regr = sc.censored_mse_loss
if not args.censored_loss:
loss_regr = functools.partial(loss_regr, censored_enabled=False)
tasks_class.training_weight = tasks_class.training_weight.to(dev)
tasks_regr.training_weight = tasks_regr.training_weight.to(dev)
tasks_regr.censored_weight = tasks_regr.censored_weight.to(dev)
#------------------------------------------------------------------
# ### Optimizer, Scheduler, GradScaler
#------------------------------------------------------------------
optimizer = torch.optim.Adam(net.parameters(), lr=args.lr, weight_decay=args.weight_decay)
scheduler = MultiStepLR(optimizer, milestones=args.lr_steps, gamma=args.lr_alpha)
scaler = torch.cuda.amp.GradScaler()
wandb.watch(net, log='all', log_freq= 10) ### Weights and Biases Initialization
reporter = None
h = None
#------------------------------------------------------------------
# ### setup memory profiling reporter
#------------------------------------------------------------------
if args.profile == 1:
torch_gpu_id = torch.cuda.current_device()
if "CUDA_VISIBLE_DEVICES" in os.environ:
ids = list(map(int, os.environ.get("CUDA_VISIBLE_DEVICES", "").split(",")))
nvml_gpu_id = ids[torch_gpu_id] # remap
else:
nvml_gpu_id = torch_gpu_id
h = nvmlDeviceGetHandleByIndex(nvml_gpu_id)
if args.profile == 1:
##### output saving #####
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
reporter = MemReporter(net)
with open(f"{args.output_dir}/memprofile.txt", "w+") as profile_file:
with redirect_stdout(profile_file):
profile_file.write(f"\nInitial model detailed report:\n\n")
reporter.report()
#------------------------------------------------------------------
# ### Display network and other values
#------------------------------------------------------------------
print("Network:")
print(net)
print(optimizer)
print(f"dev : {dev}")
print(f"args.lr : {args.lr}")
print(f"args.weight_decay : {args.weight_decay}")
print(f"args.lr_steps : {args.lr_steps}")
print(f"args.lr_steps : {args.lr_steps}")
print(f"num_int_batches : {num_int_batches}")
print(f"batch_size : {batch_size}")
print(f"EPOCHS : {args.epochs}")
print(f"scaler : {scaler}")
print(f"args.normalize_loss : {args.normalize_loss}")
print(f"loss_class : {loss_class}")
print(f"mixed precision : {args.mixed_precision}")
print(f"args.eval_train : {args.eval_train}")
#------------------------------------------------------------------
# ## Training Loop
#------------------------------------------------------------------
ns.end_epoch = ns.current_epoch + args.epochs
for ns.current_epoch in range(ns.current_epoch, ns.end_epoch, 1):
t0 = time.time()
sc.train_class_regr(
net, optimizer,
loader = loader_tr,
loss_class = loss_class,
loss_regr = loss_regr,
dev = dev,
weights_class = tasks_class.training_weight * (1-args.regression_weight) * 2,
weights_regr = tasks_regr.training_weight * args.regression_weight * 2,
censored_weight = tasks_regr.censored_weight,
normalize_loss = args.normalize_loss,
num_int_batches = num_int_batches,
progress = False,
writer = writer,
epoch = ns.current_epoch,
args = args,
scaler = scaler,
nvml_handle = h)
if args.profile == 1:
with open(f"{args.output_dir}/memprofile.txt", "a+") as profile_file:
profile_file.write(f"\nAfter epoch {epoch} model detailed report:\n\n")
with redirect_stdout(profile_file):
reporter.report()
t1 = time.time()
eval_round = (args.eval_frequency > 0) and ((ns.current_epoch + 1) % args.eval_frequency == 0)
last_round = ns.current_epoch == args.epochs - 1
if eval_round or last_round:
results_va = sc.evaluate_class_regr(net, loader_va, loss_class, loss_regr,
tasks_class= tasks_class,
tasks_regr = tasks_regr,
dev = dev,
progress = False,
normalize_inv=normalize_inv,
cal_fact_aucpr=cal_fact_aucpr)
for key, val in results_va["classification_agg"].items():
writer.add_scalar("val_metrics:aggregated/"+key, val, ns.current_epoch * batch_size)
if args.eval_train:
results_tr = sc.evaluate_class_regr(net, loader_tr, loss_class, loss_regr,
tasks_class = tasks_class,
tasks_regr = tasks_regr,
dev = dev,
progress = args.verbose >= 2)
for key, val in results_tr["classification_agg"].items():
writer.add_scalar("trn_metrics:aggregated/"+key, val, ns.current_epoch * batch_size)
else:
results_tr = None
if args.verbose:
## printing a new header every 20 lines
header = ns.num_prints % 20 == 0
ns.num_prints += 1
sc.print_metrics_cr(ns.current_epoch, t1 - t0, results_tr, results_va, header)
wandb.log(results_va["classification_agg"].to_dict())
check_for_improvement(ns, results_va)
scheduler.step()
#print("DEBUG data for hidden spliting")
#print (f"Classification mask: Sum = {net.classmask.sum()}\t Uniques: {np.unique(net.classmask)}")
#print (f"Regression mask: Sum = {net.regmask.sum()}\t Uniques: {np.unique(net.regmask)}")
#print (f"overlap: {(net.regmask * net.classmask).sum()}")
print(f"Best Epoch : {ns.best_epoch}\n"
f"Best Iteration : {ns.best_iter} \n"
f"Best Precision | |
# -*- coding: utf-8 -*-
"""
Functions to calculate rankings.
@author: Scott
"""
# %% Setup
import pandas as pd
import numpy as np
import json
# %% Functions
def find_teams(results, debug=False):
"""
Create a list of all teams in results database.
Parameters
----------
results : TYPE
Game results database.
Returns
-------
allTeams : numpy list
List of unique teams in database.
"""
if debug:
print('find_teams in Debug mode.')
allTeams = pd.Series(results['Home']).unique()
if debug:
print('Home teams: ' + len(allTeams))
allTeams = np.append(allTeams, pd.Series(results['Away']).unique())
if debug:
print('Home and Away teams: ' + len(allTeams))
allTeams = np.unique(allTeams)
if debug:
print('Unique teams: ' + len(allTeams))
# print(allTeams)
print(str(len(allTeams)) + ' unique teams.')
return allTeams
def rankings_init(allTeams, ratingCoeff, rankingTypes, debug=False):
"""
Initialize rankings for all teams.
Parameters
----------
allTeams : numpy list
List of unique teams in database.
ratingCoeff : dict
Dict of parameters for each possible ranking system.
rankingType : list
List of which ranking systems to initialize for.
Returns
-------
rankingDict : dict
Each team and their current ranking for each ranking system.
"""
if debug:
print('rankings_init in Debug mode.')
# print(rankingType)
rankingDict = {}
for x, team in np.ndenumerate(allTeams):
if debug == 'verbose':
print('x: ' + str(x))
print('value: ' + str(team))
rankingDict[team] = {'gameCount': 0, 'yearCount': 1}
for rankingType in rankingTypes:
rankingDict[team].update({
rankingType: ratingCoeff[rankingType]['avgRating']})
if debug:
print('rankingDict shape: ' + str(len(rankingDict)))
if debug == 'verbose':
print(rankingDict)
return(rankingDict)
def season_start(results, rankingDict, ratingCoeff, rankingTypes, season,
allTeams, debug=False):
"""
Regress Rankings at Season Start.
Parameters
----------
results : TYPE
DESCRIPTION.
rankingDict : TYPE
DESCRIPTION.
ratingCoeff : TYPE
DESCRIPTION.
rankingType : TYPE
DESCRIPTION.
season : TYPE
DESCRIPTION.
allTeams : TYPE
DESCRIPTION.
Returns
-------
rankingDict : TYPE
DESCRIPTION.
"""
if debug:
print('season_start in debug mode.')
seasonGames = results[results.Season == season]
seasonTeams = pd.concat(
[seasonGames['Home'], seasonGames['Away']]).unique()
if debug == 'verbose':
print(seasonGames)
print(seasonTeams)
# Regress each team's rating
for team in allTeams:
if team in seasonTeams:
yearCount = rankingDict[team]['yearCount']
rankingDict[team]['yearCount'] = yearCount + 1
for rankingType in rankingTypes:
regress = ratingCoeff[rankingType]['regress']
avgRating = ratingCoeff[rankingType]['avgRating']
# if play this season and last, regress
if team in seasonTeams:
currentRating = rankingDict[team][rankingType]
rankingDict[team][rankingType] = round(
currentRating - (regress * (currentRating - avgRating)), 2)
if debug:
print(team + ' played in ' + str(season) +
'. Regressed from ' + str(currentRating) +
' to ' + str(rankingDict[team][rankingType]))
# if don't play this season, reset
else:
initRating = ratingCoeff[rankingType]['initRating']
rankingDict[team][rankingType] = initRating
if debug:
print(team + " reverted to " +
str(ratingCoeff[rankingType]['initRating']))
return(rankingDict)
# %% Ranking Formulas
def elo_simple(homeElo, awayElo, goalDiff, k, debug=False):
"""
Elo ranking system based only on wins.
No Homefield Advantage.
No Goal Diferential.
No season regression.
Parameters
----------
homeElo : float
Elo Rating of home team.
awayElo : float
Elo Rating of away team.
goalDiff : Int
Goal difference of game (Home - Away)
k : Int
Elo k-factor.
Returns
-------
homeElo_adj : float
Adjustment to home team's elo
awayElo_adj : float
Adjustment to away team's elo
predictError : float
Prediction error as a Brier score for event
"""
if debug:
print('elo_simple in debug mode')
# Determine winner of game
if goalDiff > 0:
result = 1
elif goalDiff < 0:
result = 0
else:
result = 0.5
# Calutlate expected match score
Qa = pow(10, homeElo / 400)
Qb = pow(10, awayElo / 400)
Ea = Qa / (Qa + Qb)
Eb = Qb / (Qa + Qb)
# Change in Elo ratings
deltaElo = round(k * (result - Ea), 2)
# Expected match score error
predictError = (result - Ea) ** 2
# Adjust Elo ratings of each team based on result
homeElo_adj = round(homeElo + deltaElo, 2)
awayElo_adj = round(awayElo - deltaElo, 2)
if debug:
print('Qa: ', Qa,
' Qb: ', Qb,
' Ea: ', Ea,
' Eb: ', Eb,
' homeElo_adj: ', homeElo_adj,
' awayElo_adj: ', awayElo_adj)
return (homeElo_adj, awayElo_adj, predictError)
def rating_elo(homeElo, awayElo, goalDiff, ratingCoeffMethod, debug=False):
"""
Elo ranking system.
Includes Homefield Advantage.
Parameters
----------
homeElo : float
Elo Rating of home team.
awayElo : float
Elo Rating of away team.
goalDiff : Int
Goal difference of game (Home - Away)
ratingCoeffMethod : TYPE
DESCRIPTION
Returns
-------
homeElo_adj : float
Adjustment to home team's elo
awayElo_adj : float
Adjustment to away team's elo
predictError : float
Prediction error as a Brier score for event
"""
if debug:
print('rating_elo in debug mode.')
print(ratingCoeffMethod)
k = ratingCoeffMethod['kRating']
hfAdv = ratingCoeffMethod['hfAdvantage'] # Home Team
hiAdv = ratingCoeffMethod['hiAdvantage'] # Home Ice
# goalDiffExp = ratingCoeffMethod['goalDiffExp']
# Determine winner of game
if goalDiff > 0:
result = 1
elif goalDiff < 0:
result = 0
else:
result = 0.5
if debug:
print("home Elo: " + type(homeElo).__name__)
print("hf Adv: " + type(hfAdv).__name__)
print("hi Adv: " + type(hiAdv).__name__)
# Calutlate expected match score
Qa = pow(10, (homeElo + hfAdv + hiAdv) / 400)
Qb = pow(10, awayElo / 400)
Ea = Qa / (Qa + Qb)
Eb = Qb / (Qa + Qb)
# Change in Elo ratings
deltaElo = round(k * (result - Ea), 2)
# Expected match score error
predictError = (result - Ea) ** 2
# Adjust Elo ratings of each team based on result
homeElo_adj = round(homeElo + deltaElo, 2)
awayElo_adj = round(awayElo - deltaElo, 2)
if debug:
print('Qa: ', Qa,
' Qb: ', Qb,
' Ea: ', Ea,
' Eb: ', Eb,
' homeElo_adj: ', homeElo_adj,
' awayElo_adj: ', awayElo_adj)
return (homeElo_adj, awayElo_adj, predictError)
def game_ranking(results, ratingCoeff, rankingType,
debug=False, saveResults=True):
"""
Calculate rankings for each match.
Parameters
----------
results : TYPE
DESCRIPTION.
ratingCoeff : TYPE
DESCRIPTION.
rankingType : TYPE
DESCRIPTION.
Returns
-------
results : TYPE
DESCRIPTION.
rankingDict : TYPE
DESCRIPTION.
"""
if debug == 'verbose':
debugVerbose = True
debug = True
else:
debugVerbose = False
if debug:
print('game_ranking in debug mode.')
sep = ", "
print("Ranking systems to run: " + sep.join(rankingType))
# Get list of all teams in results
allTeams = find_teams(results)
# Create columns for ranking results for each ranking system
for rankType in rankingType:
results[rankType + '_Away'] = np.nan
results[rankType + '_Home'] = np.nan
results[rankType + '_Error'] = np.nan
# Evaluate each game for given ranking methods
print('Start scoring each game')
for index, row in enumerate(results.itertuples(index=True)):
season = row.Season
if debugVerbose:
print('Index: ' + str(index) + ' Season: ' + str(season))
print(row)
# Intitialize first season
if index == 0:
rankingDict = rankings_init(allTeams, ratingCoeff,
rankingType) # , debug)
seasonLast = season
if debug:
print('First season initialized.')
# Initialize new seasons
elif (season - seasonLast) > 0:
rankingDict = season_start(results, rankingDict, ratingCoeff,
rankingType, season, allTeams, debug)
seasonLast = season
if debug:
print(str(season) + ' season initialized')
for rankingMethod in rankingType:
if debug:
print(rankingMethod)
# print(row)
# print(ratingCoeff)
# Home and Away teams
teamAway = row.Away
teamHome = row.Home
# Home and Away teams' ratings
eloAway = rankingDict.get(teamAway, {}).get(rankingMethod)
eloHome = rankingDict.get(teamHome, {}).get(rankingMethod)
goalDiff = row.Home_Score - row.Away_Score
# goalDiff = row[5] - row[2]
if debug:
print("Away: " + teamAway + " Elo: " + str(eloAway))
print("Home: " + teamHome + " Elo: " + str(eloHome))
# Choose ranking function based on method
if 'Elo' in rankingMethod:
rateCoeff = ratingCoeff[rankingMethod]
[eloHome, eloAway, predictError] = rating_elo(eloHome,
eloAway,
goalDiff,
rateCoeff)
else:
raise ValueError('Unknown Ranking Method.')
# [eloHome, eloAway, predictError] = elo_simple(
# eloHome, eloAway, goalDiff, ratingCoeff[rankingType]['kRating'])
# Update Current Ranking Tracker
rankingDict[teamAway][rankingMethod] = eloAway
rankingDict[teamHome][rankingMethod] = eloHome
# Add Updated Elo to Results table
results.at[row.Index, rankingMethod + '_Away'] = eloAway
results.at[row.Index, rankingMethod + '_Home'] = eloHome
results.at[row.Index, rankingMethod + '_Error'] = predictError
# Increment game counter
awayCount = rankingDict[teamAway]['gameCount'] + 1
homeCount = rankingDict[teamHome]['gameCount'] + 1
rankingDict[teamAway]['gameCount'] = awayCount
rankingDict[teamHome]['gameCount'] = homeCount
# Write to CSV
if saveResults:
path_or_buf = 'Results_Rankings.csv'
results.to_csv(path_or_buf=path_or_buf, index='False')
print('Results saved to ' + path_or_buf)
with open('Ranking_Dict.txt', 'w') as file:
# use `json.loads` to do the reverse
file.write(json.dumps(rankingDict))
return (results, rankingDict)
# %% Results analysis
def team_games(results, team='Northeastern'):
"""
Collect all games by given team.
Parameters
----------
results : TYPE
DESCRIPTION.
team : TYPE, optional
DESCRIPTION. The default is 'Northeastern'.
Returns
| |
<filename>loggerapp/datalogger/driver/pymba/pymba/vimbadll.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from sys import platform as sys_plat
import platform
import os
from ctypes import *
from . import vimbastructure as structs
from .vimbaexception import VimbaException
if sys_plat == "win32":
def find_win_dll(arch):
""" Finds the highest versioned windows dll for the specified architecture. """
bases = [
r'C:\Program Files\Allied Vision Technologies\AVTVimba_%i.%i\VimbaC\Bin\Win%i\VimbaC.dll',
r'C:\Program Files\Allied Vision\Vimba_%i.%i\VimbaC\Bin\Win%i\VimbaC.dll',
r'C:\Program Files\Allied Vision\Vimba_%i.%i\Tools\Viewer\Win%i\VimbaC.dll',
]
dlls = []
for base in bases:
for major in range(3):
for minor in range(10):
candidate = base % (major, minor, arch)
if os.path.isfile(candidate):
dlls.append(candidate)
if not dlls:
if 'VIMBA_HOME' in os.environ:
candidate = os.environ ['VIMBA_HOME'] + '\VimbaC\Bin\Win%i\VimbaC.dll' % (arch)
if os.path.isfile(candidate):
dlls.append(candidate)
if not dlls:
raise IOError("VimbaC.dll not found.")
return dlls[-1]
if '64' in platform.architecture()[0]:
vimbaC_path = find_win_dll(64)
else:
vimbaC_path = find_win_dll(32)
dll_loader = windll
else:
dll_loader = cdll
if 'x86_64' in os.uname()[4]:
assert os.environ.get(
"GENICAM_GENTL64_PATH"), "you need your GENICAM_GENTL64_PATH environment set. Make sure you have Vimba installed, and you have loaded the /etc/profile.d/ scripts"
tlPath = [p for p in os.environ.get("GENICAM_GENTL64_PATH").split(":") if p][0]
vimba_dir = "/".join(tlPath.split("/")[1:-3])
vimbaC_path = "/" + vimba_dir + "/VimbaC/DynamicLib/x86_64bit/libVimbaC.so"
elif 'x86_32' in os.uname()[4]:
print("Warning: x86_32 reached!")
assert os.environ.get(
"GENICAM_GENTL32_PATH"), "you need your GENICAM_GENTL32_PATH environment set. Make sure you have Vimba installed, and you have loaded the /etc/profile.d/ scripts"
tlPath = [p for p in os.environ.get("GENICAM_GENTL32_PATH").split(":") if p][0]
vimba_dir = "/".join(tlPath.split("/")[1:-3])
vimbaC_path = "/" + vimba_dir + "/VimbaC/DynamicLib/x86_32bit/libVimbaC.so"
elif 'arm' in os.uname()[4]:
assert os.environ.get(
"GENICAM_GENTL32_PATH"), "you need your GENICAM_GENTL32_PATH environment set. Make sure you have Vimba installed, and you have loaded the /etc/profile.d/ scripts"
tlPath = [p for p in os.environ.get("GENICAM_GENTL32_PATH").split(":") if p][0]
vimba_dir = "/".join(tlPath.split("/")[1:-3])
vimbaC_path = "/" + vimba_dir + "/VimbaC/DynamicLib/arm_32bit/libVimbaC.so"
elif 'aarch64' in os.uname()[4]:
assert os.environ.get(
"GENICAM_GENTL64_PATH"), "you need your GENICAM_GENTL64_PATH environment set. Make sure you have Vimba installed, and you have loaded the /etc/profile.d/ scripts"
tlPath = [p for p in os.environ.get("GENICAM_GENTL64_PATH").split(":") if p][0]
vimba_dir = "/".join(tlPath.split("/")[1:-3])
vimbaC_path = "/" + vimba_dir + "/VimbaC/DynamicLib/arm_64bit/libVimbaC.so"
else:
raise ValueError("Pymba currently doesn't support %s" % os.uname()[4])
# Callback Function Type
if sys_plat == "win32":
CB_FUNCTYPE = WINFUNCTYPE
else:
# Untested!
CB_FUNCTYPE = CFUNCTYPE
class VimbaDLL(object):
"""
ctypes directives to make the wrapper class work cleanly,
talks to VimbaC.dll
"""
# a full list of Vimba API methods
# (only double dashed methods have been implemented so far)
#
# -- VmbVersionQuery()
#
# -- VmbStartup()
# -- VmbShutdown()
#
# -- VmbCamerasList()
# -- VmbCameraInfoQuery()
# -- VmbCameraOpen()
# -- VmbCameraClose()
#
# -- VmbFeaturesList()
# -- VmbFeatureInfoQuery()
# VmbFeatureListAffected()
# VmbFeatureListSelected()
# VmbFeatureAccessQuery()
#
# -- VmbFeatureIntGet()
# -- VmbFeatureIntSet()
# -- VmbFeatureIntRangeQuery()
# VmbFeatureIntIncrementQuery()
#
# -- VmbFeatureFloatGet()
# -- VmbFeatureFloatSet()
# -- VmbFeatureFloatRangeQuery()
#
# -- VmbFeatureEnumGet()
# -- VmbFeatureEnumSet()
# VmbFeatureEnumRangeQuery()
# VmbFeatureEnumIsAvailable()
# VmbFeatureEnumAsInt()
# VmbFeatureEnumAsString()
# VmbFeatureEnumEntryGet()
#
# -- VmbFeatureStringGet()
# -- VmbFeatureStringSet()
# VmbFeatureStringMaxlengthQuery()
#
# -- VmbFeatureBoolGet()
# -- VmbFeatureBoolSet()
#
# -- VmbFeatureCommandRun()
# VmbFeatureCommandIsDone()
#
# VmbFeatureRawGet()
# VmbFeatureRawSet()
# VmbFeatureRawLengthQuery()
#
# VmbFeatureInvalidationRegister()
# VmbFeatureInvalidationUnregister()
#
# -- VmbFrameAnnounce()
# -- VmbFrameRevoke()
# -- VmbFrameRevokeAll()
# -- VmbCaptureStart()
# -- VmbCaptureEnd()
# -- VmbCaptureFrameQueue()
# -- VmbCaptureFrameWait()
# -- VmbCaptureQueueFlush()
#
# -- VmbInterfacesList()
# -- VmbInterfaceOpen()
# -- VmbInterfaceClose()
#
# VmbAncillaryDataOpen()
# VmbAncillaryDataClose()
#
# VmbMemoryRead()
# VmbMemoryWrite()
# -- VmbRegistersRead()
# -- VmbRegistersWrite()
# Vimba C API DLL
_vimbaDLL = dll_loader.LoadLibrary(vimbaC_path)
# version query
versionQuery = _vimbaDLL.VmbVersionQuery
# returned error code
versionQuery.restype = c_int32
versionQuery.argtypes = (POINTER(structs.VimbaVersion), # pointer to version structure
c_uint32) # version structure size
# startup
startup = _vimbaDLL.VmbStartup
# returned error code
startup.restype = c_int32
# shutdown
shutdown = _vimbaDLL.VmbShutdown
# list cameras
camerasList = _vimbaDLL.VmbCamerasList
# returned error code
camerasList.restype = c_int32
camerasList.argtypes = (POINTER(structs.VimbaCameraInfo), # pointer to camera info structure
# length of list
c_uint32,
# pointer to number of cameras
POINTER(c_uint32),
c_uint32) # camera info structure size
# camera info query
cameraInfoQuery = _vimbaDLL.VmbCameraInfoQuery
cameraInfoQuery.restype = c_int32
cameraInfoQuery.argtypes = (c_char_p, # camera unique id
# pointer to camera info structure
POINTER(structs.VimbaCameraInfo),
c_uint32) # size of structure
# camera open
cameraOpen = _vimbaDLL.VmbCameraOpen
# returned error code
cameraOpen.restype = c_int32
cameraOpen.argtypes = (c_char_p, # camera unique id
# access mode
c_uint32,
c_void_p) # camera handle, pointer to a pointer
# camera close
cameraClose = _vimbaDLL.VmbCameraClose
# returned error code
cameraClose.restype = c_int32
# camera handle
cameraClose.argtypes = (c_void_p,)
# list features
featuresList = _vimbaDLL.VmbFeaturesList
featuresList.restype = c_int32
featuresList.argtypes = (c_void_p, # handle, in this case camera handle
# pointer to feature info structure
POINTER(structs.VimbaFeatureInfo),
# list length
c_uint32,
# pointer to num features found
POINTER(c_uint32),
c_uint32) # feature info size
# feature info query
featureInfoQuery = _vimbaDLL.VmbFeatureInfoQuery
featureInfoQuery.restype = c_int32
featureInfoQuery.argtypes = (c_void_p, # handle, in this case camera handle
# name of feature
c_char_p,
# pointer to feature info structure
POINTER(structs.VimbaFeatureInfo),
c_uint32) # size of structure
# get the int value of a feature
featureIntGet = _vimbaDLL.VmbFeatureIntGet
featureIntGet.restype = c_int32
featureIntGet.argtypes = (c_void_p, # handle, in this case camera handle
# name of the feature
c_char_p,
POINTER(c_int64)) # value to get
# set the int value of a feature
featureIntSet = _vimbaDLL.VmbFeatureIntSet
featureIntSet.restype = c_int32
featureIntSet.argtypes = (c_void_p, # handle, in this case camera handle
# name of the feature
c_char_p,
c_int64) # value to set # get the value of an integer feature
# query the range of values of the feature
featureIntRangeQuery = _vimbaDLL.VmbFeatureIntRangeQuery
featureIntRangeQuery.restype = c_int32
featureIntRangeQuery.argtypes = (c_void_p, # handle
# name of the feature
c_char_p,
# min range
POINTER(c_int64),
POINTER(c_int64)) # max range
# get the float value of a feature
featureFloatGet = _vimbaDLL.VmbFeatureFloatGet
featureFloatGet.restype = c_int32
featureFloatGet.argtypes = (c_void_p, # handle, in this case camera handle
# name of the feature
c_char_p,
POINTER(c_double)) # value to get
# set the float value of a feature
featureFloatSet = _vimbaDLL.VmbFeatureFloatSet
featureFloatSet.restype = c_int32
featureFloatSet.argtypes = (c_void_p, # handle, in this case camera handle
# name of the feature
c_char_p,
c_double) # value to set
# query the range of values of the feature
featureFloatRangeQuery = _vimbaDLL.VmbFeatureFloatRangeQuery
featureFloatRangeQuery.restype = c_int32
featureFloatRangeQuery.argtypes = (c_void_p, # handle
# name of the feature
c_char_p,
# min range
POINTER(c_double),
POINTER(c_double)) # max range
# get the enum value of a feature
featureEnumGet = _vimbaDLL.VmbFeatureEnumGet
featureEnumGet.restype = c_int32
featureEnumGet.argtypes = (c_void_p, # handle, in this case camera handle
# name of the feature
c_char_p,
POINTER(c_char_p)) # value to get
# set the enum value of a feature
featureEnumSet = _vimbaDLL.VmbFeatureEnumSet
featureEnumSet.restype = c_int32
featureEnumSet.argtypes = (c_void_p, # handle, in this case camera handle
# name of the feature
c_char_p,
c_char_p) # value to set
# get the string value of a feature
featureStringGet = _vimbaDLL.VmbFeatureStringGet
featureStringGet.restype = c_int32
featureStringGet.argtypes = (c_void_p, # handle, in this case camera handle
# name of the feature
c_char_p,
# string buffer to fill
c_char_p,
# size of the input buffer
c_uint32,
POINTER(c_uint32)) # string buffer to fill
# set the string value of a feature
featureStringSet = _vimbaDLL.VmbFeatureStringSet
featureStringSet.restype = c_int32
featureStringSet.argtypes = (c_void_p, # handle, in this case camera handle
# name of the feature
c_char_p,
c_char_p) # value to set
# get the boolean value of a feature
featureBoolGet = _vimbaDLL.VmbFeatureBoolGet
featureBoolGet.restype = c_int32
featureBoolGet.argtypes = (c_void_p, # handle, in this case camera handle
# name of the feature
c_char_p,
POINTER(c_bool)) # value to get
# set the boolean value of a feature
featureBoolSet = _vimbaDLL.VmbFeatureBoolSet
featureBoolSet.restype = c_int32
featureBoolSet.argtypes = (c_void_p, # handle, in this case camera handle
# name of the feature
c_char_p,
c_bool) # value to set
# run a feature command
featureCommandRun = _vimbaDLL.VmbFeatureCommandRun
featureCommandRun.restype = c_int32
featureCommandRun.argtypes = (c_void_p, # handle for a module that exposes features
c_char_p) # name of the command feature
# Check if a feature command is done
featureCommandIsDone = _vimbaDLL.VmbFeatureCommandIsDone
featureCommandIsDone.restype = c_int32
featureCommandIsDone.argtypes = (c_void_p, # handle
c_char_p, # name of the command feature
POINTER(c_bool)) # pointer to a result bool
# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.